Repository navigation
fix(tracing): emit instrumentation lifecycle spans like Next.js 16.4 #4913
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
base: main
Are you sure you want to change the base?
Changes from all commits
eb761a8
fe6f750
bcb8013
41c1680
aa7487c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,7 +26,67 @@ | |
| */ | ||
|
|
||
| import type { OnRequestErrorHandler } from "./instrumentation.js"; | ||
| import { recordFrameworkSpanError } from "./framework-tracer.js"; | ||
| import { extendTracerProviderForCacheComponents } from "./otel-tracer-extension.js"; | ||
| import { frameworkTracer } from "./tracer.js"; | ||
|
|
||
| /** When loading the instrumentation module started and finished (epoch milliseconds). */ | ||
| export type InstrumentationLoadTiming = { | ||
| endTime: number; | ||
| startTime: number; | ||
| }; | ||
|
|
||
| function getInstrumentationTimestamp(): number { | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
|
|
||
| /** | ||
| * Emits a lifecycle span of `instrumentation.ts` after the fact, as Next.js | ||
| * does (`traceBackdatedInstrumentationSpan` in | ||
| * server/lib/router-utils/instrumentation-globals.external.ts): `register()` | ||
| * commonly installs the tracer provider, so the spans can only be emitted | ||
| * once it returns, with their original timestamps. Like `next start`, which | ||
| * registers at startup, they are emitted outside of any request's trace. | ||
| */ | ||
| function traceInstrumentationLifecycleSpan( | ||
| type: "Instrumentation.loadModule" | "Instrumentation.register", | ||
| name: string, | ||
| timing: InstrumentationLoadTiming, | ||
| error?: unknown, | ||
| ): void { | ||
| // Telemetry must not change how registration ends: a throwing tracing | ||
| // integration would otherwise replace register()'s own error, or reject the | ||
| // one-shot registration for every later request. | ||
| try { | ||
| frameworkTracer.runWithDetachedContext(() => | ||
| frameworkTracer.trace( | ||
| { endTime: timing.endTime, name, recordErrors: false, startTime: timing.startTime, type }, | ||
| (span) => { | ||
| if (error !== undefined) recordFrameworkSpanError(span, error); | ||
| }, | ||
| ), | ||
| ); | ||
| } catch (traceError) { | ||
| console.error(`[vinext] Failed to emit the ${type} span:`, traceError); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Emits the failed `load instrumentation module` span when importing | ||
| * `instrumentation.ts` threw. Like Next.js, it is only exported when a tracer | ||
| * provider was already installed, since `register()` never ran. | ||
| */ | ||
| export function traceInstrumentationModuleLoadError( | ||
| timing: InstrumentationLoadTiming, | ||
| error: unknown, | ||
| ): void { | ||
| traceInstrumentationLifecycleSpan( | ||
| "Instrumentation.loadModule", | ||
| "load instrumentation module", | ||
| timing, | ||
| error, | ||
| ); | ||
| } | ||
|
|
||
| type InstrumentationState = { | ||
| initialized: boolean; | ||
|
|
@@ -83,30 +143,67 @@ function isOnRequestErrorHandler(value: unknown): value is OnRequestErrorHandler | |
| * without this helper needing to know the module path. | ||
| * @param instrumentationId - Stable source path used to deduplicate the same | ||
| * instrumentation file when Vite evaluates it in separate environments. | ||
| * @param loadTiming - When importing the module started and finished, when the | ||
| * caller imported it itself. Generated server entries import it statically, | ||
| * so it was evaluated with the entry and its load has no separate duration. | ||
| */ | ||
| export async function ensureInstrumentationRegistered( | ||
| instrumentationModule: Record<string, unknown>, | ||
| instrumentationId?: string, | ||
| loadTiming?: InstrumentationLoadTiming, | ||
| ): Promise<void> { | ||
| if (process.env.VINEXT_PRERENDER === "1") return; | ||
| const state = getInstrumentationState(instrumentationModule, instrumentationId); | ||
| if (state.initialized) return; | ||
| if (state.initPromise) return state.initPromise; | ||
|
|
||
| state.initPromise = (async () => { | ||
| const loadedAt = getInstrumentationTimestamp(); | ||
| const moduleLoadTiming = loadTiming ?? { startTime: loadedAt, endTime: loadedAt }; | ||
| if (typeof instrumentationModule.register === "function") { | ||
| await instrumentationModule.register(); | ||
| const startTime = getInstrumentationTimestamp(); | ||
| let error: unknown; | ||
| try { | ||
| await instrumentationModule.register(); | ||
| // Extend the OTel tracer provider so that span creation inside Cache | ||
| // Component renders exits the workUnitAsyncStorage context. Without | ||
| // this, spans created during prerender / fallback-resume phases would | ||
| // inherit the frozen prerender work unit store, causing span IDs to be | ||
| // reused across requests or not generated at all. Like Next.js's | ||
| // afterRegistration() (instrumentation-node-extensions.ts), it is part | ||
| // of the timed registration. | ||
| extendTracerProviderForCacheComponents(); | ||
| } catch (err) { | ||
| // Like Next.js, name the failing hook on the error it records and throws. | ||
| if (err instanceof Error) { | ||
| err.message = `An error occurred while loading instrumentation hook: ${err.message}`; | ||
| } | ||
| error = err; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Prefix
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 41c1680. A thrown |
||
| throw err; | ||
| } finally { | ||
| // Before emitting: span processors run synchronously in span.end(). | ||
| const endTime = getInstrumentationTimestamp(); | ||
| traceInstrumentationLifecycleSpan( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ℹ️ INFO · Code Quality Lifecycle span emission is not guarded inside the one-shot registration path. A tracing integration that throws could hide the real register() error, or leave registration permanently rejected.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in aa7487c. |
||
| "Instrumentation.loadModule", | ||
| "load instrumentation module", | ||
| moduleLoadTiming, | ||
| ); | ||
| traceInstrumentationLifecycleSpan( | ||
| "Instrumentation.register", | ||
| "register instrumentation", | ||
| { startTime, endTime }, | ||
| error, | ||
| ); | ||
| } | ||
| } else { | ||
| traceInstrumentationLifecycleSpan( | ||
| "Instrumentation.loadModule", | ||
| "load instrumentation module", | ||
| moduleLoadTiming, | ||
| ); | ||
| extendTracerProviderForCacheComponents(); | ||
| } | ||
|
|
||
| // Extend the OTel tracer provider after register() so that span creation | ||
| // inside Cache Component renders exits the workUnitAsyncStorage context. | ||
| // Without this, spans created during prerender / fallback-resume phases | ||
| // would inherit the frozen prerender work unit store, causing span IDs to | ||
| // be reused across requests or not generated at all. | ||
| // Mirrors Next.js's afterRegistration() in | ||
| // packages/next/src/server/lib/router-utils/instrumentation-node-extensions.ts. | ||
| extendTracerProviderForCacheComponents(); | ||
|
|
||
| // Store the onRequestError handler on globalThis so it is visible to | ||
| // reportRequestError() regardless of which Vite environment module graph | ||
| // it is called from. With @vitejs/plugin-rsc the RSC and SSR environments | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The production App and Pages entries still statically import
instrumentation.ts, so a top-level import failure aborts module evaluation before this helper ortraceInstrumentationModuleLoadError()can run. The new failed-load span therefore exists only in the developmentModuleRunnerpath, while Next.js catchesgetInstrumentationModule()failures and emitsInstrumentation.loadModulewhen a provider is already installed. Load the generated module inside the initialization promise (preserving registration-before-user-module ordering), capture its timing/error there, and add a generated-entry failure test.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Declining this one. Next only exports a failed
Instrumentation.loadModulespan when a tracer provider was installed beforeinstrumentation.tsloaded ("A load error is only exportable when a provider was already installed" inregisterInstrumentation). In vinext's production entries nothing runs before the entry module:instrumentation.tsis what installs the provider, and on Workers nothing can preload one. So no provider exists to export the span to. A top-level import failure also stops the worker or server module from evaluating at all, so no request is ever served. Switching the generated entries to a dynamic import would change chunking and startup for every app withinstrumentation.ts, which is more than this edge case is worth, and the 16.4.6 deploy test doesn't cover it. The devModuleRunnerpath, where the import can fail on its own, does emit the span (runInstrumentation).