Class: Cybertrain::RequestId

Inherits:
Middleware
  • Object
show all
Defined in:
cybertrain/middleware/request_id.rb

Overview

Gives every request an id (spec section 12.2, Rails’ ActionDispatch::RequestId), outermost in the stack: a version 4 UUID (Crypto.uuid), or the request’s X-Request-Id when a trusted proxy sent it (Cybertrain::Request.trusted_peer?, the check Cybertrain::Request#client_ip makes) and it is well-formed (RequestId.accepted?), so the proxy’s log and the application’s share it; any other X-Request-Id is discarded, never altered.

The id is Cybertrain::Request#request_id, the response’s X-Request-Id (set after the stack returned, so a 403 from HostAuthorization, a redirect or an error page carries it too), and, through the thread’s Logger::Scope (RequestId.scope_for), a tag on every line logged while the request runs: the tags log_tags (Config#log_tags) names, in its order. The Scope found before is put back when the stack returns or raises; what the stack raises goes on up unchanged.

A RequestId that finds the request’s id already set (the development server’s front_app wraps a second one around the diagnostics page) leaves the id, the Scope and the header to the outer one.

What escapes the stack as a 500 (ClientError.status_for) is reported (ErrorReporter#report_unhandled) before it goes on up, while the request’s Scope is still the thread’s, so the event carries the id, the method and the masked path; where is the controller and action (RequestId.where_for). The innermost RequestId that sees it reports it, the one that found the id set included, and marks the Context (Context#error_reported); one further out does not report it again. So a request is reported once by construction, not by the reporter’s dedupe: in development the stack’s own RequestId reports, and what the diagnostics page outside it does not take (an exception outside StandardError) reaches front_app’s RequestId already reported. A 4xx is not reported, nor what a rescue_from handled (it never escapes). In production ErrorPages, inside this middleware, reports and answers the 500 itself.

Class Method Summary collapse

Class Method Details

.accepted?(value) ⇒ Boolean

Whether value may be a request id: 1 to 255 bytes, each an ASCII letter, digit or hyphen. A header sent twice arrives joined with ", " and is refused.

Parameters:

  • value (String)

Returns:

  • (Boolean)


106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'cybertrain/middleware/request_id.rb', line 106

def self.accepted?(value)
  s = value.to_s # a fresh local for the byte scan (spikes/NOTES.md rule 62)
  n = s.bytesize
  return false if n == 0 || n > MAX_BYTES

  i = 0
  while i < n
    return false unless RequestId.id_byte?(s.getbyte(i).to_i)

    i += 1
  end
  true
end