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

url should not be set on server-components
  • Loading branch information
mydea committed Nov 15, 2024
1 parent bac6c93 commit 493f178
Show file tree
Hide file tree
Showing 21 changed files with 314 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,12 @@ test('Sends a transaction for a request to app router', async ({ page }) => {
trace_id: expect.any(String),
});

expect(transactionEvent).toEqual(
expect.objectContaining({
request: {
cookies: {},
headers: expect.any(Object),
url: expect.any(String),
},
expect(transactionEvent.request).toEqual({
cookies: {},
headers: expect.objectContaining({
'user-agent': expect.any(String),
}),
);

expect(Object.keys(transactionEvent.request?.headers!).length).toBeGreaterThan(0);
});

// The transaction should not contain any spans with the same name as the transaction
// e.g. "GET /server-component/parameter/[...parameters]"
Expand Down
11 changes: 9 additions & 2 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import {
startSpan,
withIsolationScope,
} from '@sentry/node';
import type { Scope, SpanAttributes } from '@sentry/types';
import type { Request, Scope, SpanAttributes } from '@sentry/types';
import {
addNonEnumerableProperty,
extractQueryParamsFromUrl,
logger,
objectify,
stripUrlQueryAndFragment,
Expand Down Expand Up @@ -111,7 +112,13 @@ 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,
query_string: extractQueryParamsFromUrl(request.url),
}) satisfies Request,
});

if (options.trackClientIp && isDynamicPageRequest) {
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ describe('sentryMiddleware', () => {
await middleware(ctx, next);

expect(setSDKProcessingMetadataMock).toHaveBeenCalledWith({
request: {
normalizedRequest: {
method: 'GET',
url: '/users',
headers: {
Expand Down Expand Up @@ -254,7 +254,7 @@ describe('sentryMiddleware', () => {
await middleware(ctx, next);

expect(setSDKProcessingMetadataMock).toHaveBeenCalledWith({
request: {
normalizedRequest: {
method: 'GET',
url: '/users',
},
Expand Down
9 changes: 5 additions & 4 deletions packages/bun/src/integrations/bunserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
startSpan,
withIsolationScope,
} from '@sentry/core';
import type { IntegrationFn, SpanAttributes } from '@sentry/types';
import { getSanitizedUrlString, parseUrl } from '@sentry/utils';
import type { IntegrationFn, Request, SpanAttributes } from '@sentry/types';
import { extractQueryParamsFromUrl, getSanitizedUrlString, parseUrl } from '@sentry/utils';

const INTEGRATION_NAME = 'BunServer';

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

isolationScope.setSDKProcessingMetadata({
request: {
normalizedRequest: {
url,
method: request.method,
headers: request.headers.toJSON(),
},
query_string: extractQueryParamsFromUrl(url),
} 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) });
}
2 changes: 1 addition & 1 deletion packages/cloudflare/test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ describe('withSentry', () => {
},
);

expect(sentryEvent.sdkProcessingMetadata?.request).toEqual({
expect(sentryEvent.sdkProcessingMetadata?.normalizedRequest).toEqual({
headers: {},
url: 'https://example.com/',
method: 'GET',
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
import { dateTimestampInSeconds, generatePropagationContext, isPlainObject, logger, uuid4 } from '@sentry/utils';

import { updateSession } from './session';
import { mergeSdkProcessingMetadata } from './utils/applyScopeDataToEvent';
import { _getSpanForScope, _setSpanForScope } from './utils/spanOnScope';

/**
Expand Down Expand Up @@ -479,8 +480,7 @@ class ScopeClass implements ScopeInterface {
* @inheritDoc
*/
public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {
this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };

this._sdkProcessingMetadata = mergeSdkProcessingMetadata(this._sdkProcessingMetadata, newData);
return this;
}

Expand Down
32 changes: 31 additions & 1 deletion packages/core/src/utils/applyScopeDataToEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ export function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {
mergeAndOverwriteScopeData(data, 'tags', tags);
mergeAndOverwriteScopeData(data, 'user', user);
mergeAndOverwriteScopeData(data, 'contexts', contexts);
mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);

data.sdkProcessingMetadata = mergeSdkProcessingMetadata(data.sdkProcessingMetadata, sdkProcessingMetadata);

if (level) {
data.level = level;
Expand Down Expand Up @@ -115,6 +116,35 @@ export function mergeArray<Prop extends 'breadcrumbs' | 'fingerprint'>(
event[prop] = merged.length ? merged : undefined;
}

/**
* Merge new SDK processing metadata into existing data.
* New data will overwrite existing data.
* `normalizedRequest` is special handled and will also be merged.
*/
export function mergeSdkProcessingMetadata(
sdkProcessingMetadata: ScopeData['sdkProcessingMetadata'],
newSdkProcessingMetadata: ScopeData['sdkProcessingMetadata'],
): ScopeData['sdkProcessingMetadata'] {
// We want to merge `normalizedRequest` to avoid some partial entry on the scope
// overwriting potentially more complete data on the isolation scope
const normalizedRequestBefore = sdkProcessingMetadata['normalizedRequest'];
const normalizedRequest = newSdkProcessingMetadata['normalizedRequest'];

const newData = {
...sdkProcessingMetadata,
...newSdkProcessingMetadata,
};

if (normalizedRequestBefore || normalizedRequest) {
newData['normalizedRequest'] = {
...(normalizedRequestBefore || {}),
...(normalizedRequest || {}),
};
}

return newData;
}

function applyDataToEvent(event: Event, data: ScopeData): void {
const { extra, tags, user, contexts, level, transactionName } = data;

Expand Down
45 changes: 41 additions & 4 deletions packages/core/test/lib/scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,47 @@ describe('Scope', () => {
expect(scope['_user']).toEqual({});
});

test('setProcessingMetadata', () => {
const scope = new Scope();
scope.setSDKProcessingMetadata({ dogs: 'are great!' });
expect(scope['_sdkProcessingMetadata'].dogs).toEqual('are great!');
describe('setProcessingMetadata', () => {
test('it works with no initial data', () => {
const scope = new Scope();
scope.setSDKProcessingMetadata({ dogs: 'are great!' });
expect(scope['_sdkProcessingMetadata'].dogs).toEqual('are great!');
});

test('it overwrites arbitrary data', () => {
const scope = new Scope();
scope.setSDKProcessingMetadata({ dogs: 'are great!' });
scope.setSDKProcessingMetadata({ dogs: 'are really great!' });
scope.setSDKProcessingMetadata({ cats: 'are also great!' });
scope.setSDKProcessingMetadata({ obj: { nested: 'value1' } });
scope.setSDKProcessingMetadata({ obj: { nested2: 'value2' } });

expect(scope['_sdkProcessingMetadata']).toEqual({
dogs: 'are really great!',
cats: 'are also great!',
obj: { nested2: 'value2' },
});
});

test('it merges normalizedRequest data', () => {
const scope = new Scope();
scope.setSDKProcessingMetadata({
normalizedRequest: {
url: 'value1',
method: 'value1',
},
});
scope.setSDKProcessingMetadata({
normalizedRequest: {
url: 'value2',
headers: {},
},
});

expect(scope['_sdkProcessingMetadata']).toEqual({
normalizedRequest: { url: 'value2', method: 'value1', headers: {} },
});
});
});

test('set and get propagation context', () => {
Expand Down
Loading

0 comments on commit 493f178

Please sign in to comment.