class Invoca::Metrics::GaugeCache

Constants

GAUGE_REPORT_INTERVAL

Attributes

cache[R]

Public Class Methods

new(statsd_client) click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 26
def initialize(statsd_client)
  @statsd_client = statsd_client
  @cache = {}
  start_reporting_thread
end
register(cache_key, statsd_client) click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 9
def register(cache_key, statsd_client)
  registered_gauge_caches[cache_key] ||= new(statsd_client)
end
reset() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 13
def reset
  @registered_gauge_caches = {}
end

Private Class Methods

registered_gauge_caches() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 19
def registered_gauge_caches
  @registered_gauge_caches ||= {}
end

Public Instance Methods

report() click to toggle source

Reports all gauges that have been set in the cache To avoid “RuntimeError: can’t add a new key into hash during iteration” from occurring we are temporarily duplicating the cache to iterate and send the batch of metrics

# File lib/invoca/metrics/gauge_cache.rb, line 40
def report
  @statsd_client.batch do |statsd_batch|
    @cache.dup.each do |metric, value|
      statsd_batch.gauge(metric, value) if value
    end
  end
end
service_environment() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 48
def service_environment
  @service_environment ||= ENV['RAILS_ENV'].presence || ENV['SERVICE_ENV'].presence || 'development'
end
set(metric, value) click to toggle source

Atomic method for setting the value for a particular gauge

# File lib/invoca/metrics/gauge_cache.rb, line 33
def set(metric, value)
  @cache[metric] = value
end

Private Instance Methods

reporting_loop() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 66
def reporting_loop
  next_time = Time.now.to_i
  loop do
    next_time = (((next_time + GAUGE_REPORT_INTERVAL + 1) / GAUGE_REPORT_INTERVAL) * GAUGE_REPORT_INTERVAL) - 1
    report
    if (delay = next_time - Time.now.to_i) > 0
      sleep(delay)
    else
      warn("Window to report gauge may have been missed.") unless service_environment == 'test'
    end
  end
end
reporting_loop_with_rescue() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 60
def reporting_loop_with_rescue
  reporting_loop
rescue Exception => ex
  Invoca::Metrics::Client.logger.error("GaugeCache#reporting_loop_with_rescue rescued exception:\n#{ex.class}: #{ex.message}")
end
start_reporting_thread() click to toggle source
# File lib/invoca/metrics/gauge_cache.rb, line 54
def start_reporting_thread
  Thread.new do
    reporting_loop_with_rescue
  end
end