Class: RubyReactor::OpenTelemetry

Inherits:
Middleware show all
Defined in:
lib/ruby_reactor/open_telemetry.rb

Overview

Middleware implementing OpenTelemetry instrumentation for RubyReactor execution rubocop:disable Metrics/ClassLength

Direct Known Subclasses

Middleware::OpenTelemetry

Instance Attribute Summary

Attributes inherited from Middleware

#options

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ OpenTelemetry

Returns a new instance of OpenTelemetry.



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ruby_reactor/open_telemetry.rb', line 13

def initialize(**options)
  super
  @step_spans = {}
  @step_tokens = {}
  @retry_errors = {}
  @compensation_spans = {}
  @compensation_tokens = {}
  @undo_spans = {}
  @undo_tokens = {}
  @reactor_span = nil
  @reactor_token = nil
end

Instance Method Details

#on_before_async_enqueue(context) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/ruby_reactor/open_telemetry.rb', line 350

def on_before_async_enqueue(context)
  return unless defined?(::OpenTelemetry)

  # Inject the *current* context (the active step span at enqueue time) rather
  # than forcing the reactor span. This keeps the resumed/async execution
  # nested under the step that handed it off, so the step span (and the
  # reactor span above it) reflect the total execution time of the async work
  # in the trace waterfall instead of being flattened into a sibling.
  #
  # Re-inject on every handoff, including chained handoffs from an
  # already-resumed context (async step -> async retry -> ...), so each
  # subsequent job nests under the span that is active *now* rather than being
  # pinned to the first step that ever handed off. Only keep any previously
  # stored carrier when there is no valid span to inject, so we never overwrite
  # a good parent with an empty/invalid one.
  return unless ::OpenTelemetry::Trace.current_span.context.valid?

  carrier = {}
  ::OpenTelemetry.propagation.inject(carrier)
  context.private_data[:trace_context] = carrier unless carrier.empty?
rescue StandardError => e
  RubyReactor.configuration.logger.warn("Telemetry context injection failed: #{e.message}")
end

#on_complete_compensation(step_name, result, _context) ⇒ Object



258
259
260
261
262
263
264
265
266
267
# File 'lib/ruby_reactor/open_telemetry.rb', line 258

def on_complete_compensation(step_name, result, _context)
  token = @compensation_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token

  span = @compensation_spans.delete(step_name)
  return unless span

  map_compensation_result_status(span, result)
  span.finish
end

#on_complete_reactor(_reactor_name, result, context) ⇒ Object



54
55
56
57
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
# File 'lib/ruby_reactor/open_telemetry.rb', line 54

def on_complete_reactor(_reactor_name, result, context)
  ::OpenTelemetry::Context.detach(@reactor_token) if @reactor_token
  @reactor_token = nil

  span = @reactor_span
  @reactor_span = nil

  @step_spans.clear
  @step_tokens.clear
  @retry_errors.clear
  @compensation_spans.clear
  @compensation_tokens.clear
  @undo_spans.clear
  @undo_tokens.clear

  return unless span

  if result.is_a?(RubyReactor::RetryQueuedResult)
    # This execution attempt failed and was requeued for an async retry
    # (e.g. an async step or async map element). The reactor span therefore
    # represents one failed attempt; mark it ERROR (status does not
    # propagate to the parent, so a later successful attempt keeps the
    # overall trace healthy).
    map_reactor_retry_queued_status(span, result)
  else
    map_reactor_result_status(span, result, context)
  end
  span.finish
end

#on_complete_step(step_name, result, _context) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/ruby_reactor/open_telemetry.rb', line 141

def on_complete_step(step_name, result, _context)
  token = @step_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token

  retry_error = @retry_errors.delete(step_name)

  span = @step_spans.delete(step_name)
  return unless span

  if result.is_a?(RubyReactor::AsyncResult)
    # The step was handed off to a background worker; the run block did not
    # execute here. Rename the span so it is not confused with the real
    # execution span emitted later under the resumed reactor span.
    span.name = "step.#{step_name}.enqueue" if span.respond_to?(:name=)
    span.set_attribute("step.async", true)
    span.set_attribute("step.status", "handed_off")
    span.set_attribute("step.async_job_id", result.job_id.to_s) if result.respond_to?(:job_id) && result.job_id
    span.status = ::OpenTelemetry::Trace::Status.ok
  elsif result.is_a?(RubyReactor::RetryQueuedResult)
    # This attempt failed and was requeued for an async retry. The span
    # represents a single failed attempt, so it is marked as an error.
    # OTel span status does not propagate to the parent, so the reactor
    # (and the overall trace) stays healthy if a later retry succeeds.
    map_retry_queued_status(span, result, retry_error)
  else
    map_step_result_status(span, result)
  end
  span.finish
