Module: OpenTrace::HttpTracker

Defined in:
lib/opentrace/http_tracker.rb

Instance Method Summary collapse

Instance Method Details

#request(req, body = nil, &block) ⇒ Object



7
8
9
10
11
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
# File 'lib/opentrace/http_tracker.rb', line 7

def request(req, body = nil, &block)
  # Guard 1: skip if disabled
  return super unless OpenTrace.enabled?

  # Guard 2: skip if this IS an OpenTrace dispatch call (prevent infinite recursion)
  return super if Fiber[:opentrace_http_tracking_disabled]

  collector = Fiber[:opentrace_collector]
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  response = super

  duration_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000
  host = address
  port_str = (port == 443 || port == 80) ? "" : ":#{port}"
  scheme = use_ssl? ? "https" : "http"
  url = "#{scheme}://#{host}#{port_str}#{req.path}"

  if collector
    collector.record_http(
      method: req.method,
      url: url,
      host: host,
      status: response.code.to_i,
      duration_ms: duration_ms
    )
  end

  response
rescue IOError, SystemCallError, OpenSSL::SSL::SSLError, Timeout::Error, Net::ProtocolError => e
  # Record the failed HTTP call, then re-raise
  duration_ms = start_time ? (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 : 0

  if collector
    collector.record_http(
      method: req&.method,
      url: "#{address}#{req&.path}",
      host: address,
      status: 0,
      duration_ms: duration_ms,
      error: e.class.name
    )
  end

  raise # ALWAYS re-raise — never swallow app errors
end