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.
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
- require 'securerandom'
4
+ require 'koderift/rails/trace_context'
5
5
  require 'koderift/rails/instrumentation'
6
6
  require 'koderift/rails/scope'
7
7
 
@@ -16,36 +16,30 @@ module Koderift
16
16
  config = Koderift::Rails.configuration
17
17
  return yield unless config.enabled && config.project_token.present?
18
18
 
19
- trace_id = job['koderift_trace_id'].to_s
20
- trace_id = SecureRandom.uuid if trace_id.empty?
21
- Thread.current[:koderift_trace_id] = trace_id
22
-
23
- # Ambient context for manual captures made anywhere inside the job.
24
- # The jid stands in for a request id: it is what correlates a capture
25
- # with the job's own log line, and what carries this job's spans into
26
- # log_spans (IngestLogBatchJob drops spans on a row with no request id).
27
- Thread.current[:koderift_context] = {
28
- component: job_name(job),
29
- action: 'perform',
30
- request_id: job['jid'].to_s
31
- }
32
-
33
- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
19
+ started_at_ms = TraceContext.now_ms
20
+ trace_frame = start_trace(job, started_at_ms)
21
+ trace = trace_fields(trace_frame)
34
22
 
35
23
  begin
36
- result = Instrumentation.capture { yield }
37
- duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
38
- emit_job_log(worker, job, queue, result, duration_ms, trace_id, error: nil)
24
+ result = Instrumentation.capture(started_at_ms: started_at_ms) { yield }
25
+ duration_ms = (TraceContext.now_ms - started_at_ms).round
26
+ emit_job_log(worker, job, queue, result, duration_ms, trace, error: nil)
39
27
  result
40
28
  rescue StandardError => e
41
- duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
29
+ duration_ms = (TraceContext.now_ms - started_at_ms).round
42
30
  empty_result = { spans: [], query_count: 0, partial_count: 0,
43
31
  search_count: 0, breadcrumbs: [] }
44
- emit_job_log(worker, job, queue, empty_result, duration_ms, trace_id, error: e)
32
+ emit_job_log(worker, job, queue, empty_result, duration_ms, trace, error: e)
45
33
  raise
46
34
  ensure
47
- Thread.current[:koderift_trace_id] = nil
48
- Thread.current[:koderift_context] = nil
35
+ if trace_frame
36
+ # Clears the trace and context, or, for a job run with
37
+ # perform_inline inside another unit, hands that unit back its own.
38
+ TraceContext::Current.pop(trace_frame)
39
+ else
40
+ Thread.current[:koderift_trace_id] = nil
41
+ Thread.current[:koderift_context] = nil
42
+ end
49
43
  # Sidekiq reuses threads across jobs; see the same reset in Controller.
50
44
  Koderift::Rails::Scope.reset!
51
45
  end
@@ -53,6 +47,45 @@ module Koderift
53
47
 
54
48
  private
55
49
 
50
+ # Continues the trace the client middleware stored on the job, else the
51
+ # legacy trace ID key, else starts one (TraceContext.from_job).
52
+ #
53
+ # Ambient context for manual captures made anywhere inside the job.
54
+ # The jid stands in for a request id: it is what correlates a capture
55
+ # with the job's own log line, and what carries this job's spans into
56
+ # log_spans (IngestLogBatchJob drops spans on a row with no request id).
57
+ def start_trace(job, started_at_ms)
58
+ context = {
59
+ component: job_name(job),
60
+ action: 'perform',
61
+ request_id: job['jid'].to_s
62
+ }
63
+ trace = TraceContext.from_job(job)
64
+
65
+ TraceContext::Current.push(
66
+ kind: :job,
67
+ trace_id: trace[:trace_id],
68
+ parent_span_id: trace[:parent_span_id],
69
+ flags: trace[:flags],
70
+ context: context,
71
+ started_at_ms: started_at_ms
72
+ )
73
+ rescue StandardError
74
+ Thread.current[:koderift_context] = context
75
+ nil
76
+ end
77
+
78
+ def trace_fields(frame)
79
+ return { trace_id: Thread.current[:koderift_trace_id] } unless frame
80
+
81
+ {
82
+ trace_id: frame.trace_id,
83
+ span_id: frame.root_span_id,
84
+ parent_span_id: frame.parent_span_id,
85
+ started_at: frame.started_at
86
+ }
87
+ end
88
+
56
89
  # The name Sidekiq's own JobLogger logs the job under. For ActiveJob,
