module Admin class MetricsStore HISTORY_KEY = "admin:metrics:history" NET_RX_KEY = "admin:metrics:net_rx" NET_TX_KEY = "admin:metrics:net_tx" HISTORY_LIMIT = 90 class << self def redis @redis ||= Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0")) rescue Redis::CannotConnectError nil end def push_sample(sample) return unless redis redis.lpush(HISTORY_KEY, sample.to_json) redis.ltrim(HISTORY_KEY, 0, HISTORY_LIMIT - 1) end def history return [] unless redis redis.lrange(HISTORY_KEY, 0, HISTORY_LIMIT - 1).map { |row| JSON.parse(row) }.reverse end def net_totals return { rx: nil, tx: nil } unless redis { rx: redis.get(NET_RX_KEY)&.to_i, tx: redis.get(NET_TX_KEY)&.to_i } end def save_net_totals(rx:, tx:) return unless redis redis.set(NET_RX_KEY, rx) redis.set(NET_TX_KEY, tx) end end end end