-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathspan.ts
360 lines (316 loc) · 9.07 KB
/
span.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
// tslint:disable:max-classes-per-file
import { getCurrentHub, Hub } from '@sentry/hub';
import { Span as SpanInterface, SpanContext, SpanStatus } from '@sentry/types';
import { dropUndefinedKeys, isInstanceOf, logger, timestampWithMs, uuid4 } from '@sentry/utils';
// TODO: Should this be exported?
export const TRACEPARENT_REGEXP = new RegExp(
'^[ \\t]*' + // whitespace
'([0-9a-f]{32})?' + // trace_id
'-?([0-9a-f]{16})?' + // span_id
'-?([01])?' + // sampled
'[ \\t]*$', // whitespace
);
/**
* Keeps track of finished spans for a given transaction
*/
class SpanRecorder {
private readonly _maxlen: number;
private _openSpanCount: number = 0;
public finishedSpans: Span[] = [];
public constructor(maxlen: number) {
this._maxlen = maxlen;
}
/**
* This is just so that we don't run out of memory while recording a lot
* of spans. At some point we just stop and flush out the start of the
* trace tree (i.e.the first n spans with the smallest
* start_timestamp).
*/
public startSpan(span: Span): void {
this._openSpanCount += 1;
if (this._openSpanCount > this._maxlen) {
span.spanRecorder = undefined;
}
}
/**
* Appends a span to finished spans table
* @param span Span to be added
*/
public finishSpan(span: Span): void {
this.finishedSpans.push(span);
}
}
/**
* Span contains all data about a span
*/
export class Span implements SpanInterface, SpanContext {
/**
* The reference to the current hub.
*/
private readonly _hub: Hub = (getCurrentHub() as unknown) as Hub;
/**
* @inheritDoc
*/
private readonly _traceId: string = uuid4();
/**
* @inheritDoc
*/
private readonly _spanId: string = uuid4().substring(16);
/**
* @inheritDoc
*/
private readonly _parentSpanId?: string;
/**
* @inheritDoc
*/
public sampled?: boolean;
/**
* Timestamp in seconds when the span was created.
*/
public startTimestamp: number = timestampWithMs();
/**
* Timestamp in seconds when the span ended.
*/
public timestamp?: number;
/**
* @inheritDoc
*/
public transaction?: string;
/**
* @inheritDoc
*/
public op?: string;
/**
* @inheritDoc
*/
public description?: string;
/**
* @inheritDoc
*/
public tags: { [key: string]: string } = {};
/**
* @inheritDoc
*/
public data: { [key: string]: any } = {};
/**
* List of spans that were finalized
*/
public spanRecorder?: SpanRecorder;
public constructor(spanContext?: SpanContext, hub?: Hub) {
if (isInstanceOf(hub, Hub)) {
this._hub = hub as Hub;
}
if (!spanContext) {
return this;
}
if (spanContext.traceId) {
this._traceId = spanContext.traceId;
}
if (spanContext.spanId) {
this._spanId = spanContext.spanId;
}
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.transaction) {
this.transaction = spanContext.transaction;
}
if (spanContext.op) {
this.op = spanContext.op;
}
if (spanContext.description) {
this.description = spanContext.description;
}
if (spanContext.data) {
this.data = spanContext.data;
}
if (spanContext.tags) {
this.tags = spanContext.tags;
}
}
/**
* Attaches SpanRecorder to the span itself
* @param maxlen maximum number of spans that can be recorded
*/
public initFinishedSpans(maxlen: number = 1000): void {
if (!this.spanRecorder) {
this.spanRecorder = new SpanRecorder(maxlen);
}
this.spanRecorder.startSpan(this);
}
/**
* Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.
* Also the `sampled` decision will be inherited.
*/
public child(spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId'>>): Span {
const span = new Span({
...spanContext,
parentSpanId: this._spanId,
sampled: this.sampled,
traceId: this._traceId,
});
span.spanRecorder = this.spanRecorder;
return span;
}
/**
* Continues a trace from a string (usually the header).
* @param traceparent Traceparent string
*/
public static fromTraceparent(
traceparent: string,
spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceid'>>,
): Span | undefined {
const matches = traceparent.match(TRACEPARENT_REGEXP);
if (matches) {
let sampled: boolean | undefined;
if (matches[3] === '1') {
sampled = true;
} else if (matches[3] === '0') {
sampled = false;
}
return new Span({
...spanContext,
parentSpanId: matches[2],
sampled,
traceId: matches[1],
});
}
return undefined;
}
/**
* @inheritDoc
*/
public setTag(key: string, value: string): this {
this.tags = { ...this.tags, [key]: value };
return this;
}
/**
* @inheritDoc
*/
public setData(key: string, value: any): this {
this.data = { ...this.data, [key]: value };
return this;
}
/**
* @inheritDoc
*/
public setStatus(value: SpanStatus): this {
this.setTag('status', value);
return this;
}
/**
* @inheritDoc
*/
public setHttpStatus(httpStatus: number): this {
this.setTag('http.status_code', String(httpStatus));
const spanStatus = SpanStatus.fromHttpCode(httpStatus);
if (spanStatus !== SpanStatus.UnknownError) {
this.setStatus(spanStatus);
}
return this;
}
/**
* @inheritDoc
*/
public isSuccess(): boolean {
return this.tags.status === SpanStatus.Ok;
}
/**
* Sets the finish timestamp on the current span.
* @param trimEnd If true, sets the end timestamp of the transaction to the highest timestamp of child spans, trimming
* the duration of the transaction span. This is useful to discard extra time in the transaction span that is not
* accounted for in child spans, like what happens in the idle transaction Tracing integration, where we finish the
* transaction after a given "idle time" and we don't want this "idle time" to be part of the transaction.
*/
public finish(trimEnd: boolean = false): string | undefined {
// This transaction is already finished, so we should not flush it again.
if (this.timestamp !== undefined) {
return undefined;
}
this.timestamp = timestampWithMs();
if (this.spanRecorder === undefined) {
return undefined;
}
this.spanRecorder.finishSpan(this);
if (this.transaction === undefined) {
// If this has no transaction set we assume there's a parent
// transaction for this span that would be flushed out eventually.
return undefined;
}
if (this.sampled === undefined) {
// At this point a `sampled === undefined` should have already been
// resolved to a concrete decision. If `sampled` is `undefined`, it's
// likely that somebody used `Sentry.startSpan(...)` on a
// non-transaction span and later decided to make it a transaction.
logger.warn('Discarding transaction Span without sampling decision');
return undefined;
}
const finishedSpans = this.spanRecorder ? this.spanRecorder.finishedSpans.filter(s => s !== this) : [];
if (trimEnd && finishedSpans.length > 0) {
this.timestamp = finishedSpans.reduce((prev: Span, current: Span) => {
if (prev.timestamp && current.timestamp) {
return prev.timestamp > current.timestamp ? prev : current;
}
return prev;
}).timestamp;
}
return this._hub.captureEvent({
contexts: {
trace: this.getTraceContext(),
},
spans: finishedSpans,
start_timestamp: this.startTimestamp,
tags: this.tags,
timestamp: this.timestamp,
transaction: this.transaction,
type: 'transaction',
});
}
/**
* @inheritDoc
*/
public toTraceparent(): string {
let sampledString = '';
if (this.sampled !== undefined) {
sampledString = this.sampled ? '-1' : '-0';
}
return `${this._traceId}-${this._spanId}${sampledString}`;
}
/**
* @inheritDoc
*/
public getTraceContext(): object {
return dropUndefinedKeys({
data: Object.keys(this.data).length > 0 ? this.data : undefined,
description: this.description,
op: this.op,
parent_span_id: this._parentSpanId,
span_id: this._spanId,
status: this.tags.status,
tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,
trace_id: this._traceId,
});
}
/**
* @inheritDoc
*/
public toJSON(): object {
return dropUndefinedKeys({
data: Object.keys(this.data).length > 0 ? this.data : undefined,
description: this.description,
op: this.op,
parent_span_id: this._parentSpanId,
sampled: this.sampled,
span_id: this._spanId,
start_timestamp: this.startTimestamp,
tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,
timestamp: this.timestamp,
trace_id: this._traceId,
transaction: this.transaction,
});
}
}