Skip to content

ref: Refactor remaining usage of request to normalizedRequest #14401

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
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
21 changes: 14 additions & 7 deletions packages/google-cloud-serverless/src/gcpfunction/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@ import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
handleCallbackErrors,
isString,
logger,
setHttpStatus,
stripUrlQueryAndFragment,
} from '@sentry/core';
import { isString, logger, stripUrlQueryAndFragment } from '@sentry/core';
import { captureException, continueTrace, flush, getCurrentScope, startSpanManual } from '@sentry/node';

import {
captureException,
continueTrace,
flush,
getCurrentScope,
httpRequestToRequestEventData,
startSpanManual,
} from '@sentry/node';
import { DEBUG_BUILD } from '../debug-build';
import { domainify, markEventUnhandled, proxyFunction } from '../utils';
import type { HttpFunction, WrapperOptions } from './general';
Expand Down Expand Up @@ -44,6 +52,9 @@ function _wrapHttpFunction(fn: HttpFunction, options: Partial<WrapperOptions>):
const baggage = req.headers?.baggage;

return continueTrace({ sentryTrace, baggage }, () => {
const normalizedRequest = httpRequestToRequestEventData(req);
Copy link
Member Author

Choose a reason for hiding this comment

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

IMHO it is better to set this before we start the span, so we can 100% ensure this is already set for the span.

getCurrentScope().setSDKProcessingMetadata({ normalizedRequest });

return startSpanManual(
{
name: `${reqMethod} ${reqUrl}`,
Expand All @@ -54,10 +65,6 @@ function _wrapHttpFunction(fn: HttpFunction, options: Partial<WrapperOptions>):
},
},
span => {
getCurrentScope().setSDKProcessingMetadata({
request: req,
});

// eslint-disable-next-line @typescript-eslint/unbound-method
const _end = res.end;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { captureException, withScope } from '@sentry/core';
import { vercelWaitUntil } from '@sentry/core';
import { httpRequestToRequestEventData } from '@sentry/node';
import type { NextPageContext } from 'next';
import { flushSafelyWithTimeout } from '../utils/responseEnd';

Expand Down Expand Up @@ -38,7 +39,8 @@ export async function captureUnderscoreErrorException(contextOrProps: ContextOrP

withScope(scope => {
if (req) {
scope.setSDKProcessingMetadata({ request: req });
const normalizedRequest = httpRequestToRequestEventData(req);
scope.setSDKProcessingMetadata({ normalizedRequest });
}

// If third-party libraries (or users themselves) throw something falsy, we want to capture it as a message (which
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { isString, logger, objectify } from '@sentry/core';

import { vercelWaitUntil } from '@sentry/core';
import { httpRequestToRequestEventData } from '@sentry/node';
import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout } from '../utils/responseEnd';
Expand Down Expand Up @@ -65,8 +66,9 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
},
() => {
const reqMethod = `${(req.method || 'GET').toUpperCase()} `;
const normalizedRequest = httpRequestToRequestEventData(req);

isolationScope.setSDKProcessingMetadata({ request: req });
isolationScope.setSDKProcessingMetadata({ normalizedRequest });
isolationScope.setTransactionName(`${reqMethod}${parameterizedRoute}`);

return startSpanManual(
Expand Down
6 changes: 3 additions & 3 deletions packages/nextjs/src/common/utils/wrapperUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getRootSpan,
getTraceData,
} from '@sentry/core';
import { httpRequestToRequestEventData } from '@sentry/node';
import { TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL } from '../span-attributes-with-logic-attached';

/**
Expand Down Expand Up @@ -61,10 +62,9 @@ export function withTracedServerSideDataFetcher<F extends (...args: any[]) => Pr
this: unknown,
...args: Parameters<F>
): Promise<{ data: ReturnType<F>; sentryTrace?: string; baggage?: string }> {
const normalizedRequest = httpRequestToRequestEventData(req);
getCurrentScope().setTransactionName(`${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`);
getIsolationScope().setSDKProcessingMetadata({
request: req,
});
getIsolationScope().setSDKProcessingMetadata({ normalizedRequest });

const span = getActiveSpan();

Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/src/common/wrapMiddlewareWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import {
handleCallbackErrors,
setCapturedScopesOnSpan,
startSpan,
vercelWaitUntil,
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import { vercelWaitUntil, winterCGRequestToRequestData } from '@sentry/core';
import type { TransactionSource } from '@sentry/types';
import type { EdgeRouteHandler } from '../edge/types';
import { flushSafelyWithTimeout } from './utils/responseEnd';
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { httpIntegration } from './integrations/http';
export { httpRequestToRequestEventData } from './integrations/http/SentryHttpInstrumentation';
export { nativeNodeFetchIntegration } from './integrations/node-fetch';
export { fsIntegration } from './integrations/fs';

Expand Down
45 changes: 26 additions & 19 deletions packages/node/src/integrations/http/SentryHttpInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,26 +131,9 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns

instrumentation._diag.debug('http instrumentation for incoming request');

const request = args[0] as http.IncomingMessage;

const isolationScope = getIsolationScope().clone();

const headers = request.headers;
const host = headers.host || '<no host>';
const protocol = request.socket && (request.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http';
const originalUrl = request.url || '';
const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;

// This is non-standard, but may be set on e.g. Next.js or Express requests
const cookies = (request as PolymorphicRequest).cookies;

const normalizedRequest: RequestEventData = {
url: absoluteUrl,
method: request.method,
query_string: extractQueryParamsFromUrl(request.url || ''),
headers: headersToDict(request.headers),
cookies,
};
const request = args[0] as http.IncomingMessage;
const normalizedRequest = httpRequestToRequestEventData(request);

patchRequestToCaptureBody(request, isolationScope);

Expand Down Expand Up @@ -445,3 +428,27 @@ function patchRequestToCaptureBody(req: IncomingMessage, isolationScope: Scope):
// ignore errors if we can't patch stuff
}
}

/**
* Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.
*/
export function httpRequestToRequestEventData(request: IncomingMessage): RequestEventData {
const headers = request.headers || {};
const host = headers.host || '<no host>';
const protocol = request.socket && (request.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http';
const originalUrl = request.url || '';
const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;

// This is non-standard, but may be set on e.g. Next.js or Express requests
const cookies = (request as PolymorphicRequest).cookies;

const normalizedRequest: RequestEventData = {
url: absoluteUrl,
method: request.method,
query_string: extractQueryParamsFromUrl(originalUrl),
headers: headersToDict(headers),
cookies,
};

return normalizedRequest;
}
27 changes: 14 additions & 13 deletions packages/remix/src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import type { AppData, DataFunctionArgs, EntryContext, HandleDocumentRequestFunction } from '@remix-run/node';
import { captureException, getClient, handleCallbackErrors } from '@sentry/core';
import { addExceptionMechanism, isPrimitive, logger, objectify } from '@sentry/core';
import type { Span } from '@sentry/types';
import {
addExceptionMechanism,
captureException,
getClient,
handleCallbackErrors,
isPrimitive,
logger,
objectify,
winterCGRequestToRequestData,
} from '@sentry/core';
import type { RequestEventData, Span } from '@sentry/types';
import { DEBUG_BUILD } from './debug-build';
import type { RemixOptions } from './remixOptions';
import { storeFormDataKeys } from './utils';
import { extractData, isResponse, isRouteErrorResponse } from './vendor/response';
import type { DataFunction, RemixRequest } from './vendor/types';
import { normalizeRemixRequest } from './web-fetch';

/**
* Captures an exception happened in the Remix server.
Expand Down Expand Up @@ -41,24 +48,18 @@ export async function captureRemixServerException(
return;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let normalizedRequest: Record<string, unknown> = request as unknown as any;
let normalizedRequest: RequestEventData = {};

try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
normalizedRequest = normalizeRemixRequest(request as unknown as any);
normalizedRequest = winterCGRequestToRequestData(request);
Copy link
Member Author

Choose a reason for hiding this comment

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

I don't really know if we need to try-catch this, I am not confident about how the shape of this is 😅 so I left it like this to be on the safe side...

} catch (e) {
DEBUG_BUILD && logger.warn('Failed to normalize Remix request');
}

const objectifiedErr = objectify(err);

captureException(isResponse(objectifiedErr) ? await extractResponseError(objectifiedErr) : objectifiedErr, scope => {
scope.setSDKProcessingMetadata({
request: {
...normalizedRequest,
},
});
scope.setSDKProcessingMetadata({ normalizedRequest });

scope.addEventProcessor(event => {
addExceptionMechanism(event, {
Expand Down
14 changes: 5 additions & 9 deletions packages/remix/src/utils/instrumentServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import {
spanToJSON,
spanToTraceHeader,
startSpan,
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import { dynamicSamplingContextToSentryBaggageHeader, fill, isNodeEnv, loadModule, logger } from '@sentry/core';
import { continueTrace, getDynamicSamplingContextFromSpan } from '@sentry/opentelemetry';
import type { TransactionSource, WrappedFunction } from '@sentry/types';
import type { RequestEventData, TransactionSource, WrappedFunction } from '@sentry/types';
import type { Span } from '@sentry/types';

import { DEBUG_BUILD } from './debug-build';
Expand All @@ -39,7 +40,6 @@ import type {
ServerRoute,
ServerRouteManifest,
} from './vendor/types';
import { normalizeRemixRequest } from './web-fetch';

let FUTURE_FLAGS: FutureConfig | undefined;

Expand Down Expand Up @@ -296,10 +296,10 @@ function wrapRequestHandler(
return withIsolationScope(async isolationScope => {
const options = getClient()?.getOptions();

let normalizedRequest: Record<string, unknown> = request;
let normalizedRequest: RequestEventData = {};

try {
normalizedRequest = normalizeRemixRequest(request);
normalizedRequest = winterCGRequestToRequestData(request);
} catch (e) {
DEBUG_BUILD && logger.warn('Failed to normalize Remix request');
}
Expand All @@ -311,11 +311,7 @@ function wrapRequestHandler(
isolationScope.setTransactionName(name);
}

isolationScope.setSDKProcessingMetadata({
request: {
...normalizedRequest,
},
});
isolationScope.setSDKProcessingMetadata({ normalizedRequest });

if (!options || !hasTracingEnabled(options)) {
return origRequestHandler.call(this, request, loadContext);
Expand Down
Loading
Loading