forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactiveSpans.ts
More file actions
77 lines (65 loc) · 2.39 KB
/
activeSpans.ts
File metadata and controls
77 lines (65 loc) · 2.39 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
import type {StartSpanOptions} from '@sentry/core';
import * as Sentry from '@sentry/react-native';
import Log from '@libs/Log';
import CONST from '@src/CONST';
const activeSpans = new Map<string, ReturnType<typeof Sentry.startInactiveSpan>>();
const spanStartTimes = new Map<string, number>();
type StartSpanExtraOptions = Partial<{
/**
* Minimum duration of the span in milliseconds. If the span is shorter than this duration, it will be discarded (filtered out) before sending to Sentry.
*
*/
minDuration: number;
}>;
function startSpan(spanId: string, options: StartSpanOptions, extraOptions: StartSpanExtraOptions = {}) {
// End any existing span for this name
cancelSpan(spanId);
const span = Sentry.startInactiveSpan(options);
if (extraOptions.minDuration) {
span.setAttribute(CONST.TELEMETRY.ATTRIBUTE_MIN_DURATION, extraOptions.minDuration);
}
activeSpans.set(spanId, span);
spanStartTimes.set(spanId, options.startTime ? Number(options.startTime) * 1000 : Date.now());
return span;
}
function endSpan(spanId: string) {
const span = activeSpans.get(spanId);
if (!span) {
return;
}
span.setStatus({code: 1});
span.setAttribute(CONST.TELEMETRY.ATTRIBUTE_FINISHED_MANUALLY, true);
span.end();
if (__DEV__) {
const startTime = spanStartTimes.get(spanId);
if (startTime !== undefined) {
Log.info(`[Telemetry] Span "${spanId}" duration: ${Date.now() - startTime}ms`);
}
}
activeSpans.delete(spanId);
spanStartTimes.delete(spanId);
}
function cancelSpan(spanId: string) {
const span = activeSpans.get(spanId);
span?.setAttribute(CONST.TELEMETRY.ATTRIBUTE_CANCELED, true);
// In Sentry there are only OK or ERROR status codes.
// We treat canceled spans as OK, so we can properly track spans that are not finished at all (their status would be different)
span?.setStatus({code: 1});
endSpan(spanId);
}
function cancelAllSpans() {
for (const [spanId] of activeSpans.entries()) {
cancelSpan(spanId);
}
}
function cancelSpansByPrefix(prefix: string) {
for (const [spanID] of activeSpans.entries()) {
if (spanID.startsWith(prefix)) {
cancelSpan(spanID);
}
}
}
function getSpan(spanId: string) {
return activeSpans.get(spanId);
}
export {startSpan, endSpan, getSpan, cancelSpan, cancelAllSpans, cancelSpansByPrefix};