Skip to content

ref(nextjs): Remove internally used deprecated APIs #10453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/nextjs/src/common/utils/commonObjectTracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ const commonMap = new WeakMap<object, PropagationContext>();

/**
* Takes a shared (garbage collectable) object between resources, e.g. a headers object shared between Next.js server components and returns a common propagation context.
*
* @param commonObject The shared object.
* @param propagationContext The propagation context that should be shared between all the resources if no propagation context was registered yet.
* @returns the shared propagation context.
*/
export function commonObjectToPropagationContext(
commonObject: unknown,
Expand Down
20 changes: 10 additions & 10 deletions packages/nextjs/src/common/utils/responseEnd.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { ServerResponse } from 'http';
import { flush, setHttpStatus } from '@sentry/core';
import type { Transaction } from '@sentry/types';
import type { Span } from '@sentry/types';
import { fill, logger } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import type { ResponseEndMethod, WrappedResponseEndMethod } from '../types';

/**
* Wrap `res.end()` so that it closes the transaction and flushes events before letting the request finish.
* Wrap `res.end()` so that it ends the span and flushes events before letting the request finish.
*
* Note: This wraps a sync method with an async method. While in general that's not a great idea in terms of keeping
* things in the right order, in this case it's safe, because the native `.end()` actually *is* (effectively) async, and
Expand All @@ -20,13 +20,13 @@ import type { ResponseEndMethod, WrappedResponseEndMethod } from '../types';
* `end` doesn't delay data getting to the end user. See
* https://nodejs.org/api/http.html#responseenddata-encoding-callback.
*
* @param transaction The transaction tracing request handling
* @param span The span tracking the request
* @param res: The request's corresponding response
*/
export function autoEndTransactionOnResponseEnd(transaction: Transaction, res: ServerResponse): void {
export function autoEndSpanOnResponseEnd(span: Span, res: ServerResponse): void {
const wrapEndMethod = (origEnd: ResponseEndMethod): WrappedResponseEndMethod => {
return function sentryWrappedEnd(this: ServerResponse, ...args: unknown[]) {
finishTransaction(transaction, this);
finishSpan(span, this);
return origEnd.call(this, ...args);
};
};
Expand All @@ -38,11 +38,11 @@ export function autoEndTransactionOnResponseEnd(transaction: Transaction, res: S
}
}

/** Finish the given response's transaction and set HTTP status data */
export function finishTransaction(transaction: Transaction | undefined, res: ServerResponse): void {
if (transaction) {
setHttpStatus(transaction, res.statusCode);
transaction.end();
/** Finish the given response's span and set HTTP status data */
export function finishSpan(span: Span | undefined, res: ServerResponse): void {
if (span) {
setHttpStatus(span, res.statusCode);
span.end();
}
}

Expand Down
228 changes: 93 additions & 135 deletions packages/nextjs/src/common/utils/wrapperUtils.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
import type { IncomingMessage, ServerResponse } from 'http';
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
captureException,
getActiveSpan,
getActiveTransaction,
getCurrentScope,
runWithAsyncContext,
startTransaction,
continueTrace,
startInactiveSpan,
startSpan,
startSpanManual,
withActiveSpan,
withIsolationScope,
} from '@sentry/core';
import type { Span, Transaction } from '@sentry/types';
import { isString, tracingContextFromHeaders } from '@sentry/utils';
import type { Span } from '@sentry/types';
import { isString } from '@sentry/utils';

import { platformSupportsStreaming } from './platformSupportsStreaming';
import { autoEndTransactionOnResponseEnd, flushQueue } from './responseEnd';
import { autoEndSpanOnResponseEnd, flushQueue } from './responseEnd';

declare module 'http' {
interface IncomingMessage {
_sentryTransaction?: Transaction;
_sentrySpan?: Span;
}
}

/**
* Grabs a transaction off a Next.js datafetcher request object, if it was previously put there via
* `setTransactionOnRequest`.
* Grabs a span off a Next.js datafetcher request object, if it was previously put there via
* `setSpanOnRequest`.
*
* @param req The Next.js datafetcher request object
* @returns the Transaction on the request object if there is one, or `undefined` if the request object didn't have one.
* @returns the span on the request object if there is one, or `undefined` if the request object didn't have one.
*/
export function getTransactionFromRequest(req: IncomingMessage): Transaction | undefined {
return req._sentryTransaction;
export function getSpanFromRequest(req: IncomingMessage): Span | undefined {
return req._sentrySpan;
}

function setTransactionOnRequest(transaction: Transaction, req: IncomingMessage): void {
req._sentryTransaction = transaction;
function setSpanOnRequest(transaction: Span, req: IncomingMessage): void {
req._sentrySpan = transaction;
}

/**
Expand Down Expand Up @@ -85,99 +87,68 @@ export function withTracedServerSideDataFetcher<F extends (...args: any[]) => Pr
},
): (...params: Parameters<F>) => Promise<ReturnType<F>> {
return async function (this: unknown, ...args: Parameters<F>): Promise<ReturnType<F>> {
return runWithAsyncContext(async () => {
const scope = getCurrentScope();
const previousSpan: Span | undefined = getTransactionFromRequest(req) ?? getActiveSpan();
let dataFetcherSpan;
return withIsolationScope(async isolationScope => {
isolationScope.setSDKProcessingMetadata({
request: req,
});

const sentryTrace =
req.headers && isString(req.headers['sentry-trace']) ? req.headers['sentry-trace'] : undefined;
const baggage = req.headers?.baggage;
// eslint-disable-next-line deprecation/deprecation
const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(
sentryTrace,
baggage,
);
scope.setPropagationContext(propagationContext);

if (platformSupportsStreaming()) {
let spanToContinue: Span;
if (previousSpan === undefined) {
// TODO: Refactor this to use `startSpan()`
// eslint-disable-next-line deprecation/deprecation
const newTransaction = startTransaction(
return continueTrace({ sentryTrace, baggage }, () => {
let requestSpan: Span | undefined = getSpanFromRequest(req);
if (!requestSpan) {
// TODO(v8): Simplify these checks when startInactiveSpan always returns a span
requestSpan = startInactiveSpan({
name: options.requestedRouteName,
op: 'http.server',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
});
if (requestSpan) {
requestSpan.setStatus('ok');
setSpanOnRequest(requestSpan, req);
autoEndSpanOnResponseEnd(requestSpan, res);
}
}

const withActiveSpanCallback = (): Promise<ReturnType<F>> => {
return startSpanManual(
{
op: 'http.server',
name: options.requestedRouteName,
origin: 'auto.function.nextjs',
...traceparentData,
status: 'ok',
metadata: {
request: req,
source: 'route',
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
op: 'function.nextjs',
name: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
},
{ request: req },
async dataFetcherSpan => {
dataFetcherSpan?.setStatus('ok');
try {
return await origDataFetcher.apply(this, args);
} catch (e) {
dataFetcherSpan?.setStatus('internal_error');
requestSpan?.setStatus('internal_error');
throw e;
} finally {
dataFetcherSpan?.end();
if (!platformSupportsStreaming()) {
await flushQueue();
}
}
},
);
};

if (platformSupportsStreaming()) {
// On platforms that don't support streaming, doing things after res.end() is unreliable.
autoEndTransactionOnResponseEnd(newTransaction, res);
}

// Link the transaction and the request together, so that when we would normally only have access to one, it's
// still possible to grab the other.
setTransactionOnRequest(newTransaction, req);
spanToContinue = newTransaction;
if (requestSpan) {
return withActiveSpan(requestSpan, withActiveSpanCallback);
} else {
spanToContinue = previousSpan;
}

// eslint-disable-next-line deprecation/deprecation
dataFetcherSpan = spanToContinue.startChild({
op: 'function.nextjs',
description: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,
origin: 'auto.function.nextjs',
status: 'ok',
});
} else {
// TODO: Refactor this to use `startSpan()`
// eslint-disable-next-line deprecation/deprecation
dataFetcherSpan = startTransaction({
op: 'function.nextjs',
name: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,
origin: 'auto.function.nextjs',
...traceparentData,
status: 'ok',
metadata: {
request: req,
source: 'route',
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
},
});
}

// eslint-disable-next-line deprecation/deprecation
scope.setSpan(dataFetcherSpan);
scope.setSDKProcessingMetadata({ request: req });

try {
return await origDataFetcher.apply(this, args);
} catch (e) {
// Since we finish the span before the error can bubble up and trigger the handlers in `registerErrorInstrumentation`
// that set the transaction status, we need to manually set the status of the span & transaction
dataFetcherSpan.setStatus('internal_error');
previousSpan?.setStatus('internal_error');
throw e;
} finally {
dataFetcherSpan.end();
// eslint-disable-next-line deprecation/deprecation
scope.setSpan(previousSpan);
if (!platformSupportsStreaming()) {
await flushQueue();
return withActiveSpanCallback();
}
}
});
});
};
}
Expand All @@ -199,43 +170,30 @@ export async function callDataFetcherTraced<F extends (...args: any[]) => Promis
): Promise<ReturnType<F>> {
const { parameterizedRoute, dataFetchingMethodName } = options;

// eslint-disable-next-line deprecation/deprecation
const transaction = getActiveTransaction();

if (!transaction) {
return origFunction(...origFunctionArgs);
}

// TODO: Make sure that the given route matches the name of the active transaction (to prevent background data
// fetching from switching the name to a completely other route) -- We'll probably switch to creating a transaction
// right here so making that check will probabably not even be necessary.
// Logic will be: If there is no active transaction, start one with correct name and source. If there is an active
// transaction, create a child span with correct name and source.
transaction.updateName(parameterizedRoute);
transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
return startSpan(
{
op: 'function.nextjs',
name: `${dataFetchingMethodName} (${parameterizedRoute})`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
},
async dataFetcherSpan => {
dataFetcherSpan?.setStatus('ok');

// Capture the route, since pre-loading, revalidation, etc might mean that this span may happen during another
// route's transaction
// eslint-disable-next-line deprecation/deprecation
const span = transaction.startChild({
op: 'function.nextjs',
origin: 'auto.function.nextjs',
description: `${dataFetchingMethodName} (${parameterizedRoute})`,
status: 'ok',
});

try {
return await origFunction(...origFunctionArgs);
} catch (err) {
// Since we finish the span before the error can bubble up and trigger the handlers in `registerErrorInstrumentation`
// that set the transaction status, we need to manually set the status of the span & transaction
transaction.setStatus('internal_error');
span.setStatus('internal_error');
span.end();

// TODO Copy more robust error handling over from `withSentry`
captureException(err, { mechanism: { handled: false } });

throw err;
}
try {
return await origFunction(...origFunctionArgs);
} catch (e) {
dataFetcherSpan?.setStatus('internal_error');
captureException(e, { mechanism: { handled: false } });
throw e;
} finally {
dataFetcherSpan?.end();
if (!platformSupportsStreaming()) {
await flushQueue();
}
}
},
);
}
Loading