Skip to content

Commit

Permalink
ref: Set normalizedRequest instead of request various places
Browse files Browse the repository at this point in the history
The request data integration prefers this over `request`, we want to get rid of `request` in v9.

Part of #14298
  • Loading branch information
mydea committed Nov 14, 2024
1 parent f4c5900 commit 68a27e5
Show file tree
Hide file tree
Showing 13 changed files with 52 additions and 40 deletions.
2 changes: 1 addition & 1 deletion packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async function instrumentRequest(
getCurrentScope().setSDKProcessingMetadata({
// We store the request on the current scope, not isolation scope,
// because we may have multiple requests nested inside each other
request: isDynamicPageRequest ? winterCGRequestToRequestData(request) : { method, url: request.url },
normalizedRequest: isDynamicPageRequest ? winterCGRequestToRequestData(request) : { method, url: request.url },
});

if (options.trackClientIp && isDynamicPageRequest) {
Expand Down
6 changes: 3 additions & 3 deletions packages/bun/src/integrations/bunserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
startSpan,
withIsolationScope,
} from '@sentry/core';
import type { IntegrationFn, SpanAttributes } from '@sentry/types';
import type { IntegrationFn, Request, SpanAttributes } from '@sentry/types';
import { getSanitizedUrlString, parseUrl } from '@sentry/utils';

const INTEGRATION_NAME = 'BunServer';
Expand Down Expand Up @@ -76,11 +76,11 @@ function instrumentBunServeOptions(serveOptions: Parameters<typeof Bun.serve>[0]
const url = getSanitizedUrlString(parsedUrl);

isolationScope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
url,
method: request.method,
headers: request.headers.toJSON(),
},
} satisfies Request,
});

return continueTrace(
Expand Down
2 changes: 1 addition & 1 deletion packages/cloudflare/src/scope-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ export function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties)
* Set request data on scope
*/
export function addRequest(scope: Scope, request: Request): void {
scope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(request) });
scope.setSDKProcessingMetadata({ normalizedRequest: winterCGRequestToRequestData(request) });
}
8 changes: 5 additions & 3 deletions packages/nextjs/src/common/captureRequestError.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { captureException, withScope } from '@sentry/core';
import type { Request } from '@sentry/types';
import { headersToDict } from '@sentry/utils';

type RequestInfo = {
path: string;
Expand All @@ -18,10 +20,10 @@ type ErrorContext = {
export function captureRequestError(error: unknown, request: RequestInfo, errorContext: ErrorContext): void {
withScope(scope => {
scope.setSDKProcessingMetadata({
request: {
headers: request.headers,
normalizedRequest: {
headers: headersToDict(request.headers),
method: request.method,
},
} satisfies Request,
});

scope.setContext('nextjs', {
Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/src/common/withServerActionInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
startSpan,
withIsolationScope,
} from '@sentry/core';
import type { Request } from '@sentry/types';
import { logger, vercelWaitUntil } from '@sentry/utils';

import { DEBUG_BUILD } from './debug-build';
Expand Down Expand Up @@ -89,9 +90,9 @@ async function withServerActionInstrumentationImplementation<A extends (...args:

isolationScope.setTransactionName(`serverAction/${serverActionName}`);
isolationScope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
headers: fullHeadersObject,
},
} satisfies Request,
});

return continueTrace(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
withIsolationScope,
withScope,
} from '@sentry/core';
import type { WebFetchHeaders } from '@sentry/types';
import type { Request, WebFetchHeaders } from '@sentry/types';
import { propagationContextFromHeaders, uuid4, winterCGHeadersToDict } from '@sentry/utils';

import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
Expand Down Expand Up @@ -68,9 +68,9 @@ export function wrapGenerationFunctionWithSentry<F extends (...args: any[]) => a
scope.setTransactionName(`${componentType}.${generationFunctionIdentifier} (${componentRoute})`);

isolationScope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
headers: headersDict,
},
} satisfies Request,
});

