Class: OpenTrace::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



8
9
10
# File 'lib/opentrace/middleware.rb', line 8

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
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
# File 'lib/opentrace/middleware.rb', line 12

def call(env)
  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

  # Create RequestCollector for accumulate-and-summarize pattern
  if OpenTrace.enabled? && OpenTrace.config.request_summary
    collector = OpenTrace::RequestCollector.new(
      max_timeline: OpenTrace.config.timeline_max_events
    )
    Fiber[:opentrace_collector] = collector

    # Memory snapshot before request (opt-in)
    if OpenTrace.config.memory_tracking
      collector.memory_before = current_rss_mb
    end
  end

  @app.call(env)
ensure
  # 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

  Fiber[:opentrace_collector] = nil
  Fiber[:opentrace_cached_context] = nil
  Fiber[:opentrace_sql_count] = nil
  Fiber[:opentrace_sql_total_ms] = nil
  Fiber[:opentrace_trace_id] = nil
  Fiber[:opentrace_span_id] = nil
  Fiber[:opentrace_parent_span_id] = nil
  OpenTrace.current_request_id = nil
end