koderift-rails 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,15 +2,70 @@
2
2
 
3
3
  require 'time'
4
4
  require 'active_support/core_ext/string/filters'
5
+ require 'koderift/rails/frame_stack'
6
+ require 'koderift/rails/trace_context'
5
7
 
6
8
  module Koderift
7
9
  module Rails
8
10
  module Instrumentation
11
+ # One unit of work's collections. The frame is also the owner token the
12
+ # subscription callbacks check: ActiveSupport::Notifications subscribers
13
+ # are process-wide, so without that check every unit in flight recorded
14
+ # every other thread's SQL, partials and searches as its own.
15
+ class CaptureFrame
16
+ include FrameStack::Member
17
+
18
+ attr_reader :config, :partials, :queries, :search_queries, :breadcrumbs,
19
+ :custom_spans, :external_calls, :started_at_ms
20
+
21
+ def initialize(config:, started_at_ms:, restore_outside:)
22
+ @config = config
23
+ @started_at_ms = started_at_ms
24
+ @restore_outside = restore_outside
25
+ @partials = []
26
+ @queries = []
27
+ @search_queries = []
28
+ @breadcrumbs = []
29
+ @custom_spans = []
30
+ @external_calls = []
31
+ end
32
+
33
+ # Whole milliseconds from the unit's start to a CLOCK_MONOTONIC time in
34
+ # float milliseconds. Nil for a time outside the unit, so a clock
35
+ # mix-up leaves start_ms out rather than emitting a wrong value.
36
+ def offset_ms(mono_ms)
37
+ return nil unless mono_ms.is_a?(Numeric)
38
+
39
+ offset = mono_ms - @started_at_ms
40
+ return nil if offset < -1.0 || mono_ms > TraceContext.now_ms + 1.0
41
+
42
+ offset.negative? ? 0 : offset.round
43
+ rescue StandardError
44
+ nil
45
+ end
46
+ end
47
+
48
+ # Published for the same reason external_calls always was: code that runs
49
+ # somewhere else entirely -- the Net::HTTP patch, Koderift.add_breadcrumb,
50
+ # Koderift.with_child_span -- has no other way to find the collection
51
+ # belonging to the unit of work currently in flight on this thread.
52
+ CAPTURES = FrameStack.new(
53
+ :koderift_capture_frames,
54
+ %i[koderift_breadcrumbs koderift_custom_spans koderift_external_calls koderift_external_config]
55
+ ) do |frame|
56
+ [frame.breadcrumbs, frame.custom_spans, frame.external_calls, frame.config]
57
+ end
58
+
59
+ # A start time this many times larger than the monotonic clock in seconds
60
+ # is in milliseconds. Rails 7.1.0-7.1.3 replays load_async events with
61
+ # millisecond times where seconds are expected.
62
+ MILLISECOND_START_FACTOR = 100
63
+
9
64
  # Subscribes to Rails notifications during a request to capture
10
65
  # partial render times, SQL query times, and breadcrumbs.
11
66
  # Returns a hash of captured data to be merged into the log payload.
12
- def self.capture
13
- state = start_capture
67
+ def self.capture(restore_outside: false, started_at_ms: nil)
68
+ state = start_capture(restore_outside: restore_outside, started_at_ms: started_at_ms)
14
69
  begin
15
70
  yield
16
71
  ensure
@@ -24,90 +79,56 @@ module Koderift
24
79
  # implementation. Tracing::Transaction is that caller: it has to be
25
80
  # started and finished by two separate calls to mirror Sentry's
26
81
  # start_transaction / finish, which a block-shaped API cannot express.
27
- def self.start_capture
28
- config = Koderift::Rails.configuration
29
- partials = []
30
- queries = []
31
- search_queries = []
32
- breadcrumbs = []
33
- custom_spans = []
34
- external_calls = []
35
-
36
- partial_sub = ActiveSupport::Notifications.subscribe('render_partial.action_view') do |*args|
37
- event = ActiveSupport::Notifications::Event.new(*args)
38
- payload = event.payload
39
- duration = (payload[:duration] || event.duration).round
40
- identifier = payload[:identifier].to_s
41
- .sub(rails_root_prefix, '')
42
- .sub(%r{\A/app/views/}, '')
43
-
44
- partials << { partial: identifier, duration_ms: duration }
45
- breadcrumbs << {
46
- type: 'render',
47
- message: identifier,
48
- duration_ms: duration,
49
- timestamp: Time.now.utc.iso8601
50
- }
51
- end
52
-
53
- query_sub = ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
54
- event = ActiveSupport::Notifications::Event.new(*args)
55
- payload = event.payload
56
- next if payload[:name].to_s.match?(/\A(CACHE|SCHEMA)/)
57
-
58
- duration = (payload[:duration] || event.duration).round
59
- sql = payload[:sql].to_s.squish.truncate(300)
60
-
61
- queries << { sql: sql, duration_ms: duration }
62
- breadcrumbs << {
63
- type: 'sql',
64
- message: sql,
65
- duration_ms: duration,
66
- timestamp: Time.now.utc.iso8601
67
- }
82
+ #
83
+ # restore_outside: when this is the outermost frame, put back what the
84
+ # thread held before instead of clearing it (transactions). Requests and
85
+ # jobs clear.
86
+ #
87
+ # monotonic_subscribe, not subscribe: the start time a subscriber is handed
88
+ # is then CLOCK_MONOTONIC seconds on every supported Rails. Event#time is
89
+ # not used for start_ms because it changed units inside 7.1 (milliseconds
90
+ # up to 7.1.3, seconds from 7.1.4).
91
+ def self.start_capture(restore_outside: false, started_at_ms: nil)
92
+ config = Koderift::Rails.configuration
93
+ frame = CaptureFrame.new(
94
+ config: config,
95
+ started_at_ms: started_at_ms || TraceContext.now_ms,
96
+ restore_outside: restore_outside
97
+ )
98
+
99
+ partial_sub = ActiveSupport::Notifications.monotonic_subscribe('render_partial.action_view') do |*args|
100
+ record_partial(frame, args) if current_frame.equal?(frame)
101
+ end
102
+
103
+ query_sub = ActiveSupport::Notifications.monotonic_subscribe('sql.active_record') do |*args|
104
+ record_query(frame, args) if current_frame.equal?(frame)
68
105
  end
69
106
 
70
107
  # Single-model search: fired by Model.search(...)
71
108
  # payload: { name: "Admin10 Search", query: {...} }
72
- search_sub = ActiveSupport::Notifications.subscribe('search.searchkick') do |*args|
73
- event = ActiveSupport::Notifications::Event.new(*args)
74
- payload = event.payload
75
- duration = (payload[:duration] || event.duration).round
76
-
77
- index = payload[:name].to_s.sub(/\s*Search\z/i, '').strip
78
- index = 'unknown' if index.blank?
79
-
80
- search_queries << { index: index, duration_ms: duration }
109
+ search_sub = ActiveSupport::Notifications.monotonic_subscribe('search.searchkick') do |*args|
110
+ record_search(frame, args) if current_frame.equal?(frame)
81
111
  end
82
112
 
83
113
  # Multi search: fired by Searchkick.multi_search([...])
84
114
  # payload: { name: "Multi Search", body: "..." }
85
115
  # Duration covers the entire batch — record as a single entry.
86
- multi_search_sub = ActiveSupport::Notifications.subscribe('multi_search.searchkick') do |*args|
87
- event = ActiveSupport::Notifications::Event.new(*args)
88
- duration = event.duration.round
89
-
90
- search_queries << { index: 'multi_search', duration_ms: duration }
116
+ multi_search_sub = ActiveSupport::Notifications.monotonic_subscribe('multi_search.searchkick') do |*args|
117
+ record_multi_search(frame, args) if current_frame.equal?(frame)
91
118
  end
92
119
 
93
- # Published for the same reason external_calls is: code that runs
94
- # somewhere else entirely — the Net::HTTP patch, Koderift.add_breadcrumb,
95
- # Koderift.with_child_span — has no other way to find the collection
96
- # belonging to the unit of work currently in flight on this thread.
97
- Thread.current[:koderift_breadcrumbs] = breadcrumbs
98
- Thread.current[:koderift_custom_spans] = custom_spans
99
- Thread.current[:koderift_external_calls] = external_calls
100
- Thread.current[:koderift_external_config] = config
120
+ CAPTURES.push(frame)
101
121
 
