|
1 |
| -import { captureException } from '@sentry/core'; |
| 1 | +import { captureException, getCurrentHub, startTransaction } from '@sentry/core'; |
2 | 2 | import { getActiveTransaction } from '@sentry/tracing';
|
| 3 | +import { Transaction } from '@sentry/types'; |
| 4 | +import { fill } from '@sentry/utils'; |
| 5 | +import * as domain from 'domain'; |
| 6 | +import { IncomingMessage, ServerResponse } from 'http'; |
| 7 | + |
| 8 | +declare module 'http' { |
| 9 | + interface IncomingMessage { |
| 10 | + _sentryTransaction?: Transaction; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +function getTransactionFromRequest(req: IncomingMessage): Transaction | undefined { |
| 15 | + return req._sentryTransaction; |
| 16 | +} |
| 17 | + |
| 18 | +function setTransactionOnRequest(transaction: Transaction, req: IncomingMessage): void { |
| 19 | + req._sentryTransaction = transaction; |
| 20 | +} |
| 21 | + |
| 22 | +function autoEndTransactionOnResponseEnd(transaction: Transaction, res: ServerResponse): void { |
| 23 | + fill(res, 'end', (originalEnd: ServerResponse['end']) => { |
| 24 | + return function (this: unknown, ...endArguments: Parameters<ServerResponse['end']>) { |
| 25 | + transaction.finish(); |
| 26 | + return originalEnd.call(this, ...endArguments); |
| 27 | + }; |
| 28 | + }); |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Wraps a function that potentially throws. If it does, the error is passed to `captureException` and retrhrown. |
| 33 | + */ |
| 34 | +export function withErrorInstrumentation<F extends (...args: any[]) => any>( |
| 35 | + origFunction: F, |
| 36 | +): (...params: Parameters<F>) => ReturnType<F> { |
| 37 | + return function (this: unknown, ...origFunctionArguments: Parameters<F>): ReturnType<F> { |
| 38 | + const potentialPromiseResult = origFunction.call(this, ...origFunctionArguments); |
| 39 | + // We do this instead of await so we do not change the method signature of the passed function from `() => unknown` to `() => Promise<unknown>` |
| 40 | + Promise.resolve(potentialPromiseResult).catch(err => { |
| 41 | + // TODO: Extract error logic from `withSentry` in here or create a new wrapper with said logic or something like that. |
| 42 | + captureException(err); |
| 43 | + }); |
| 44 | + return potentialPromiseResult; |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Calls a server-side data fetching function (that takes a `req` and `res` object in its context) with tracing |
| 50 | + * instrumentation. A transaction will be created for the incoming request (if it doesn't already exist) in addition to |
| 51 | + * a span for the wrapped data fetching function. |
| 52 | + * |
| 53 | + * All of the above happens in an isolated domain, meaning all thrown errors will be associated with the correct span. |
| 54 | + * |
| 55 | + * @param origFunction The data fetching method to call. |
| 56 | + * @param origFunctionArguments The arguments to call the data fetching method with. |
| 57 | + * @param req The data fetching function's request object. |
| 58 | + * @param res The data fetching function's response object. |
| 59 | + * @param options Options providing details for the created transaction and span. |
| 60 | + * @returns what the data fetching method call returned. |
| 61 | + */ |
| 62 | +export function callServerSideDataFetcherWithTracingInstrumentation<F extends (...args: any[]) => Promise<any> | any>( |
| 63 | + origFunction: F, |
| 64 | + origFunctionArguments: Parameters<F>, |
| 65 | + req: IncomingMessage, |
| 66 | + res: ServerResponse, |
| 67 | + options: { |
| 68 | + parameterizedRoute: string; |
| 69 | + functionName: string; |
| 70 | + }, |
| 71 | +): Promise<ReturnType<F>> { |
| 72 | + return domain.create().bind(async () => { |
| 73 | + let requestTransaction: Transaction | undefined = getTransactionFromRequest(req); |
| 74 | + |
| 75 | + if (requestTransaction === undefined) { |
| 76 | + // TODO: Extract trace data from `req` object (trace and baggage headers) and attach it to transaction |
| 77 | + |
| 78 | + const newTransaction = startTransaction({ |
| 79 | + op: 'nextjs.data', |
| 80 | + name: options.parameterizedRoute, |
| 81 | + metadata: { |
| 82 | + source: 'route', |
| 83 | + }, |
| 84 | + }); |
| 85 | + |
| 86 | + requestTransaction = newTransaction; |
| 87 | + autoEndTransactionOnResponseEnd(newTransaction, res); |
| 88 | + setTransactionOnRequest(newTransaction, req); |
| 89 | + } |
| 90 | + |
| 91 | + const dataFetcherSpan = requestTransaction.startChild({ |
| 92 | + op: 'nextjs.data', |
| 93 | + description: `${options.functionName} (${options.parameterizedRoute})`, |
| 94 | + }); |
| 95 | + |
| 96 | + const currentScope = getCurrentHub().getScope(); |
| 97 | + if (currentScope) { |
| 98 | + currentScope.setSpan(dataFetcherSpan); |
| 99 | + } |
| 100 | + |
| 101 | + try { |
| 102 | + // TODO: Inject trace data into returned props |
| 103 | + return await origFunction(...origFunctionArguments); |
| 104 | + } finally { |
| 105 | + dataFetcherSpan.finish(); |
| 106 | + } |
| 107 | + })(); |
| 108 | +} |
3 | 109 |
|
4 | 110 | /**
|
5 | 111 | * Call a data fetcher and trace it. Only traces the function if there is an active transaction on the scope.
|
6 | 112 | *
|
7 | 113 | * We only do the following until we move transaction creation into this function: When called, the wrapped function
|
8 | 114 | * will also update the name of the active transaction with a parameterized route provided via the `options` argument.
|
9 | 115 | */
|
| 116 | +// TODO: Delete this helper. It is only used by getStaticProps because it is so different from the other data fetching methods. |
10 | 117 | export async function callDataFetcherTraced<F extends (...args: any[]) => Promise<any> | any>(
|
11 | 118 | origFunction: F,
|
12 | 119 | origFunctionArgs: Parameters<F>,
|
@@ -40,13 +147,7 @@ export async function callDataFetcherTraced<F extends (...args: any[]) => Promis
|
40 | 147 |
|
41 | 148 | try {
|
42 | 149 | return await origFunction(...origFunctionArgs);
|
43 |
| - } catch (err) { |
44 |
| - if (span) { |
45 |
| - span.finish(); |
46 |
| - } |
47 |
| - |
48 |
| - // TODO Copy more robust error handling over from `withSentry` |
49 |
| - captureException(err); |
50 |
| - throw err; |
| 150 | + } finally { |
| 151 | + span.finish(); |
51 | 152 | }
|
52 | 153 | }
|
0 commit comments