Class: PgCanary::Middleware

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

Overview

Rack middleware: collects the detections raised while the request runs (via the thread-local collector .collect appends to), collapses repeats of the same query within that request, and injects a footer panel into HTML responses.

Constant Summary collapse

COLLECTOR_KEY =
:pg_canary_request_detections

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



17
18
19
# File 'lib/pg_canary/middleware.rb', line 17

def initialize(app)
  @app = app
end

Class Method Details

.collect(detections) ⇒ Object



13
14
15
# File 'lib/pg_canary/middleware.rb', line 13

def self.collect(detections)
  Thread.current[COLLECTOR_KEY]&.concat(detections)
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pg_canary/middleware.rb', line 21

def call(env)
  return @app.call(env) unless active?

  detections = []
  previous = Thread.current[COLLECTOR_KEY]
  Thread.current[COLLECTOR_KEY] = detections
  status, headers, body = @app.call(env)
  detections = dedup(detections)
  return [status, headers, body] if detections.empty?

  inject(status, headers, body, detections)
ensure
  Thread.current[COLLECTOR_KEY] = previous
end