-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsentrySpan.ts
438 lines (384 loc) · 12.9 KB
/
sentrySpan.ts
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
import { getClient, getCurrentScope } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
import { createSpanEnvelope } from '../envelope';
import {
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
SEMANTIC_ATTRIBUTE_PROFILE_ID,
SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
} from '../semanticAttributes';
import type {
SentrySpanArguments,
Span,
SpanAttributeValue,
SpanAttributes,
SpanContextData,
SpanEnvelope,
SpanJSON,
SpanOrigin,
SpanStatus,
SpanTimeInput,
TimedEvent,
TransactionEvent,
TransactionSource,
} from '../types-hoist';
import type { SpanLink } from '../types-hoist/link';
import { logger } from '../utils-hoist/logger';
import { dropUndefinedKeys } from '../utils-hoist/object';
import { generateSpanId, generateTraceId } from '../utils-hoist/propagationContext';
import { timestampInSeconds } from '../utils-hoist/time';
import {
TRACE_FLAG_NONE,
TRACE_FLAG_SAMPLED,
convertSpanLinksForEnvelope,
getRootSpan,
getSpanDescendants,
getStatusMessage,
spanTimeInputToSeconds,
spanToJSON,
spanToTransactionTraceContext,
} from '../utils/spanUtils';
import { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';
import { logSpanEnd } from './logSpans';
import { timedEventsToMeasurements } from './measurement';
import { getCapturedScopesOnSpan } from './utils';
const MAX_SPAN_COUNT = 1000;
/**
* Span contains all data about a span
*/
export class SentrySpan implements Span {
protected _traceId: string;
protected _spanId: string;
protected _parentSpanId?: string | undefined;
protected _sampled: boolean | undefined;
protected _name?: string | undefined;
protected _attributes: SpanAttributes;
protected _links?: SpanLink[];
/** Epoch timestamp in seconds when the span started. */
protected _startTime: number;
/** Epoch timestamp in seconds when the span ended. */
protected _endTime?: number | undefined;
/** Internal keeper of the status */
protected _status?: SpanStatus;
/** The timed events added to this span. */
protected _events: TimedEvent[];
/** if true, treat span as a standalone span (not part of a transaction) */
private _isStandaloneSpan?: boolean;
/**
* You should never call the constructor manually, always use `Sentry.startSpan()`
* or other span methods.
* @internal
* @hideconstructor
* @hidden
*/
public constructor(spanContext: SentrySpanArguments = {}) {
this._traceId = spanContext.traceId || generateTraceId();
this._spanId = spanContext.spanId || generateSpanId();
this._startTime = spanContext.startTimestamp || timestampInSeconds();
this._links = spanContext.links;
this._attributes = {};
this.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,
...spanContext.attributes,
});
this._name = spanContext.name;
if (spanContext.parentSpanId) {
this._parentSpanId = spanContext.parentSpanId;
}
// We want to include booleans as well here
if ('sampled' in spanContext) {
this._sampled = spanContext.sampled;
}
if (spanContext.endTimestamp) {
this._endTime = spanContext.endTimestamp;
}
this._events = [];
this._isStandaloneSpan = spanContext.isStandalone;
// If the span is already ended, ensure we finalize the span immediately
if (this._endTime) {
this._onSpanEnded();
}
}
/** @inheritDoc */
public addLink(link: SpanLink): this {
if (this._links) {
this._links.push(link);
} else {
this._links = [link];
}
return this;
}
/** @inheritDoc */
public addLinks(links: SpanLink[]): this {
if (this._links) {
this._links.push(...links);
} else {
this._links = links;
}
return this;
}
/**
* This should generally not be used,
* but it is needed for being compliant with the OTEL Span interface.
*
* @hidden
* @internal
*/
public recordException(_exception: unknown, _time?: number | undefined): void {
// noop
}
/** @inheritdoc */
public spanContext(): SpanContextData {
const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
return {
spanId,
traceId,
traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,
};
}
/** @inheritdoc */
public setAttribute(key: string, value: SpanAttributeValue | undefined): this {
if (value === undefined) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._attributes[key];
} else {
this._attributes[key] = value;
}
return this;
}
/** @inheritdoc */
public setAttributes(attributes: SpanAttributes): this {
Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));
return this;
}
/**
* This should generally not be used,
* but we need it for browser tracing where we want to adjust the start time afterwards.
* USE THIS WITH CAUTION!
*
* @hidden
* @internal
*/
public updateStartTime(timeInput: SpanTimeInput): void {
this._startTime = spanTimeInputToSeconds(timeInput);
}
/**
* @inheritDoc
*/
public setStatus(value: SpanStatus): this {
this._status = value;
return this;
}
/**
* @inheritDoc
*/
public updateName(name: string): this {
this._name = name;
this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');
return this;
}
/** @inheritdoc */
public end(endTimestamp?: SpanTimeInput): void {
// If already ended, skip
if (this._endTime) {
return;
}
this._endTime = spanTimeInputToSeconds(endTimestamp);
logSpanEnd(this);
this._onSpanEnded();
}
/**
* Get JSON representation of this span.
*
* @hidden
* @internal This method is purely for internal purposes and should not be used outside
* of SDK code. If you need to get a JSON representation of a span,
* use `spanToJSON(span)` instead.
*/
public getSpanJSON(): SpanJSON {
return dropUndefinedKeys({
data: this._attributes,
description: this._name,
op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
parent_span_id: this._parentSpanId,
span_id: this._spanId,
start_timestamp: this._startTime,
status: getStatusMessage(this._status),
timestamp: this._endTime,
trace_id: this._traceId,
origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,
profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,
exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,
measurements: timedEventsToMeasurements(this._events),
is_segment: (this._isStandaloneSpan && getRootSpan(this) === this) || undefined,
segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,
links: convertSpanLinksForEnvelope(this._links),
});
}
/** @inheritdoc */
public isRecording(): boolean {
return !this._endTime && !!this._sampled;
}
/**
* @inheritdoc
*/
public addEvent(
name: string,
attributesOrStartTime?: SpanAttributes | SpanTimeInput,
startTime?: SpanTimeInput,
): this {
DEBUG_BUILD && logger.log('[Tracing] Adding an event to span:', name);
const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();
const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};
const event: TimedEvent = {
name,
time: spanTimeInputToSeconds(time),
attributes,
};
this._events.push(event);
return this;
}
/**
* This method should generally not be used,
* but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.
* USE THIS WITH CAUTION!
* @internal
* @hidden
* @experimental
*/
public isStandaloneSpan(): boolean {
return !!this._isStandaloneSpan;
}
/** Emit `spanEnd` when the span is ended. */
private _onSpanEnded(): void {
const client = getClient();
if (client) {
client.emit('spanEnd', this);
}
// A segment span is basically the root span of a local span tree.
// So for now, this is either what we previously refer to as the root span,
// or a standalone span.
const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);
if (!isSegmentSpan) {
return;
}
// if this is a standalone span, we send it immediately
if (this._isStandaloneSpan) {
if (this._sampled) {
sendSpanEnvelope(createSpanEnvelope([this], client));
} else {
DEBUG_BUILD &&
logger.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');
if (client) {
client.recordDroppedEvent('sample_rate', 'span');
}
}
return;
}
const transactionEvent = this._convertSpanToTransaction();
if (transactionEvent) {
const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
scope.captureEvent(transactionEvent);
}
}
/**
* Finish the transaction & prepare the event to send to Sentry.
*/
private _convertSpanToTransaction(): TransactionEvent | undefined {
// We can only convert finished spans
if (!isFullFinishedSpan(spanToJSON(this))) {
return undefined;
}
if (!this._name) {
DEBUG_BUILD && logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');
this._name = '<unlabeled transaction>';
}
const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);
if (this._sampled !== true) {
return undefined;
}
// The transaction span itself as well as any potential standalone spans should be filtered out
const finishedSpans = getSpanDescendants(this).filter(span => span !== this && !isStandaloneSpan(span));
const spans = finishedSpans.map(span => spanToJSON(span)).filter(isFullFinishedSpan);
const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionSource | undefined;
// remove internal root span attributes we don't need to send.
/* eslint-disable @typescript-eslint/no-dynamic-delete */
delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
spans.forEach(span => {
delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
});
// eslint-enabled-next-line @typescript-eslint/no-dynamic-delete
const transaction: TransactionEvent = {
contexts: {
trace: spanToTransactionTraceContext(this),
},
spans:
// spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here
// we do not use spans anymore after this point
spans.length > MAX_SPAN_COUNT
? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)
: spans,
start_timestamp: this._startTime,
timestamp: this._endTime,
transaction: this._name,
type: 'transaction',
sdkProcessingMetadata: {
capturedSpanScope,
capturedSpanIsolationScope,
...dropUndefinedKeys({
dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),
}),
},
...(source && {
transaction_info: {
source,
},
}),
};
const measurements = timedEventsToMeasurements(this._events);
const hasMeasurements = measurements && Object.keys(measurements).length;
if (hasMeasurements) {
DEBUG_BUILD &&
logger.log(
'[Measurements] Adding measurements to transaction event',
JSON.stringify(measurements, undefined, 2),
);
transaction.measurements = measurements;
}
return transaction;
}
}
function isSpanTimeInput(value: undefined | SpanAttributes | SpanTimeInput): value is SpanTimeInput {
return (value && typeof value === 'number') || value instanceof Date || Array.isArray(value);
}
// We want to filter out any incomplete SpanJSON objects
function isFullFinishedSpan(input: Partial<SpanJSON>): input is SpanJSON {
return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
}
/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */
function isStandaloneSpan(span: Span): boolean {
return span instanceof SentrySpan && span.isStandaloneSpan();
}
/**
* Sends a `SpanEnvelope`.
*
* Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`,
* the envelope will not be sent either.
*/
function sendSpanEnvelope(envelope: SpanEnvelope): void {
const client = getClient();
if (!client) {
return;
}
const spanItems = envelope[1];
if (!spanItems || spanItems.length === 0) {
client.recordDroppedEvent('before_send', 'span');
return;
}
// sendEnvelope should not throw
// eslint-disable-next-line @typescript-eslint/no-floating-promises
client.sendEnvelope(envelope);
}