Unverified Commit 68725018 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Run the dev Cache Components validation in a trace of its own

The background validation runs after the response has finished. Its spans
inherited the render's context, so they outlived their request's spans. Run
it as the children of a new root span, validate route (app) <page>, linked
to the render span.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent d1238274
...@@ -297,6 +297,18 @@ Attributes: ...@@ -297,6 +297,18 @@ Attributes:
- `next.span_type` - `next.span_type`
- `next.route` - `next.route`
### `validate route (app) [next.route]`
- `next.span_type`: `AppRender.devValidation`
This span represents the validation `next dev` runs in the background after rendering a route with [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents). It runs after the response has finished, so it is the root of a trace of its own, with a link to the `render route (app) [next.route]` span of the render it validates. The spans of the validation render are its children.
Attributes:
- `next.span_name`
- `next.span_type`
- `next.route`
### `fetch [http.method] [http.url]` ### `fetch [http.method] [http.url]`
- `next.span_type`: `AppRender.fetch` - `next.span_type`: `AppRender.fetch`
......
...@@ -116,6 +116,7 @@ import { ...@@ -116,6 +116,7 @@ import {
runWithRequestInsightsIdentity, runWithRequestInsightsIdentity,
} from '../lib/trace/request-insights-identity' } from '../lib/trace/request-insights-identity'
import { getTracer, SpanStatusCode } from '../lib/trace/tracer' import { getTracer, SpanStatusCode } from '../lib/trace/tracer'
import type { Span } from '../lib/trace/tracer'
import { traceLocalSpan } from '../lib/trace/local-span-recorder' import { traceLocalSpan } from '../lib/trace/local-span-recorder'
import { isRequestInsightsEnabled } from '../lib/trace/request-insights' import { isRequestInsightsEnabled } from '../lib/trace/request-insights'
import { FlightRenderResult } from './flight-render-result' import { FlightRenderResult } from './flight-render-result'
...@@ -4795,6 +4796,8 @@ function runDevValidationInBackground( ...@@ -4795,6 +4796,8 @@ function runDevValidationInBackground(
validationGeneration: DevValidationGeneration validationGeneration: DevValidationGeneration
): void { ): void {
const validationAbortSignal = validationGeneration.signal const validationAbortSignal = validationGeneration.signal
// The render's span, active while the render schedules the validation.
const renderSpanContext = getTracer().getActiveScopeSpan()?.spanContext()
void consoleAsyncStorage void consoleAsyncStorage
.run({ dim: true }, async () => { .run({ dim: true }, async () => {
...@@ -4815,7 +4818,8 @@ function runDevValidationInBackground( ...@@ -4815,7 +4818,8 @@ function runDevValidationInBackground(
return return
} }
return runInstantInsightsWithTracing(ctx, async (runSpan) => { return runInDevValidationTrace(ctx, renderSpanContext, () =>
runInstantInsightsWithTracing(ctx, async (runSpan) => {
// Read whether the streamed render errored only now that it has fully // Read whether the streamed render errored only now that it has fully
// settled. // settled.
const devRenderDidError = getDevRenderDidError() const devRenderDidError = getDevRenderDidError()
...@@ -4847,7 +4851,10 @@ function runDevValidationInBackground( ...@@ -4847,7 +4851,10 @@ function runDevValidationInBackground(
// errors happen in either. // errors happen in either.
return Promise.all([ return Promise.all([
lazyInputs.instantInputs lazyInputs.instantInputs
? resolveLazyDevValidationInputs(lazyInputs.instantInputs, ctx) ? resolveLazyDevValidationInputs(
lazyInputs.instantInputs,
ctx
)
: null, : null,
resolveLazyDevValidationInputs(lazyInputs.staticInputs, ctx), resolveLazyDevValidationInputs(lazyInputs.staticInputs, ctx),
]) ])
...@@ -4946,6 +4953,7 @@ function runDevValidationInBackground( ...@@ -4946,6 +4953,7 @@ function runDevValidationInBackground(
} }
) )
}) })
)
}) })
// The catch keeps a failed render, or anything thrown inside validation, // The catch keeps a failed render, or anything thrown inside validation,
// from surfacing as an unhandled rejection. // from surfacing as an unhandled rejection.
...@@ -4996,6 +5004,38 @@ function runWithoutInstantInsightsSpan<T>( ...@@ -4996,6 +5004,38 @@ function runWithoutInstantInsightsSpan<T>(
return fn() return fn()
} }
/**
* Runs the background dev validation of a render in a trace of its own, as
* the children of a new root span (`validate route (app) <page>`) with a link
* to the render's span. The validation runs after the response has finished,
* so its spans would otherwise outlive the request's spans they'd be the
* children of. The span ends when `fn` settles, with an error status if it
* rejects.
*
* With Request Insights, the validation already runs in a local trace isolated
* from OpenTelemetry (see `runInstantInsightsWithTracing`), so nothing changes.
*/
function runInDevValidationTrace<T>(
ctx: AppRenderContext,
renderSpanContext: ReturnType<Span['spanContext']> | undefined,
fn: () => Promise<T>
): Promise<T> {
const tracer = getTracer()
if (isRequestInsightsEnabled() || !tracer.isOpenTelemetryEnabled()) {
return fn()
}
return tracer.trace(
AppRenderSpan.devValidation,
{
spanName: `validate route (app) ${ctx.pagePath}`,
root: true,
links: renderSpanContext ? [{ context: renderSpanContext }] : undefined,
attributes: { 'next.route': ctx.pagePath },
},
fn
)
}
async function runInstantInsightsWithTracing<T>( async function runInstantInsightsWithTracing<T>(
ctx: AppRenderContext, ctx: AppRenderContext,
fn: (runSpan: RunInstantInsightsSpan) => Promise<T> fn: (runSpan: RunInstantInsightsSpan) => Promise<T>
......
...@@ -97,6 +97,7 @@ enum AppRenderSpan { ...@@ -97,6 +97,7 @@ enum AppRenderSpan {
instantInsights = 'AppRender.instantInsights', instantInsights = 'AppRender.instantInsights',
instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation', instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',
instantInsightsRunValidation = 'AppRender.instantInsights.runValidation', instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',
devValidation = 'AppRender.devValidation',
} }
enum DevBundlerServiceSpan { enum DevBundlerServiceSpan {
...@@ -167,6 +168,7 @@ export const NextVanillaSpanAllowlist = new Set([ ...@@ -167,6 +168,7 @@ export const NextVanillaSpanAllowlist = new Set([
RenderSpan.getStaticProps, RenderSpan.getStaticProps,
AppRenderSpan.fetch, AppRenderSpan.fetch,
AppRenderSpan.getBodyResult, AppRenderSpan.getBodyResult,
AppRenderSpan.devValidation,
LoadComponentsSpan.loadRouteModule, LoadComponentsSpan.loadRouteModule,
RenderSpan.renderDocument, RenderSpan.renderDocument,
NodeSpan.runHandler, NodeSpan.runHandler,
......
...@@ -3,6 +3,7 @@ import { randomBytes } from 'crypto' ...@@ -3,6 +3,7 @@ import { randomBytes } from 'crypto'
import { isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils' import { isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils'
import type { NextInstance } from 'e2e-utils' import type { NextInstance } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { retry } from 'next-test-utils'
import { import {
isOneTimeSpan, isOneTimeSpan,
printSpanTree, printSpanTree,
...@@ -12,6 +13,7 @@ import { ...@@ -12,6 +13,7 @@ import {
import { import {
collectSpanGroups, collectSpanGroups,
collectSpans, collectSpans,
parseSpanEvents,
type SpanGroup, type SpanGroup,
type SpanGroupResult, type SpanGroupResult,
} from 'otel-span-capture' } from 'otel-span-capture'
...@@ -302,6 +304,49 @@ function expectNoInternalHeaders(res: Response) { ...@@ -302,6 +304,49 @@ function expectNoInternalHeaders(res: Response) {
} }
} }
// Self-hosted dev: the span tree of the Cache Components validation of a
// request's render (`renderName`), from the server output. The validation
// runs in the background after the response, as the root of a trace of its
// own, with a link to the render span. Fails unless exactly one such root
// exists, without a parent.
async function getDevValidationTree(
next: NextInstance,
res: Response,
renderName: string
) {
const traceId = res.headers.get('x-mw-trace-id')
const endEvents = () =>
parseSpanEvents(next.cliOutput).events.filter(
(event) => event.event === 'end'
)
const render = await retry(() => {
const found = endEvents().filter(
(event) => event.traceId === traceId && event.name === renderName
)
expect(found).toHaveLength(1)
return found[0]
})
const root = await retry(() => {
const found = endEvents().filter((event) =>
event.links?.some(
(link) => link.traceId === render.traceId && link.spanId === render.id
)
)
expect(found).toHaveLength(1)
return found[0]
}, 10_000)
expect(root.parentId).toBeUndefined()
expect(root.traceId).not.toBe(render.traceId)
return printSpanTree(
await collectSpans(next, {
traceIds: [root.traceId],
expected: [root.type!, 'NextNodeServer.createComponentTree'],
since: new Date(Date.now() - LOGS_WINDOW_MS),
}),
{ omit: isOneTimeSpan }
)
}
// The environment a test runs in, which selects its span tree snapshot: how // The environment a test runs in, which selects its span tree snapshot: how
// the app runs (`start`, `dev`, or `deploy`, deployed with the adapter or // the app runs (`start`, `dev`, or `deploy`, deployed with the adapter or
// without it, `(no adapter)`), the bundler (Turbopack, or ` (webpack)`), // without it, `(no adapter)`), the bundler (Turbopack, or ` (webpack)`),
...@@ -1119,18 +1164,14 @@ describe.each(VARIANTS)( ...@@ -1119,18 +1164,14 @@ describe.each(VARIANTS)(
) { ) {
expect(tree).toMatchInlineSnapshot(` expect(tree).toMatchInlineSnapshot(`
"[trace A] GET (BaseServer.handleRequest) {http.target=/rewrite-isr, http.status_code=200} [error: doesn't cover descendants] "[trace A] GET (BaseServer.handleRequest) {http.target=/rewrite-isr, http.status_code=200} [error: doesn't cover descendants]
├─ GET /isr (BaseServer.handleRequest) {http.target=/rewrite-isr, http.route=/isr, next.route=/isr, http.status_code=200} [error: doesn't cover descendants] ├─ GET /isr (BaseServer.handleRequest) {http.target=/rewrite-isr, http.route=/isr, next.route=/isr, http.status_code=200}
│ ├─ NextNodeServer.clientComponentLoading │ ├─ NextNodeServer.clientComponentLoading
│ ├─ prepare route module (RouteModule.prepare) │ ├─ prepare route module (RouteModule.prepare)
│ ├─ render route (app) /isr (AppRender.getBodyResult) {next.route=/isr} [error: doesn't cover descendants] │ ├─ render route (app) /isr (AppRender.getBodyResult) {next.route=/isr}
│ │ ├─ build component tree (NextNodeServer.createComponentTree)
│ │ │ ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
│ │ │ └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
│ │ ├─ build component tree (NextNodeServer.createComponentTree) │ │ ├─ build component tree (NextNodeServer.createComponentTree)
│ │ │ ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule) │ │ │ ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
│ │ │ └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule) │ │ │ └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
│ │ ├─ generateMetadata /layout (ResolveMetadata.generateMetadata) │ │ ├─ generateMetadata /layout (ResolveMetadata.generateMetadata)
│ │ ├─ generateMetadata /layout (ResolveMetadata.generateMetadata)
│ │ └─ start response (NextNodeServer.startResponse) │ │ └─ start response (NextNodeServer.startResponse)
│ └─ resolve page components (NextNodeServer.findPageComponents) {next.route=/isr} │ └─ resolve page components (NextNodeServer.findPageComponents) {next.route=/isr}
│ └─ load route module (LoadComponents.loadRouteModule) │ └─ load route module (LoadComponents.loadRouteModule)
...@@ -1158,6 +1199,20 @@ describe.each(VARIANTS)( ...@@ -1158,6 +1199,20 @@ describe.each(VARIANTS)(
// Not observed yet (filled from CI). // Not observed yet (filled from CI).
expect(tree).toMatchInlineSnapshot() expect(tree).toMatchInlineSnapshot()
} }
// In dev, Cache Components validate the page in the background after
// the response: in a trace of its own, linked to the render.
if (isNextDev && process.env.__NEXT_CACHE_COMPONENTS) {
expect(
await getDevValidationTree(next, res, 'render route (app) /isr')
).toMatchInlineSnapshot(`
"[trace A] validate route (app) /isr (AppRender.devValidation) {next.route=/isr}
├─ build component tree (NextNodeServer.createComponentTree)
│ ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
│ └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)
└─ generateMetadata /layout (ResolveMetadata.generateMetadata)"
`)
}
} }
) )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment