Class: ShieldPressTracker::HttpCollector

Inherits:
Object
  • Object
show all
Defined in:
lib/shieldpress_tracker/collectors.rb

Instance Method Summary collapse

Constructor Details

#initializeHttpCollector

Returns a new instance of HttpCollector.



16
17
18
# File 'lib/shieldpress_tracker/collectors.rb', line 16

def initialize
  @records, @started, @mutex = [], Process.clock_gettime(Process::CLOCK_MONOTONIC), Mutex.new
end

Instance Method Details

#flushObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/shieldpress_tracker/collectors.rb', line 24

def flush
  records = @mutex.synchronize { rows = @records; @records = []; rows }
  return nil if records.empty?
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC); elapsed = [now - @started, 0.001].max; @started = now
  durations, statuses, grouped = records.map(&:last), Hash.new(0), Hash.new { |h, k| h[k] = [] }
  records.each { |path, method, status, ms| statuses[status.to_s] += 1; grouped[[method, path]] << [status, ms] }
  top = grouped.map do |(method, path), rows|
    times = rows.map(&:last)
    { path: path, method: method, count: rows.length, avgMs: (times.sum / times.length).round,
      p95Ms: Helpers.percentile(times, 95), errorCount: rows.count { |r| r[0] >= 400 } }
  end.sort_by { |x| -x[:count] }.first(20)
  { totalRequests: records.length, totalErrors: records.count { |r| r[2] >= 500 }, avgResponseMs: (durations.sum / durations.length).round,
    p50ResponseMs: Helpers.percentile(durations, 50), p95ResponseMs: Helpers.percentile(durations, 95),
    p99ResponseMs: Helpers.percentile(durations, 99), maxResponseMs: durations.max, statusCodes: statuses,
    topPaths: top, requestsPerSecond: (records.length / elapsed).round(2) }
rescue StandardError
  nil
end

#record(path:, method:, status_code:, duration_ms:) ⇒ Object



19
20
21
22
23
# File 'lib/shieldpress_tracker/collectors.rb', line 19

def record(path:, method:, status_code:, duration_ms:)
  @mutex.synchronize { @records.shift(1000) if @records.length >= 10_000; @records << [path, method, status_code.to_i, duration_ms.to_f] }
rescue StandardError
  nil
end