102
122
  {
103
123
  config: config,
104
- partials: partials,
105
- queries: queries,
106
- search_queries: search_queries,
107
- breadcrumbs: breadcrumbs,
108
- custom_spans: custom_spans,
109
- external_calls: external_calls,
110
- subscriptions: [partial_sub, query_sub, search_sub, multi_search_sub]
124
+ partials: frame.partials,
125
+ queries: frame.queries,
126
+ search_queries: frame.search_queries,
127
+ breadcrumbs: frame.breadcrumbs,
128
+ custom_spans: frame.custom_spans,
129
+ external_calls: frame.external_calls,
130
+ subscriptions: [partial_sub, query_sub, search_sub, multi_search_sub],
131
+ frame: frame
111
132
  }
112
133
  end
113
134
 
@@ -115,46 +136,44 @@ module Koderift
115
136
  state[:subscriptions].each do |sub|
116
137
  ActiveSupport::Notifications.unsubscribe(sub)
117
138
  end
118
- Thread.current[:koderift_breadcrumbs] = nil
119
- Thread.current[:koderift_custom_spans] = nil
120
- Thread.current[:koderift_external_calls] = nil
121
- Thread.current[:koderift_external_config] = nil
122
139
  state
140
+ ensure
141
+ CAPTURES.pop(state[:frame]) if state.is_a?(Hash) && state[:frame]
123
142
  end
124
143
 
125
144
  def self.build_result(state)
126
145
  spans = []
127
146
 
128
147
  state[:partials].each_with_index do |p, i|
129
- spans << { type: 'partial', name: p[:partial], duration_ms: p[:duration_ms], sequence: i }
148
+ spans << with_span_fields({ type: 'partial', name: p[:partial], duration_ms: p[:duration_ms], sequence: i }, p)
130
149
  end
131
150
 
132
151
  state[:queries].each_with_index do |q, i|
133
- spans << { type: 'sql', name: q[:sql], duration_ms: q[:duration_ms], sequence: i }
152
+ spans << with_span_fields({ type: 'sql', name: q[:sql], duration_ms: q[:duration_ms], sequence: i }, q)
134
153
  end
135
154
 
136
155
  state[:search_queries].each_with_index do |s, i|
137
- spans << { type: 'search', name: s[:index], duration_ms: s[:duration_ms], sequence: i }
156
+ spans << with_span_fields({ type: 'search', name: s[:index], duration_ms: s[:duration_ms], sequence: i }, s)
138
157
  end
139
158
 
140
159
  state[:external_calls].each_with_index do |c, i|
141
- spans << {
160
+ spans << with_span_fields({
142
161
  type: 'http',
143
162
  name: "#{c[:host]}#{c[:endpoint]}",
144
163
  duration_ms: c[:duration_ms],
145
164
  detail: { method: c[:method], status: c[:status], trace_id: c[:trace_id] }.compact.to_json,
146
165
  sequence: i
147
- }
166
+ }, c)
148
167
  end
149
168
 
150
169
  state[:custom_spans].each_with_index do |c, i|
151
- spans << {
170
+ spans << with_span_fields({
152
171
  type: 'custom',
153
172
  name: c[:name],
154
173
  duration_ms: c[:duration_ms],
155
174
  detail: c[:detail],
156
175
  sequence: i
157
- }.compact
176
+ }.compact, c)
158
177
  end
159
178
 
160
179
  {
@@ -166,6 +185,136 @@ module Koderift
166
185
  }
167
186
  end
168
187
 