end

#on_complete_undo(step_name, result, _context) ⇒ Object



320
321
322
323
324
325
326
327
328
329
# File 'lib/ruby_reactor/open_telemetry.rb', line 320

def on_complete_undo(step_name, result, _context)
  token = @undo_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token

  span = @undo_spans.delete(step_name)
  return unless span

  map_undo_result_status(span, result)
  span.finish
end

#on_failed_compensation(step_name, error, _context) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/ruby_reactor/open_telemetry.rb', line 269

def on_failed_compensation(step_name, error, _context)
  token = @compensation_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token

  span = @compensation_spans.delete(step_name)
  return unless span

  span.set_attribute("compensation.status", "failed")
  if error.is_a?(Exception)
    span.status = ::OpenTelemetry::Trace::Status.error(error.message)
    span.record_exception(error)
    span.set_attribute("error.message", error.message)
    span.set_attribute("error.class", error.class.name)
  else
    map_compensation_result_status(span, error)
  end
  span.finish
end

#on_failed_reactor(_reactor_name, error, context) ⇒ Object



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
110
# File 'lib/ruby_reactor/open_telemetry.rb', line 84

def on_failed_reactor(_reactor_name, error, context)
  ::OpenTelemetry::Context.detach(@reactor_token) if @reactor_token
  @reactor_token = nil

  span = @reactor_span
  @reactor_span = nil

  @step_spans.clear
  @step_tokens.clear
  @retry_errors.clear
  @compensation_spans.clear
  @compensation_tokens.clear
  @undo_spans.clear
  @undo_tokens.clear

  return unless span

  if error.is_a?(Exception)
    span.status = ::OpenTelemetry::Trace::Status.error(error.message)
    span.record_exception(error)
  elsif error.is_a?(RubyReactor::RetryQueuedResult)
    map_reactor_retry_queued_status(span, error)
  else
    map_reactor_result_status(span, error, context)
  end
  span.finish
end

#on_failed_step(step_name, error, _context) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/ruby_reactor/open_telemetry.rb', line 171

def on_failed_step(step_name, error, _context)
  token = @step_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token
  @retry_errors.delete(step_name)

  span = @step_spans.delete(step_name)
  return unless span

  if error.is_a?(Exception)
    span.status = ::OpenTelemetry::Trace::Status.error(error.message)
    span.record_exception(error)
  else
    map_step_result_status(span, error)
  end
  span.finish
end

#on_failed_undo(step_name, error, _context) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/ruby_reactor/open_telemetry.rb', line 331

def on_failed_undo(step_name, error, _context)
  token = @undo_tokens.delete(step_name)
  ::OpenTelemetry::Context.detach(token) if token

  span = @undo_spans.delete(step_name)
  return unless span

  span.set_attribute("undo.status", "failed")
  if error.is_a?(Exception)
    span.status = ::OpenTelemetry::Trace::Status.error(error.message)
    span.record_exception(error)
    span.set_attribute("error.message", error.message)
    span.set_attribute("error.class", error.class.name)
  else
    map_undo_result_status(span, error)
  end
  span.finish
end

#on_lock_acquired(key, _context) ⇒ Object



374
375
376
377
378
379
380
# File 'lib/ruby_reactor/open_telemetry.rb', line 374

def on_lock_acquired(key, _context)
  span = @reactor_span
  return unless span

  span.set_attribute("reactor.lock.key", key.to_s)
  span.add_event("lock_acquired", attributes: { "lock.key" => key.to_s })
end

#on_lock_failed(key, error, _context) ⇒ Object



389
390
391
392
393
394
395
396
397
398
# File 'lib/ruby_reactor/open_telemetry.rb', line 389

