-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathwithServerActionInstrumentation.ts
151 lines (137 loc) · 5.37 KB
/
withServerActionInstrumentation.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
import {
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
SPAN_STATUS_ERROR,
getIsolationScope,
withIsolationScope,
} from '@sentry/core';
import { captureException, continueTrace, getClient, handleCallbackErrors, startSpan } from '@sentry/core';
import { logger, vercelWaitUntil } from '@sentry/utils';
import { DEBUG_BUILD } from './debug-build';
import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavigationErrorUtils';
import { flushSafelyWithTimeout } from './utils/responseEnd';
import { escapeNextjsTracing } from './utils/tracingUtils';
interface Options {
formData?: FormData;
/**
* Headers as returned from `headers()`.
*
* Currently accepts both a plain `Headers` object and `Promise<ReadonlyHeaders>` to be compatible with async APIs introduced in Next.js 15: https://github.com/vercel/next.js/pull/68812
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
headers?: Headers | Promise<any>;
/**
* Whether the server action response should be included in any events captured within the server action.
*/
recordResponse?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function withServerActionInstrumentation<A extends (...args: any[]) => any>(
serverActionName: string,
callback: A,
): Promise<ReturnType<A>>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function withServerActionInstrumentation<A extends (...args: any[]) => any>(
serverActionName: string,
options: Options,
callback: A,
): Promise<ReturnType<A>>;
/**
* Wraps a Next.js Server Action implementation with Sentry Error and Performance instrumentation.
*/
export function withServerActionInstrumentation<A extends (...args: unknown[]) => unknown>(
...args: [string, Options, A] | [string, A]
): Promise<ReturnType<A>> {
if (typeof args[1] === 'function') {
const [serverActionName, callback] = args;
return withServerActionInstrumentationImplementation(serverActionName, {}, callback);
} else {
const [serverActionName, options, callback] = args;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return withServerActionInstrumentationImplementation(serverActionName, options, callback!);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function withServerActionInstrumentationImplementation<A extends (...args: any[]) => any>(
serverActionName: string,
options: Options,
callback: A,
): Promise<ReturnType<A>> {
return escapeNextjsTracing(() => {
return withIsolationScope(async isolationScope => {
const sendDefaultPii = getClient()?.getOptions().sendDefaultPii;
let sentryTraceHeader;
let baggageHeader;
const fullHeadersObject: Record<string, string> = {};
try {
const awaitedHeaders: Headers = await options.headers;
sentryTraceHeader = awaitedHeaders?.get('sentry-trace') ?? undefined;
baggageHeader = awaitedHeaders?.get('baggage');
awaitedHeaders?.forEach((value, key) => {
fullHeadersObject[key] = value;
});
} catch (e) {
DEBUG_BUILD &&
logger.warn(
"Sentry wasn't able to extract the tracing headers for a server action. Will not trace this request.",
);
}
isolationScope.setTransactionName(`serverAction/${serverActionName}`);
isolationScope.setSDKProcessingMetadata({
request: {
headers: fullHeadersObject,
},
});
return continueTrace(
{
sentryTrace: sentryTraceHeader,
baggage: baggageHeader,
},
async () => {
try {
return await startSpan(
{
op: 'function.server_action',
name: `serverAction/${serverActionName}`,
forceTransaction: true,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
},
async span => {
const result = await handleCallbackErrors(callback, error => {
if (isNotFoundNavigationError(error)) {
// We don't want to report "not-found"s
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'not_found' });
} else if (isRedirectNavigationError(error)) {
// Don't do anything for redirects
} else {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
captureException(error, {
mechanism: {
handled: false,
},
});
}
});
if (options.recordResponse !== undefined ? options.recordResponse : sendDefaultPii) {
getIsolationScope().setExtra('server_action_result', result);
}
if (options.formData) {
options.formData.forEach((value, key) => {
getIsolationScope().setExtra(
`server_action_form_data.${key}`,
typeof value === 'string' ? value : '[non-string value]',
);
});
}
return result;
},
);
} finally {
vercelWaitUntil(flushSafelyWithTimeout());
}
},
);
});
});
}