diff --git a/packages/astro/src/client/sdk.ts b/packages/astro/src/client/sdk.ts index aa32e9dcc095..2fd98b8a96cd 100644 --- a/packages/astro/src/client/sdk.ts +++ b/packages/astro/src/client/sdk.ts @@ -1,6 +1,6 @@ import type { BrowserOptions } from '@sentry/browser'; import { BrowserTracing, init as initBrowserSdk } from '@sentry/browser'; -import { configureScope, hasTracingEnabled } from '@sentry/core'; +import { getCurrentScope, hasTracingEnabled } from '@sentry/core'; import { addOrUpdateIntegration } from '@sentry/utils'; import { applySdkMetadata } from '../common/metadata'; @@ -20,9 +20,7 @@ export function init(options: BrowserOptions): void { initBrowserSdk(options); - configureScope(scope => { - scope.setTag('runtime', 'browser'); - }); + getCurrentScope().setTag('runtime', 'browser'); } function addClientIntegrations(options: BrowserOptions): void { diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index 37603a2cdb62..5e3b2de18622 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -1,8 +1,8 @@ import { captureException, - configureScope, continueTrace, getCurrentHub, + getCurrentScope, runWithAsyncContext, startSpan, } from '@sentry/node'; @@ -106,9 +106,7 @@ async function instrumentRequest( } if (options.trackClientIp) { - configureScope(scope => { - scope.setUser({ ip_address: ctx.clientAddress }); - }); + getCurrentScope().setUser({ ip_address: ctx.clientAddress }); } try { diff --git a/packages/astro/src/server/sdk.ts b/packages/astro/src/server/sdk.ts index 8c867ca46fc2..e69d27781ed5 100644 --- a/packages/astro/src/server/sdk.ts +++ b/packages/astro/src/server/sdk.ts @@ -1,4 +1,4 @@ -import { configureScope } from '@sentry/core'; +import { getCurrentScope } from '@sentry/core'; import type { NodeOptions } from '@sentry/node'; import { init as initNodeSdk } from '@sentry/node'; @@ -13,7 +13,5 @@ export function init(options: NodeOptions): void { initNodeSdk(options); - configureScope(scope => { - scope.setTag('runtime', 'node'); - }); + getCurrentScope().setTag('runtime', 'node'); } diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts index dc3b0139b965..ef81d69214c5 100644 --- a/packages/astro/test/server/middleware.test.ts +++ b/packages/astro/test/server/middleware.test.ts @@ -172,7 +172,7 @@ describe('sentryMiddleware', () => { it('attaches client IP and request headers if options are set', async () => { const scope = { setUser: vi.fn(), setPropagationContext: vi.fn() }; // @ts-expect-error, only passing a partial Scope object - const configureScopeSpy = vi.spyOn(SentryNode, 'configureScope').mockImplementation(cb => cb(scope)); + const getCurrentScopeSpy = vi.spyOn(SentryNode, 'getCurrentScope').mockImplementation(() => scope); const middleware = handleRequest({ trackClientIp: true, trackHeaders: true }); const ctx = { @@ -192,7 +192,7 @@ describe('sentryMiddleware', () => { // @ts-expect-error, a partial ctx object is fine here await middleware(ctx, next); - expect(configureScopeSpy).toHaveBeenCalledTimes(1); + expect(getCurrentScopeSpy).toHaveBeenCalledTimes(1); expect(scope.setUser).toHaveBeenCalledWith({ ip_address: '192.168.0.1' }); expect(startSpanSpy).toHaveBeenCalledWith( diff --git a/packages/browser-integration-tests/suites/replay/dsc/test.ts b/packages/browser-integration-tests/suites/replay/dsc/test.ts index ffd2cf1877da..4468a254bde4 100644 --- a/packages/browser-integration-tests/suites/replay/dsc/test.ts +++ b/packages/browser-integration-tests/suites/replay/dsc/test.ts @@ -21,6 +21,9 @@ sentryTest( const transactionReq = waitForTransactionRequest(page); + // Wait for this to be available + await page.waitForFunction('!!window.Replay'); + await page.evaluate(() => { (window as unknown as TestWindow).Replay.start(); }); @@ -28,10 +31,9 @@ sentryTest( await waitForReplayRunning(page); await page.evaluate(() => { - (window as unknown as TestWindow).Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); - }); + const scope = (window as unknown as TestWindow).Sentry.getCurrentScope(); + scope.setUser({ id: 'user123', segment: 'segmentB' }); + scope.setTransactionName('testTransactionDSC'); }); const req0 = await transactionReq; @@ -74,10 +76,9 @@ sentryTest( await waitForReplayRunning(page); await page.evaluate(() => { - (window as unknown as TestWindow).Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); - }); + const scope = (window as unknown as TestWindow).Sentry.getCurrentScope(); + scope.setUser({ id: 'user123', segment: 'segmentB' }); + scope.setTransactionName('testTransactionDSC'); }); const req0 = await transactionReq; @@ -132,10 +133,9 @@ sentryTest( }); await page.evaluate(() => { - (window as unknown as TestWindow).Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); - }); + const scope = (window as unknown as TestWindow).Sentry.getCurrentScope(); + scope.setUser({ id: 'user123', segment: 'segmentB' }); + scope.setTransactionName('testTransactionDSC'); }); const req0 = await transactionReq; @@ -181,10 +181,9 @@ sentryTest( const transactionReq = waitForTransactionRequest(page); await page.evaluate(async () => { - (window as unknown as TestWindow).Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); - }); + const scope = (window as unknown as TestWindow).Sentry.getCurrentScope(); + scope.setUser({ id: 'user123', segment: 'segmentB' }); + scope.setTransactionName('testTransactionDSC'); }); const req0 = await transactionReq; diff --git a/packages/browser-integration-tests/suites/tracing/envelope-header-transaction-name/init.js b/packages/browser-integration-tests/suites/tracing/envelope-header-transaction-name/init.js index efb7b577f75b..7d000c0ac2cd 100644 --- a/packages/browser-integration-tests/suites/tracing/envelope-header-transaction-name/init.js +++ b/packages/browser-integration-tests/suites/tracing/envelope-header-transaction-name/init.js @@ -11,8 +11,7 @@ Sentry.init({ debug: true, }); -Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); - scope.getTransaction().setMetadata({ source: 'custom' }); -}); +const scope = Sentry.getCurrentScope(); +scope.setUser({ id: 'user123', segment: 'segmentB' }); +scope.setTransactionName('testTransactionDSC'); +scope.getTransaction().setMetadata({ source: 'custom' }); diff --git a/packages/browser-integration-tests/suites/tracing/envelope-header/init.js b/packages/browser-integration-tests/suites/tracing/envelope-header/init.js index fbce5a16116a..f382a49c153d 100644 --- a/packages/browser-integration-tests/suites/tracing/envelope-header/init.js +++ b/packages/browser-integration-tests/suites/tracing/envelope-header/init.js @@ -11,7 +11,6 @@ Sentry.init({ debug: true, }); -Sentry.configureScope(scope => { - scope.setUser({ id: 'user123', segment: 'segmentB' }); - scope.setTransactionName('testTransactionDSC'); -}); +const scope = Sentry.getCurrentScope(); +scope.setUser({ id: 'user123', segment: 'segmentB' }); +scope.setTransactionName('testTransactionDSC'); diff --git a/packages/browser/test/unit/index.test.ts b/packages/browser/test/unit/index.test.ts index bc0058ba7d16..62bf08d0ee25 100644 --- a/packages/browser/test/unit/index.test.ts +++ b/packages/browser/test/unit/index.test.ts @@ -12,10 +12,10 @@ import { captureEvent, captureException, captureMessage, - configureScope, flush, getClient, getCurrentHub, + getCurrentScope, init, showReportDialog, wrap, @@ -58,27 +58,21 @@ describe('SentryBrowser', () => { describe('getContext() / setContext()', () => { it('should store/load extra', () => { - configureScope((scope: Scope) => { - scope.setExtra('abc', { def: [1] }); - }); + getCurrentScope().setExtra('abc', { def: [1] }); expect(global.__SENTRY__.hub._stack[1].scope._extra).toEqual({ abc: { def: [1] }, }); }); it('should store/load tags', () => { - configureScope((scope: Scope) => { - scope.setTag('abc', 'def'); - }); + getCurrentScope().setTag('abc', 'def'); expect(global.__SENTRY__.hub._stack[1].scope._tags).toEqual({ abc: 'def', }); }); it('should store/load user', () => { - configureScope((scope: Scope) => { - scope.setUser({ id: 'def' }); - }); + getCurrentScope().setUser({ id: 'def' }); expect(global.__SENTRY__.hub._stack[1].scope._user).toEqual({ id: 'def', }); @@ -95,9 +89,7 @@ describe('SentryBrowser', () => { const options = getDefaultBrowserClientOptions({ dsn }); const client = new BrowserClient(options); it('uses the user on the scope', () => { - configureScope(scope => { - scope.setUser(EX_USER); - }); + getCurrentScope().setUser(EX_USER); getCurrentHub().bindClient(client); showReportDialog(); @@ -110,9 +102,7 @@ describe('SentryBrowser', () => { }); it('prioritizes options user over scope user', () => { - configureScope(scope => { - scope.setUser(EX_USER); - }); + getCurrentScope().setUser(EX_USER); getCurrentHub().bindClient(client); const DIALOG_OPTION_USER = { email: 'option@example.com' }; diff --git a/packages/core/src/tracing/idletransaction.ts b/packages/core/src/tracing/idletransaction.ts index b49b1d15e9b1..75630de373f1 100644 --- a/packages/core/src/tracing/idletransaction.ts +++ b/packages/core/src/tracing/idletransaction.ts @@ -121,7 +121,7 @@ export class IdleTransaction extends Transaction { // We set the transaction here on the scope so error events pick up the trace // context and attach it to the error. DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`); - _idleHub.configureScope(scope => scope.setSpan(this)); + _idleHub.getScope().setSpan(this); } this._restartIdleTimeout(); diff --git a/packages/core/test/lib/hint.test.ts b/packages/core/test/lib/hint.test.ts index cdcfa9368cbe..5fb69ce39fff 100644 --- a/packages/core/test/lib/hint.test.ts +++ b/packages/core/test/lib/hint.test.ts @@ -1,4 +1,4 @@ -import { captureEvent, configureScope } from '@sentry/core'; +import { captureEvent, getCurrentScope } from '@sentry/core'; import { GLOBAL_OBJ } from '@sentry/utils'; import { initAndBind } from '../../src/sdk'; @@ -109,7 +109,7 @@ describe('Hint', () => { const options = getDefaultTestClientOptions({ dsn: PUBLIC_DSN }); initAndBind(TestClient, options); - configureScope(scope => scope.addAttachment({ filename: 'scope.file', data: 'great content!' })); + getCurrentScope().addAttachment({ filename: 'scope.file', data: 'great content!' }); captureEvent({}, { attachments: [{ filename: 'some-file.txt', data: 'Hello' }] }); diff --git a/packages/core/test/lib/tracing/errors.test.ts b/packages/core/test/lib/tracing/errors.test.ts index f4de76234ca2..20db043865a9 100644 --- a/packages/core/test/lib/tracing/errors.test.ts +++ b/packages/core/test/lib/tracing/errors.test.ts @@ -40,7 +40,7 @@ describe('registerErrorHandlers()', () => { }); afterEach(() => { - hub.configureScope(scope => scope.setSpan(undefined)); + hub.getScope().setSpan(undefined); }); it('registers error instrumentation', () => { @@ -67,7 +67,7 @@ describe('registerErrorHandlers()', () => { it('sets status for transaction on scope on error', () => { registerErrorInstrumentation(); const transaction = hub.startTransaction({ name: 'test' }); - hub.configureScope(scope => scope.setSpan(transaction)); + hub.getScope().setSpan(transaction); mockErrorCallback({} as HandlerDataError); expect(transaction.status).toBe('internal_error'); @@ -78,7 +78,7 @@ describe('registerErrorHandlers()', () => { it('sets status for transaction on scope on unhandledrejection', () => { registerErrorInstrumentation(); const transaction = hub.startTransaction({ name: 'test' }); - hub.configureScope(scope => scope.setSpan(transaction)); + hub.getScope().setSpan(transaction); mockUnhandledRejectionCallback({}); expect(transaction.status).toBe('internal_error'); diff --git a/packages/core/test/mocks/integration.ts b/packages/core/test/mocks/integration.ts index ce95d04520a7..4c229ce27294 100644 --- a/packages/core/test/mocks/integration.ts +++ b/packages/core/test/mocks/integration.ts @@ -1,6 +1,6 @@ import type { Event, EventProcessor, Integration } from '@sentry/types'; -import { configureScope, getCurrentHub } from '../../src'; +import { getCurrentHub, getCurrentScope } from '../../src'; export class TestIntegration implements Integration { public static id: string = 'TestIntegration'; @@ -18,9 +18,7 @@ export class TestIntegration implements Integration { eventProcessor.id = this.name; - configureScope(scope => { - scope.addEventProcessor(eventProcessor); - }); + getCurrentScope().addEventProcessor(eventProcessor); } } diff --git a/packages/e2e-tests/test-applications/create-next-app/pages/api/success.ts b/packages/e2e-tests/test-applications/create-next-app/pages/api/success.ts index ed4372065792..7585c88f0ab1 100644 --- a/packages/e2e-tests/test-applications/create-next-app/pages/api/success.ts +++ b/packages/e2e-tests/test-applications/create-next-app/pages/api/success.ts @@ -4,7 +4,7 @@ import type { NextApiRequest, NextApiResponse } from 'next'; export default function handler(req: NextApiRequest, res: NextApiResponse) { const transaction = Sentry.startTransaction({ name: 'test-transaction', op: 'e2e-test' }); - Sentry.getCurrentHub().configureScope(scope => scope.setSpan(transaction)); + Sentry.getCurrentHub().getScope().setSpan(transaction); const span = transaction.startChild(); diff --git a/packages/e2e-tests/test-applications/node-express-app/src/app.ts b/packages/e2e-tests/test-applications/node-express-app/src/app.ts index e9de96631259..fd83fcdfa23a 100644 --- a/packages/e2e-tests/test-applications/node-express-app/src/app.ts +++ b/packages/e2e-tests/test-applications/node-express-app/src/app.ts @@ -35,7 +35,7 @@ app.get('/test-param/:param', function (req, res) { app.get('/test-transaction', async function (req, res) { const transaction = Sentry.startTransaction({ name: 'test-transaction', op: 'e2e-test' }); - Sentry.getCurrentHub().configureScope(scope => scope.setSpan(transaction)); + Sentry.getCurrentHub().getScope().setSpan(transaction); const span = transaction.startChild(); diff --git a/packages/nextjs/src/client/index.ts b/packages/nextjs/src/client/index.ts index 8fd55568e70e..0c10a8344bd7 100644 --- a/packages/nextjs/src/client/index.ts +++ b/packages/nextjs/src/client/index.ts @@ -4,8 +4,8 @@ import type { BrowserOptions } from '@sentry/react'; import { BrowserTracing, Integrations, - configureScope, defaultRequestInstrumentationOptions, + getCurrentScope, init as reactInit, } from '@sentry/react'; import type { EventProcessor } from '@sentry/types'; @@ -56,17 +56,16 @@ export function init(options: BrowserOptions): void { reactInit(opts); - configureScope(scope => { - scope.setTag('runtime', 'browser'); - const filterTransactions: EventProcessor = event => - event.type === 'transaction' && event.transaction === '/404' ? null : event; - filterTransactions.id = 'NextClient404Filter'; - scope.addEventProcessor(filterTransactions); + const scope = getCurrentScope(); + scope.setTag('runtime', 'browser'); + const filterTransactions: EventProcessor = event => + event.type === 'transaction' && event.transaction === '/404' ? null : event; + filterTransactions.id = 'NextClient404Filter'; + scope.addEventProcessor(filterTransactions); - if (process.env.NODE_ENV === 'development') { - scope.addEventProcessor(devErrorSymbolicationEventProcessor); - } - }); + if (process.env.NODE_ENV === 'development') { + scope.addEventProcessor(devErrorSymbolicationEventProcessor); + } } function addClientIntegrations(options: BrowserOptions): void { diff --git a/packages/nextjs/src/common/wrapPageComponentWithSentry.ts b/packages/nextjs/src/common/wrapPageComponentWithSentry.ts index ece566bc2e5a..2051d015b0c4 100644 --- a/packages/nextjs/src/common/wrapPageComponentWithSentry.ts +++ b/packages/nextjs/src/common/wrapPageComponentWithSentry.ts @@ -1,4 +1,4 @@ -import { addTracingExtensions, captureException, configureScope, runWithAsyncContext } from '@sentry/core'; +import { addTracingExtensions, captureException, getCurrentScope, runWithAsyncContext } from '@sentry/core'; import { extractTraceparentData } from '@sentry/utils'; interface FunctionComponent { @@ -26,24 +26,23 @@ export function wrapPageComponentWithSentry(pageComponent: FunctionComponent | C return class SentryWrappedPageComponent extends pageComponent { public render(...args: unknown[]): unknown { return runWithAsyncContext(() => { - configureScope(scope => { - // We extract the sentry trace data that is put in the component props by datafetcher wrappers - const sentryTraceData = - typeof this.props === 'object' && - this.props !== null && - '_sentryTraceData' in this.props && - typeof this.props._sentryTraceData === 'string' - ? this.props._sentryTraceData - : undefined; + const scope = getCurrentScope(); + // We extract the sentry trace data that is put in the component props by datafetcher wrappers + const sentryTraceData = + typeof this.props === 'object' && + this.props !== null && + '_sentryTraceData' in this.props && + typeof this.props._sentryTraceData === 'string' + ? this.props._sentryTraceData + : undefined; - if (sentryTraceData) { - const traceparentData = extractTraceparentData(sentryTraceData); - scope.setContext('trace', { - span_id: traceparentData?.parentSpanId, - trace_id: traceparentData?.traceId, - }); - } - }); + if (sentryTraceData) { + const traceparentData = extractTraceparentData(sentryTraceData); + scope.setContext('trace', { + span_id: traceparentData?.parentSpanId, + trace_id: traceparentData?.traceId, + }); + } try { return super.render(...args); @@ -62,18 +61,18 @@ export function wrapPageComponentWithSentry(pageComponent: FunctionComponent | C return new Proxy(pageComponent, { apply(target, thisArg, argArray: [{ _sentryTraceData?: string } | undefined]) { return runWithAsyncContext(() => { - configureScope(scope => { - // We extract the sentry trace data that is put in the component props by datafetcher wrappers - const sentryTraceData = argArray?.[0]?._sentryTraceData; + const scope = getCurrentScope(); + // We extract the sentry trace data that is put in the component props by datafetcher wrappers + const sentryTraceData = argArray?.[0]?._sentryTraceData; + + if (sentryTraceData) { + const traceparentData = extractTraceparentData(sentryTraceData); + scope.setContext('trace', { + span_id: traceparentData?.parentSpanId, + trace_id: traceparentData?.traceId, + }); + } - if (sentryTraceData) { - const traceparentData = extractTraceparentData(sentryTraceData); - scope.setContext('trace', { - span_id: traceparentData?.parentSpanId, - trace_id: traceparentData?.traceId, - }); - } - }); try { return target.apply(thisArg, argArray); } catch (e) { diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index b049be2c31b8..a7549506ae14 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -2,7 +2,7 @@ import * as path from 'path'; import { addTracingExtensions } from '@sentry/core'; import { RewriteFrames } from '@sentry/integrations'; import type { NodeOptions } from '@sentry/node'; -import { Integrations, configureScope, getCurrentHub, init as nodeInit } from '@sentry/node'; +import { Integrations, getCurrentHub, getCurrentScope, init as nodeInit } from '@sentry/node'; import type { EventProcessor } from '@sentry/types'; import type { IntegrationWithExclusionOption } from '@sentry/utils'; import { addOrUpdateIntegration, escapeStringForRegex, logger } from '@sentry/utils'; @@ -101,18 +101,17 @@ export function init(options: NodeOptions): void { filterTransactions.id = 'NextServer404TransactionFilter'; - configureScope(scope => { - scope.setTag('runtime', 'node'); - if (IS_VERCEL) { - scope.setTag('vercel', true); - } + const scope = getCurrentScope(); + scope.setTag('runtime', 'node'); + if (IS_VERCEL) { + scope.setTag('vercel', true); + } - scope.addEventProcessor(filterTransactions); + scope.addEventProcessor(filterTransactions); - if (process.env.NODE_ENV === 'development') { - scope.addEventProcessor(devErrorSymbolicationEventProcessor); - } - }); + if (process.env.NODE_ENV === 'development') { + scope.addEventProcessor(devErrorSymbolicationEventProcessor); + } DEBUG_BUILD && logger.log('SDK successfully initialized'); } diff --git a/packages/node-integration-tests/suites/public-api/configureScope/clear_scope/scenario.ts b/packages/node-integration-tests/suites/public-api/configureScope/clear_scope/scenario.ts index 93a950c257f2..588c56c273e9 100644 --- a/packages/node-integration-tests/suites/public-api/configureScope/clear_scope/scenario.ts +++ b/packages/node-integration-tests/suites/public-api/configureScope/clear_scope/scenario.ts @@ -5,11 +5,10 @@ Sentry.init({ release: '1.0', }); -Sentry.configureScope(scope => { - scope.setTag('foo', 'bar'); - scope.setUser({ id: 'baz' }); - scope.setExtra('qux', 'quux'); - scope.clear(); -}); +const scope = Sentry.getCurrentScope(); +scope.setTag('foo', 'bar'); +scope.setUser({ id: 'baz' }); +scope.setExtra('qux', 'quux'); +scope.clear(); Sentry.captureMessage('cleared_scope'); diff --git a/packages/node-integration-tests/suites/public-api/configureScope/set_properties/scenario.ts b/packages/node-integration-tests/suites/public-api/configureScope/set_properties/scenario.ts index 941265006ee8..b3f3f4d4ae15 100644 --- a/packages/node-integration-tests/suites/public-api/configureScope/set_properties/scenario.ts +++ b/packages/node-integration-tests/suites/public-api/configureScope/set_properties/scenario.ts @@ -5,10 +5,9 @@ Sentry.init({ release: '1.0', }); -Sentry.configureScope(scope => { - scope.setTag('foo', 'bar'); - scope.setUser({ id: 'baz' }); - scope.setExtra('qux', 'quux'); -}); +const scope = Sentry.getCurrentScope(); +scope.setTag('foo', 'bar'); +scope.setUser({ id: 'baz' }); +scope.setExtra('qux', 'quux'); Sentry.captureMessage('configured_scope'); diff --git a/packages/node-integration-tests/suites/tracing-new/apollo-graphql/scenario.ts b/packages/node-integration-tests/suites/tracing-new/apollo-graphql/scenario.ts index 5bd8aa815cbe..7fdbfce0351c 100644 --- a/packages/node-integration-tests/suites/tracing-new/apollo-graphql/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/apollo-graphql/scenario.ts @@ -29,9 +29,7 @@ const server = new ApolloServer({ const transaction = Sentry.startTransaction({ name: 'test_transaction', op: 'transaction' }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); void (async () => { // Ref: https://www.apollographql.com/docs/apollo-server/testing/testing/#testing-using-executeoperation diff --git a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mongodb/scenario.ts b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mongodb/scenario.ts index 31d7356765e9..cae4627e7096 100644 --- a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mongodb/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mongodb/scenario.ts @@ -21,9 +21,7 @@ async function run(): Promise { op: 'transaction', }); - Sentry.configureScope(scope => { - scope.setSpan(transaction); - }); + Sentry.getCurrentScope().setSpan(transaction); try { await client.connect(); diff --git a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withConnect/scenario.ts b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withConnect/scenario.ts index 0f576cb793aa..7d94099ea30c 100644 --- a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withConnect/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withConnect/scenario.ts @@ -24,9 +24,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); connection.query('SELECT 1 + 1 AS solution', function () { connection.query('SELECT NOW()', ['1', '2'], () => { diff --git a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutCallback/scenario.ts b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutCallback/scenario.ts index ac1d6421dec8..4b3346caed20 100644 --- a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutCallback/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutCallback/scenario.ts @@ -24,9 +24,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); const query = connection.query('SELECT 1 + 1 AS solution'); const query2 = connection.query('SELECT NOW()', ['1', '2']); diff --git a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutConnect/scenario.ts b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutConnect/scenario.ts index c7cc0e660fc4..2e13bf49b9ac 100644 --- a/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutConnect/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/auto-instrument/mysql/withoutConnect/scenario.ts @@ -18,9 +18,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); connection.query('SELECT 1 + 1 AS solution', function () { connection.query('SELECT NOW()', ['1', '2'], () => { diff --git a/packages/node-integration-tests/suites/tracing-new/auto-instrument/pg/scenario.ts b/packages/node-integration-tests/suites/tracing-new/auto-instrument/pg/scenario.ts index a7859fd562a3..c10661094981 100644 --- a/packages/node-integration-tests/suites/tracing-new/auto-instrument/pg/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/auto-instrument/pg/scenario.ts @@ -13,9 +13,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); const client = new pg.Client(); client.query('SELECT * FROM foo where bar ilike "baz%"', ['a', 'b'], () => diff --git a/packages/node-integration-tests/suites/tracing-new/prisma-orm/scenario.ts b/packages/node-integration-tests/suites/tracing-new/prisma-orm/scenario.ts index 27d82a4c4dd1..c7a5ef761a82 100644 --- a/packages/node-integration-tests/suites/tracing-new/prisma-orm/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/prisma-orm/scenario.ts @@ -18,9 +18,7 @@ async function run(): Promise { op: 'transaction', }); - Sentry.configureScope(scope => { - scope.setSpan(transaction); - }); + Sentry.getCurrentScope().setSpan(transaction); try { await client.user.create({ diff --git a/packages/node-integration-tests/suites/tracing-new/tracePropagationTargets/scenario.ts b/packages/node-integration-tests/suites/tracing-new/tracePropagationTargets/scenario.ts index 9084c06441fb..d1eb5fe017ed 100644 --- a/packages/node-integration-tests/suites/tracing-new/tracePropagationTargets/scenario.ts +++ b/packages/node-integration-tests/suites/tracing-new/tracePropagationTargets/scenario.ts @@ -12,9 +12,7 @@ Sentry.init({ const transaction = Sentry.startTransaction({ name: 'test_transaction' }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); http.get('http://match-this-url.com/api/v0'); http.get('http://match-this-url.com/api/v1'); diff --git a/packages/node-integration-tests/suites/tracing/apollo-graphql/scenario.ts b/packages/node-integration-tests/suites/tracing/apollo-graphql/scenario.ts index 732d32814f95..4a4d5a989227 100644 --- a/packages/node-integration-tests/suites/tracing/apollo-graphql/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/apollo-graphql/scenario.ts @@ -31,9 +31,7 @@ const server = new ApolloServer({ const transaction = Sentry.startTransaction({ name: 'test_transaction', op: 'transaction' }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); void (async () => { // Ref: https://www.apollographql.com/docs/apollo-server/testing/testing/#testing-using-executeoperation diff --git a/packages/node-integration-tests/suites/tracing/auto-instrument/mongodb/scenario.ts b/packages/node-integration-tests/suites/tracing/auto-instrument/mongodb/scenario.ts index 896a91181846..5bd16772d50f 100644 --- a/packages/node-integration-tests/suites/tracing/auto-instrument/mongodb/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/auto-instrument/mongodb/scenario.ts @@ -22,9 +22,7 @@ async function run(): Promise { op: 'transaction', }); - Sentry.configureScope(scope => { - scope.setSpan(transaction); - }); + Sentry.getCurrentScope().setSpan(transaction); try { await client.connect(); diff --git a/packages/node-integration-tests/suites/tracing/auto-instrument/mysql/scenario.ts b/packages/node-integration-tests/suites/tracing/auto-instrument/mysql/scenario.ts index f852eec7b2df..2cf161c0ab78 100644 --- a/packages/node-integration-tests/suites/tracing/auto-instrument/mysql/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/auto-instrument/mysql/scenario.ts @@ -25,9 +25,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); connection.query('SELECT 1 + 1 AS solution', function () { connection.query('SELECT NOW()', ['1', '2'], () => { diff --git a/packages/node-integration-tests/suites/tracing/auto-instrument/pg/scenario.ts b/packages/node-integration-tests/suites/tracing/auto-instrument/pg/scenario.ts index 97a08d088cce..c39069909082 100644 --- a/packages/node-integration-tests/suites/tracing/auto-instrument/pg/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/auto-instrument/pg/scenario.ts @@ -14,9 +14,7 @@ const transaction = Sentry.startTransaction({ name: 'Test Transaction', }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); const client = new pg.Client(); client.query('SELECT * FROM foo where bar ilike "baz%"', ['a', 'b'], () => diff --git a/packages/node-integration-tests/suites/tracing/prisma-orm/scenario.ts b/packages/node-integration-tests/suites/tracing/prisma-orm/scenario.ts index 7d953353dfe3..0014717b5fc4 100644 --- a/packages/node-integration-tests/suites/tracing/prisma-orm/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/prisma-orm/scenario.ts @@ -20,9 +20,7 @@ async function run(): Promise { op: 'transaction', }); - Sentry.configureScope(scope => { - scope.setSpan(transaction); - }); + Sentry.getCurrentScope().setSpan(transaction); try { await client.user.create({ diff --git a/packages/node-integration-tests/suites/tracing/tracePropagationTargets/scenario.ts b/packages/node-integration-tests/suites/tracing/tracePropagationTargets/scenario.ts index 23ca6e7122cc..c07faeeb9a3f 100644 --- a/packages/node-integration-tests/suites/tracing/tracePropagationTargets/scenario.ts +++ b/packages/node-integration-tests/suites/tracing/tracePropagationTargets/scenario.ts @@ -14,9 +14,7 @@ Sentry.init({ const transaction = Sentry.startTransaction({ name: 'test_transaction' }); -Sentry.configureScope(scope => { - scope.setSpan(transaction); -}); +Sentry.getCurrentScope().setSpan(transaction); http.get('http://match-this-url.com/api/v0'); http.get('http://match-this-url.com/api/v1'); diff --git a/packages/node/src/handlers.ts b/packages/node/src/handlers.ts index 3160c77b416a..35f1a90190c3 100644 --- a/packages/node/src/handlers.ts +++ b/packages/node/src/handlers.ts @@ -86,9 +86,7 @@ export function tracingHandler(): ( ); // We put the transaction on the scope so users can attach children to it - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); // We also set __sentry_transaction on the response so people can grab the transaction there to add // spans to it later. @@ -186,21 +184,19 @@ export function requestHandler( } runWithAsyncContext(() => { const currentHub = getCurrentHub(); - currentHub.configureScope(scope => { - scope.setSDKProcessingMetadata({ - request: req, - // TODO (v8): Stop passing this - requestDataOptionsFromExpressHandler: requestDataOptions, - }); - - const client = currentHub.getClient(); - if (isAutoSessionTrackingEnabled(client)) { - const scope = currentHub.getScope(); - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: 'ok' }); - } + const scope = currentHub.getScope(); + scope.setSDKProcessingMetadata({ + request: req, + // TODO (v8): Stop passing this + requestDataOptionsFromExpressHandler: requestDataOptions, }); + const client = currentHub.getClient(); + if (isAutoSessionTrackingEnabled(client)) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope.setRequestSession({ status: 'ok' }); + } + res.once('finish', () => { const client = currentHub.getClient(); if (isAutoSessionTrackingEnabled(client)) { diff --git a/packages/node/test/eventbuilders.test.ts b/packages/node/test/eventbuilders.test.ts index 53598505d474..3c2ae88f03e3 100644 --- a/packages/node/test/eventbuilders.test.ts +++ b/packages/node/test/eventbuilders.test.ts @@ -12,7 +12,6 @@ jest.mock('@sentry/core', () => { getCurrentHub(): { getClient(): Client; getScope(): Scope; - configureScope(scopeFunction: (scope: Scope) => void): void; } { return { getClient(): any { @@ -23,10 +22,7 @@ jest.mock('@sentry/core', () => { }; }, getScope(): Scope { - return new Scope(); - }, - configureScope(scopeFunction: (scope: Scope) => void): void { - scopeFunction(testScope); + return testScope; }, }; }, diff --git a/packages/node/test/index.test.ts b/packages/node/test/index.test.ts index 2b91dc414ee1..3bb90a710708 100644 --- a/packages/node/test/index.test.ts +++ b/packages/node/test/index.test.ts @@ -1,16 +1,16 @@ import { LinkedErrors, SDK_VERSION, getMainCarrier, initAndBind, runWithAsyncContext } from '@sentry/core'; import type { EventHint, Integration } from '@sentry/types'; -import type { Event, Scope } from '../src'; +import type { Event } from '../src'; import { NodeClient, addBreadcrumb, captureEvent, captureException, captureMessage, - configureScope, getClient, getCurrentHub, + getCurrentScope, init, } from '../src'; import { setNodeAsyncContextStrategy } from '../src/async'; @@ -48,27 +48,21 @@ describe('SentryNode', () => { describe('getContext() / setContext()', () => { test('store/load extra', async () => { - configureScope((scope: Scope) => { - scope.setExtra('abc', { def: [1] }); - }); + getCurrentScope().setExtra('abc', { def: [1] }); expect(global.__SENTRY__.hub._stack[1].scope._extra).toEqual({ abc: { def: [1] }, }); }); test('store/load tags', async () => { - configureScope((scope: Scope) => { - scope.setTag('abc', 'def'); - }); + getCurrentScope().setTag('abc', 'def'); expect(global.__SENTRY__.hub._stack[1].scope._tags).toEqual({ abc: 'def', }); }); test('store/load user', async () => { - configureScope((scope: Scope) => { - scope.setUser({ id: 'def' }); - }); + getCurrentScope().setUser({ id: 'def' }); expect(global.__SENTRY__.hub._stack[1].scope._user).toEqual({ id: 'def', }); @@ -138,9 +132,7 @@ describe('SentryNode', () => { dsn, }); getCurrentHub().bindClient(new NodeClient(options)); - configureScope((scope: Scope) => { - scope.setTag('test', '1'); - }); + getCurrentScope().setTag('test', '1'); try { throw new Error('test'); } catch (e) { @@ -165,9 +157,7 @@ describe('SentryNode', () => { dsn, }); getCurrentHub().bindClient(new NodeClient(options)); - configureScope((scope: Scope) => { - scope.setTag('test', '1'); - }); + getCurrentScope().setTag('test', '1'); try { throw 'test string exception'; } catch (e) { @@ -197,9 +187,7 @@ describe('SentryNode', () => { integrations: [new ContextLines()], }); getCurrentHub().bindClient(new NodeClient(options)); - configureScope((scope: Scope) => { - scope.setTag('test', '1'); - }); + getCurrentScope().setTag('test', '1'); try { throw new Error('test'); } catch (e) { diff --git a/packages/node/test/integrations/http.test.ts b/packages/node/test/integrations/http.test.ts index ba5bbe91151c..3a147af422dd 100644 --- a/packages/node/test/integrations/http.test.ts +++ b/packages/node/test/integrations/http.test.ts @@ -38,12 +38,10 @@ describe('tracing', () => { const hub = new Hub(new NodeClient(options)); addTracingExtensions(); - hub.configureScope(scope => - scope.setUser({ - id: 'uid123', - segment: 'segmentA', - }), - ); + hub.getScope().setUser({ + id: 'uid123', + segment: 'segmentA', + }); jest.spyOn(sentryCore, 'getCurrentHub').mockReturnValue(hub); diff --git a/packages/opentelemetry-node/test/spanprocessor.test.ts b/packages/opentelemetry-node/test/spanprocessor.test.ts index 9de394d2232d..69ef554c132c 100644 --- a/packages/opentelemetry-node/test/spanprocessor.test.ts +++ b/packages/opentelemetry-node/test/spanprocessor.test.ts @@ -966,9 +966,7 @@ describe('SentrySpanProcessor', () => { makeMain(hub); const newHub = new Hub(client, hub.getScope().clone()); - newHub.configureScope(scope => { - scope.setTag('foo', 'bar'); - }); + newHub.getScope().setTag('foo', 'bar'); const tracer = provider.getTracer('default'); diff --git a/packages/react/src/redux.ts b/packages/react/src/redux.ts index b81622f8797c..38f99d7af825 100644 --- a/packages/react/src/redux.ts +++ b/packages/react/src/redux.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { addEventProcessor, configureScope, getClient } from '@sentry/browser'; +import { addEventProcessor, getClient, getCurrentScope } from '@sentry/browser'; import type { Scope } from '@sentry/types'; import { addNonEnumerableProperty } from '@sentry/utils'; @@ -116,44 +116,43 @@ function createReduxEnhancer(enhancerOptions?: Partial): const sentryReducer: Reducer = (state, action): S => { const newState = reducer(state, action); - configureScope(scope => { - /* Action breadcrumbs */ - const transformedAction = options.actionTransformer(action); - if (typeof transformedAction !== 'undefined' && transformedAction !== null) { - scope.addBreadcrumb({ - category: ACTION_BREADCRUMB_CATEGORY, - data: transformedAction, - type: ACTION_BREADCRUMB_TYPE, - }); - } - - /* Set latest state to scope */ - const transformedState = options.stateTransformer(newState); - if (typeof transformedState !== 'undefined' && transformedState !== null) { - const client = getClient(); - const options = client && client.getOptions(); - const normalizationDepth = (options && options.normalizeDepth) || 3; // default state normalization depth to 3 - - // Set the normalization depth of the redux state to the configured `normalizeDepth` option or a sane number as a fallback - const newStateContext = { state: { type: 'redux', value: transformedState } }; - addNonEnumerableProperty( - newStateContext, - '__sentry_override_normalization_depth__', - 3 + // 3 layers for `state.value.transformedState` - normalizationDepth, // rest for the actual state - ); - - scope.setContext('state', newStateContext); - } else { - scope.setContext('state', null); - } - - /* Allow user to configure scope with latest state */ - const { configureScopeWithState } = options; - if (typeof configureScopeWithState === 'function') { - configureScopeWithState(scope, newState); - } - }); + const scope = getCurrentScope(); + /* Action breadcrumbs */ + const transformedAction = options.actionTransformer(action); + if (typeof transformedAction !== 'undefined' && transformedAction !== null) { + scope.addBreadcrumb({ + category: ACTION_BREADCRUMB_CATEGORY, + data: transformedAction, + type: ACTION_BREADCRUMB_TYPE, + }); + } + + /* Set latest state to scope */ + const transformedState = options.stateTransformer(newState); + if (typeof transformedState !== 'undefined' && transformedState !== null) { + const client = getClient(); + const options = client && client.getOptions(); + const normalizationDepth = (options && options.normalizeDepth) || 3; // default state normalization depth to 3 + + // Set the normalization depth of the redux state to the configured `normalizeDepth` option or a sane number as a fallback + const newStateContext = { state: { type: 'redux', value: transformedState } }; + addNonEnumerableProperty( + newStateContext, + '__sentry_override_normalization_depth__', + 3 + // 3 layers for `state.value.transformedState` + normalizationDepth, // rest for the actual state + ); + + scope.setContext('state', newStateContext); + } else { + scope.setContext('state', null); + } + + /* Allow user to configure scope with latest state */ + const { configureScopeWithState } = options; + if (typeof configureScopeWithState === 'function') { + configureScopeWithState(scope, newState); + } return newState; }; diff --git a/packages/react/test/redux.test.ts b/packages/react/test/redux.test.ts index 61b908a1d5fe..60cf59abd74e 100644 --- a/packages/react/test/redux.test.ts +++ b/packages/react/test/redux.test.ts @@ -9,11 +9,12 @@ const mockSetContext = jest.fn(); jest.mock('@sentry/browser', () => ({ ...jest.requireActual('@sentry/browser'), - configureScope: (callback: (scope: any) => Partial) => - callback({ + getCurrentScope() { + return { addBreadcrumb: mockAddBreadcrumb, setContext: mockSetContext, - }), + }; + }, addEventProcessor: jest.fn(), })); @@ -240,8 +241,7 @@ describe('createReduxEnhancer', () => { value: 'latest', }); - let scopeRef; - Sentry.configureScope(scope => (scopeRef = scope)); + const scopeRef = Sentry.getCurrentScope(); expect(configureScopeWithState).toBeCalledWith(scopeRef, { value: 'latest', diff --git a/packages/remix/src/index.client.tsx b/packages/remix/src/index.client.tsx index fd37f3001d83..63b39253416d 100644 --- a/packages/remix/src/index.client.tsx +++ b/packages/remix/src/index.client.tsx @@ -1,4 +1,4 @@ -import { configureScope, init as reactInit } from '@sentry/react'; +import { getCurrentScope, init as reactInit } from '@sentry/react'; import { buildMetadata } from './utils/metadata'; import type { RemixOptions } from './utils/remixOptions'; @@ -12,7 +12,5 @@ export function init(options: RemixOptions): void { reactInit(options); - configureScope(scope => { - scope.setTag('runtime', 'browser'); - }); + getCurrentScope().setTag('runtime', 'browser'); } diff --git a/packages/remix/src/index.server.ts b/packages/remix/src/index.server.ts index 12fc10b522cf..1c1c0ffee072 100644 --- a/packages/remix/src/index.server.ts +++ b/packages/remix/src/index.server.ts @@ -1,5 +1,5 @@ import type { NodeOptions } from '@sentry/node'; -import { configureScope, getCurrentHub, init as nodeInit } from '@sentry/node'; +import { getCurrentHub, getCurrentScope, init as nodeInit } from '@sentry/node'; import { logger } from '@sentry/utils'; import { DEBUG_BUILD } from './utils/debug-build'; @@ -86,7 +86,5 @@ export function init(options: RemixOptions): void { nodeInit(options as NodeOptions); - configureScope(scope => { - scope.setTag('runtime', 'node'); - }); + getCurrentScope().setTag('runtime', 'node'); } diff --git a/packages/serverless/src/gcpfunction/cloud_events.ts b/packages/serverless/src/gcpfunction/cloud_events.ts index 05595867c191..63303470d9e9 100644 --- a/packages/serverless/src/gcpfunction/cloud_events.ts +++ b/packages/serverless/src/gcpfunction/cloud_events.ts @@ -1,4 +1,4 @@ -import { captureException, flush, getCurrentHub } from '@sentry/node'; +import { captureException, flush, getCurrentHub, getCurrentScope } from '@sentry/node'; import { isThenable, logger } from '@sentry/utils'; import { DEBUG_BUILD } from '../debug-build'; @@ -43,11 +43,10 @@ function _wrapCloudEventFunction( // getCurrentHub() is expected to use current active domain as a carrier // since functions-framework creates a domain for each incoming request. // So adding of event processors every time should not lead to memory bloat. - hub.configureScope(scope => { - scope.setContext('gcp.function.context', { ...context }); - // We put the transaction on the scope so users can attach children to it - scope.setSpan(transaction); - }); + const scope = getCurrentScope(); + scope.setContext('gcp.function.context', { ...context }); + // We put the transaction on the scope so users can attach children to it + scope.setSpan(transaction); const newCallback = domainify((...args: unknown[]) => { if (args[0] !== null && args[0] !== undefined) { diff --git a/packages/serverless/src/gcpfunction/events.ts b/packages/serverless/src/gcpfunction/events.ts index c3be42c6a6c2..29d151593990 100644 --- a/packages/serverless/src/gcpfunction/events.ts +++ b/packages/serverless/src/gcpfunction/events.ts @@ -1,4 +1,4 @@ -import { captureException, flush, getCurrentHub } from '@sentry/node'; +import { captureException, flush, getCurrentHub, getCurrentScope } from '@sentry/node'; import { isThenable, logger } from '@sentry/utils'; import { DEBUG_BUILD } from '../debug-build'; @@ -45,11 +45,10 @@ function _wrapEventFunction // getCurrentHub() is expected to use current active domain as a carrier // since functions-framework creates a domain for each incoming request. // So adding of event processors every time should not lead to memory bloat. - hub.configureScope(scope => { - scope.setContext('gcp.function.context', { ...context }); - // We put the transaction on the scope so users can attach children to it - scope.setSpan(transaction); - }); + const scope = getCurrentScope(); + scope.setContext('gcp.function.context', { ...context }); + // We put the transaction on the scope so users can attach children to it + scope.setSpan(transaction); const newCallback = domainify((...args: unknown[]) => { if (args[0] !== null && args[0] !== undefined) { diff --git a/packages/serverless/src/gcpfunction/http.ts b/packages/serverless/src/gcpfunction/http.ts index 8f4a77099696..95c84cafeb80 100644 --- a/packages/serverless/src/gcpfunction/http.ts +++ b/packages/serverless/src/gcpfunction/http.ts @@ -1,4 +1,5 @@ import type { AddRequestDataToEventOptions } from '@sentry/node'; +import { getCurrentScope } from '@sentry/node'; import { captureException, flush, getCurrentHub } from '@sentry/node'; import { isString, isThenable, logger, stripUrlQueryAndFragment, tracingContextFromHeaders } from '@sentry/utils'; @@ -63,6 +64,7 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial { const hub = getCurrentHub(); + const scope = getCurrentScope(); const reqMethod = (req.method || '').toUpperCase(); const reqUrl = stripUrlQueryAndFragment(req.originalUrl || req.url || ''); @@ -73,7 +75,7 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial { - scope.setSDKProcessingMetadata({ - request: req, - requestDataOptionsFromGCPWrapper: options.addRequestDataToEventOptions, - }); - // We put the transaction on the scope so users can attach children to it - scope.setSpan(transaction); + scope.setSDKProcessingMetadata({ + request: req, + requestDataOptionsFromGCPWrapper: options.addRequestDataToEventOptions, }); + // We put the transaction on the scope so users can attach children to it + scope.setSpan(transaction); // We also set __sentry_transaction on the response so people can grab the transaction there to add // spans to it later. diff --git a/packages/serverless/test/__mocks__/@sentry/node.ts b/packages/serverless/test/__mocks__/@sentry/node.ts index c29f8f78dd0a..b9eba4b132a9 100644 --- a/packages/serverless/test/__mocks__/@sentry/node.ts +++ b/packages/serverless/test/__mocks__/@sentry/node.ts @@ -35,6 +35,7 @@ export const fakeTransaction = { export const init = jest.fn(); export const addGlobalEventProcessor = jest.fn(); export const getCurrentHub = jest.fn(() => fakeHub); +export const getCurrentScope = jest.fn(() => fakeScope); export const startTransaction = jest.fn(_ => fakeTransaction); export const captureException = jest.fn(); export const captureMessage = jest.fn(); diff --git a/packages/sveltekit/src/client/sdk.ts b/packages/sveltekit/src/client/sdk.ts index 900813ce7f9b..ebfd1f281404 100644 --- a/packages/sveltekit/src/client/sdk.ts +++ b/packages/sveltekit/src/client/sdk.ts @@ -1,6 +1,6 @@ import { hasTracingEnabled } from '@sentry/core'; import type { BrowserOptions } from '@sentry/svelte'; -import { BrowserTracing, WINDOW, configureScope, init as initSvelteSdk } from '@sentry/svelte'; +import { BrowserTracing, WINDOW, getCurrentScope, init as initSvelteSdk } from '@sentry/svelte'; import { addOrUpdateIntegration } from '@sentry/utils'; import { applySdkMetadata } from '../common/metadata'; @@ -34,9 +34,7 @@ export function init(options: BrowserOptions): void { restoreFetch(actualFetch); } - configureScope(scope => { - scope.setTag('runtime', 'browser'); - }); + getCurrentScope().setTag('runtime', 'browser'); } function addClientIntegrations(options: BrowserOptions): void { diff --git a/packages/sveltekit/src/server/sdk.ts b/packages/sveltekit/src/server/sdk.ts index 613fe8d834f0..03847d6cc4e4 100644 --- a/packages/sveltekit/src/server/sdk.ts +++ b/packages/sveltekit/src/server/sdk.ts @@ -1,4 +1,4 @@ -import { configureScope } from '@sentry/core'; +import { getCurrentScope } from '@sentry/core'; import { RewriteFrames } from '@sentry/integrations'; import type { NodeOptions } from '@sentry/node'; import { init as initNodeSdk } from '@sentry/node'; @@ -18,9 +18,7 @@ export function init(options: NodeOptions): void { initNodeSdk(options); - configureScope(scope => { - scope.setTag('runtime', 'node'); - }); + getCurrentScope().setTag('runtime', 'node'); } function addServerIntegrations(options: NodeOptions): void { diff --git a/packages/tracing-internal/test/browser/backgroundtab.test.ts b/packages/tracing-internal/test/browser/backgroundtab.test.ts index 031d68d01d78..2687d59069c5 100644 --- a/packages/tracing-internal/test/browser/backgroundtab.test.ts +++ b/packages/tracing-internal/test/browser/backgroundtab.test.ts @@ -30,7 +30,7 @@ conditionalTest({ min: 10 })('registerBackgroundTabDetection', () => { afterEach(() => { events = {}; - hub.configureScope(scope => scope.setSpan(undefined)); + hub.getScope().setSpan(undefined); }); it('does not create an event listener if global document is undefined', () => { @@ -48,7 +48,7 @@ conditionalTest({ min: 10 })('registerBackgroundTabDetection', () => { it('finishes a transaction on visibility change', () => { registerBackgroundTabDetection(); const transaction = hub.startTransaction({ name: 'test' }); - hub.configureScope(scope => scope.setSpan(transaction)); + hub.getScope().setSpan(transaction); // Simulate document visibility hidden event // @ts-expect-error need to override global document diff --git a/packages/tracing-internal/test/browser/request.test.ts b/packages/tracing-internal/test/browser/request.test.ts index 29cf7e287f0c..0f3ce191278a 100644 --- a/packages/tracing-internal/test/browser/request.test.ts +++ b/packages/tracing-internal/test/browser/request.test.ts @@ -74,7 +74,7 @@ describe('callbacks', () => { beforeEach(() => { transaction = hub.startTransaction({ name: 'organizations/users/:userid', op: 'pageload' }) as Transaction; - hub.configureScope(scope => scope.setSpan(transaction)); + hub.getScope().setSpan(transaction); }); afterEach(() => { diff --git a/packages/tracing/test/hub.test.ts b/packages/tracing/test/hub.test.ts index 86fcf5d6807e..817e88c9c55e 100644 --- a/packages/tracing/test/hub.test.ts +++ b/packages/tracing/test/hub.test.ts @@ -40,9 +40,7 @@ describe('Hub', () => { const transaction = hub.startTransaction({ name: 'dogpark' }); transaction.sampled = true; - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); expect(hub.getScope().getTransaction()).toBe(transaction); }); @@ -53,9 +51,7 @@ describe('Hub', () => { makeMain(hub); const transaction = hub.startTransaction({ name: 'dogpark', sampled: false }); - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); expect(hub.getScope().getTransaction()).toBe(transaction); }); @@ -472,9 +468,7 @@ The transaction will not be sampled. Please use the otel instrumentation to star makeMain(hub); const transaction = hub.startTransaction({ name: 'dogpark' }); - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); const request = new XMLHttpRequest(); await new Promise(resolve => { @@ -513,9 +507,7 @@ The transaction will not be sampled. Please use the otel instrumentation to star makeMain(hub); const transaction = hub.startTransaction({ name: 'dogpark', sampled: false }); - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); const request = new XMLHttpRequest(); await new Promise(resolve => { diff --git a/packages/tracing/test/idletransaction.test.ts b/packages/tracing/test/idletransaction.test.ts index 32be1c2e421a..30cd97f775b1 100644 --- a/packages/tracing/test/idletransaction.test.ts +++ b/packages/tracing/test/idletransaction.test.ts @@ -25,18 +25,16 @@ describe('IdleTransaction', () => { ); transaction.initSpanRecorder(10); - hub.configureScope(s => { - expect(s.getTransaction()).toBe(transaction); - }); + const scope = hub.getScope(); + expect(scope.getTransaction()).toBe(transaction); }); it('does not set the transaction on the scope on creation if onScope is falsey', () => { const transaction = new IdleTransaction({ name: 'foo' }, hub); transaction.initSpanRecorder(10); - hub.configureScope(s => { - expect(s.getTransaction()).toBe(undefined); - }); + const scope = hub.getScope(); + expect(scope.getTransaction()).toBe(undefined); }); it('removes sampled transaction from scope on finish if onScope is true', () => { @@ -53,9 +51,8 @@ describe('IdleTransaction', () => { transaction.finish(); jest.runAllTimers(); - hub.configureScope(s => { - expect(s.getTransaction()).toBe(undefined); - }); + const scope = hub.getScope(); + expect(scope.getTransaction()).toBe(undefined); }); it('removes unsampled transaction from scope on finish if onScope is true', () => { @@ -71,9 +68,8 @@ describe('IdleTransaction', () => { transaction.finish(); jest.runAllTimers(); - hub.configureScope(s => { - expect(s.getTransaction()).toBe(undefined); - }); + const scope = hub.getScope(); + expect(scope.getTransaction()).toBe(undefined); }); it('does not remove transaction from scope on finish if another transaction was set there', () => { @@ -94,9 +90,8 @@ describe('IdleTransaction', () => { transaction.finish(); jest.runAllTimers(); - hub.configureScope(s => { - expect(s.getTransaction()).toBe(otherTransaction); - }); + const scope = hub.getScope(); + expect(scope.getTransaction()).toBe(otherTransaction); }); }); diff --git a/packages/tracing/test/span.test.ts b/packages/tracing/test/span.test.ts index 1a7981ad95f6..3e6c267b1233 100644 --- a/packages/tracing/test/span.test.ts +++ b/packages/tracing/test/span.test.ts @@ -226,9 +226,7 @@ describe('Span', () => { const childSpanOne = transaction.startChild(); childSpanOne.finish(); - hub.configureScope(scope => { - scope.setSpan(childSpanOne); - }); + hub.getScope().setSpan(childSpanOne); const spanTwo = transaction.startChild(); spanTwo.finish(); @@ -282,9 +280,7 @@ describe('Span', () => { childSpanOne.finish(); - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + hub.getScope().setSpan(transaction); const spanTwo = transaction.startChild({}); spanTwo.finish(); diff --git a/packages/utils/src/eventbuilder.ts b/packages/utils/src/eventbuilder.ts index 03af0b3d1905..5dac2f583bb6 100644 --- a/packages/utils/src/eventbuilder.ts +++ b/packages/utils/src/eventbuilder.ts @@ -82,9 +82,7 @@ export function eventFromUnknownInput( const hub = getCurrentHub(); const client = hub.getClient(); const normalizeDepth = client && client.getOptions().normalizeDepth; - hub.configureScope(scope => { - scope.setExtra('__serialized__', normalizeToSize(exception, normalizeDepth)); - }); + hub.getScope().setExtra('__serialized__', normalizeToSize(exception, normalizeDepth)); const message = getMessageForObject(exception); ex = (hint && hint.syntheticException) || new Error(message); diff --git a/packages/utils/test/eventbuilder.test.ts b/packages/utils/test/eventbuilder.test.ts index 137860b16ce4..b1c46630de08 100644 --- a/packages/utils/test/eventbuilder.test.ts +++ b/packages/utils/test/eventbuilder.test.ts @@ -1,10 +1,17 @@ -import type { Hub } from '@sentry/types'; +import type { Hub, Scope } from '@sentry/types'; import { createStackParser, eventFromUnknownInput, nodeStackLineParser } from '../src'; function getCurrentHub(): Hub { // Some fake hub to get us through - return { getClient: () => undefined, configureScope: () => {} } as unknown as Hub; + return { + getClient: () => undefined, + getScope: () => { + return { + setExtra: () => {}, + } as unknown as Scope; + }, + } as unknown as Hub; } const stackParser = createStackParser(nodeStackLineParser());