Class: Lens::Rails::MetricsExporter

Inherits:
Object
  • Object
show all
Defined in:
lib/lens/rails/metrics_exporter.rb

Overview

Rack middleware that tracks request counts and durations, flushing aggregated metrics to POST /v1/metrics every 30s via a persistent HTTPS connection.

Constant Summary collapse

RESERVOIR_SIZE =
1024
FLUSH_INTERVAL =
30

Instance Method Summary collapse

Constructor Details

#initialize(app, url:, token:, service_name:, open_timeout: 2, read_timeout: 2) ⇒ MetricsExporter

Returns a new instance of MetricsExporter.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/lens/rails/metrics_exporter.rb', line 16

def initialize(app, url:, token:, service_name:,
  open_timeout: 2,
  read_timeout: 2)
  @app = app
  @token = token
  @service_name = service_name
  @uri = URI("#{url}/v1/metrics")
  @open_timeout = open_timeout
  @read_timeout = read_timeout
  @mutex = Mutex.new
  @http = nil
  reset_window
  start_flush_thread
  Lens::Rails.register_flushable(self)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/lens/rails/metrics_exporter.rb', line 32

def call(env)
  Thread.current[:lens_request_id] = env["action_dispatch.request_id"]
  wall_start = Time.now
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  status, headers, body = @app.call(env)
  duration = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000.0
  queue_time = parse_queue_time(env, wall_start)

  @mutex.synchronize do
    @request_count += 1
    @error_count += 1 if status >= 500
    @duration_sum += duration
    @duration_min = duration if @duration_min.nil? || duration < @duration_min
    @duration_max = duration if @duration_max.nil? || duration > @duration_max
    if @samples.size < RESERVOIR_SIZE
      @samples << duration
    else
      idx = rand(@request_count)
      @samples[idx] = duration if idx < RESERVOIR_SIZE
    end
    if queue_time
      @queue_samples << queue_time
      @queue_sum += queue_time
    end
  end

  [status, headers, body]
ensure
  Thread.current[:lens_request_id] = nil
end

#restart_flush_threadObject



69
70
71
72
73
74
75
76
77
# File 'lib/lens/rails/metrics_exporter.rb', line 69

def restart_flush_thread
  begin
    @flush_thread&.kill
  rescue
    nil
  end
  close_http
  start_flush_thread
end

#shutdown(timeout:) ⇒ Object



63
64
65
66
67
# File 'lib/lens/rails/metrics_exporter.rb', line 63

def shutdown(timeout:)
  @flush_thread&.kill
  Thread.new { flush }.join(timeout)
rescue
end