-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtrace.ts
More file actions
625 lines (538 loc) · 22.2 KB
/
trace.ts
File metadata and controls
625 lines (538 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
53
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
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
110
111
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
140
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/* eslint-disable max-lines */
import { getAsyncContextStrategy } from '../asyncContext';
import type { AsyncContextStrategy } from '../asyncContext/types';
import { getMainCarrier } from '../carrier';
import { getClient, getCurrentScope, getIsolationScope, withScope } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
import type { Scope } from '../scope';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
} from '../semanticAttributes';
import type { DynamicSamplingContext } from '../types-hoist/envelope';
import type { ClientOptions } from '../types-hoist/options';
import type { SentrySpanArguments, Span, SpanTimeInput } from '../types-hoist/span';
import type { StartSpanOptions } from '../types-hoist/startSpanOptions';
import { baggageHeaderToDynamicSamplingContext } from '../utils/baggage';
import { debug } from '../utils/debug-logger';
import { handleCallbackErrors } from '../utils/handleCallbackErrors';
import { hasSpansEnabled } from '../utils/hasSpansEnabled';
import { shouldIgnoreSpan } from '../utils/should-ignore-span';
import { hasSpanStreamingEnabled } from './spans/hasSpanStreamingEnabled';
import { parseSampleRate } from '../utils/parseSampleRate';
import { generateTraceId } from '../utils/propagationContext';
import { safeMathRandom } from '../utils/randomSafeContext';
import { _getSpanForScope, _setSpanForScope } from '../utils/spanOnScope';
import { addChildSpanToSpan, getRootSpan, spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';
import { propagationContextFromHeaders, shouldContinueTrace } from '../utils/tracing';
import { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';
import { logSpanStart } from './logSpans';
import { sampleSpan } from './sampling';
import { SentryNonRecordingSpan } from './sentryNonRecordingSpan';
import { SentrySpan } from './sentrySpan';
import { SPAN_STATUS_ERROR } from './spanstatus';
import { setCapturedScopesOnSpan } from './utils';
import type { Client } from '../client';
const SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__';
/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
*
* If you want to create a span that is not set as active, use {@link startInactiveSpan}.
*
* You'll always get a span passed to the callback,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
export function startSpan<T>(options: StartSpanOptions, callback: (span: Span) => T): T {
const acs = getAcs();
if (acs.startSpan) {
return acs.startSpan(options, callback);
}
const spanArguments = parseSentrySpanArguments(options);
const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
// We still need to fork a potentially passed scope, as we set the active span on it
// and we need to ensure that it is cleaned up properly once the span ends.
const customForkedScope = customScope?.clone();
return withScope(customForkedScope, () => {
// If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`
const wrapper = getActiveSpanWrapper<T>(customParentSpan);
return wrapper(() => {
const scope = getCurrentScope();
const parentSpan = getParentSpan(scope, customParentSpan);
const client = getClient();
const missingRequiredParent = options.onlyIfParent && !parentSpan;
const activeSpan = missingRequiredParent
? new SentryNonRecordingSpan()
: createChildOrRootSpan({
parentSpan,
spanArguments,
forceTransaction,
scope,
});
if (missingRequiredParent) {
client?.recordDroppedEvent('no_parent_span', 'span');
}
// Ignored root spans still need to be set on scope so that `getActiveSpan()` returns them
// and descendants are also non-recording. Ignored child spans don't need this because
// the parent span is already on scope.
if (!_isIgnoredSpan(activeSpan) || !parentSpan) {
_setSpanForScope(scope, activeSpan);
}
return handleCallbackErrors(
() => callback(activeSpan),
() => {
// Only update the span status if it hasn't been changed yet, and the span is not yet finished
const { status } = spanToJSON(activeSpan);
if (activeSpan.isRecording() && (!status || status === 'ok')) {
activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
}
},
() => {
activeSpan.end();
},
);
});
});
}
/**
* Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span
* after the function is done automatically. Use `span.end()` to end the span.
*
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
*
* You'll always get a span passed to the callback,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
export function startSpanManual<T>(options: StartSpanOptions, callback: (span: Span, finish: () => void) => T): T {
const acs = getAcs();
if (acs.startSpanManual) {
return acs.startSpanManual(options, callback);
}
const spanArguments = parseSentrySpanArguments(options);
const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
const customForkedScope = customScope?.clone();
return withScope(customForkedScope, () => {
// If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`
const wrapper = getActiveSpanWrapper<T>(customParentSpan);
return wrapper(() => {
const scope = getCurrentScope();
const parentSpan = getParentSpan(scope, customParentSpan);
const missingRequiredParent = options.onlyIfParent && !parentSpan;
const activeSpan = missingRequiredParent
? new SentryNonRecordingSpan()
: createChildOrRootSpan({
parentSpan,
spanArguments,
forceTransaction,
scope,
});
if (missingRequiredParent) {
getClient()?.recordDroppedEvent('no_parent_span', 'span');
}
// We don't set ignored child spans onto the scope because there likely is an active,
// unignored span on the scope already.
if (!_isIgnoredSpan(activeSpan) || !parentSpan) {
_setSpanForScope(scope, activeSpan);
}
return handleCallbackErrors(
// We pass the `finish` function to the callback, so the user can finish the span manually
// this is mainly here for historic purposes because previously, we instructed users to call
// `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`
// or `finish` has the same effect and we simply leave it here to avoid breaking user code.
() => callback(activeSpan, () => activeSpan.end()),
() => {
// Only update the span status if it hasn't been changed yet, and the span is not yet finished
const { status } = spanToJSON(activeSpan);
if (activeSpan.isRecording() && (!status || status === 'ok')) {
activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
}
},
);
});
});
}
/**
* Creates a span. This span is not set as active, so will not get automatic instrumentation spans
* as children or be able to be accessed via `Sentry.getActiveSpan()`.
*
* If you want to create a span that is set as active, use {@link startSpan}.
*
* This function will always return a span,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
export function startInactiveSpan(options: StartSpanOptions): Span {
const acs = getAcs();
if (acs.startInactiveSpan) {
return acs.startInactiveSpan(options);
}
const spanArguments = parseSentrySpanArguments(options);
const { forceTransaction, parentSpan: customParentSpan } = options;
// If `options.scope` is defined, we use this as as a wrapper,
// If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`
const wrapper = options.scope
? (callback: () => Span) => withScope(options.scope, callback)
: customParentSpan !== undefined
? (callback: () => Span) => withActiveSpan(customParentSpan, callback)
: (callback: () => Span) => callback();
return wrapper(() => {
const scope = getCurrentScope();
const parentSpan = getParentSpan(scope, customParentSpan);
const client = getClient();
const missingRequiredParent = options.onlyIfParent && !parentSpan;
if (missingRequiredParent) {
client?.recordDroppedEvent('no_parent_span', 'span');
return new SentryNonRecordingSpan();
}
return createChildOrRootSpan({
parentSpan,
spanArguments,
forceTransaction,
scope,
});
});
}
/**
* Continue a trace from `sentry-trace` and `baggage` values.
* These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">`
* and `<meta name="baggage">` HTML tags.
*
* Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically
* be attached to the incoming trace.
*/
export const continueTrace = <V>(
options: {
sentryTrace: Parameters<typeof propagationContextFromHeaders>[0];
baggage: Parameters<typeof propagationContextFromHeaders>[1];
},
callback: () => V,
): V => {
const carrier = getMainCarrier();
const acs = getAsyncContextStrategy(carrier);
if (acs.continueTrace) {
return acs.continueTrace(options, callback);
}
const { sentryTrace, baggage } = options;
const client = getClient();
const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);
if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) {
return startNewTrace(callback);
}
return withScope(scope => {
const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
scope.setPropagationContext(propagationContext);
_setSpanForScope(scope, undefined);
return callback();
});
};
/**
* Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
* passed `null` to start an entirely new span tree.
*
* @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
* spans started within the callback will not be attached to a parent span.
* @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
* @returns the value returned from the provided callback function.
*/
export function withActiveSpan<T>(span: Span | null, callback: (scope: Scope) => T): T {
const acs = getAcs();
if (acs.withActiveSpan) {
return acs.withActiveSpan(span, callback);
}
return withScope(scope => {
_setSpanForScope(scope, span || undefined);
return callback(scope);
});
}
/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */
export function suppressTracing<T>(callback: () => T): T {
const acs = getAcs();
if (acs.suppressTracing) {
return acs.suppressTracing(callback);
}
return withScope(scope => {
// Note: We do not wait for the callback to finish before we reset the metadata
// the reason for this is that otherwise, in the browser this can lead to very weird behavior
// as there is only a single top scope, if the callback takes longer to finish,
// other, unrelated spans may also be suppressed, which we do not want
// so instead, we only suppress tracing synchronoysly in the browser
scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });
const res = callback();
scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: undefined });
return res;
});
}
/**
* Starts a new trace for the duration of the provided callback. Spans started within the
* callback will be part of the new trace instead of a potentially previously started trace.
*
* Important: Only use this function if you want to override the default trace lifetime and
* propagation mechanism of the SDK for the duration and scope of the provided callback.
* The newly created trace will also be the root of a new distributed trace, for example if
* you make http requests within the callback.
* This function might be useful if the operation you want to instrument should not be part
* of a potentially ongoing trace.
*
* Default behavior:
* - Server-side: A new trace is started for each incoming request.
* - Browser: A new trace is started for each page our route. Navigating to a new route
* or page will automatically create a new trace.
*/
export function startNewTrace<T>(callback: () => T): T {
const acs = getAcs();
if (acs.startNewTrace) {
return acs.startNewTrace(callback);
}
return withScope(scope => {
scope.setPropagationContext({
traceId: generateTraceId(),
sampleRand: safeMathRandom(),
});
DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);
return withActiveSpan(null, callback);
});
}
function createChildOrRootSpan({
parentSpan,
spanArguments,
forceTransaction,
scope,
}: {
parentSpan: SentrySpan | undefined;
spanArguments: SentrySpanArguments;
forceTransaction?: boolean;
scope: Scope;
}): Span {
if (!hasSpansEnabled()) {
const span = new SentryNonRecordingSpan();
// If this is a root span, we ensure to freeze a DSC
// So we can have at least partial data here
if (forceTransaction || !parentSpan) {
const dsc = {
sampled: 'false',
sample_rate: '0',
transaction: spanArguments.name,
...getDynamicSamplingContextFromSpan(span),
} satisfies Partial<DynamicSamplingContext>;
freezeDscOnSpan(span, dsc);
}
return span;
}
const client = getClient();
if (_shouldIgnoreStreamedSpan(client, spanArguments)) {
if (!_isTracingSuppressed(scope)) {
// if tracing is actively suppressed (Sentry.suppressTracing(...)),
// we don't want to record a client outcome for the ignored span
client?.recordDroppedEvent('ignored', 'span');
}
return new SentryNonRecordingSpan({
dropReason: 'ignored',
traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId,
});
}
const isolationScope = getIsolationScope();
let span: Span;
if (parentSpan && !forceTransaction) {
span = _startChildSpan(parentSpan, scope, spanArguments);
addChildSpanToSpan(parentSpan, span);
} else if (parentSpan) {
// If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope
const dsc = getDynamicSamplingContextFromSpan(parentSpan);
const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
const parentSampled = spanIsSampled(parentSpan);
span = _startRootSpan(
{
traceId,
parentSpanId,
...spanArguments,
},
scope,
parentSampled,
);
freezeDscOnSpan(span, dsc);
} else {
const {
traceId,
dsc,
parentSpanId,
sampled: parentSampled,
} = {
...isolationScope.getPropagationContext(),
...scope.getPropagationContext(),
};
span = _startRootSpan(
{
traceId,
parentSpanId,
...spanArguments,
},
scope,
parentSampled,
);
if (dsc) {
freezeDscOnSpan(span, dsc);
}
}
logSpanStart(span);
setCapturedScopesOnSpan(span, scope, isolationScope);
return span;
}
/**
* This converts StartSpanOptions to SentrySpanArguments.
* For the most part (for now) we accept the same options,
* but some of them need to be transformed.
*/
function parseSentrySpanArguments(options: StartSpanOptions): SentrySpanArguments {
const exp = options.experimental || {};
const initialCtx: SentrySpanArguments = {
isStandalone: exp.standalone,
...options,
};
if (options.startTime) {
const ctx: SentrySpanArguments & { startTime?: SpanTimeInput } = { ...initialCtx };
ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);
delete ctx.startTime;
return ctx;
}
return initialCtx;
}
function getAcs(): AsyncContextStrategy {
const carrier = getMainCarrier();
return getAsyncContextStrategy(carrier);
}
function _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parentSampled?: boolean): SentrySpan {
const client = getClient();
const options: Partial<ClientOptions> = client?.getOptions() || {};
const { name = '' } = spanArguments;
const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };
// we don't care about the decision for the moment; this is just a placeholder
client?.emit('beforeSampling', mutableSpanSamplingData, { decision: false });
// If hook consumers override the parentSampled flag, we will use that value instead of the actual one
const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;
const finalAttributes = mutableSpanSamplingData.spanAttributes;
const currentPropagationContext = scope.getPropagationContext();
const isTracingSuppressed = _isTracingSuppressed(scope);
const [sampled, sampleRate, localSampleRateWasApplied] = isTracingSuppressed
? [false]
: sampleSpan(
options,
{
name,
parentSampled: finalParentSampled,
attributes: finalAttributes,
parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate),
},
currentPropagationContext.sampleRand,
);
const rootSpan = new SentrySpan({
...spanArguments,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',
[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:
sampleRate !== undefined && localSampleRateWasApplied ? sampleRate : undefined,
...finalAttributes,
},
sampled,
});
if (!sampled && client && !isTracingSuppressed) {
DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
client.recordDroppedEvent('sample_rate', hasSpanStreamingEnabled(client) ? 'span' : 'transaction');
}
if (client) {
client.emit('spanStart', rootSpan);
}
return rootSpan;
}
/**
* Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.
* This inherits the sampling decision from the parent span.
*/
function _startChildSpan(parentSpan: Span, scope: Scope, spanArguments: SentrySpanArguments): Span {
const { spanId, traceId } = parentSpan.spanContext();
const isTracingSuppressed = _isTracingSuppressed(scope);
const sampled = isTracingSuppressed ? false : spanIsSampled(parentSpan);
const childSpan = sampled
? new SentrySpan({
...spanArguments,
parentSpanId: spanId,
traceId,
sampled,
})
: new SentryNonRecordingSpan({ traceId });
addChildSpanToSpan(parentSpan, childSpan);
const client = getClient();
if (!client) {
return childSpan;
}
if (hasSpanStreamingEnabled(client) && childSpan instanceof SentryNonRecordingSpan) {
if (parentSpan instanceof SentryNonRecordingSpan && parentSpan.dropReason) {
// We land here if the parent span was a segment span that was ignored (`ignoreSpans`).
// In this case, the child was also ignored (see `sampled` above) but we need to
// record a client outcome for the child.
childSpan.dropReason = parentSpan.dropReason;
client.recordDroppedEvent(parentSpan.dropReason, 'span');
} else if (!isTracingSuppressed) {
// Otherwise, the child is not sampled due to sampling of the parent span,
// hence we record a sample_rate client outcome for the child.
childSpan.dropReason = 'sample_rate';
client.recordDroppedEvent('sample_rate', 'span');
}
}
client.emit('spanStart', childSpan);
// If it has an endTimestamp, it's already ended
if (spanArguments.endTimestamp) {
client.emit('spanEnd', childSpan);
client.emit('afterSpanEnd', childSpan);
}
return childSpan;
}
function getParentSpan(scope: Scope, customParentSpan: Span | null | undefined): SentrySpan | undefined {
// always use the passed in span directly
if (customParentSpan) {
return customParentSpan as SentrySpan;
}
// This is different from `undefined` as it means the user explicitly wants no parent span
if (customParentSpan === null) {
return undefined;
}
const span = _getSpanForScope(scope) as SentrySpan | undefined;
if (!span) {
return undefined;
}
const client = getClient();
const options: Partial<ClientOptions> = client ? client.getOptions() : {};
if (options.parentSpanIsAlwaysRootSpan) {
return getRootSpan(span) as SentrySpan;
}
return span;
}
function getActiveSpanWrapper<T>(parentSpan: Span | undefined | null): (callback: () => T) => T {
return parentSpan !== undefined
? (callback: () => T) => {
return withActiveSpan(parentSpan, callback);
}
: (callback: () => T) => callback();
}
/* Checks if `ignoreSpans` applies (extracted for bundle size)*/
function _shouldIgnoreStreamedSpan(client: Client | undefined, spanArguments: SentrySpanArguments): boolean {
const ignoreSpans = client?.getOptions().ignoreSpans;
if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) {
return false;
}
return shouldIgnoreSpan(
{
description: spanArguments.name || '',
op: spanArguments.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP] || spanArguments.op,
attributes: spanArguments.attributes,
},
ignoreSpans,
);
}
function _isIgnoredSpan(span: Span): span is SentryNonRecordingSpan {
return span instanceof SentryNonRecordingSpan && span.dropReason === 'ignored';
}
function _isTracingSuppressed(scope: Scope): boolean {
return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true;
}