Class: AllStak::Integrations::Rack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/allstak/integrations/rack.rb

Overview

Rack middleware that:

  1. Starts a fresh trace per request (or adopts X-AllStak-Trace-Id / traceparent)

  2. Captures inbound HTTP request telemetry

  3. Auto-captures unhandled exceptions with full request context, user, stack, and trace link

  4. Re-raises so the framework’s exception handler runs

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



13
14
15
# File 'lib/allstak/integrations/rack.rb', line 13

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/allstak/integrations/rack.rb', line 17

def call(env)
  return @app.call(env) unless AllStak.initialized?

  client = AllStak.client
  config = client.config

  start = now_ms
  started_at = Time.now.utc.iso8601(3)

  trace_id = trace_id_from_env(env)
  parent_span_id = parent_span_id_from_env(env)
  request_id = env["HTTP_X_REQUEST_ID"] || env["HTTP_X_ALLSTAK_REQUEST_ID"] || SecureRandom.hex(16)
  if trace_id && !trace_id.empty?
    client.tracing.set_trace_id(trace_id)
  else
    client.tracing.reset_trace
  end
  trace_id = client.tracing.current_trace_id
  span = client.tracing.start_span(
    "http.server",
    description: "#{env["REQUEST_METHOD"] || "GET"} #{env["PATH_INFO"] || "/"}",
    tags: {
      "http.method" => env["REQUEST_METHOD"] || "GET",
      "http.route" => env["PATH_INFO"] || "/"
    }
  )

  status = 0
  headers = {}
  body = nil
  captured = nil

  begin
    status, headers, body = @app.call(env)
  rescue => e
    captured = e
    status = 500 if status.to_i == 0
    raise
  ensure
    duration = now_ms - start

    # Request telemetry
    if config.capture_http_requests
      begin
        req_size = env["CONTENT_LENGTH"].to_i
        resp_size = headers && headers["Content-Length"].to_i
        user_id = extract_user_id(env)
        path = env["PATH_INFO"] || "/"

        client.http.record(
          direction: "inbound",
          method: env["REQUEST_METHOD"] || "GET",
          host: env["HTTP_HOST"] || "localhost",
          path: path,
          status_code: status.to_i,
          duration_ms: duration,
          request_size: req_size,
          response_size: resp_size || 0,
          trace_id: trace_id,
          request_id: request_id,
          span_id: span.span_id,
          parent_span_id: parent_span_id,
          user_id: user_id
        )
        span.set_tag("http.status_code", status.to_i.to_s)
        span.finish(status.to_i >= 500 || captured ? "error" : "ok")

        # Inbound-request breadcrumb so it lands on the trail of any
        # exception captured later in the same thread. Auto-gated.
        client.errors.add_breadcrumb(
          type: "http",
          message: "#{env["REQUEST_METHOD"] || "GET"} #{path} #{status.to_i}",
          level: (status.to_i >= 500 || captured) ? "error" : "info",
          data: {
            "direction" => "inbound",
            "method"    => env["REQUEST_METHOD"] || "GET",
            "host"      => env["HTTP_HOST"] || "localhost",
            "path"      => path,
            "status"    => status.to_i,
            "durationMs" => duration
          },
          auto: true
        )
      rescue => err
        # never raise into host
        config.debug && warn("[AllStak] rack request capture failed: #{err.message}")
      end
    end
    span.finish(status.to_i >= 500 || captured ? "error" : "ok") unless span.finished?

    # Exception capture
    if captured && config.capture_unhandled_exceptions
      begin
        user_ctx = config.capture_user_context ? build_user_context(env, config) : nil
        req_ctx = AllStak::Models::RequestContext.new(
          method: env["REQUEST_METHOD"],
          path: env["PATH_INFO"],
          host: env["HTTP_HOST"],
          status_code: status.to_i == 0 ? 500 : status.to_i,
          user_agent: env["HTTP_USER_AGENT"]
        )
        meta = {
          "http.method" => env["REQUEST_METHOD"],
          "http.path"   => env["PATH_INFO"],
          "http.host"   => env["HTTP_HOST"],
          "http.status" => status.to_i == 0 ? 500 : status.to_i,
          "traceId"     => trace_id,
          "requestId"   => request_id
        }
        client.errors.capture_exception(
          captured,
          user: user_ctx,
          request_context: req_ctx,
          trace_id: trace_id,
          metadata: meta
        )
      rescue => err
        config.debug && warn("[AllStak] rack exception capture failed: #{err.message}")
      end
    end

    # Best-effort response headers for downstream trace linkage.
    AllStak::Propagation.apply_headers(
      headers,
      trace_id: trace_id,
      request_id: request_id,
      span_id: span.span_id,
      sampled: client.tracing.current_trace_sampled?
    ) if headers && !captured
  end

  [status, headers, body]
end