Skip to content

fix(nextjs): Use Proxies to wrap to preserve static methods #7002

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 2 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
28 changes: 15 additions & 13 deletions packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,24 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
handler: H,
parameterizedRoute: string,
): (...params: Parameters<H>) => Promise<ReturnType<H>> {
return async function (this: unknown, ...args: Parameters<H>): Promise<ReturnType<H>> {
const req = args[0];
return new Proxy(handler, {
apply: async (wrappingTarget, thisArg, args: Parameters<H>) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this supported, e.g. having an async apply? Just wondering :D I guess we don't even really need it here, though? Or am I missing something?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the term "supported" but from my testing, using an async function just seems to return a promise which is about what I would expect to happen. We definitely need it here though because we wanna await the result so that the events are flushed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, good, if it works then 👍 maybe it is just a restriction for get based proxies, I vaguely remember having issues with such a thing in the past. But all good then, nice!

const req = args[0];

const activeSpan = !!getCurrentHub().getScope()?.getSpan();
const activeSpan = !!getCurrentHub().getScope()?.getSpan();

const wrappedHandler = withEdgeWrapping(handler, {
spanDescription:
activeSpan || !(req instanceof Request)
? `handler (${parameterizedRoute})`
: `${req.method} ${parameterizedRoute}`,
spanOp: activeSpan ? 'function' : 'http.server',
mechanismFunctionName: 'wrapApiHandlerWithSentry',
});
const wrappedHandler = withEdgeWrapping(wrappingTarget, {
spanDescription:
activeSpan || !(req instanceof Request)
? `handler (${parameterizedRoute})`
: `${req.method} ${parameterizedRoute}`,
spanOp: activeSpan ? 'function' : 'http.server',
mechanismFunctionName: 'wrapApiHandlerWithSentry',
});

return await wrappedHandler.apply(this, args);
};
return await wrappedHandler.apply(thisArg, args);
},
});
}

/**
Expand Down
12 changes: 8 additions & 4 deletions packages/nextjs/src/edge/wrapMiddlewareWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ import { withEdgeWrapping } from './utils/edgeWrapperUtils';
export function wrapMiddlewareWithSentry<H extends EdgeRouteHandler>(
middleware: H,
): (...params: Parameters<H>) => Promise<ReturnType<H>> {
return withEdgeWrapping(middleware, {
spanDescription: 'middleware',
spanOp: 'middleware.nextjs',
mechanismFunctionName: 'withSentryMiddleware',
return new Proxy(middleware, {
apply: async (wrappingTarget, thisArg, args: Parameters<H>) => {
return withEdgeWrapping(wrappingTarget, {
spanDescription: 'middleware',
spanOp: 'middleware.nextjs',
mechanismFunctionName: 'withSentryMiddleware',
}).apply(thisArg, args);
},
});
}
31 changes: 0 additions & 31 deletions packages/nextjs/src/server/utils/nextLogger.ts

This file was deleted.

343 changes: 164 additions & 179 deletions packages/nextjs/src/server/wrapApiHandlerWithSentry.ts

Large diffs are not rendered by default.

88 changes: 45 additions & 43 deletions packages/nextjs/src/server/wrapAppGetInitialPropsWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,58 +21,60 @@ type AppGetInitialProps = typeof App['getInitialProps'];
* @returns A wrapped version of the function
*/
export function wrapAppGetInitialPropsWithSentry(origAppGetInitialProps: AppGetInitialProps): AppGetInitialProps {
return async function (this: unknown, ...args: Parameters<AppGetInitialProps>): ReturnType<AppGetInitialProps> {
if (isBuild()) {
return origAppGetInitialProps.apply(this, args);
}
return new Proxy(origAppGetInitialProps, {
apply: async (wrappingTarget, thisArg, args: Parameters<AppGetInitialProps>) => {
if (isBuild()) {
return wrappingTarget.apply(thisArg, args);
}

const [context] = args;
const { req, res } = context.ctx;
const [context] = args;
const { req, res } = context.ctx;

const errorWrappedAppGetInitialProps = withErrorInstrumentation(origAppGetInitialProps);
const options = getCurrentHub().getClient()?.getOptions();
const errorWrappedAppGetInitialProps = withErrorInstrumentation(wrappingTarget);
const options = getCurrentHub().getClient()?.getOptions();

// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedAppGetInitialProps, req, res, {
dataFetcherRouteName: '/_app',
requestedRouteName: context.ctx.pathname,
dataFetchingMethodName: 'getInitialProps',
});
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedAppGetInitialProps, req, res, {
dataFetcherRouteName: '/_app',
requestedRouteName: context.ctx.pathname,
dataFetchingMethodName: 'getInitialProps',
});

const appGetInitialProps: {
pageProps: {
_sentryTraceData?: string;
_sentryBaggage?: string;
};
} = await tracedGetInitialProps.apply(this, args);
const appGetInitialProps: {
pageProps: {
_sentryTraceData?: string;
_sentryBaggage?: string;
};
} = await tracedGetInitialProps.apply(thisArg, args);

const requestTransaction = getTransactionFromRequest(req);
const requestTransaction = getTransactionFromRequest(req);

// Per definition, `pageProps` is not optional, however an increased amount of users doesn't seem to call
// `App.getInitialProps(appContext)` in their custom `_app` pages which is required as per
// https://nextjs.org/docs/advanced-features/custom-app - resulting in missing `pageProps`.
// For this reason, we just handle the case where `pageProps` doesn't exist explicitly.
if (!appGetInitialProps.pageProps) {
appGetInitialProps.pageProps = {};
}
// Per definition, `pageProps` is not optional, however an increased amount of users doesn't seem to call
// `App.getInitialProps(appContext)` in their custom `_app` pages which is required as per
// https://nextjs.org/docs/advanced-features/custom-app - resulting in missing `pageProps`.
// For this reason, we just handle the case where `pageProps` doesn't exist explicitly.
if (!appGetInitialProps.pageProps) {
appGetInitialProps.pageProps = {};
}

if (requestTransaction) {
appGetInitialProps.pageProps._sentryTraceData = requestTransaction.toTraceparent();
if (requestTransaction) {
appGetInitialProps.pageProps._sentryTraceData = requestTransaction.toTraceparent();

const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();
appGetInitialProps.pageProps._sentryBaggage =
dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
}
const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();
appGetInitialProps.pageProps._sentryBaggage =
dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
}

return appGetInitialProps;
} else {
return errorWrappedAppGetInitialProps.apply(this, args);
}
};
return appGetInitialProps;
} else {
return errorWrappedAppGetInitialProps.apply(thisArg, args);
}
},
});
}