188
+ def self.current_frame
189
+ CAPTURES.top
190
+ end
191
+
192
+ # Whether that capture is still running on this thread.
193
+ def self.capturing?(frame)
194
+ CAPTURES.include?(frame)
195
+ end
196
+
197
+ def self.clear_captures!
198
+ CAPTURES.clear!
199
+ end
200
+
201
+ # The trace keys every span carries, appended after the existing ones.
202
+ # parent_span_id is left out when the parent is the line's own root span,
203
+ # which is most spans: a missing parent means the root. A span recorded
204
+ # without an ID (a hash pushed straight onto a collection) gets one here,
205
+ # so every emitted span has a span_id.
206
+ def self.with_span_fields(span, entry)
207
+ span[:span_id] = entry[:span_id] || TraceContext.new_span_id
208
+ span[:parent_span_id] = entry[:parent_span_id] if entry[:parent_span_id]
209
+ span[:start_ms] = entry[:start_ms] if entry[:start_ms]
210
+ span
211
+ rescue StandardError
212
+ span
213
+ end
214
+
215
+ # Trace keys for an entry recorded now: a new span ID, the enclosing
216
+ # with_child_span (if any) as parent, and the start offset.
217
+ def self.span_fields(start_ms, span_id: nil)
218
+ fields = { span_id: span_id || TraceContext.new_span_id }
219
+ parent = TraceContext::Current.enclosing_span_id
220
+ fields[:parent_span_id] = parent if parent
221
+ fields[:start_ms] = start_ms if start_ms
222
+ fields
223
+ rescue StandardError
224
+ {}
225
+ end
226
+
227
+ # The callbacks below run inside the instrumented code's own call, and
228
+ # ActiveSupport re-raises a subscriber's exception there (7.1+), so a
229
+ # bug here would fail the host app's SQL query or render. Each one
230
+ # swallows its own errors.
231
+ def self.record_partial(frame, args)
232
+ event = ActiveSupport::Notifications::Event.new(*args)
233
+ payload = event.payload
234
+ timing = event_timing(frame, args, event)
235
+ duration = (payload[:duration] || timing[:duration]).round
236
+ identifier = payload[:identifier].to_s
237
+ .sub(rails_root_prefix, '')
238
+ .sub(%r{\A/app/views/}, '')
239
+
240
+ frame.partials << { partial: identifier, duration_ms: duration }.merge(span_fields(timing[:start_ms]))
241
+ frame.breadcrumbs << {
242
+ type: 'render',
243
+ message: identifier,
244
+ duration_ms: duration,
245
+ timestamp: Time.now.utc.iso8601
246
+ }
247
+ rescue StandardError
248
+ nil
249
+ end
250
+
251
+ def self.record_query(frame, args)
252
+ event = ActiveSupport::Notifications::Event.new(*args)
253
+ payload = event.payload
254
+ return if payload[:name].to_s.match?(/\A(CACHE|SCHEMA)/)
255
+
256
+ timing = event_timing(frame, args, event)
257
+ duration = (payload[:duration] || timing[:duration]).round
258
+ sql = payload[:sql].to_s.squish.truncate(300)
259
+
260
+ frame.queries << { sql: sql, duration_ms: duration }.merge(span_fields(timing[:start_ms]))
261
+ frame.breadcrumbs << {
262
+ type: 'sql',
263
+ message: sql,
264
+ duration_ms: duration,
265
+ timestamp: Time.now.utc.iso8601
266
+ }
267
+ rescue StandardError
268
+ nil
269
+ end
270
+
271
+ def self.record_search(frame, args)
272
+ event = ActiveSupport::Notifications::Event.new(*args)
273
+ payload = event.payload
274
+ timing = event_timing(frame, args, event)
275
+ duration = (payload[:duration] || timing[:duration]).round
276
+
277
+ index = payload[:name].to_s.sub(/\s*Search\z/i, '').strip
278
+ index = 'unknown' if index.blank?
279
+
280
+ frame.search_queries << { index: index, duration_ms: duration }.merge(span_fields(timing[:start_ms]))
281
+ rescue StandardError
282
+ nil
283
+ end
284
+
285
+ def self.record_multi_search(frame, args)
286
+ event = ActiveSupport::Notifications::Event.new(*args)
287
+ timing = event_timing(frame, args, event)
288
+ duration = timing[:duration].round
289
+
290
+ frame.search_queries << { index: 'multi_search', duration_ms: duration }.merge(span_fields(timing[:start_ms]))
291
+ rescue StandardError
292
+ nil
293
+ end
294
+
295
+ # The event's duration and its start offset, from the raw start argument
296
+ # (CLOCK_MONOTONIC seconds under monotonic_subscribe). On Rails
297
+ # 7.1.0-7.1.3 a replayed load_async event arrives in milliseconds, which
298
+ # also inflates its duration a thousandfold; both are corrected, but only
299
+ # when the corrected start actually falls inside this unit.
300
+ def self.event_timing(frame, args, event)
301
+ duration = event.duration
302
+ start = args[1]
303
+ return { duration: duration, start_ms: nil } unless start.is_a?(Numeric)
304
+
305
+ start = start.to_f
306
+ if start > Process.clock_gettime(Process::CLOCK_MONOTONIC) * MILLISECOND_START_FACTOR
307
+ offset = frame.offset_ms(start)
308
+ return { duration: duration, start_ms: nil } unless offset
309
+
310
+ return { duration: duration && duration / 1000.0, start_ms: offset }
311
+ end
312
+
313
+ { duration: duration, start_ms: frame.offset_ms(start * 1000.0) }
314
+ rescue StandardError
315
+ { duration: event.duration, start_ms: nil }
316
+ end
317
+
169
318
  def self.rails_root_prefix
