Class: NatsWork::RateTracker

Inherits:
Object
  • Object
show all
Defined in:
lib/natswork/error_tracker.rb

Overview

Rate tracker for monitoring error frequencies

Instance Method Summary collapse

Constructor Details

#initialize(window_size = 3600) ⇒ RateTracker

Returns a new instance of RateTracker.



239
240
241
242
243
# File 'lib/natswork/error_tracker.rb', line 239

def initialize(window_size = 3600)
  @timestamps = Concurrent::Array.new
  @window_size = window_size
  @mutex = Mutex.new
end

Instance Method Details

#count(period_seconds = @window_size) ⇒ Object



261
262
263
264
265
266
267
# File 'lib/natswork/error_tracker.rb', line 261

def count(period_seconds = @window_size)
  @mutex.synchronize do
    cleanup_old_timestamps
    cutoff_time = Time.now.to_f - period_seconds
    @timestamps.count { |ts| ts >= cutoff_time }
  end
end

#incrementObject



245
246
247
248
249
250
# File 'lib/natswork/error_tracker.rb', line 245

def increment
  @mutex.synchronize do
    @timestamps << Time.now.to_f
    cleanup_old_timestamps
  end
end

#rate(period_seconds = @window_size) ⇒ Object



252
253
254
255
256
257
258
259
# File 'lib/natswork/error_tracker.rb', line 252

def rate(period_seconds = @window_size)
  @mutex.synchronize do
    cleanup_old_timestamps
    cutoff_time = Time.now.to_f - period_seconds
    recent_count = @timestamps.count { |ts| ts >= cutoff_time }
    recent_count.to_f / period_seconds
  end
end