Module: DeadBro::WatchTracker

Defined in:
lib/dead_bro/watch_tracker.rb

Overview

Records user-defined timed blocks (DeadBro.watch) during an instrumented request or background job. Spans include wall duration, nesting depth, and SQL attributable to the block (delta from SqlSubscriber aggregates).

SQL attribution: each span diffs the global SQL counter at block entry vs exit. Nested blocks each get their own diff; a parent span's sql_count / sql_duration_ms therefore includes queries run inside nested child spans (inclusive totals, not exclusive). Compare inner spans when you need per-block SQL; do not sum parent and child counts.

Unlike DeadBro.analyze, watch spans are sent to the DeadBro backend as part of the normal request/job payload when watch_enabled is on.

Constant Summary collapse

THREAD_LOCAL_EVENTS_KEY =
:dead_bro_watch_events
THREAD_LOCAL_ACTIVE_STACK_KEY =
:dead_bro_watch_active_stack
MAX_DEPTH =

Deepest depth index still recorded — depths 0..MAX_DEPTH are kept, anything nested below that yields untracked.

10
MAX_SPANS_PER_REQUEST =
50
MAX_LABEL_LENGTH =
200
MAX_TAGS =
5
MAX_TAG_VALUE_LENGTH =
100

Class Method Summary collapse

Class Method Details

.append_completed_span(events, frame) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/dead_bro/watch_tracker.rb', line 151

def append_completed_span(events, frame)
  return unless events.is_a?(Array)

  slot = frame[:slot]
  return unless slot.is_a?(Integer) && slot < events.length

  elapsed_ms = begin
    ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - frame[:block_start]) * 1000.0).round(2)
  rescue StandardError
    0.0
  end

  sql_after = sql_metrics_snapshot
  sql_before = frame[:sql_before] || {count: 0, duration_ms: 0.0}
  sql_count = [(sql_after[:count] || 0).to_i - (sql_before[:count] || 0).to_i, 0].max
  sql_duration_ms = [
    (sql_after[:duration_ms] || 0.0).to_f - (sql_before[:duration_ms] || 0.0).to_f,
    0.0
  ].max.round(2)

  span = {
    label: frame[:label],
    duration_ms: elapsed_ms,
    start_offset_ms: frame[:start_offset_ms],
    depth: frame[:depth],
    sql_count: sql_count,
    sql_duration_ms: sql_duration_ms,
    error: frame[:error] == true
  }
  span[:exception_class] = frame[:exception_class] if frame[:exception_class]
  tags = frame[:tags]
  span[:tags] = tags if tags.is_a?(Hash) && tags.any?

  events[slot] = span
rescue StandardError
  # Never raise from instrumentation
end

.compute_start_offset_msObject



134
135
136
137
138
139
140
141
# File 'lib/dead_bro/watch_tracker.rb', line 134

def compute_start_offset_ms
  tracking_start = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
  return 0.0 unless tracking_start

  ((Time.now - tracking_start) * 1000.0).round(2)
rescue StandardError
  0.0
end

.enabled?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/dead_bro/watch_tracker.rb', line 30

def enabled?
  DeadBro.configuration.watch_enabled?
rescue StandardError
  false
end

.sanitize_label(label) ⇒ Object



111
112
113
114
115
116
117
# File 'lib/dead_bro/watch_tracker.rb', line 111

def sanitize_label(label)
  text = label.to_s.strip
  text = "block" if text.empty?
  (text.length > MAX_LABEL_LENGTH) ? text[0, MAX_LABEL_LENGTH] + "..." : text
rescue StandardError
  "block"
end

.sanitize_tags(tags) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/dead_bro/watch_tracker.rb', line 119

def sanitize_tags(tags)
  return {} unless tags.is_a?(Hash) && tags.any?

  tags.first(MAX_TAGS).each_with_object({}) do |(key, value), out|
    k = key.to_s.strip[0, 50]
    next if k.empty?

    v = value.to_s.strip
    v = v[0, MAX_TAG_VALUE_LENGTH] + "..." if v.length > MAX_TAG_VALUE_LENGTH
    out[k] = v
  end
rescue StandardError
  {}
end

.sql_metrics_snapshotObject



143
144
145
146
147
148
149
# File 'lib/dead_bro/watch_tracker.rb', line 143

def sql_metrics_snapshot
  return {count: 0, duration_ms: 0.0} unless defined?(DeadBro::SqlSubscriber)

  DeadBro::SqlSubscriber.current_sql_metrics
rescue StandardError
  {count: 0, duration_ms: 0.0}
end

.start_request_trackingObject



42
43
44
45
# File 'lib/dead_bro/watch_tracker.rb', line 42

def start_request_tracking
  Thread.current[THREAD_LOCAL_EVENTS_KEY] = []
  Thread.current[THREAD_LOCAL_ACTIVE_STACK_KEY] = []
end

.stop_request_trackingObject



47
48
49
50
51
52
53
54
55
56
# File 'lib/dead_bro/watch_tracker.rb', line 47

def stop_request_tracking
  events = Thread.current[THREAD_LOCAL_EVENTS_KEY]
  Thread.current[THREAD_LOCAL_EVENTS_KEY] = nil
  Thread.current[THREAD_LOCAL_ACTIVE_STACK_KEY] = nil
  # compact drops reserved slots whose block never completed — can't happen
  # for a lexical block, but keeps a nil out of the payload if it ever does.
  events.is_a?(Array) ? events.compact : []
rescue StandardError
  []
end

.tracking_active?Boolean

Returns:

  • (Boolean)


36
37
38
39
40
# File 'lib/dead_bro/watch_tracker.rb', line 36

def tracking_active?
  Thread.current[THREAD_LOCAL_EVENTS_KEY].is_a?(Array)
rescue StandardError
  false
end

.watch(label = nil, **tags) ⇒ Object



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
# File 'lib/dead_bro/watch_tracker.rb', line 58

def watch(label = nil, **tags)
  return yield unless block_given?
  return yield unless enabled?
  return yield unless tracking_active?

  events = Thread.current[THREAD_LOCAL_EVENTS_KEY]
  active_stack = Thread.current[THREAD_LOCAL_ACTIVE_STACK_KEY]
  return yield unless events.is_a?(Array) && active_stack.is_a?(Array)

  depth = active_stack.length
  return yield if depth > MAX_DEPTH
  return yield if events.length >= MAX_SPANS_PER_REQUEST

  sanitized_label = sanitize_label(label)
  sanitized_tags = sanitize_tags(tags)
  start_offset_ms = compute_start_offset_ms
  sql_before = sql_metrics_snapshot
  block_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  frame = {
    label: sanitized_label,
    depth: depth,
    tags: sanitized_tags,
    start_offset_ms: start_offset_ms,
    sql_before: sql_before,
    block_start: block_start,
    error: false,
    exception_class: nil
  }
  # Reserve the slot on entry so spans come out in start order. Blocks only
  # complete inner-first, so appending on completion would emit a nested span
  # ahead of its own parent; the placeholder keeps parents before children.
  # It also makes MAX_SPANS_PER_REQUEST count blocks still in flight.
  frame[:slot] = events.length
  events << nil
  active_stack << frame

  begin
    yield
  rescue StandardError => e
    frame[:error] = true
    # Anonymous classes (Class.new(StandardError)) have a nil name — leave the
    # field unset rather than shipping an empty string the dashboard would
    # render as a blank exception.
    class_name = e.class.name
    frame[:exception_class] = class_name[0, 200] if class_name
    raise
  ensure
    active_stack.pop if active_stack.last.equal?(frame)
    append_completed_span(events, frame)
  end
end