/**
Expand Down
59 changes: 29 additions & 30 deletions packages/nextjs/src/server/wrapDocumentGetInitialPropsWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,35 @@ type DocumentGetInitialProps = typeof Document.getInitialProps;
export function wrapDocumentGetInitialPropsWithSentry(
origDocumentGetInitialProps: DocumentGetInitialProps,
): DocumentGetInitialProps {
return async function (
this: unknown,
...args: Parameters<DocumentGetInitialProps>
): ReturnType<DocumentGetInitialProps> {
if (isBuild()) {
return origDocumentGetInitialProps.apply(this, args);
}

const [context] = args;
const { req, res } = context;

const errorWrappedGetInitialProps = withErrorInstrumentation(origDocumentGetInitialProps);
const options = getCurrentHub().getClient()?.getOptions();

// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_document',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});

return await tracedGetInitialProps.apply(this, args);
} else {
return errorWrappedGetInitialProps.apply(this, args);
}
};
return new Proxy(origDocumentGetInitialProps, {
apply: async (wrappingTarget, thisArg, args: Parameters<DocumentGetInitialProps>) => {
if (isBuild()) {
return wrappingTarget.apply(thisArg, args);
}

const [context] = args;
const { req, res } = context;

const errorWrappedGetInitialProps = withErrorInstrumentation(wrappingTarget);
const options = getCurrentHub().getClient()?.getOptions();

// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_document',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});

return await tracedGetInitialProps.apply(thisArg, args);
} else {
return errorWrappedGetInitialProps.apply(thisArg, args);
}
},
});
}

/**
Expand Down
68 changes: 35 additions & 33 deletions packages/nextjs/src/server/wrapErrorGetInitialPropsWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,46 +24,48 @@ type ErrorGetInitialProps = (context: NextPageContext) => Promise<ErrorProps>;
export function wrapErrorGetInitialPropsWithSentry(
origErrorGetInitialProps: ErrorGetInitialProps,
): ErrorGetInitialProps {
return async function (this: unknown, ...args: Parameters<ErrorGetInitialProps>): ReturnType<ErrorGetInitialProps> {
if (isBuild()) {
return origErrorGetInitialProps.apply(this, args);
}
return new Proxy(origErrorGetInitialProps, {
apply: async (wrappingTarget, thisArg, args: Parameters<ErrorGetInitialProps>) => {
if (isBuild()) {
return wrappingTarget.apply(thisArg, args);
}

const [context] = args;
const { req, res } = context;
const [context] = args;
const { req, res } = context;

const errorWrappedGetInitialProps = withErrorInstrumentation(origErrorGetInitialProps);
const options = getCurrentHub().getClient()?.getOptions();
const errorWrappedGetInitialProps = withErrorInstrumentation(wrappingTarget);
const options = getCurrentHub().getClient()?.getOptions();

// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_error',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (hasTracingEnabled() && req && res && options?.instrumenter === 'sentry') {
const tracedGetInitialProps = withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_error',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});

const errorGetInitialProps: ErrorProps & {
_sentryTraceData?: string;
_sentryBaggage?: string;
} = await tracedGetInitialProps.apply(this, args);
const errorGetInitialProps: ErrorProps & {
_sentryTraceData?: string;
_sentryBaggage?: string;
} = await tracedGetInitialProps.apply(thisArg, args);

const requestTransaction = getTransactionFromRequest(req);
if (requestTransaction) {
errorGetInitialProps._sentryTraceData = requestTransaction.toTraceparent();
const requestTransaction = getTransactionFromRequest(req);
if (requestTransaction) {
errorGetInitialProps._sentryTraceData = requestTransaction.toTraceparent();

const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();
errorGetInitialProps._sentryBaggage = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
}
const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();
errorGetInitialProps._sentryBaggage = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
}

return errorGetInitialProps;
} else {
return errorWrappedGetInitialProps.apply(this, args);
}
};
return errorGetInitialProps;
} else {
return errorWrappedGetInitialProps.apply(thisArg, args);
}
},
});
}

/**
Expand Down
Loading