-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtraceLinks.ts
More file actions
84 lines (77 loc) · 2.49 KB
/
traceLinks.ts
File metadata and controls
84 lines (77 loc) · 2.49 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
import type { DurableObjectStorage } from '@cloudflare/workers-types';
import { TraceFlags } from '@opentelemetry/api';
import { getActiveSpan } from '@sentry/core';
/** Storage key prefix for the span context that links consecutive method invocations */
const SENTRY_TRACE_LINK_KEY_PREFIX = '__SENTRY_TRACE_LINK__';
/** Stored span context for creating span links */
export interface StoredSpanContext {
traceId: string;
spanId: string;
sampled: boolean;
}
/** Span link structure for connecting traces */
export interface SpanLink {
context: {
traceId: string;
spanId: string;
traceFlags: number;
};
attributes?: Record<string, string>;
}
/**
* Gets the storage key for a specific method's trace link.
*/
export function getTraceLinkKey(methodName: string): string {
return `${SENTRY_TRACE_LINK_KEY_PREFIX}${methodName}`;
}
/**
* Stores the current span context in Durable Object storage for trace linking.
* Uses the original uninstrumented storage to avoid creating spans for internal operations.
* Errors are silently ignored to prevent internal storage failures from propagating to user code.
*/
export async function storeSpanContext(originalStorage: DurableObjectStorage, methodName: string): Promise<void> {
try {
const activeSpan = getActiveSpan();
if (activeSpan) {
const spanContext = activeSpan.spanContext();
const storedContext: StoredSpanContext = {
traceId: spanContext.traceId,
spanId: spanContext.spanId,
sampled: spanContext.traceFlags === TraceFlags.SAMPLED,
};
await originalStorage.put(getTraceLinkKey(methodName), storedContext);
}
} catch {
// Silently ignore storage errors to prevent internal failures from affecting user code
}
}
/**
* Retrieves a stored span context from Durable Object storage.
*/
export async function getStoredSpanContext(
originalStorage: DurableObjectStorage,
methodName: string,
): Promise<StoredSpanContext | undefined> {
try {
return await originalStorage.get<StoredSpanContext>(getTraceLinkKey(methodName));
} catch {
return undefined;
}
}
/**
* Builds span links from a stored span context.
*/
export function buildSpanLinks(storedContext: StoredSpanContext): SpanLink[] {
return [
{
context: {
traceId: storedContext.traceId,
spanId: storedContext.spanId,
traceFlags: storedContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
},
attributes: {
'sentry.link.type': 'previous_trace',
},
},
];
}