const activeSpan = getActiveSpan();
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/common/wrapMiddlewareWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function wrapMiddlewareWithSentry<H extends EdgeRouteHandler>(

if (req instanceof Request) {
isolationScope.setSDKProcessingMetadata({
request: winterCGRequestToRequestData(req),
normalizedRequest: winterCGRequestToRequestData(req),
});
spanName = `middleware ${req.method} ${new URL(req.url).pathname}`;
spanSource = 'url';
Expand Down
6 changes: 3 additions & 3 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
withIsolationScope,
withScope,
} from '@sentry/core';

import type { Request as SentryRequest } from '@sentry/types';
import type { RouteHandlerContext } from './types';

import { propagationContextFromHeaders, winterCGHeadersToDict } from '@sentry/utils';
Expand Down Expand Up @@ -64,10 +64,10 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
);
scope.setPropagationContext(incomingPropagationContext);
scope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
method,
headers: completeHeadersDict,
},
} satisfies SentryRequest,
});
}

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/src/common/wrapServerComponentWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
withIsolationScope,
withScope,
} from '@sentry/core';
import type { Request as SentryRequest } from '@sentry/types';
import { propagationContextFromHeaders, uuid4, vercelWaitUntil, winterCGHeadersToDict } from '@sentry/utils';

import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
Expand Down Expand Up @@ -49,9 +50,9 @@ export function wrapServerComponentWithSentry<F extends (...args: any[]) => any>
const headersDict = context.headers ? winterCGHeadersToDict(context.headers) : undefined;

isolationScope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
headers: headersDict,
},
} satisfies SentryRequest,
});

return withIsolationScope(isolationScope, () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(

if (req instanceof Request) {
isolationScope.setSDKProcessingMetadata({
request: winterCGRequestToRequestData(req),
normalizedRequest: winterCGRequestToRequestData(req),
});
currentScope.setTransactionName(`${req.method} ${parameterizedRoute}`);
} else {
Expand Down
18 changes: 1 addition & 17 deletions packages/node/src/integrations/http/SentryHttpInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { PolymorphicRequest, Request, SanitizedRequestData } from '@sentry/
import {
getBreadcrumbLogLevelFromHttpStatusCode,
getSanitizedUrlString,
headersToDict,
logger,
parseUrl,
stripUrlQueryAndFragment,
Expand Down Expand Up @@ -455,20 +456,3 @@ function extractQueryParams(req: IncomingMessage): string | undefined {
return undefined;
}
}

function headersToDict(reqHeaders: Record<string, string | string[] | undefined>): Record<string, string> {
const headers: Record<string, string> = Object.create(null);

try {
Object.entries(reqHeaders).forEach(([key, value]) => {
if (typeof value === 'string') {
headers[key] = value;
}
});
} catch (e) {
DEBUG_BUILD &&
logger.warn('Sentry failed extracting headers from a request object. If you see this, please file an issue.');
}

return headers;
}
8 changes: 6 additions & 2 deletions packages/sveltekit/src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ export function sentryHandle(handlerOptions?: SentryHandleOptions): Handle {
return withIsolationScope(isolationScope => {
// We only call continueTrace in the initial top level request to avoid
// creating a new root span for the sub request.
isolationScope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(input.event.request.clone()) });
isolationScope.setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(input.event.request.clone()),
});
return continueTrace(getTracePropagationData(input.event), () => instrumentHandle(input, options));
});
};
Expand Down Expand Up @@ -167,7 +169,9 @@ async function instrumentHandle(
name: routeName,
},
async (span?: Span) => {
getCurrentScope().setSDKProcessingMetadata({ request: winterCGRequestToRequestData(event.request.clone()) });
getCurrentScope().setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(event.request.clone()),
});
const res = await resolve(event, {
transformPageChunk: addSentryCodeToPage(options),
});
Expand Down
22 changes: 21 additions & 1 deletion packages/utils/src/requestdata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,10 +434,30 @@ export function winterCGHeadersToDict(winterCGHeaders: WebFetchHeaders): Record<
return headers;
}

/**
* Convert common request headers to a simple dictionary.
*/
export function headersToDict(reqHeaders: Record<string, string | string[] | undefined>): Record<string, string> {
const headers: Record<string, string> = Object.create(null);

try {
Object.entries(reqHeaders).forEach(([key, value]) => {
if (typeof value === 'string') {
headers[key] = value;
}
});
} catch (e) {
DEBUG_BUILD &&
logger.warn('Sentry failed extracting headers from a request object. If you see this, please file an issue.');
}

return headers;
}

/**
* Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.
*/
export function winterCGRequestToRequestData(req: WebFetchRequest): PolymorphicRequest {
export function winterCGRequestToRequestData(req: WebFetchRequest): Request {
const headers = winterCGHeadersToDict(req.headers);
return {
method: req.method,
Expand Down

0 comments on commit 68a27e5

Please sign in to comment.