| |
| |
| |
| |
| @@ -242,6 +242,19 @@ class NextTracerImpl implements NextTracer { |
| return trace.getSpan(context?.active()) |
| } |
| |
| + /** |
| + * Run `fn` with the active span cleared, so spans created inside become new |
| + * roots (or parent to incoming propagated context). Used for in-process |
| + * Node.js middleware so its span is a sibling of the request span, matching |
| + * edge middleware which runs in a detached sandbox. |
| + */ |
| + public runWithDetachedContext<T>(fn: () => T): T { |
| + if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isTracingEnabled()) { |
| + return fn() |
| + } |
| + return context.with(ROOT_CONTEXT, fn) |
| + } |
| + |
| public withPropagatedContext<T, C>( |
| carrier: C, |
| fn: () => T, |
| |
| |
| |
| |
| @@ -1730,19 +1730,25 @@ export default class NextNodeServer extends BaseServer< |
| Boolean(requestData.body) |
| |
| try { |
| - result = await adapterFn({ |
| - handler: |
| - middlewareModule.proxy || |
| - middlewareModule.middleware || |
| - middlewareModule, |
| - request: { |
| - ...requestData, |
| - body: hasRequestBody |
| - ? requestData.body.cloneBodyStream() |
| - : undefined, |
| - }, |
| - page: 'middleware', |
| - }) |
| + // Node.js middleware runs in-process, inside the active |
| + // `handleRequest` span. Detach that span so the middleware span |
| + // becomes a sibling root (or parents to an incoming traceparent), |
| + // matching edge middleware which runs in a detached sandbox. |
| + result = await getTracer().runWithDetachedContext(() => |
| + adapterFn({ |
| + handler: |
| + middlewareModule.proxy || |
| + middlewareModule.middleware || |
| + middlewareModule, |
| + request: { |
| + ...requestData, |
| + body: hasRequestBody |
| + ? requestData.body.cloneBodyStream() |
| + : undefined, |
| + }, |
| + page: 'middleware', |
| + }) |
| + ) |
| } finally { |
| if (hasRequestBody) { |
| await requestData.body.finalize() |
|
|