Skip to content

Commit ee59473

Browse files
committed
aggregator add impl
1 parent be9422d commit ee59473

File tree

1 file changed

+37
-7
lines changed

1 file changed

+37
-7
lines changed

sentry-ruby/lib/sentry/metrics/aggregator.rb

+37-7
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ class Aggregator
88
FLUSH_INTERVAL = 5
99
ROLLUP_IN_SECONDS = 10
1010

11+
METRIC_TYPES = {
12+
c: CounterMetric,
13+
d: DistributionMetric,
14+
g: GaugeMetric,
15+
s: SetMetric
16+
}
17+
1118
def initialize(configuration, client)
1219
@client = client
1320
@logger = configuration.logger
@@ -16,8 +23,13 @@ def initialize(configuration, client)
1623

1724
@thread = nil
1825
@exited = false
26+
@mutex = Mutex.new
1927

28+
# buckets are a nested hash of timestamp -> bucket keys -> Metric instance
2029
@buckets = {}
30+
31+
# the flush interval needs to be shifted once per startup to create jittering
32+
@flush_shift = Random.rand * ROLLUP_IN_SECONDS
2133
end
2234

2335
def add(type,
@@ -34,19 +46,30 @@ def add(type,
3446
# this is integer division and thus takes the floor of the division
3547
# and buckets into 10 second intervals
3648
bucket_timestamp = (timestamp / ROLLUP_IN_SECONDS) * ROLLUP_IN_SECONDS
49+
3750
serialized_tags = serialize_tags(tags)
3851
bucket_key = [type, key, unit, serialized_tags]
3952

40-
# TODO lock and add to bucket
41-
42
53+
@mutex.synchronize do
54+
@buckets[bucket_timestamp] ||= {}
55+
56+
if @buckets[bucket_timestamp][bucket_key]
57+
@buckets[bucket_timestamp][bucket_key].add(value)
58+
else
59+
@buckets[bucket_timestamp][bucket_key] = METRIC_TYPES[type].new(value)
60+
end
61+
end
4262
end
4363

4464
def flush
45-
# TODO
65+
@mutex.synchronize do
66+
log_debug("[Metrics::Aggregator] current bucket state: #{@buckets}")
67+
# TODO
68+
end
4669
end
4770

4871
def kill
49-
log_debug("[Metrics::Aggregator] killing thread")
72+
log_debug('[Metrics::Aggregator] killing thread')
5073

5174
@exited = true
5275
@thread&.kill
@@ -68,15 +91,22 @@ def ensure_thread
6891

6992
true
7093
rescue ThreadError
71-
log_debug("[Metrics::Aggregator] thread creation failed")
94+
log_debug('[Metrics::Aggregator] thread creation failed')
7295
@exited = true
7396
false
7497
end
7598

7699
def serialize_tags(tags)
77-
# TODO support array tags
78100
return [] unless tags
79-
tags.map { |k, v| [k.to_s, v.to_s] }
101+
102+
# important to sort for key consistency
103+
tags.map do |k, v|
104+
if v.is_a?(Array)
105+
v.map { |x| [k.to_s, x.to_s] }
106+
else
107+
[k.to_s, v.to_s]
108+
end
109+
end.flatten.sort
80110
end
81111
end
82112
end

0 commit comments

Comments
 (0)