def on_lock_failed(key, error, _context)
  span = @reactor_span
  return unless span

  span.add_event("lock_acquisition_failed", attributes: {
                   "lock.key" => key.to_s,
                   "error.message" => error.message,
                   "error.class" => error.class.name
                 })
end

#on_lock_released(key, _context) ⇒ Object



382
383
384
385
386
387
# File 'lib/ruby_reactor/open_telemetry.rb', line 382

def on_lock_released(key, _context)
  span = @reactor_span
  return unless span

  span.add_event("lock_released", attributes: { "lock.key" => key.to_s })
end

#on_retry_attempt(step_name, attempt, error, _context) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/ruby_reactor/open_telemetry.rb', line 188

def on_retry_attempt(step_name, attempt, error, _context)
  return unless defined?(::OpenTelemetry)

  # Remember the error that triggered this attempt so we can annotate the
  # span if the step is requeued for an async retry (RetryQueuedResult does
  # not carry the error itself).
  @retry_errors[step_name] = error

  span = @step_spans[step_name]
  return unless span

  span.add_event("retry_attempt", attributes: {
                   "attempt" => attempt.to_i,
                   "error.message" => error.respond_to?(:message) ? error.message : error.to_s,
                   "error.class" => error.is_a?(Exception) ? error.class.name : "RubyReactor::Failure"
                 })
end

#on_semaphore_acquired(key, limit, _context) ⇒ Object



400
401
402
403
404
405
406
407
408
# File 'lib/ruby_reactor/open_telemetry.rb', line 400

def on_semaphore_acquired(key, limit, _context)
  span = @reactor_span
  return unless span

  span.set_attribute("reactor.semaphore.key", key.to_s)
  span.set_attribute("reactor.semaphore.limit", limit.to_i)
  span.add_event("semaphore_acquired",
                 attributes: { "semaphore.key" => key.to_s, "semaphore.limit" => limit.to_i })
end

#on_semaphore_failed(key, limit, error, _context) ⇒ Object



417
418
419
420
421
422
423
424
425
426
427
# File 'lib/ruby_reactor/open_telemetry.rb', line 417

def on_semaphore_failed(key, limit, error, _context)
  span = @reactor_span
  return unless span

  span.add_event("semaphore_acquisition_failed", attributes: {
                   "semaphore.key" => key.to_s,
                   "semaphore.limit" => limit.to_i,
                   "error.message" => error.message,
                   "error.class" => error.class.name
                 })
end

#on_semaphore_released(key, _context) ⇒ Object



410
411
412
413
414
415
# File 'lib/ruby_reactor/open_telemetry.rb', line 410

def on_semaphore_released(key, _context)
  span = @reactor_span
  return unless span

  span.add_event("semaphore_released", attributes: { "semaphore.key" => key.to_s })
end

#on_start_compensation(step_name, error, arguments, context) ⇒ Object

rubocop:disable Metrics/MethodLength



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/ruby_reactor/open_telemetry.rb', line 206

def on_start_compensation(step_name, error, arguments, context) # rubocop:disable Metrics/MethodLength
  ensure_opentelemetry_loaded!

  # Finish step span if it is still open, as compensation happens after the step execution has failed
  if (step_span = @step_spans.delete(step_name))
    step_token = @step_tokens.delete(step_name)
    ::OpenTelemetry::Context.detach(step_token) if step_token

    if error.is_a?(Exception)
      step_span.status = ::OpenTelemetry::Trace::Status.error(error.message)
      step_span.record_exception(error)
    else
      map_step_result_status(step_span, error)
    end
    step_span.finish
  end

  tracer = ::OpenTelemetry.tracer_provider.tracer("ruby_reactor")

  redact_keys = if context.reactor_class.respond_to?(:inputs)
                  context.reactor_class.inputs.select do |_, c|
                    c[:redact]
                  end.keys
                else
                  []
                end
  attributes = { "step.name" => step_name.to_s }
  arguments.each do |k, v|
    val = redact_keys.include?(k.to_sym) ? "[REDACTED]" : safe_value(v)
    attributes["step.arguments.#{k}"] = val
  end

  if error.is_a?(Exception)
    attributes["compensation.trigger_error.class"] = error.class.name
    attributes["compensation.trigger_error.message"] = error.message
  else
    attributes["compensation.trigger_error.message"] = error.to_s
  end

  parent_context = if @reactor_span
                     ::OpenTelemetry::Trace.context_with_span(@reactor_span)
                   else
                     ::OpenTelemetry::Context.current
                   end

  span = tracer.start_span("compensate.#{step_name}", attributes: attributes, with_parent: parent_context)
  token = ::OpenTelemetry::Context.attach(::OpenTelemetry::Trace.context_with_span(span))

  @compensation_spans[step_name] = span
  @compensation_tokens[step_name] = token
