-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathedgeWrapperUtils.ts
91 lines (83 loc) · 2.86 KB
/
edgeWrapperUtils.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
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
SPAN_STATUS_OK,
captureException,
continueTrace,
handleCallbackErrors,
setHttpStatus,
startSpan,
withIsolationScope,
} from '@sentry/core';
import { vercelWaitUntil, winterCGRequestToRequestData } from '@sentry/utils';
import type { EdgeRouteHandler } from '../../edge/types';
import { flushSafelyWithTimeout } from './responseEnd';
import { commonObjectToIsolationScope, escapeNextjsTracing } from './tracingUtils';
/**
* Wraps a function on the edge runtime with error and performance monitoring.
*/
export function withEdgeWrapping<H extends EdgeRouteHandler>(
handler: H,
options: { spanDescription: string; spanOp: string; mechanismFunctionName: string },
): (...params: Parameters<H>) => Promise<ReturnType<H>> {
return async function (this: unknown, ...args) {
return escapeNextjsTracing(() => {
const req: unknown = args[0];
return withIsolationScope(commonObjectToIsolationScope(req), isolationScope => {
let sentryTrace;
let baggage;
if (req instanceof Request) {
sentryTrace = req.headers.get('sentry-trace') || '';
baggage = req.headers.get('baggage');
isolationScope.setSDKProcessingMetadata({
request: winterCGRequestToRequestData(req),
});
}
isolationScope.setTransactionName(options.spanDescription);
return continueTrace(
{
sentryTrace,
baggage,
},
() => {
return startSpan(
{
name: options.spanDescription,
op: options.spanOp,
forceTransaction: true,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.withEdgeWrapping',
},
},
async span => {
const handlerResult = await handleCallbackErrors(
() => handler.apply(this, args),
error => {
captureException(error, {
mechanism: {
type: 'instrument',
handled: false,
data: {
function: options.mechanismFunctionName,
},
},
});
},
);
if (handlerResult instanceof Response) {
setHttpStatus(span, handlerResult.status);
} else {
span.setStatus({ code: SPAN_STATUS_OK });
}
return handlerResult;
},
);
},
).finally(() => {
vercelWaitUntil(flushSafelyWithTimeout());
});
});
});
};
}