@@ -3,22 +3,28 @@ import {
33 SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN ,
44 SEMANTIC_ATTRIBUTE_SENTRY_SOURCE ,
55 applySdkMetadata ,
6+ getCapturedScopesOnSpan ,
67 getClient ,
8+ getCurrentScope ,
79 getGlobalScope ,
10+ getIsolationScope ,
811 getRootSpan ,
12+ setCapturedScopesOnSpan ,
913 spanToJSON ,
1014} from '@sentry/core' ;
1115import { getDefaultIntegrations , init as nodeInit } from '@sentry/node' ;
1216import type { NodeClient , NodeOptions } from '@sentry/node' ;
1317import { GLOBAL_OBJ , logger } from '@sentry/utils' ;
1418
19+ import { context } from '@opentelemetry/api' ;
1520import {
1621 ATTR_HTTP_REQUEST_METHOD ,
1722 ATTR_HTTP_ROUTE ,
1823 SEMATTRS_HTTP_METHOD ,
1924 SEMATTRS_HTTP_TARGET ,
2025} from '@opentelemetry/semantic-conventions' ;
21- import type { EventProcessor } from '@sentry/types' ;
26+ import { getScopesFromContext } from '@sentry/opentelemetry' ;
27+ import type { EventProcessor , Scope } from '@sentry/types' ;
2228import { DEBUG_BUILD } from '../common/debug-build' ;
2329import { devErrorSymbolicationEventProcessor } from '../common/devErrorSymbolicationEventProcessor' ;
2430import { getVercelEnv } from '../common/getVercelEnv' ;
@@ -197,6 +203,22 @@ export function init(options: NodeOptions): NodeClient | undefined {
197203 // We want to rename these spans because they look like "GET /path/to/route" and we already emit spans that look
198204 // like this with our own http instrumentation.
199205 if ( spanAttributes ?. [ 'next.span_type' ] === 'BaseServer.handleRequest' ) {
206+ const isRootSpan = span === getRootSpan ( span ) ;
207+ if ( isRootSpan ) {
208+ // TODO(lforst): Verify if this is actually working and add tests
209+ const scopes = getCapturedScopesOnSpan ( span ) ;
210+
211+ const isolationScope = ( scopes . isolationScope || getIsolationScope ( ) ) . clone ( ) ;
212+ const scope = scopes . scope || getCurrentScope ( ) ;
213+
214+ const client = getClient < NodeClient > ( ) ;
215+ if ( client && client . getOptions ( ) . autoSessionTracking ) {
216+ isolationScope . setRequestSession ( { status : 'ok' } ) ;
217+ }
218+ setIsolationScope ( isolationScope ) ;
219+ setCapturedScopesOnSpan ( span , scope , isolationScope ) ;
220+ }
221+ } else {
200222 span . updateName ( 'next server handler' ) ; // This is all lowercase because the spans that Next.js emits by itself generally look like this.
201223 }
202224 } ) ;
@@ -327,3 +349,14 @@ function sdkAlreadyInitialized(): boolean {
327349export * from '../common' ;
328350
329351export { wrapApiHandlerWithSentry } from '../common/wrapApiHandlerWithSentry' ;
352+
353+ /*
354+ * Update the active isolation scope.
355+ * Should be used with caution!
356+ */
357+ function setIsolationScope ( isolationScope : Scope ) : void {
358+ const scopes = getScopesFromContext ( context . active ( ) ) ;
359+ if ( scopes ) {
360+ scopes . isolationScope = isolationScope ;
361+ }
362+ }
0 commit comments