Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/vinext/src/server/framework-tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,22 @@ type FrameworkSpanAttributeValue = string | number | boolean;

type FrameworkSpanDescriptor = {
attributes?: Readonly<Record<string, FrameworkSpanAttributeValue | undefined>>;
/** Backdated end time (epoch milliseconds), for work that already happened. */
endTime?: number;
kind?: "client" | "internal" | "server";
name?: string;
recordErrors?: boolean;
/** Backdated start time (epoch milliseconds), for work that already happened. */
startTime?: number;
type: string;
};

export type ResolvedFrameworkSpanDescriptor = {
attributes: Readonly<Record<string, FrameworkSpanAttributeValue>>;
endTime?: number;
kind: "client" | "internal" | "server";
name: string;
startTime?: number;
type: string;
};

Expand Down Expand Up @@ -64,12 +70,15 @@ function resolveDescriptor(descriptor: FrameworkSpanDescriptor): ResolvedFramewo
for (const [key, value] of Object.entries(descriptor.attributes ?? {})) {
if (value !== undefined) attributes[key] = value;
}
return {
const resolved: ResolvedFrameworkSpanDescriptor = {
attributes,
kind: descriptor.kind ?? "internal",
name,
type: descriptor.type,
};
if (descriptor.startTime !== undefined) resolved.startTime = descriptor.startTime;
if (descriptor.endTime !== undefined) resolved.endTime = descriptor.endTime;
return resolved;
}

