1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using InfluxDB . Collector . Pipeline . Common ;
5
+
6
+ namespace InfluxDB . Collector . Pipeline . Aggregate
7
+ {
8
+ class AggregatePointEmitter : IntervalEmitterBase
9
+ {
10
+ readonly bool _sumIncrements ;
11
+ readonly Func < IEnumerable < long > , double > _timesAggregation ;
12
+ readonly IPointEmitter _parent ;
13
+
14
+ public AggregatePointEmitter ( TimeSpan timeSpan , bool sumIncrements , Func < IEnumerable < long > , double > timesAggregation , IPointEmitter parent )
15
+ : base ( timeSpan )
16
+ {
17
+ _sumIncrements = sumIncrements ;
18
+ _timesAggregation = timesAggregation ;
19
+ _parent = parent ;
20
+ }
21
+
22
+ protected override void HandleBatch ( IReadOnlyCollection < PointData > batch )
23
+ {
24
+ var grouped = batch . GroupBy ( x => new GroupingKey (
25
+ x . UtcTimestamp . HasValue ? x . UtcTimestamp . Value . Ticks / _interval . Ticks : 0 ,
26
+ DetermineKind ( x ) ,
27
+ x . Measurement ,
28
+ x . Tags
29
+ ) ) ;
30
+
31
+ var aggregated = grouped . SelectMany ( Aggregate ) . ToArray ( ) ;
32
+
33
+ _parent . Emit ( aggregated ) ;
34
+ }
35
+
36
+ IEnumerable < PointData > Aggregate ( IGrouping < GroupingKey , PointData > group )
37
+ {
38
+ GroupingKey key = group . Key ;
39
+ MeasurementKind kind = key . Kind ;
40
+
41
+ if ( kind == MeasurementKind . Increment && _sumIncrements )
42
+ {
43
+ long sum = group . Sum ( x => ( long ) x . Fields [ "count" ] ) ;
44
+ return new [ ]
45
+ {
46
+ new PointData (
47
+ key . Measurement ,
48
+ new Dictionary < string , object > { { "count" , sum } } ,
49
+ key . Tags ,
50
+ AverageTime ( key ) )
51
+ } ;
52
+ }
53
+
54
+ if ( kind == MeasurementKind . Time && _timesAggregation != null )
55
+ {
56
+ long ticks = ( long ) _timesAggregation ( group . Select ( x => ( ( TimeSpan ) x . Fields [ "value" ] ) . Ticks ) ) ;
57
+ return new [ ]
58
+ {
59
+ new PointData (
60
+ key . Measurement ,
61
+ new Dictionary < string , object > { { "value" , new TimeSpan ( ticks ) } } ,
62
+ key . Tags ,
63
+ AverageTime ( key ) )
64
+ } ;
65
+ }
66
+
67
+ return group ;
68
+ }
69
+
70
+ private DateTime AverageTime ( GroupingKey key )
71
+ {
72
+ return new DateTime ( key . Bucket * _interval . Ticks + _interval . Ticks / 2 , DateTimeKind . Utc ) ;
73
+ }
74
+
75
+ static MeasurementKind DetermineKind ( PointData x )
76
+ {
77
+ if ( x . Fields . Count != 1 ) return MeasurementKind . Other ;
78
+
79
+ if ( x . Fields . TryGetValue ( "count" , out var count ) && count is long )
80
+ {
81
+ return MeasurementKind . Increment ;
82
+ }
83
+ else if ( x . Fields . TryGetValue ( "value" , out var value ) && value is TimeSpan )
84
+ {
85
+ return MeasurementKind . Time ;
86
+ }
87
+ else
88
+ {
89
+ return MeasurementKind . Other ;
90
+ }
91
+ }
92
+ }
93
+ }
0 commit comments