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