Skip to content
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

feat(nextjs): Use OTEL tracing for pages router #13739

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 1 addition & 1 deletion packages/nextjs/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { applyTunnelRouteOption } from './tunnelRoute';

export * from '@sentry/react';

export { captureUnderscoreErrorException } from '../common/_error';
export { captureUnderscoreErrorException } from '../common/pages-router-instrumentation/_error';

const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
__rewriteFramesAssetPrefixPath__: string;
Expand Down
26 changes: 13 additions & 13 deletions packages/nextjs/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
export { wrapGetStaticPropsWithSentry } from './wrapGetStaticPropsWithSentry';
export { wrapGetInitialPropsWithSentry } from './wrapGetInitialPropsWithSentry';
export { wrapAppGetInitialPropsWithSentry } from './wrapAppGetInitialPropsWithSentry';
export { wrapDocumentGetInitialPropsWithSentry } from './wrapDocumentGetInitialPropsWithSentry';
export { wrapErrorGetInitialPropsWithSentry } from './wrapErrorGetInitialPropsWithSentry';
export { wrapGetServerSidePropsWithSentry } from './wrapGetServerSidePropsWithSentry';
export { wrapServerComponentWithSentry } from './wrapServerComponentWithSentry';
export { wrapRouteHandlerWithSentry } from './wrapRouteHandlerWithSentry';
export { wrapApiHandlerWithSentryVercelCrons } from './wrapApiHandlerWithSentryVercelCrons';
export { wrapMiddlewareWithSentry } from './wrapMiddlewareWithSentry';
export { wrapPageComponentWithSentry } from './wrapPageComponentWithSentry';
export { wrapGenerationFunctionWithSentry } from './wrapGenerationFunctionWithSentry';
export { wrapApiHandlerWithSentryVercelCrons } from './pages-router-instrumentation/wrapApiHandlerWithSentryVercelCrons';
export { wrapAppGetInitialPropsWithSentry } from './pages-router-instrumentation/wrapAppGetInitialPropsWithSentry';
export { wrapDocumentGetInitialPropsWithSentry } from './pages-router-instrumentation/wrapDocumentGetInitialPropsWithSentry';
export { wrapErrorGetInitialPropsWithSentry } from './pages-router-instrumentation/wrapErrorGetInitialPropsWithSentry';
export { wrapGetInitialPropsWithSentry } from './pages-router-instrumentation/wrapGetInitialPropsWithSentry';
export { wrapGetServerSidePropsWithSentry } from './pages-router-instrumentation/wrapGetServerSidePropsWithSentry';
export { wrapGetStaticPropsWithSentry } from './pages-router-instrumentation/wrapGetStaticPropsWithSentry';
export { wrapPageComponentWithSentry } from './pages-router-instrumentation/wrapPageComponentWithSentry';
export { withServerActionInstrumentation } from './withServerActionInstrumentation';
export { wrapGenerationFunctionWithSentry } from './wrapGenerationFunctionWithSentry';
export { wrapMiddlewareWithSentry } from './wrapMiddlewareWithSentry';
export { wrapRouteHandlerWithSentry } from './wrapRouteHandlerWithSentry';
export { wrapServerComponentWithSentry } from './wrapServerComponentWithSentry';
// eslint-disable-next-line deprecation/deprecation
export { experimental_captureRequestError, captureRequestError } from './captureRequestError';
export { captureRequestError, experimental_captureRequestError } from './captureRequestError';
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { captureException, withScope } from '@sentry/core';
import type { NextPageContext } from 'next';
import { flushSafelyWithTimeout } from './utils/responseEnd';
import { vercelWaitUntil } from './utils/vercelWaitUntil';
import { flushSafelyWithTimeout } from '../utils/responseEnd';
import { vercelWaitUntil } from '../utils/vercelWaitUntil';

