Class: Philiprehberger::RateCounter::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/rate_counter/registry.rb

Overview

A registry of named rate counters with a shared default window

Examples:

reg = Registry.new(window: 60)
reg[:requests].increment
reg[:errors].increment
reg[:requests].rate

Instance Method Summary collapse

Constructor Details

#initialize(window: 60) ⇒ Registry

Create a new registry

Parameters:

  • window (Numeric) (defaults to: 60)

    default window size in seconds for new counters



16
17
18
19
20
# File 'lib/philiprehberger/rate_counter/registry.rb', line 16

def initialize(window: 60)
  @window = window
  @counters = {}
  @mutex = Mutex.new
end

Instance Method Details

#[](name) ⇒ Counter

Access or create a named counter

Parameters:

  • name (Symbol, String)

    the counter name

Returns:



26
27
28
29
30
# File 'lib/philiprehberger/rate_counter/registry.rb', line 26

def [](name)
  @mutex.synchronize do
    @counters[name] ||= Counter.new(window: @window)
  end
end

#namesArray<Symbol, String>

List all registered counter names

Returns:

  • (Array<Symbol, String>)


35
36
37
# File 'lib/philiprehberger/rate_counter/registry.rb', line 35

def names
  @mutex.synchronize { @counters.keys }
end

#reset_allvoid

This method returns an undefined value.

Reset all counters



42
43
44
45
46
# File 'lib/philiprehberger/rate_counter/registry.rb', line 42

def reset_all
  @mutex.synchronize do
    @counters.each_value(&:reset)
  end
end

#sizeInteger

Return the number of registered counters

Returns:

  • (Integer)


51
52
53
# File 'lib/philiprehberger/rate_counter/registry.rb', line 51

def size
  @mutex.synchronize { @counters.size }
end

#snapshotHash

Return a frozen snapshot of all counter states

Returns:

  • (Hash)

    frozen hash of name to counter snapshot



58
59
60
61
62
63
64
# File 'lib/philiprehberger/rate_counter/registry.rb', line 58

def snapshot
  @mutex.synchronize do
    @counters.each_with_object({}) do |(name, counter), result|
      result[name] = counter.snapshot
    end.freeze
  end
end