Class: Flare::MetricCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/flare/metric_counter.rb

Overview

Thread-safe counter for metric aggregation. Uses atomic operations for lock-free increments.

Note: Durations are stored as integer milliseconds. Sub-millisecond durations are truncated to 0. For very fast operations (e.g., cache hits), the sum_ms may undercount actual time spent.

Instance Method Summary collapse

Constructor Details

#initializeMetricCounter

Returns a new instance of MetricCounter.



13
14
15
16
17
# File 'lib/flare/metric_counter.rb', line 13

def initialize
  @count = Concurrent::AtomicFixnum.new(0)
  @sum_ms = Concurrent::AtomicFixnum.new(0)
  @error_count = Concurrent::AtomicFixnum.new(0)
end

Instance Method Details

#countObject



25
26
27
# File 'lib/flare/metric_counter.rb', line 25

def count
  @count.value
end

#error_countObject



33
34
35
# File 'lib/flare/metric_counter.rb', line 33

def error_count
  @error_count.value
end

#increment(duration_ms:, error: false) ⇒ Object



19
20
21
22
23
# File 'lib/flare/metric_counter.rb', line 19

def increment(duration_ms:, error: false)
  @count.increment
  @sum_ms.increment(duration_ms.to_i)
  @error_count.increment if error
end

#sum_msObject



29
30
31
# File 'lib/flare/metric_counter.rb', line 29

def sum_ms
  @sum_ms.value
end

#to_hObject



37
38
39
40
41
42
43
# File 'lib/flare/metric_counter.rb', line 37

def to_h
  {
    count: @count.value,
    sum_ms: @sum_ms.value,
    error_count: @error_count.value
  }
end