type ContextOrProps = {
req?: NextPageContext['req'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {
import { consoleSandbox, isString, logger, objectify } from '@sentry/utils';

import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
import type { AugmentedNextApiRequest, AugmentedNextApiResponse, NextApiHandler } from './types';
import { flushSafelyWithTimeout } from './utils/responseEnd';
import { escapeNextjsTracing } from './utils/tracingUtils';
import { vercelWaitUntil } from './utils/vercelWaitUntil';
import type { AugmentedNextApiRequest, AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout } from '../utils/responseEnd';
import { escapeNextjsTracing } from '../utils/tracingUtils';
import { vercelWaitUntil } from '../utils/vercelWaitUntil';

/**
* Wrap the given API route handler for tracing and error capturing. Thin wrapper around `withSentry`, which only
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { captureCheckIn } from '@sentry/core';
import type { NextApiRequest } from 'next';

import type { VercelCronsConfig } from './types';
import type { VercelCronsConfig } from '../types';

type EdgeRequest = {
nextUrl: URL;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type App from 'next/app';

import { isBuild } from './utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from '../utils/wrapperUtils';

type AppGetInitialProps = (typeof App)['getInitialProps'];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type Document from 'next/document';

import { isBuild } from './utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from '../utils/wrapperUtils';

type DocumentGetInitialProps = typeof Document.getInitialProps;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { NextPageContext } from 'next';
import type { ErrorProps } from 'next/error';

import { isBuild } from './utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from '../utils/wrapperUtils';

type ErrorGetInitialProps = (context: NextPageContext) => Promise<ErrorProps>;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { NextPage } from 'next';

import { isBuild } from './utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from '../utils/wrapperUtils';

type GetInitialProps = Required<NextPage>['getInitialProps'];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { GetServerSideProps } from 'next';

import { isBuild } from './utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { withErrorInstrumentation, withTracedServerSideDataFetcher } from '../utils/wrapperUtils';

/**
* Create a wrapped version of the user's exported `getServerSideProps` function
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { GetStaticProps } from 'next';

import { isBuild } from './utils/isBuild';
import { callDataFetcherTraced, withErrorInstrumentation } from './utils/wrapperUtils';
import { isBuild } from '../utils/isBuild';
import { callDataFetcherTraced, withErrorInstrumentation } from '../utils/wrapperUtils';

type Props = { [key: string]: unknown };

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { captureException, getCurrentScope, withIsolationScope } from '@sentry/core';
import { extractTraceparentData } from '@sentry/utils';
import { escapeNextjsTracing } from './utils/tracingUtils';
import { escapeNextjsTracing } from '../utils/tracingUtils';

interface FunctionComponent {
(...args: unknown[]): unknown;
Expand Down
98 changes: 54 additions & 44 deletions packages/nextjs/src/common/utils/wrapperUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
SPAN_STATUS_OK,
captureException,
continueTrace,
getActiveSpan,
getRootSpan,
getTraceData,
startInactiveSpan,
startSpan,
Expand All @@ -17,7 +19,7 @@ import type { Span } from '@sentry/types';
import { isString } from '@sentry/utils';

import { autoEndSpanOnResponseEnd, flushSafelyWithTimeout } from './responseEnd';
import { commonObjectToIsolationScope, escapeNextjsTracing } from './tracingUtils';
import { commonObjectToIsolationScope } from './tracingUtils';
import { vercelWaitUntil } from './vercelWaitUntil';

declare module 'http' {
Expand Down Expand Up @@ -94,49 +96,49 @@ export function withTracedServerSideDataFetcher<F extends (...args: any[]) => Pr
this: unknown,
...args: Parameters<F>
): Promise<{ data: ReturnType<F>; sentryTrace?: string; baggage?: string }> {
return escapeNextjsTracing(() => {
const isolationScope = commonObjectToIsolationScope(req);
return withIsolationScope(isolationScope, () => {
isolationScope.setTransactionName(`${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`);
isolationScope.setSDKProcessingMetadata({
request: req,
});
const isolationScope = commonObjectToIsolationScope(req);
return withIsolationScope(isolationScope, () => {
isolationScope.setTransactionName(`${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`);
isolationScope.setSDKProcessingMetadata({
request: req,
});

const sentryTrace =
req.headers && isString(req.headers['sentry-trace']) ? req.headers['sentry-trace'] : undefined;
const baggage = req.headers?.baggage;

return continueTrace({ sentryTrace, baggage }, () => {
const requestSpan = getOrStartRequestSpan(req, res, options.requestedRouteName);
return withActiveSpan(requestSpan, () => {
return startSpanManual(
{
op: 'function.nextjs',
name: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
const sentryTrace =
req.headers && isString(req.headers['sentry-trace']) ? req.headers['sentry-trace'] : undefined;
const baggage = req.headers?.baggage;

return continueTrace({ sentryTrace, baggage }, () => {
const overarchingSpan = getOrStartOverarchingSpan(req, res, options.requestedRouteName);
getRootSpan(overarchingSpan).setAttribute('sentry.datafetcher', true);

return withActiveSpan(overarchingSpan, () => {
return startSpanManual(
{
op: 'function.nextjs',
name: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
},
async dataFetcherSpan => {
dataFetcherSpan.setStatus({ code: SPAN_STATUS_OK });
const { 'sentry-trace': sentryTrace, baggage } = getTraceData();
try {
return {
sentryTrace: sentryTrace,
baggage: baggage,
data: await origDataFetcher.apply(this, args),
};
} catch (e) {
dataFetcherSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
requestSpan?.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
throw e;
} finally {
dataFetcherSpan.end();
}
},
);
});
},
async dataFetcherSpan => {
dataFetcherSpan.setStatus({ code: SPAN_STATUS_OK });
const { 'sentry-trace': sentryTrace, baggage } = getTraceData();
try {
return {
sentryTrace: sentryTrace,
baggage: baggage,
data: await origDataFetcher.apply(this, args),
};
} catch (e) {
dataFetcherSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
overarchingSpan?.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
throw e;
} finally {
dataFetcherSpan.end();
}
},
);
});
});
}).finally(() => {
Expand All @@ -145,14 +147,22 @@ export function withTracedServerSideDataFetcher<F extends (...args: any[]) => Pr
};
}

function getOrStartRequestSpan(req: IncomingMessage, res: ServerResponse, name: string): Span {
/**
* TODO
*/
function getOrStartOverarchingSpan(req: IncomingMessage, res: ServerResponse, routeName: string): Span {
const activeSpan = getActiveSpan();
if (activeSpan) {
return activeSpan;
}

const existingSpan = getSpanFromRequest(req);
if (existingSpan) {
return existingSpan;
}

const requestSpan = startInactiveSpan({
name,
name: req.method ? `${req.method} ${routeName}` : routeName,
forceTransaction: true,
op: 'http.server',
attributes: {
Expand Down
25 changes: 16 additions & 9 deletions packages/nextjs/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { GLOBAL_OBJ, logger } from '@sentry/utils';
import {
ATTR_HTTP_REQUEST_METHOD,
ATTR_HTTP_ROUTE,
ATTR_URL_QUERY,
SEMATTRS_HTTP_METHOD,
SEMATTRS_HTTP_TARGET,
} from '@opentelemetry/semantic-conventions';
Expand All @@ -26,7 +27,7 @@ import { distDirRewriteFramesIntegration } from './distDirRewriteFramesIntegrati

export * from '@sentry/node';

export { captureUnderscoreErrorException } from '../common/_error';
export { captureUnderscoreErrorException } from '../common/pages-router-instrumentation/_error';

const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
__rewriteFramesDistDir__?: string;
Expand Down Expand Up @@ -157,11 +158,14 @@ export function init(options: NodeOptions): NodeClient | undefined {
// We need to drop these spans.
if (
// eslint-disable-next-line deprecation/deprecation
typeof spanAttributes[SEMATTRS_HTTP_TARGET] === 'string' &&
// eslint-disable-next-line deprecation/deprecation
spanAttributes[SEMATTRS_HTTP_TARGET].includes('sentry_key') &&
// eslint-disable-next-line deprecation/deprecation
spanAttributes[SEMATTRS_HTTP_TARGET].includes('sentry_client')
(typeof spanAttributes[SEMATTRS_HTTP_TARGET] === 'string' &&
// eslint-disable-next-line deprecation/deprecation
spanAttributes[SEMATTRS_HTTP_TARGET].includes('sentry_key') &&
// eslint-disable-next-line deprecation/deprecation
spanAttributes[SEMATTRS_HTTP_TARGET].includes('sentry_client')) ||
(typeof spanAttributes[ATTR_URL_QUERY] === 'string' &&
spanAttributes[ATTR_URL_QUERY].includes('sentry_key') &&
spanAttributes[ATTR_URL_QUERY].includes('sentry_client'))
) {
samplingDecision.decision = false;
}
Expand Down Expand Up @@ -211,11 +215,14 @@ export function init(options: NodeOptions): NodeClient | undefined {
return null;
}

// We only want to use our HTTP integration/instrumentation for app router requests, which are marked with the `sentry.rsc` attribute.
// We only want to use our HTTP integration/instrumentation for
// - app router requests, which are marked with the `sentry.rsc` attribute.
// - pages router requests, which are marked with the `sentry.datafetcher` attribute.
if (
(event.contexts?.trace?.data?.[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] === 'auto.http.otel.http' ||
event.contexts?.trace?.data?.['next.span_type'] === 'BaseServer.handleRequest') &&
event.contexts?.trace?.data?.['sentry.rsc'] !== true
event.contexts?.trace?.data?.['sentry.rsc'] !== true &&
event.contexts?.trace?.data?.['sentry.datafetcher'] !== true
) {
return null;
}
Expand Down Expand Up @@ -325,4 +332,4 @@ function sdkAlreadyInitialized(): boolean {

export * from '../common';

export { wrapApiHandlerWithSentry } from '../common/wrapApiHandlerWithSentry';
export { wrapApiHandlerWithSentry } from '../common/pages-router-instrumentation/wrapApiHandlerWithSentry';
Loading