170
319
  defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root ? ::Rails.root.to_s : ''
171
320
  end
@@ -173,7 +322,8 @@ module Koderift
173
322
 
174
323
  # Installed once when the gem loads (see the prepend at the bottom of this
175
324
  # file). Writes to the thread-local external_calls array set by
176
- # Instrumentation.capture; outside of a capture block it is a pass-through.
325
+ # Instrumentation.capture; outside of a capture block it is a pass-through
326
+ # that still propagates the trace.
177
327
  #
178
328
  # CONTRACT: exactly one entry per LOGICAL outbound call. Net::HTTP#request
179
329
  # re-enters itself whenever it is called on a session that is not started:
@@ -188,29 +338,38 @@ module Koderift
188
338
  # `Connection: close` and start's ensure closes the socket, so an affected
189
339
  # call site double-counts on EVERY call, not intermittently.
190
340
  module NetHttpPatch
341
+ OWN_TRACEPARENT = :@koderift_traceparent
342
+ LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '[::1]'].freeze
343
+
191
344
  def request(req, *args, &block)
345
+ # The stdlib recursion re-invokes with the SAME req object, so request
346
+ # identity separates "my own re-entry" from a genuinely different call
347
+ # issued while this one is in flight. The outer frame has already set
348
+ # the headers and will record the call. This check runs whether or not
349
+ # a capture is active, so the inner frame never mints a second span ID
350
+ # for the same call. Do NOT use `started?` (it keeps the inner frame,
351
+ # which cannot see connection setup, and the spec stand-ins do not all
352
+ # define it) and do NOT use an object ivar (one Net::HTTP shared across
353
+ # threads would silently lose most of its spans).
354
+ in_flight = (Thread.current[:koderift_http_in_flight] ||= [])
355
+ return super(req, *args, &block) if in_flight.any? { |r| r.equal?(req) }
356
+
192
357
  calls = Thread.current[:koderift_external_calls]
193
358
  config = Thread.current[:koderift_external_config]
194
359
  trace_id = Thread.current[:koderift_trace_id]
195
360
 
196
361
  req['X-Koderift-Trace-ID'] = trace_id if trace_id
197
362
 
198
- # Nothing below this line may run before the pass-through return: the
199
- # spec stand-in defines only #request, and the header injection must
200
- # still happen when instrumentation is not capturing.
201
- return super(req, *args, &block) unless calls && config
202
-
203
- # The stdlib recursion re-invokes with the SAME req object, so request
204
- # identity separates "my own re-entry" from a genuinely different call
205
- # issued while this one is in flight. Do NOT use `started?` (it keeps
206
- # the inner frame, which cannot see connection setup, and the stand-in
207
- # does not define it) and do NOT use an object ivar (one Net::HTTP
208
- # shared across threads would silently lose most of its spans).
209
- in_flight = (Thread.current[:koderift_http_in_flight] ||= [])
210
- return super(req, *args, &block) if in_flight.any? { |r| r.equal?(req) }
363
+ # Whether this call will be recorded is known before it is made: the
364
+ # host is fixed at Net::HTTP.new and the ignore list is configuration.
365
+ # `address` is only read while capturing; the pass-through stand-in in
366
+ # the specs does not define it.
367
+ host = calls && config ? NetHttpPatch.host_of(self) : nil
368
+ record = host ? !NetHttpPatch.ignored_host?(host, config) : false
369
+ span_id = NetHttpPatch.propagate(req, trace_id, record)
211
370
 
212
371
  in_flight << req
213
- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
372
+ start_ms = TraceContext.now_ms
214
373
  begin
215
374
  response = super(req, *args, &block)
216
375
  ensure
@@ -220,24 +379,83 @@ module Koderift
220
379
  # without it one failure would silence every later call on this thread.
