Class: OpenTrace::Middleware

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

Constant Summary collapse

FIBER_KEYS =

All Fiber-local keys managed by this middleware. Centralised so cleanup never misses one.

%i[
  opentrace_collector
  opentrace_cached_context
  opentrace_sql_count
  opentrace_sql_total_ms
  opentrace_trace_id
  opentrace_span_id
  opentrace_parent_span_id
  opentrace_transaction_name
  opentrace_breadcrumbs
  opentrace_session_id
  opentrace_pending_explains
  opentrace_buffer
  opentrace_buffer_allocation_bytes
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



27
28
29
# File 'lib/opentrace/middleware.rb', line 27

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/opentrace/middleware.rb', line 31

def call(env)
  # When OpenTrace is disabled, pass through with zero overhead
  return @app.call(env) unless OpenTrace.enabled?
  return @app.call(env) if ignored_path?(env["PATH_INFO"])

  # Sampling: skip ALL Fiber-local setup for unsampled requests.
  # Subscribers check Fiber-locals and return instantly when nil.
  unless OpenTrace.sampler.sample?(env)
    OpenTrace.send(:client).stats.increment(:sampled_out)
    return @app.call(env)
  end

  request_id = env["action_dispatch.request_id"] || env["HTTP_X_REQUEST_ID"]
  OpenTrace.current_request_id = request_id
  Fiber[:opentrace_sql_count] = 0
  Fiber[:opentrace_sql_total_ms] = 0.0

  # Extract or generate trace context
  if OpenTrace.config.trace_propagation
    trace_id, parent_span_id = extract_trace_context(env)
    span_id = TraceContext.generate_span_id

    Fiber[:opentrace_trace_id] = trace_id
    Fiber[:opentrace_span_id] = span_id
    Fiber[:opentrace_parent_span_id] = parent_span_id
  end

  # Session tracking (opt-in)
  if OpenTrace.config.session_tracking
    session_id = extract_session_id(env)
    Fiber[:opentrace_session_id] = session_id if session_id
  end

  # Create RequestCollector only when features that need it are enabled
  cfg = OpenTrace.config
  needs_collector = cfg.request_summary &&
    (cfg.view_tracking || cfg.cache_tracking || cfg.http_tracking ||
     cfg.timeline || cfg.memory_tracking)

  if needs_collector
    max_timeline = cfg.timeline ? cfg.timeline_max_events : 0
    collector = OpenTrace::RequestCollector.new(max_timeline: max_timeline)
    Fiber[:opentrace_collector] = collector

    if cfg.memory_tracking
      collector.memory_before = current_rss_mb
    end
  end

  # ── Deep capture: set up InstrumentationContext ──
  buffer = setup_buffer(env, cfg) if request_capture_enabled?(cfg)

  # ── Call the downstream app ──
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  had_error = false

  status, headers, body = @app.call(env)

  # ── Capture response data into the buffer ──
  capture_response(buffer, status, headers, body) if buffer

  [status, headers, body]
rescue StandardError => e
  had_error = true
  raise
ensure
  # Calculate duration
  duration_ms = if start_time
                  ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round(2)
                end

  # Memory snapshot after request (opt-in)
  collector = Fiber[:opentrace_collector]
  if collector && OpenTrace.config.memory_tracking && collector.memory_before
    collector.memory_after = current_rss_mb
  end

  # ── Deep capture: teardown and enqueue ──
  begin
    if Fiber[:opentrace_buffer]
      doc = InstrumentationContext.teardown(
        status: status,
        duration_ms: duration_ms,
        error: had_error
      )
      OpenTrace.client_enqueue_raw(doc) if doc
    end
  rescue StandardError
    # Never affect the host app
  end

  cleanup_fiber_locals
  OpenTrace.current_request_id = nil
end