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
58
59
60
61
62
63
# File 'lib/opentrace/middleware.rb', line 12

def call(env)
  # When OpenTrace is disabled, pass through with zero overhead
  return @app.call(env) unless OpenTrace.enabled?

  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 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

  @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