Repository navigation
fix(tracing): trace route module loading and preparation like Next.js 16.4 #4912
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
e0af8f9
1ba735b
fba2a13
e9e893a
ea51fbc
20d8109
0c2cfeb
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 |
|---|---|---|
|
|
@@ -11,7 +11,7 @@ import { | |
| normalizePathnameForRouteMatchStrict, | ||
| } from "../routing/utils.js"; | ||
| import { patternToNextFormat } from "../routing/route-validation.js"; | ||
| import { traceFindPageComponents } from "./pages-execution-tracing.js"; | ||
| import { tracePrepareRouteModule, traceRouteModuleLoad } from "./pages-execution-tracing.js"; | ||
| import { isExternalUrl } from "../utils/external-url.js"; | ||
| import { | ||
| getActiveDraftModeState, | ||
|
|
@@ -2609,6 +2609,41 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| const isFinalRouteMatch = isInterceptionMatch || requestsLiteralRoutePattern; | ||
| const preActionMatchIsFinal = | ||
| preActionMatch !== null && (isFinalRouteMatch || !preActionMatch.route.isDynamic); | ||
| // Next.js prepares the matched route module once, at the start of its | ||
| // handler (`RouteModule.prepare`), before handling a Server Action or a | ||
| // prefetch. Routing that resumes after a miss prepares the route it lands on. | ||
| let preparedRoute: TRoute | null = null; | ||
| const prepareRouteModule = <T>(route: TRoute, callback: () => T): T => { | ||
| if (preparedRoute === route) return callback(); | ||
| preparedRoute = route; | ||
| return tracePrepareRouteModule(callback); | ||
| }; | ||
| // The route whose modules this request already resolved, so the page render | ||
| // that follows a form-state action doesn't resolve them again. | ||
| let loadedRoute: TRoute | null = null; | ||
| const loadRouteModule = async (route: TRoute) => { | ||
| if (!options.ensureRouteLoaded) return; | ||
| if (loadedRoute === route) { | ||
| await options.ensureRouteLoaded(route); | ||
| return; | ||
| } | ||
| loadedRoute = route; | ||
| await traceRouteModuleLoad(route.pattern, () => options.ensureRouteLoaded!(route)); | ||
| }; | ||
| // Like Next.js, prepare the action's page before handling the action. The | ||
| // action and the page it renders see the route's root params. | ||
| const prepareActionRoute = (routeMatch: AppRscRouteMatch<TRoute>) => | ||
| prepareRouteModule(routeMatch.route, () => | ||
| setRootParams(pickRootParams(routeMatch.params, routeMatch.route.rootParamNames)), | ||
| ); | ||
| // Load the action's page, then prepare it. A Server Action that may be | ||
| // forwarded to the route that owns it loads the page only once it isn't, so | ||
| // the page's modules don't run for a forwarded action. | ||
| const loadAndPrepareActionRoute = async (routeMatch: AppRscRouteMatch<TRoute> | null) => { | ||
| if (!routeMatch) return; | ||
| await loadRouteModule(routeMatch.route); | ||
| prepareActionRoute(routeMatch); | ||
| }; | ||
| let serverActionHandled = false; | ||
| const handleServerAction = async ( | ||
| routeMatch: AppRscRouteMatch<TRoute> | null, | ||
|
|
@@ -2617,10 +2652,13 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| if (!filesystemRouteEligible || !isPostRequest || !actionId) return null; | ||
| if (routeMatch && isAppRouteHandlerRoute(routeMatch.route)) return null; | ||
| if (!options.handleServerActionRequest) { | ||
| // A build without Server Actions has nothing to forward. | ||
| await loadAndPrepareActionRoute(routeMatch); | ||
| return markServerActionResponse( | ||
| respondServerActionNotFound(actionId, options.clearRequestContext), | ||
| ); | ||
| } | ||
| if (routeMatch) prepareActionRoute(routeMatch); | ||
| const sourceConfigHeaders = new Headers(); | ||
| await applyAppRscConfigHeaders(sourceConfigHeaders, request, { | ||
| basePath: options.basePath, | ||
|
|
@@ -2658,11 +2696,16 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| if (!filesystemRouteEligible || !isProgressiveActionRequest) return null; | ||
| if (routeMatch && isAppRouteHandlerRoute(routeMatch.route)) return null; | ||
| if (!options.handleProgressiveActionRequest) { | ||
| // A build without Server Actions has nothing to forward. | ||
| await loadAndPrepareActionRoute(routeMatch); | ||
| return unrenderedRouteMatch?.route.__loadPage && | ||
| !unrenderedRouteMatch.route.__loadRouteHandler | ||
| ? markServerActionResponse(respondServerActionNotFound(null, options.clearRequestContext)) | ||
| : null; | ||
| } | ||
| // The action may be forwarded, so its page loads only for the render that | ||
| // follows a form-state result. | ||
| if (routeMatch) prepareActionRoute(routeMatch); | ||
| const progressiveActionResult = await options.handleProgressiveActionRequest({ | ||
| actionId, | ||
| cleanPathname, | ||
|
|
@@ -3243,11 +3286,13 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| : rewriteCachePathname(canonicalPathname, cleanPathname); | ||
| // Hydrate lazy page/route-handler modules before the page-vs-handler dispatch | ||
| // branch and any downstream synchronous module reads. | ||
| if (options.ensureRouteLoaded) { | ||
| await traceFindPageComponents(route.pattern, () => options.ensureRouteLoaded!(route)); | ||
| } | ||
| const resolvedSearchParams = getResolvedSearchParams(); | ||
| await loadRouteModule(route); | ||
|
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. An unmatched App request returns through
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. Declining this one for this PR, for the same reason as the metadata routes. vinext renders an unmatched App request through the fallback renderer (
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. This still emits
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. Declining this one. Next's edge templates skip |
||
| const isRouteTreePrefetch = isRouteTreePrefetchRequest(request) && !route.routeHandler; | ||
| // A tree prefetch answers from the matched route alone, so reading its | ||
| // query is all it prepares, before its params are admitted. | ||
| const resolvedSearchParams = isRouteTreePrefetch | ||
| ? prepareRouteModule(route, getResolvedSearchParams) | ||
| : getResolvedSearchParams(); | ||
| // Next.js rejects a dynamicParams = false miss while routing, outside draft | ||
| // mode, so a fallback rewrite can claim the URL's route tree. Without one | ||
| // that could, vinext doesn't run the route's generators for each prefetched | ||
|
|
@@ -3271,6 +3316,7 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| return new Response(null, { status: 404 }); | ||
| } | ||
| setFrameworkRequestRoute(patternToNextFormat(route.pattern), isRscRequest); | ||
| const matchedResponseStage = transportedResponseStage ?? options.renderResponseStageLocally; | ||
| if (isRouteTreePrefetch) { | ||
| const response = await createRouteTreePrefetchResponse(route, { | ||
| buildId: options.buildId, | ||
|
|
@@ -3301,7 +3347,6 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| : cleanPathnameIsRequestPathname | ||
| ? requestPathname || "/" | ||
| : cleanPathname || "/"; | ||
| const matchedResponseStage = transportedResponseStage ?? options.renderResponseStageLocally; | ||
| let runtimeFallbackShells: AppPagePprFallbackCacheShell[] = []; | ||
| if ( | ||
| options.createPprFallbackShells && | ||
|
|
@@ -3319,13 +3364,22 @@ async function handleAppRscRequest<TRoute extends AppRscHandlerRoute>( | |
| params, | ||
| ); | ||
| } | ||
| options.setNavigationContext({ | ||
| pathname: canonicalPathname, | ||
| searchParams: resolvedSearchParams, | ||
| params: renderParams, | ||
| }); | ||
| const rootParams = pickRootParams(renderParams, route.rootParamNames); | ||
| setRootParams(rootParams); | ||
| const setMatchedRouteContext = () => { | ||
| options.setNavigationContext({ | ||
| pathname: canonicalPathname, | ||
| searchParams: resolvedSearchParams, | ||
| params: renderParams, | ||
| }); | ||
| const matchedRootParams = pickRootParams(renderParams, route.rootParamNames); | ||
| setRootParams(matchedRootParams); | ||
| return matchedRootParams; | ||
| }; | ||
| // A response stage prepares the route module it renders. Next.js's edge | ||
| // route handler template doesn't prepare its route module. | ||
| const rootParams = | ||
| matchedResponseStage || (route.routeHandler && isEdgeRouteHandler(route.routeHandler)) | ||
| ? setMatchedRouteContext() | ||
| : prepareRouteModule(route, setMatchedRouteContext); | ||
|
|
||
| if (route.routeHandler) { | ||
| // Next.js edge route handlers run through web/adapter.ts, which strips | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -106,6 +106,8 @@ import { | |
| tracePagesDocument, | ||
| tracePagesDocumentStream, | ||
| traceFindPageComponents, | ||
| traceLoadRouteModule, | ||
| tracePrepareRouteModule, | ||
| } from "./pages-execution-tracing.js"; | ||
| import { logRequestError } from "./request-error-log.js"; | ||
| import type { FontOwners } from "vinext/shims/font-utils"; | ||
|
|
@@ -924,7 +926,9 @@ export function createSSRHandler( | |
| // beneath one findPageComponents span before data methods run. | ||
| const { pageModule, AppComponent, appFilePath, DocumentComponent } = | ||
| await traceFindPageComponents(route.pattern, async () => { | ||
| const pageModule = await importModule(runner, route.filePath); | ||
| const pageModule = await traceLoadRouteModule(() => | ||
| importModule(runner, route.filePath), | ||
| ); | ||
| const appFilePath = findFileWithExts(pagesDir, "_app", matcher); | ||
| const appModule = appFilePath ? await importModule(runner, appFilePath) : null; | ||
| const docFilePath = findFileWithExts(pagesDir, "_document", matcher); | ||
|
|
@@ -990,20 +994,22 @@ export function createSSRHandler( | |
| pagesNextData, | ||
| ) | ||
| : true; | ||
| if (typeof routerShim.setSSRContext === "function") { | ||
| routerShim.setSSRContext({ | ||
| pathname: patternToNextFormat(route.pattern), | ||
| query, | ||
| asPath: requestAsPath, | ||
| navigationIsReady, | ||
| nextData: pagesNextData, | ||
| locale: locale ?? currentDefaultLocale, | ||
| locales: i18nConfig?.locales, | ||
| defaultLocale: currentDefaultLocale, | ||
| domainLocales, | ||
| isPreview: requestPreviewData !== false, | ||
| }); | ||
| } | ||
| tracePrepareRouteModule(() => { | ||
| if (typeof routerShim.setSSRContext === "function") { | ||
| routerShim.setSSRContext({ | ||
| pathname: patternToNextFormat(route.pattern), | ||
| query, | ||
| asPath: requestAsPath, | ||
| navigationIsReady, | ||
| nextData: pagesNextData, | ||
| locale: locale ?? currentDefaultLocale, | ||
| locales: i18nConfig?.locales, | ||
| defaultLocale: currentDefaultLocale, | ||
| domainLocales, | ||
| isPreview: requestPreviewData !== false, | ||
| }); | ||
| } | ||
| }); | ||
| // Mark end of compile phase: everything from here is rendering. | ||
| _compileEnd = now(); | ||
|
|
||
|
|
@@ -1951,7 +1957,9 @@ async function renderErrorPage( | |
| const errorPage = candidate === "_error" ? "/_error" : `/${candidate}`; | ||
| const { errorModule, AppComponent, appAssetPath, DocumentComponent } = | ||
| await traceFindPageComponents(errorPage, async () => { | ||
| const errorModule = await importModule(runner, errorAssetPath ?? "next/error"); | ||
| const errorModule = await traceLoadRouteModule(() => | ||
|
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. The error route now emits
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 1ba735b. |
||
| importModule(runner, errorAssetPath ?? "next/error"), | ||
| ); | ||
| const appAssetPath = findFileWithExts(pagesDir, "_app", matcher); | ||
| const appModule = appAssetPath ? await importModule(runner, appAssetPath) : null; | ||
| const docFilePath = findFileWithExts(pagesDir, "_document", matcher); | ||
|
|
@@ -1986,12 +1994,15 @@ async function renderErrorPage( | |
| }; | ||
| try { | ||
| errorRouterShim = await importModule(runner, "next/router"); | ||
| if (typeof errorRouterShim.setSSRContext === "function") { | ||
| errorRouterShim.setSSRContext({ | ||
| ...errorRouter, | ||
| navigationIsReady: true, | ||
| }); | ||
| } | ||
| // The error page's own handler prepares it, as in Next.js. | ||
| tracePrepareRouteModule(() => { | ||
| if (typeof errorRouterShim.setSSRContext === "function") { | ||
| errorRouterShim.setSSRContext({ | ||
| ...errorRouter, | ||
| navigationIsReady: true, | ||
| }); | ||
| } | ||
| }); | ||
| } catch { | ||
| // router shim not available — continue without it | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -105,3 +105,40 @@ export function createFindPageComponentsSpanDescriptor(routePattern: string) { | |
| export function traceFindPageComponents<T>(routePattern: string, callback: () => T): T { | ||
| return frameworkTracer.trace(createFindPageComponentsSpanDescriptor(routePattern), callback); | ||
| } | ||
|
|
||
| // Next.js 16.4 traces loading the page's own module inside | ||
| // `findPageComponents` (`loadRouteModule` in server/load-components.ts) and | ||
| // the route module's request preparation (`RouteModule.prepare` in | ||
| // server/route-modules/route-module.ts) on every request. | ||
| const LOAD_ROUTE_MODULE_SPAN = { | ||
| name: "load route module", | ||
| type: "LoadComponents.loadRouteModule", | ||
| } as const; | ||
|
|
||
| const PREPARE_ROUTE_MODULE_SPAN = { | ||
| name: "prepare route module", | ||
| type: "RouteModule.prepare", | ||
| } as const; | ||
|
|
||
| export function createLoadRouteModuleSpanDescriptor() { | ||
| return LOAD_ROUTE_MODULE_SPAN; | ||
| } | ||
|
|
||
| export function createPrepareRouteModuleSpanDescriptor() { | ||
| return PREPARE_ROUTE_MODULE_SPAN; | ||
| } | ||
|
|
||
| /** Resolve the page's own module, beneath its `findPageComponents` span. */ | ||
| export function traceLoadRouteModule<T>(callback: () => T): T { | ||
| return frameworkTracer.trace(LOAD_ROUTE_MODULE_SPAN, callback); | ||
| } | ||
|
|
||
| /** Resolve a matched route's modules, as Next.js's `findPageComponents`. */ | ||
| export function traceRouteModuleLoad<T>(routePattern: string, load: () => T): T { | ||
| return traceFindPageComponents(routePattern, () => traceLoadRouteModule(load)); | ||
| } | ||
|
|
||
| /** Set up the matched route's request context (pathname, query, params). */ | ||
| export function tracePrepareRouteModule<T>(callback: () => T): T { | ||
|
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. The new preparation span is not wired into Pages API requests. Production/Workers dispatch in
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 ea51fbc. Node Pages API routes now prepare by wrapping their query and params, which is what Next's |
||
| return frameworkTracer.trace(PREPARE_ROUTE_MODULE_SPAN, callback); | ||
| } | ||
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.
This helper is unreachable for metadata routes:
renderMetadataRouteIfMatched()returns at lines 1960-1963 before matched-route loading/preparation runs, and the splitapp-metadatastage likewise returns before its tracing block. Next.js 16.4 compiles metadata files as App Route modules; its app-route template callsrouteModule.prepare()for them, and the self-hosted path also wraps their module load inLoadComponents.loadRouteModule. Consequently requests such as/robots.txtstill omitRouteModule.prepare(and, on the local/self-hosted path, the load span). Route metadata dispatch through equivalent tracing in both local and response-stage execution.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 for this PR. vinext doesn't serve metadata files through route modules. A separate metadata dispatcher (
metadata-route-response.ts) matches and answers them through several distinct paths: generated sitemaps, prerendered cache reads and dynamic renders. There is no route-module load or prepare step to wrap, so matching Next's spans there means restructuring that dispatcher. That is separate from this PR, which ports the spans for the route modules vinext does dispatch through: App pages, Node route handlers, and Pages pages and API routes.