Class: AndOne::Middleware

Inherits:
Object
  • Object
show all
Includes:
ScanHelper
Defined in:
lib/and_one/middleware.rb

Overview

Rack middleware that wraps each request in an N+1 scan. Designed to NOT interfere with error propagation — if the app raises, we cleanly stop scanning without adding to or corrupting the original backtrace.

When AndOne.dev_toast is enabled (default in development), detected N+1s are injected as a toast notification into HTML responses with a link to the DevUI dashboard.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



15
16
17
# File 'lib/and_one/middleware.rb', line 15

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/and_one/middleware.rb', line 19

def call(env)
  return @app.call(env) if !AndOne.enabled? || AndOne.scanning?

  begin
    AndOne.scan
    status, headers, body = @app.call(env)
    detections = AndOne.finish

    if AndOne.dev_toast && detections&.any? && html_response?(headers) && status == 200
      body = inject_toast(body, detections)
      # Recalculate Content-Length since we modified the body
      headers.delete("content-length")
      headers.delete("Content-Length")
    end

    [status, headers, body]
  rescue Exception # rubocop:disable Lint/RescueException
    and_one_quietly_stop
    raise
  end
end