Class: Berater::Middleware::Statsd

Inherits:
Object
  • Object
show all
Defined in:
lib/berater/middleware/statsd.rb

Instance Method Summary collapse

Constructor Details

#initialize(client, tags: {}) ⇒ Statsd

Returns a new instance of Statsd.



4
5
6
7
# File 'lib/berater/middleware/statsd.rb', line 4

def initialize(client, tags: {})
  @client = client
  @tags = tags
end

Instance Method Details

#call(limiter, **opts) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/berater/middleware/statsd.rb', line 9

def call(limiter, **opts)
  duration = -Process.clock_gettime(Process::CLOCK_MONOTONIC)
  lock = yield
rescue Exception => error
  # capture exception for reporting, then propagate
  raise
ensure
  duration += Process.clock_gettime(Process::CLOCK_MONOTONIC)
  duration = (duration * 1_000).round(2) # milliseconds

  tags = build_tags(limiter, opts)

  @client.timing(
    'berater.limiter.limit',
    duration,
    tags: tags,
  )

  @client.gauge(
    'berater.limiter.capacity',
    limiter.capacity,
    tags: tags,
  )

  if lock
    @client.increment(
      'berater.lock.acquired',
      tags: tags,
    )

    if lock.contention >= 0 # not a failsafe lock
      @client.gauge(
        'berater.lock.capacity',
        lock.capacity,
        tags: tags,
      )
      @client.gauge(
        'berater.lock.contention',
        lock.contention,
        tags: tags,
      )
    end
  end

  if error
    if error.is_a?(Berater::Overloaded)
      @client.increment(
        'berater.limiter.overloaded',
        tags: tags,
      )
    else
      @client.increment(
        'berater.limiter.error',
        tags: tags.merge(type: error.class.to_s.gsub('::', '_'))
      )
    end
  end
end