end

#on_start_reactor(reactor_name, inputs, context) ⇒ Object



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/ruby_reactor/open_telemetry.rb', line 26

def on_start_reactor(reactor_name, inputs, context)
  ensure_opentelemetry_loaded!
  parent_ctx = extract_context(context)

  tracer = ::OpenTelemetry.tracer_provider.tracer("ruby_reactor")

  redact_keys = if context.reactor_class.respond_to?(:inputs)
                  context.reactor_class.inputs.select do |_, c|
                    c[:redact]
                  end.keys
                else
                  []
                end
  attributes = {
    "reactor.name" => reactor_name,
    "reactor.context_id" => context.context_id
  }
  inputs.each do |k, v|
    val = redact_keys.include?(k.to_sym) ? "[REDACTED]" : safe_value(v)
    attributes["reactor.inputs.#{k}"] = val
  end

  attributes["reactor.resumed"] = true if context.status.to_s != "pending"

  @reactor_span = tracer.start_span(reactor_name, attributes: attributes, with_parent: parent_ctx || ::OpenTelemetry::Context.current)
  @reactor_token = ::OpenTelemetry::Context.attach(::OpenTelemetry::Trace.context_with_span(@reactor_span))
end

#on_start_step(step_name, arguments, context) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ruby_reactor/open_telemetry.rb', line 112

def on_start_step(step_name, arguments, context)
  ensure_opentelemetry_loaded!
  tracer = ::OpenTelemetry.tracer_provider.tracer("ruby_reactor")

  redact_keys = if context.reactor_class.respond_to?(:inputs)
                  context.reactor_class.inputs.select do |_, c|
                    c[:redact]
                  end.keys
                else
                  []
                end
  attributes = { "step.name" => step_name.to_s }
  arguments.each do |k, v|
    val = redact_keys.include?(k.to_sym) ? "[REDACTED]" : safe_value(v)
    attributes["step.arguments.#{k}"] = val
  end

  # Nest under the current OpenTelemetry context rather than forcing the
  # reactor span as the parent. Steps run sequentially, so the current span
  # is the reactor span (or an enclosing step/element span for composed and
  # mapped reactors); honouring it keeps the trace hierarchy intact instead
  # of flattening every span directly under the reactor.
  span = tracer.start_span("step.#{step_name}", attributes: attributes)
  token = ::OpenTelemetry::Context.attach(::OpenTelemetry::Trace.context_with_span(span))

  @step_spans[step_name] = span
  @step_tokens[step_name] = token
end

#on_start_undo(step_name, step_result, arguments, context) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/ruby_reactor/open_telemetry.rb', line 288

def on_start_undo(step_name, step_result, arguments, context)
  ensure_opentelemetry_loaded!
  tracer = ::OpenTelemetry.tracer_provider.tracer("ruby_reactor")

  redact_keys = if context.reactor_class.respond_to?(:inputs)
                  context.reactor_class.inputs.select do |_, c|
                    c[:redact]
                  end.keys
                else
                  []
                end
  attributes = { "step.name" => step_name.to_s }
  arguments.each do |k, v|
    val = redact_keys.include?(k.to_sym) ? "[REDACTED]" : safe_value(v)
    attributes["step.arguments.#{k}"] = val
  end

  attributes["undo.original_result.value"] = safe_value(step_result.value) if step_result.respond_to?(:value)

  parent_context = if @reactor_span
                     ::OpenTelemetry::Trace.context_with_span(@reactor_span)
                   else
                     ::OpenTelemetry::Context.current
                   end

  span = tracer.start_span("undo.#{step_name}", attributes: attributes, with_parent: parent_context)
  token = ::OpenTelemetry::Context.attach(::OpenTelemetry::Trace.context_with_span(span))

  @undo_spans[step_name] = span
  @undo_tokens[step_name] = token
end