function errorType(error: unknown): string {
Expand Down
117 changes: 107 additions & 10 deletions packages/vinext/src/server/instrumentation-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.

Copy link
Copy Markdown
Contributor

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 or traceInstrumentationModuleLoadError() can run. The new failed-load span therefore exists only in the development ModuleRunner path, while Next.js catches getInstrumentationModule() failures and emits Instrumentation.loadModule when 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.

Copy link
Copy Markdown
Member Author

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.loadModule span when a tracer provider was installed before instrumentation.ts loaded ("A load error is only exportable when a provider was already installed" in registerInstrumentation). In vinext's production entries nothing runs before the entry module: instrumentation.ts is 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 with instrumentation.ts, which is more than this edge case is worth, and the 16.4.6 deploy test doesn't cover it. The dev ModuleRunner path, where the import can fail on its own, does emit the span (runInstrumentation).

*/
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefix Error messages before recording and rethrowing them, as Next.js 16.4 does (An error occurred while loading instrumentation hook: ...). This PR newly emits the register failure span, but currently records the raw message as both the exception and span status, so its telemetry differs from Next; the test at tests/instrumentation-tracing.test.ts:116 also codifies the unprefixed value.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41c1680. A thrown Error now gets Next's An error occurred while loading instrumentation hook: prefix, as in registerInstrumentation (16.2.6 and 16.4.6). The prefix is added before the error is recorded on the register span and rethrown, and this also covers a failing tracer-provider extension, which Next runs in the same try. Both span tests now assert the prefixed status. Non-Error throws are left unchanged.

throw err;
} finally {
// Before emitting: span processors run synchronously in span.end().
const endTime = getInstrumentationTimestamp();
traceInstrumentationLifecycleSpan(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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.

traceInstrumentationLifecycleSpan is now called from this finally block and from the branch with no register() (line 192). frameworkTracer.trace doesn't catch errors from an integration's span creation or span.end(). If one throws here, it replaces the user's register() error. In the no-register() branch it fires before onRequestError is stored and state.initialized is set, so initPromise stays rejected and every later request fails. The OpenTelemetry SDK usually catches processor errors itself, so this is unlikely, but wrapping the body of traceInstrumentationLifecycleSpan in a try/catch would keep telemetry failures from changing how registration ends.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in aa7487c. traceInstrumentationLifecycleSpan now catches and logs any error from the tracing integration, so telemetry can't replace register()'s own error or leave the one-shot registration rejected. Covered by "keeps a throwing tracing integration from changing how registration ends": the register error still propagates unchanged, and registration without register() still completes and stores onRequestError.

"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
Expand Down
22 changes: 19 additions & 3 deletions packages/vinext/src/server/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ import path from "pathslash";
import { getRequestExecutionContext } from "vinext/shims/request-context";
import { ValidFileMatcher } from "../routing/file-matcher.js";
import { patternToNextFormat } from "../routing/route-validation.js";
import { ensureInstrumentationRegistered } from "./instrumentation-runtime.js";
import {
ensureInstrumentationRegistered,
traceInstrumentationModuleLoadError,
} from "./instrumentation-runtime.js";
/**
* Minimal duck-typed interface for the module runner passed to
* `runInstrumentation`. Only `.import()` is used — this avoids requiring
Expand Down Expand Up @@ -162,8 +165,21 @@ export async function runInstrumentation(
runner: ModuleImporter,
instrumentationPath: string,
): Promise<void> {
const mod = (await runner.import(instrumentationPath)) as Record<string, unknown>;
await ensureInstrumentationRegistered(mod, instrumentationPath);
const startTime = performance.timeOrigin + performance.now();
let mod: Record<string, unknown>;
try {
mod = (await runner.import(instrumentationPath)) as Record<string, unknown>;
} catch (error) {
traceInstrumentationModuleLoadError(
{ startTime, endTime: performance.timeOrigin + performance.now() },
error,
);
throw error;
}
await ensureInstrumentationRegistered(mod, instrumentationPath, {
startTime,
endTime: performance.timeOrigin + performance.now(),
});
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/vinext/src/server/opentelemetry-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type OpenTelemetryContext = {
};

export type OpenTelemetrySpan = {
end(): void;
end(endTime?: number): void;
isRecording(): boolean;
recordException(error: unknown): void;
setAttribute(key: string, value: OpenTelemetryAttributeValue): void;
Expand All @@ -27,6 +27,7 @@ export type OpenTelemetryTracer = {
options: {
attributes: Record<string, OpenTelemetryAttributeValue>;
kind?: number;
startTime?: number;
},
callback: (span: OpenTelemetrySpan) => T,
): T;
Expand Down
8 changes: 5 additions & 3 deletions packages/vinext/src/server/opentelemetry-tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,24 @@ export const openTelemetryTracingIntegration: FrameworkTracingIntegration = {
const api = getOpenTelemetryApi();
if (!api || !isEnabled(api)) return callback(noopSpan);

const { endTime } = descriptor;
return api.trace.getTracer("next.js", "0.0.1").startActiveSpan(
descriptor.name,
{
attributes: descriptor.attributes,
kind: spanKinds[descriptor.kind],
startTime: descriptor.startTime,
},
(span) => {
try {
const result = callback(backendSpan(span));
if (!isPromiseLike(result)) {
span.end();
span.end(endTime);
return result;
}
return Promise.resolve(result).finally(() => span.end()) as unknown as T;
return Promise.resolve(result).finally(() => span.end(endTime)) as unknown as T;
} catch (error) {
span.end();
span.end(endTime);
throw error;
}
},
Expand Down
53 changes: 53 additions & 0 deletions tests/framework-tracer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,59 @@ describe("OpenTelemetry integration", () => {
]);
});

it("passes backdated start and end times to the registered provider", () => {
const requireFromSentry = createRequire(import.meta.resolve("@sentry/nextjs/package.json"));
const api = requireFromSentry("@opentelemetry/api") as {
trace: {
disable(): void;
setGlobalTracerProvider(provider: unknown): boolean;
};
};
const timings: Array<{ endTime?: number; startTime?: number }> = [];
api.trace.disable();
api.trace.setGlobalTracerProvider({
getTracer: () => ({
startActiveSpan<T>(
_name: string,
options: { startTime?: number },
callback: (span: unknown) => T,
): T {
const timing: { endTime?: number; startTime?: number } = {
startTime: options.startTime,
};
timings.push(timing);
return callback({
end: (endTime?: number) => {
timing.endTime = endTime;
},
isRecording: () => true,
recordException() {},
setAttribute() {},
setStatus() {},
spanContext: () => ({}),
updateName() {},
});
},
}),
});

try {
const tracer = createFrameworkTracer([openTelemetryTracingIntegration]);
tracer.trace(
{ endTime: 2_000, startTime: 1_000, type: "Instrumentation.register" },
() => {},
);
tracer.trace({ type: "AppRender.fetch" }, () => {});
} finally {
api.trace.disable();
}

expect(timings).toEqual([
{ startTime: 1_000, endTime: 2_000 },
{ startTime: undefined, endTime: undefined },
]);
});

it("extracts incoming propagation only when no span is already active", () => {
const spanKey = Symbol.for("OpenTelemetry Context Key SPAN");
type TestContext = {
Expand Down
Loading
Loading