Skip to content

Commit

Permalink
stat: synchronize to_h with increment_ms
Browse files Browse the repository at this point in the history
Possibly fixes #545
(>4.4.0 <=4.13.0 causing RuntimeError: can't add a new key into hash during
iteration)
  • Loading branch information
kyrylo committed Feb 26, 2020
1 parent 202b405 commit 1787e09
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions lib/airbrake-ruby/stat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,21 @@ def initialize(sum: 0.0, sumsq: 0.0, tdigest: TDigest.new(0.05))
@sum = sum
@sumsq = sumsq
@tdigest = tdigest
@mutex = Mutex.new
end

# @return [Hash{String=>Object}] stats as a hash with compressed TDigest
# (serialized as base64)
def to_h
tdigest.compress!
{
'count' => tdigest.size,
'sum' => sum,
'sumsq' => sumsq,
'tdigest' => Base64.strict_encode64(tdigest.as_small_bytes),
}
@mutex.synchronize do
tdigest.compress!
{
'count' => tdigest.size,
'sum' => sum,
'sumsq' => sumsq,
'tdigest' => Base64.strict_encode64(tdigest.as_small_bytes),
}
end
end

# Increments tdigest timings and updates tdigest with the difference between
Expand All @@ -45,19 +48,23 @@ def to_h
# @param [Date] end_time
# @return [void]
def increment(start_time, end_time = nil)
end_time ||= Time.new
increment_ms((end_time - start_time) * 1000)
@mutex.synchronize do
end_time ||= Time.new
increment_ms((end_time - start_time) * 1000)
end
end

# Increments tdigest timings and updates tdigest with given +ms+ value.
#
# @param [Float] ms
# @return [void]
def increment_ms(ms)
self.sum += ms
self.sumsq += ms * ms
@mutex.synchronize do
self.sum += ms
self.sumsq += ms * ms

tdigest.push(ms)
tdigest.push(ms)
end
end

# We define custom inspect so that we weed out uninformative TDigest, which
Expand Down

0 comments on commit 1787e09

Please sign in to comment.