Class: OpenTrace::CaptureRules

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

Constant Summary collapse

LEVELS =
%i[none minimal standard full].freeze
LEVEL_ORDER =

{ none: 0, minimal: 1, standard: 2, full: 3 }

LEVELS.each_with_index.to_h.freeze

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ CaptureRules

Returns a new instance of CaptureRules.



8
9
10
11
12
13
14
# File 'lib/opentrace/capture_rules.rb', line 8

def initialize(&block)
  @path_rules = []
  @error_rule = nil
  @slow_rule = nil

  block&.call(self)
end

Instance Method Details

#on_error(&block) ⇒ Object

Register a rule that fires when the request resulted in an error.



25
26
27
# File 'lib/opentrace/capture_rules.rb', line 25

def on_error(&block)
  @error_rule = block
end

#on_path(pattern, &block) ⇒ Object

Register a path-matching rule. Pattern supports:

** — matches any number of path segments (including zero)
*  — matches exactly one path segment


19
20
21
22
# File 'lib/opentrace/capture_rules.rb', line 19

def on_path(pattern, &block)
  regex = path_pattern_to_regex(pattern)
  @path_rules << { regex: regex, block: block }
end

#on_slow(threshold:, &block) ⇒ Object

Register a rule that fires when the request duration exceeds a threshold. threshold is in milliseconds.



31
32
33
# File 'lib/opentrace/capture_rules.rb', line 31

def on_slow(threshold:, &block)
  @slow_rule = { threshold: threshold, block: block }
end

#resolve(env, base_level: :standard, status: nil, duration_ms: nil, error: false) ⇒ Object

Evaluate all rules for a given request and return the final capture level.

env — Rack env hash (must contain “PATH_INFO”) base_level — fallback level when no path rule matches (default :standard) status — HTTP response status (not used directly, reserved) duration_ms — request duration in milliseconds (for on_slow) error — whether the request raised an error (for on_error)



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/opentrace/capture_rules.rb', line 42

def resolve(env, base_level: :standard, status: nil, duration_ms: nil, error: false)
  level = resolve_path(env) || base_level

  # Post-request upgrades: only go up, never down
  if error && @error_rule
    error_level = @error_rule.call
    level = max_level(level, error_level)
  end

  if duration_ms && @slow_rule && duration_ms > @slow_rule[:threshold]
    slow_level = @slow_rule[:block].call
    level = max_level(level, slow_level)
  end

  level
end

#resolve_domain(domain, resolved_level, overrides) ⇒ Object

Apply per-domain overrides. If the domain has an explicit override, use it. Otherwise return the resolved_level as-is.



61
62
63
64
# File 'lib/opentrace/capture_rules.rb', line 61

def resolve_domain(domain, resolved_level, overrides)
  override = overrides[domain]
  override.nil? ? resolved_level : override
end