221
380
  in_flight.pop
222
381
  end
223
- duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
382
+ return response unless record
383
+
384
+ duration = (TraceContext.now_ms - start_ms).round
385
+ raw_path = req.path.to_s.split('?').first.to_s
386
+ segments = raw_path.split('/').reject(&:empty?).first(2)
387
+ endpoint = segments.empty? ? '/' : '/' + segments.join('/')
224
388
 
225
- host = address.to_s
226
- ignored = ['127.0.0.1', 'localhost', '[::1]'].include?(host) ||
227
- config.external_call_ignore_hosts.any? { |h| host.include?(h) }
389
+ calls << {
390
+ host: host, endpoint: endpoint, method: req.method.to_s.upcase,
391
+ status: response.code.to_i, duration_ms: duration, trace_id: trace_id
392
+ }.merge(NetHttpPatch.span_fields(span_id, start_ms))
228
393
 
229
- unless ignored
230
- raw_path = req.path.to_s.split('?').first.to_s
231
- segments = raw_path.split('/').reject(&:empty?).first(2)
232
- endpoint = segments.empty? ? '/' : '/' + segments.join('/')
394
+ response
395
+ end
233
396
 
234
- calls << {
235
- host: host, endpoint: endpoint, method: req.method.to_s.upcase,
236
- status: response.code.to_i, duration_ms: duration, trace_id: trace_id
237
- }
397
+ def self.host_of(http)
398
+ http.address.to_s
399
+ rescue StandardError
400
+ nil
401
+ end
402
+
403
+ def self.ignored_host?(host, config)
404
+ LOOPBACK_HOSTS.include?(host) ||
405
+ config.external_call_ignore_hosts.any? { |h| host.include?(h) }
406
+ rescue StandardError
407
+ false
408
+ end
409
+
410
+ # Sets the outbound trace headers and returns the HTTP span's ID when the
411
+ # call will be recorded (nil otherwise).
412
+ #
413
+ # X-Koderift-Traceparent is the gem's own copy of the context, always
414
+ # written: APM instrumentation (OpenTelemetry, Datadog, New Relic)
415
+ # rewrites `traceparent` but never touches it, so a Koderift app
416
+ # downstream can still nest under this exact span.
417
+ #
418
+ # `traceparent` itself is written only if absent, or if it is the value
419
+ # this patch wrote on this same request object earlier (a request
420
+ # reused for a retry). One set by anyone else is never overwritten.
421
+ #
422
+ # The parent ID sent is the HTTP span's own ID when the span will be
423
+ # recorded, else the span open around the call, so a downstream line
424
+ # points at a span that exists. A call that raises records nothing, so
425
+ # its downstream may name a parent no span carries.
426
+ def self.propagate(req, trace_id, record)
427
+ return nil unless TraceContext.valid_trace_id?(trace_id)
428
+
429
+ current = TraceContext::Current.current_span_id
430
+ span_id = if record || current.nil?
431
+ TraceContext.new_span_id
432
+ else
433
+ current
434
+ end
435
+ header = TraceContext::Current.traceparent(span_id)
436
+ return nil unless header
437
+
438
+ req[TraceContext::KODERIFT_TRACEPARENT] = header
439
+
440
+ existing = req['traceparent']
441
+ if existing.nil? || existing == req.instance_variable_get(OWN_TRACEPARENT)
442
+ req['traceparent'] = header
443
+ req.instance_variable_set(OWN_TRACEPARENT, header)
444
+
445
+ tracestate = TraceContext::Current.tracestate
446
+ req['tracestate'] = tracestate if tracestate && req['tracestate'].nil?
238
447
  end
239
448
 
240
- response
449
+ record ? span_id : nil
450
+ rescue StandardError
451
+ nil
452
+ end
453
+
454
+ def self.span_fields(span_id, start_ms)
455
+ frame = Instrumentation.current_frame
456
+ Instrumentation.span_fields(frame && frame.offset_ms(start_ms), span_id: span_id)
457
+ rescue StandardError
458
+ {}
241
459
  end
242
460
  end
243
461
  end
@@ -29,6 +29,9 @@ module Koderift
29
29
  exception: event.payload[:exception]&.join(': '),
30
30
  request_id: event.payload[:koderift_request_id],
31
31
  trace_id: event.payload[:koderift_trace_id],