57
90
  # job['class'] is the adapter's wrapper (Sidekiq::ActiveJob::Wrapper,
58
91
  # ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper) for every job, and
@@ -62,7 +95,7 @@ module Koderift
62
95
  (job['wrapped'] || job['class']).to_s
63
96
  end
64
97
 
65
- def emit_job_log(_worker, job, queue, result, duration_ms, trace_id, error:)
98
+ def emit_job_log(_worker, job, queue, result, duration_ms, trace, error:)
66
99
  config = Koderift::Rails.configuration
67
100
 
68
101
  level = if error
@@ -80,7 +113,10 @@ module Koderift
80
113
  status: error ? 500 : 200,
81
114
  duration: duration_ms,
82
115
  level: level,
83
- trace_id: trace_id,
116
+ trace_id: trace[:trace_id],
117
+ span_id: trace[:span_id],
118
+ parent_span_id: trace[:parent_span_id],
119
+ started_at: trace[:started_at],
84
120
  spans: result[:spans],
85
121
  query_count: result[:query_count],
86
122
  search_count: result[:search_count],
@@ -0,0 +1,322 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+ require 'time'
5
+ require 'koderift/rails/frame_stack'
6
+
7
+ module Koderift
8
+ module Rails
9
+ # W3C Trace Context (https://www.w3.org/TR/trace-context/, the Level 1
10
+ # Recommendation) plus the two other ways a trace reaches this gem: Sentry's
11
+ # `sentry-trace` header and the gem's own headers.
12
+ #
13
+ # Everything at module level is a pure function and never raises: a
14
+ # malformed header is ignored and the unit of work starts a new trace.
15
+ module TraceContext
16
+ DEFAULT_FLAGS = '01'
17
+
18
+ TRACEPARENT_RE = /\A([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?\z/.freeze
19
+ SENTRY_TRACE_RE = /\A([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?\z/.freeze
20
+ LEGACY_RE = /\A(?:\h{8}-\h{4}-\h{4}-\h{4}-\h{12}|\h{32})\z/.freeze
21
+ TRACE_ID_RE = /\A[0-9a-f]{32}\z/.freeze
22
+ SPAN_ID_RE = /\A[0-9a-f]{16}\z/.freeze
23
+ TRACESTATE_RE = /\A[\x20-\x7e]*\z/.freeze
24
+
25
+ ZERO_TRACE_ID = ('0' * 32).freeze
26
+ ZERO_SPAN_ID = ('0' * 16).freeze
27
+
28
+ MAX_HEADER = 512
29
+ MAX_TRACESTATE = 512
30
+ MAX_TRACESTATE_ITEM = 128
31
+
32
+ KODERIFT_TRACEPARENT = 'X-Koderift-Traceparent'
33
+ LEGACY_TRACE_HEADER = 'X-Koderift-Trace-ID'
34
+
35
+ class << self
36
+ def new_trace_id
37
+ SecureRandom.hex(16)
38
+ end
39
+
40
+ def new_span_id
41
+ SecureRandom.hex(8)
42
+ end
43
+
44
+ def new_context
45
+ { trace_id: new_trace_id, parent_span_id: nil, flags: DEFAULT_FLAGS, tracestate: nil }
46
+ end
47
+
48
+ def valid_trace_id?(value)
49
+ value.is_a?(String) && TRACE_ID_RE.match?(value) && value != ZERO_TRACE_ID
50
+ end
51
+
52
+ def valid_span_id?(value)
53
+ value.is_a?(String) && SPAN_ID_RE.match?(value) && value != ZERO_SPAN_ID
54
+ end
55
+
56
+ # Lowercase hex only (the spec forbids uppercase). Version ff is
57
+ # invalid. Version 00 is exactly 55 characters. A higher version is
58
+ # read by its first four fields, and anything after the flags must
59
+ # start with a dash. Only the sampled bit of the flags is kept: Level 1
60
+ # says unknown flags are zeroed before they are sent on.
61
+ def parse_traceparent(value)
62
+ return nil unless value.is_a?(String) && value.bytesize <= MAX_HEADER
63
+
64
+ match = TRACEPARENT_RE.match(value.strip)
65
+ return nil unless match
66
+
67
+ version, trace_id, span_id, flags, rest = match.captures
68
+ return nil if version == 'ff'
69
+ return nil if version == '00' && rest
70
+ return nil unless valid_trace_id?(trace_id) && valid_span_id?(span_id)
71
+
72
+ { trace_id: trace_id, parent_span_id: span_id, flags: sampled_flags(flags) }
73
+ rescue StandardError
74
+ nil
75
+ end
76
+
77
+ # Returns nil when either ID is invalid, so a non-hex trace ID that
78
+ # older code put on the thread never becomes a malformed header.
79
+ def format_traceparent(trace_id, span_id, flags = DEFAULT_FLAGS)
80
+ return nil unless valid_trace_id?(trace_id) && valid_span_id?(span_id)
81
+
82
+ flags = DEFAULT_FLAGS unless flags.is_a?(String) && /\A[0-9a-f]{2}\z/.match?(flags)
83
+ "00-#{trace_id}-#{span_id}-#{flags}"
84
+ rescue StandardError
85
+ nil
86
+ end
87
+
88
+ # `<trace id>-<span id>[-<sampled>]`. A missing sampled flag is
89
+ # Sentry's "decide later"; it is treated as sampled.
90
+ def parse_sentry_trace(value)
91
+ return nil unless value.is_a?(String) && value.bytesize <= MAX_HEADER
92
+
93
+ match = SENTRY_TRACE_RE.match(value.strip)
94
+ return nil unless match
95
+
96
+ trace_id, span_id, sampled = match.captures
97
+ return nil unless valid_trace_id?(trace_id) && valid_span_id?(span_id)
98
+
99
+ { trace_id: trace_id, parent_span_id: span_id, flags: sampled == '0' ? '00' : DEFAULT_FLAGS }
100
+ rescue StandardError
101
+ nil
102
+ end
103
+
104
+ # The trace ID gem versions before 2.2 sent: a UUID. Dashed or not, any
105
+ # case, it becomes 32 lowercase hex. Anything else is not a trace ID.
106
+ def normalise_legacy(value)
107
+ return nil unless value.is_a?(String) && value.bytesize <= MAX_HEADER
108
+
109
+ stripped = value.strip
110
+ return nil unless LEGACY_RE.match?(stripped)
111
+
112
+ id = stripped.delete('-').downcase
113
+ valid_trace_id?(id) ? id : nil
114
+ rescue StandardError
115
+ nil
116
+ end
117
+
118
+ # Vendors that receive tracestate must pass it on. Kept as received
119
+ # when it is printable ASCII within 512 characters; longer values are
120
+ # cut the way the spec allows, dropping entries over 128 characters
121
+ # and then entries from the end.
122
+ def parse_tracestate(value)
123
+ return nil unless value.is_a?(String) && value.bytesize <= MAX_HEADER * 8
124
+
125
+ stripped = value.strip
126
+ return nil if stripped.empty? || !TRACESTATE_RE.match?(stripped)
127
+ return stripped if stripped.length <= MAX_TRACESTATE
128
+
129
+ entries = stripped.split(',').map(&:strip).reject(&:empty?)
130
+ entries = entries.reject { |e| e.length > MAX_TRACESTATE_ITEM }
131
+ entries.pop while entries.any? && entries.join(',').length > MAX_TRACESTATE
132
+ entries.empty? ? nil : entries.join(',')
133
+ rescue StandardError
134
+ nil
135
+ end
136
+
137
+ # Precedence: X-Koderift-Traceparent (our own copy, which APM
138
+ # instrumentation never rewrites), traceparent, sentry-trace, the
139
+ # legacy X-Koderift-Trace-ID, then a new trace.
140
+ #
141
+ # A Koderift trace ID wins whenever it disagrees, because nothing but
142
+ # this gem sets it. A caller on a version before 2.2 sends only the
143
+ # legacy header, and if it also runs Sentry or an APM, that tool's
144
+ # sentry-trace or traceparent arrives too, carrying a different trace.
145
+ # The legacy ID is then used, with no parent (that header carries
146
+ # none), so the trace still links. When the two agree, the W3C or
147
+ # Sentry parent is kept.
148
+ #
149
+ # tracestate belongs to the incoming traceparent, so it is kept only
150
+ # when the trace chosen is that header's trace.
151
+ def incoming(source)
152
+ return new_context if source.nil?
153
+
154
+ koderift = parse_traceparent(header(source, KODERIFT_TRACEPARENT))
155
+ w3c = parse_traceparent(header(source, 'traceparent'))
156
+ foreign = w3c || parse_sentry_trace(header(source, 'sentry-trace'))
157
+ legacy = koderift ? nil : normalise_legacy(header(source, LEGACY_TRACE_HEADER))
158
+
159
+ context = if koderift
160
+ koderift
161
+ elsif legacy && (foreign.nil? || foreign[:trace_id] != legacy)
162
+ { trace_id: legacy, parent_span_id: nil, flags: DEFAULT_FLAGS }
163
+ else
164
+ foreign
165
+ end
166
+ return new_context unless context
167
+
168
+ tracestate = nil
169
+ if w3c && w3c[:trace_id] == context[:trace_id]
170
+ tracestate = parse_tracestate(header(source, 'tracestate'))
171
+ end
172
+ context.merge(tracestate: tracestate)
173
+ rescue StandardError
174
+ new_context
175
+ end
176
+
177
+ # The trace a Sidekiq job continues: the traceparent the client
178
+ # middleware stored, then the legacy trace ID key, then a new trace.
179
+ def from_job(job)
180
+ return new_context unless job.is_a?(Hash)
181
+
182
+ context = parse_traceparent(job['koderift_traceparent'])
183
+ unless context
184
+ legacy = normalise_legacy(job['koderift_trace_id'])
185
+ context = { trace_id: legacy, parent_span_id: nil, flags: DEFAULT_FLAGS } if legacy
186
+ end
187
+ context ? context.merge(tracestate: nil) : new_context
188
+ rescue StandardError
189
+ new_context
190
+ end
191
+
192
+ # A transaction joins the trace already on the thread, as a child of
193
+ # the span open there; otherwise it starts one.
194
+ def continue_current
195
+ trace_id = Current.trace_id
196
+ return new_context if trace_id.nil? || trace_id.to_s.empty?
197
+
198
+ {
199
+ trace_id: trace_id,
200
+ parent_span_id: Current.current_span_id,
201
+ flags: Current.flags || DEFAULT_FLAGS,
202
+ tracestate: Current.tracestate
203
+ }
204
+ rescue StandardError
205
+ new_context
206
+ end
207
+
208
+ def now_ms
209
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
210
+ end
211
+
212
+ private
213
+
214
+ def sampled_flags(flags)
215
+ (flags.to_i(16) & 1) == 1 ? '01' : '00'
216
+ end
217
+
218
+ # ActionDispatch::Http::Headers maps `traceparent` to HTTP_TRACEPARENT
219
+ # itself; a bare Rack env needs the HTTP_ form; a plain hash may use
220
+ # either.
221
+ def header(source, name)
222
+ value = source[name]
223
+ value = source["HTTP_#{name.upcase.tr('-', '_')}"] if value.nil?
224
+ value.is_a?(String) ? value : nil
225
+ rescue StandardError
226
+ nil
227
+ end
228
+ end
229
+
230
+ # The trace state of one unit of work.
231
+ class Frame
232
+ include FrameStack::Member
233
+
234
+ attr_reader :kind, :trace_id, :root_span_id, :parent_span_id, :flags,
235
+ :tracestate, :span_stack, :started_at_ms, :started_at, :context
236
+
237
+ def initialize(kind:, trace_id:, parent_span_id:, flags:, tracestate:, context:,
238
+ started_at_ms:, started_at:, restore_outside:)
239
+ @kind = kind
240
+ @trace_id = trace_id
241
+ @root_span_id = TraceContext.new_span_id
242
+ @parent_span_id = parent_span_id
243
+ @flags = flags || DEFAULT_FLAGS
244
+ @tracestate = tracestate
245
+ @context = context
246
+ @span_stack = []
247
+ @started_at_ms = started_at_ms || TraceContext.now_ms
248
+ @started_at = (started_at || Time.now).utc.iso8601(3)
249
+ @restore_outside = restore_outside
250
+ end
251
+ end
252
+
253
+ # The thread's trace state. The trace ID itself stays published in
254
+ # Thread.current[:koderift_trace_id], which Capture and NetHttpPatch read,
255
+ # and the ambient capture context in Thread.current[:koderift_context].
256
+ # Only frames write those two keys.
257
+ module Current
258
+ STACK = FrameStack.new(:koderift_trace_frames, %i[koderift_trace_id koderift_context]) do |frame|
259
+ [frame.trace_id, frame.context]
260
+ end
261
+
262
+ class << self
263
+ def push(kind:, trace_id:, parent_span_id: nil, flags: nil, tracestate: nil,
264
+ context: nil, started_at_ms: nil, started_at: nil, restore_outside: false)
265
+ STACK.push(Frame.new(
266
+ kind: kind, trace_id: trace_id, parent_span_id: parent_span_id,
267
+ flags: flags, tracestate: tracestate, context: context,
268
+ started_at_ms: started_at_ms, started_at: started_at,
269
+ restore_outside: restore_outside
270
+ ))
271
+ end
272
+
273
+ def pop(frame)
274
+ frame ? STACK.pop(frame) : false
275
+ end
276
+
277
+ def frame
278
+ STACK.top
279
+ end
280
+
281
+ def clear!
282
+ STACK.clear!
283
+ end
284
+
285
+ def trace_id
286
+ Thread.current[:koderift_trace_id]
287
+ end
288
+
289
+ # The innermost open span: a with_child_span block, else the unit's
290
+ # root span. What a job, a downstream request or a nested
291
+ # transaction names as its parent.
292
+ def current_span_id
293
+ f = frame
294
+ f && (f.span_stack.last || f.root_span_id)
295
+ end
296
+
297
+ # The innermost open with_child_span, or nil when the unit's root is
298
+ # the parent. Spans inside a line leave parent_span_id out in that
299
+ # case: missing means the root.
300
+ def enclosing_span_id
301
+ f = frame
302
+ f && f.span_stack.last
303
+ end
304
+
305
+ def flags
306
+ f = frame
307
+ f && f.flags
308
+ end
309
+
310
+ def tracestate
311
+ f = frame
312
+ f && f.tracestate
313
+ end
314
+
315
+ def traceparent(span_id = current_span_id)
316
+ TraceContext.format_traceparent(trace_id, span_id, flags || DEFAULT_FLAGS)
317
+ end
318
+ end
319
+ end
320
+ end
321
+ end
322
+ end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'json'
4
4
  require 'securerandom'
5
+ require 'koderift/rails/trace_context'
5
6
  require 'koderift/rails/instrumentation'
6
7
  require 'koderift/rails/capture'
7
8
 
@@ -53,7 +54,7 @@ module Koderift
53
54
  # exactly as those two do, so its SQL, HTTP and custom spans reach the
54
55
  # APM trace view.
55
56
  class Transaction
56
- attr_reader :name, :op, :request_id, :trace_id
57
+ attr_reader :name, :op, :request_id, :trace_id, :span_id, :parent_span_id
57
58
 
58
59
  def initialize(name:, op: nil)
59
60
  @name = name.to_s
@@ -66,20 +67,24 @@ module Koderift
66
67
  # reaches log_spans — the trace would arrive empty, with no error
67
68
  # anywhere to explain why.
68
69
  @request_id = SecureRandom.uuid
69
- @trace_id = Thread.current[:koderift_trace_id] || SecureRandom.uuid
70
70
 
71
- @previous_trace_id = Thread.current[:koderift_trace_id]
72
- @previous_context = Thread.current[Capture::CONTEXT_KEY]
73
-
74
- Thread.current[:koderift_trace_id] = @trace_id
75
- Thread.current[Capture::CONTEXT_KEY] = {
76
- component: component,
77
- action: action,
78
- request_id: @request_id
79
- }
80
-
81
- @started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
82
- @state = Instrumentation.start_capture
71
+ # Inside a request or job this joins that trace as a child of the
72
+ # span open there; otherwise it starts a new one. (start_transaction
73
+ # finishes a transaction already open on the thread before starting
74
+ # this one, as it did before 2.2.)
75
+ # Its frames restore what the thread held before when it finishes,
76
+ # and a transaction finished after the unit it began in has ended
77
+ # (an abandoned non-block one) finds its frames gone and restores
78
+ # nothing.
79
+ @started_at_ms = TraceContext.now_ms
80
+ trace = TraceContext.continue_current
81
+ @trace_id = trace[:trace_id]
82
+ @parent_span_id = trace[:parent_span_id]
83
+ @frame = push_frame(trace)
84
+ @span_id = @frame && @frame.root_span_id
85
+ @started_at = @frame && @frame.started_at
86
+
87
+ @state = Instrumentation.start_capture(restore_outside: true, started_at_ms: @started_at_ms)
83
88
  end
84
89
 
85
90
  def finished?
@@ -90,25 +95,27 @@ module Koderift
90
95
  return nil if @finished
91
96
 
92
97
  @finished = true
93
- duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - @started_at) * 1000).round
98
+ duration_ms = (TraceContext.now_ms - @started_at_ms).round
94
99
 
95
100
  Instrumentation.stop_capture(@state)
96
101
  result = Instrumentation.build_result(@state)
97
102
 
98
103
  Capture.transaction(
99
- component: component,
100
- action: action,
101
- message: "Completed in #{(duration_ms / 1000.0).round(1)}s",
102
- duration_ms: duration_ms,
103
- request_id: @request_id,
104
- trace_id: @trace_id,
105
- result: result
104
+ component: component,
105
+ action: action,
106
+ message: "Completed in #{(duration_ms / 1000.0).round(1)}s",
107
+ duration_ms: duration_ms,
108
+ request_id: @request_id,
109
+ trace_id: @trace_id,
110
+ span_id: @span_id,
111
+ parent_span_id: @parent_span_id,
112
+ started_at: @started_at,
113
+ result: result
106
114
  )
107
115
  rescue StandardError
108
116
  nil
109
117
  ensure
110
- Thread.current[:koderift_trace_id] = @previous_trace_id
111
- Thread.current[Capture::CONTEXT_KEY] = @previous_context
118
+ TraceContext::Current.pop(@frame)
112
119
  Tracing.clear_current(self)
113
120
  end
114
121
 
@@ -124,17 +131,36 @@ module Koderift
124
131
  op = @op.to_s
125
132
  op.empty? ? 'call' : op
126
133
  end
134
+
135
+ private
136
+
137
+ def push_frame(trace)
138
+ TraceContext::Current.push(
139
+ kind: :transaction,
140
+ trace_id: trace[:trace_id],
141
+ parent_span_id: trace[:parent_span_id],
142
+ flags: trace[:flags],
143
+ tracestate: trace[:tracestate],
144
+ context: { component: component, action: action, request_id: @request_id },
145
+ started_at_ms: @started_at_ms,
146
+ restore_outside: true
147
+ )
148
+ rescue StandardError
149
+ nil
150
+ end
127
151
  end
128
152
 
129
153
  class << self
130
154
  def with_child_span(op: nil, description: nil)
131
155
  span = ChildSpan.new(op: op, description: description)
132
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
156
+ started = TraceContext.now_ms
157
+ opened = open_span
133
158
  begin
134
159
  yield span
135
160
  ensure
136
- elapsed = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
137
- record(span, elapsed)
161
+ close_span(opened)
162
+ elapsed = (TraceContext.now_ms - started).round
163
+ record(span, elapsed, opened, started)
138
164
  end
139
165
  end
140
166
 
@@ -172,20 +198,70 @@ module Koderift
172
198
 
173
199
  private
174
200
 
201
+ # The span's ID goes on the open-span stack of the trace frame in force
202
+ # when it starts, so SQL, HTTP calls and child spans inside the block
203
+ # name it as their parent. The stack array itself is remembered: if a
204
+ # transaction is started inside the block and is still open when the
205
+ # block ends, the ID is still removed from the right stack. The
206
+ # capture in force is remembered too, so the span is recorded on the
207
+ # line of the unit it was opened in.
208
+ def open_span
209
+ span_id = TraceContext.new_span_id
210
+ opened = { span_id: span_id, capture: Instrumentation.current_frame }
211
+ frame = TraceContext::Current.frame
212
+ return opened unless frame
213
+
214
+ stack = frame.span_stack
215
+ parent = stack.last
216
+ stack.push(span_id)
217
+ opened.merge(parent_span_id: parent, stack: stack)
218
+ rescue StandardError
219
+ nil
220
+ end
221
+
222
+ def close_span(opened)
223
+ stack = opened && opened[:stack]
224
+ return unless stack
225
+
226
+ index = stack.rindex(opened[:span_id])
227
+ stack.delete_at(index) if index
228
+ rescue StandardError
229
+ nil
230
+ end
231
+
175
232
  # Outside a captured unit of work there is no array to append to, so the
176
233
  # span is simply not recorded. That is inertness for want of a place to
177
234
  # put it, not a stub: inside a request, job or transaction the very same
178
235
  # call produces a real span.
179
- def record(span, duration_ms)
180
- spans = Thread.current[:koderift_custom_spans]
181
- return nil unless spans.is_a?(Array)
236
+ #
237
+ # The span goes on the line of the unit it was opened in while that
238
+ # unit is still running, even if a transaction started inside the
239
+ # block is still open. If that unit has already ended (a transaction
240
+ # finished inside the block), the span goes on the line of the unit
241
+ # running now, under the span open there, rather than onto a line that
242
+ # has already been written.
243
+ def record(span, duration_ms, opened, started)
244
+ opened_in = opened && opened[:capture]
245
+ if opened_in && Instrumentation.capturing?(opened_in)
246
+ capture = opened_in
247
+ parent = opened[:parent_span_id]
248
+ else
249
+ capture = Instrumentation.current_frame
250
+ parent = TraceContext::Current.enclosing_span_id
251
+ end
252
+ return nil unless capture
182
253
 
183
- name = span.name.to_s
184
- spans << {
254
+ name = span.name.to_s
255
+ entry = {
185
256
  name: name.length > MAX_SPAN_NAME ? name[0, MAX_SPAN_NAME] : name,
186
257
  duration_ms: duration_ms,
187
- detail: span.detail
258
+ detail: span.detail,
259
+ span_id: (opened && opened[:span_id]) || TraceContext.new_span_id
188
260
  }
261
+ entry[:parent_span_id] = parent if parent
262
+ start_ms = capture.offset_ms(started)
263
+ entry[:start_ms] = start_ms if start_ms
264
+ capture.custom_spans << entry
189
265
  rescue StandardError
190
266
  nil
191
267
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Koderift
4
4
  module Rails
5
- VERSION = '2.1.2'
5
+ VERSION = '2.2.0'
6
6
  end
7
7
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require 'koderift/rails/version'
4
4
  require 'koderift/rails/configuration'
5
+ require 'koderift/rails/frame_stack'
6
+ require 'koderift/rails/trace_context'
5
7
  require 'koderift/rails/instrumentation'
6
8
  require 'koderift/rails/lograge_config'
7
9
  require 'koderift/rails/event'
@@ -28,6 +30,8 @@ module Koderift
28
30
  @configuration = Configuration.new
29
31
  Capture.reset_rate_limiter!
30
32
  Scope.reset!
33
+ TraceContext::Current.clear!
34
+ Instrumentation.clear_captures!
31
35
  Breadcrumbs.clear
32
36
  RumHelper.reset_warnings!
33
37
  end