32
+ span_id: event.payload[:koderift_span_id],
33
+ parent_span_id: event.payload[:koderift_parent_span_id],
34
+ started_at: event.payload[:koderift_started_at],
32
35
  ip: event.payload[:koderift_ip],
33
36
  user_agent: event.payload[:koderift_user_agent],
34
37
  allocations: event.payload[:allocations],
@@ -69,19 +69,41 @@ module Koderift
69
69
  end
70
70
  end
71
71
 
72
- # Register Sidekiq server middleware lazily when Sidekiq is present.
72
+ # Sidekiq middleware: the client half carries the trace into each job
73
+ # it enqueues; the server half runs the job as a traced unit of work.
74
+ # Clients run in every process, servers enqueue jobs too, so the client
75
+ # middleware is added to both. chain.add replaces an existing entry of
76
+ # the same class, so registering twice is harmless.
77
+ def self.register_sidekiq_middleware
78
+ return unless defined?(::Sidekiq) && ::Sidekiq.respond_to?(:configure_server)
79
+
80
+ require 'koderift/rails/sidekiq_middleware'
81
+ require 'koderift/rails/sidekiq_client_middleware'
82
+
83
+ if ::Sidekiq.respond_to?(:configure_client)
84
+ ::Sidekiq.configure_client do |sidekiq_config|
85
+ sidekiq_config.client_middleware do |chain|
86
+ chain.add Koderift::Rails::SidekiqClientMiddleware
87
+ end
88
+ end
89
+ end
90
+
91
+ ::Sidekiq.configure_server do |sidekiq_config|
92
+ sidekiq_config.client_middleware do |chain|
93
+ chain.add Koderift::Rails::SidekiqClientMiddleware
94
+ end
95
+ sidekiq_config.server_middleware do |chain|
96
+ chain.add Koderift::Rails::SidekiqMiddleware
97
+ end
98
+ end
99
+ end
100
+
101
+ # Registered lazily, once Sidekiq has had the chance to load.
73
102
  initializer 'koderift.sidekiq_middleware', after: :load_config_initializers do
74
103
  next unless Koderift::Rails.configuration.enabled
75
104
 
76
105
  ActiveSupport.on_load(:after_initialize) do
77
- if defined?(Sidekiq) && Sidekiq.respond_to?(:configure_server)
78
- require 'koderift/rails/sidekiq_middleware'
79
- Sidekiq.configure_server do |sidekiq_config|
80
- sidekiq_config.server_middleware do |chain|
81
- chain.add Koderift::Rails::SidekiqMiddleware
82
- end
83
- end
84
- end
106
+ Koderift::Rails::Railtie.register_sidekiq_middleware
85
107
  end
86
108
  end
87
109
  end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'koderift/rails/trace_context'
4
+
5
+ module Koderift
6
+ module Rails
7
+ # Sidekiq client middleware: carries the enqueuing unit's trace into the
8
+ # job, so a request and the jobs it enqueues share one trace and each job
9
+ # names the span that enqueued it as its parent.
10
+ #
11
+ # Registered for clients in every process, including Sidekiq servers,
12
+ # because jobs enqueue jobs.
13
+ class SidekiqClientMiddleware
14
+ def call(_job_class, job, _queue, _redis_pool = nil)
15
+ inject(job)
16
+ yield
17
+ end
18
+
19
+ private
20
+
21
+ # Keys already on the job are never replaced. A retry, a scheduled job
22
+ # moved onto its queue by the poller, or a job someone gave a trace by
23
+ # hand all keep the trace they were enqueued with.
24
+ #
25
+ # koderift_trace_id is still written alongside koderift_traceparent
26
+ # because servers running gem versions before 2.2 read only that key.
27
+ def inject(job)
28
+ return unless job.is_a?(Hash)
29
+ return if job.key?('koderift_traceparent') || job.key?('koderift_trace_id')
30
+
31
+ trace_id = TraceContext::Current.trace_id
32
+ return if trace_id.nil? || trace_id.to_s.empty?
33
+
34
+ traceparent = TraceContext::Current.traceparent
35
+ job['koderift_traceparent'] = traceparent if traceparent
36
+ job['koderift_trace_id'] = trace_id
37
+ rescue StandardError
38
+ nil
39
+ end
40
+ end
41
+ end
42
+ end