vercel/next.js · #100690

Run the dev Cache Components validation in an OTel trace of its own

sokra · merged Nov 17, 20264 files · 263 + / 153 −
docs/01-app/02-guides/open-telemetry.mdx12 + / 0 −
@@ -297,6 +297,18 @@ Attributes: - `next.span_type` - `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]`  - `next.span_type`: `AppRender.fetch`
packages/next/src/server/app-render/app-render.tsx188 + / 147 −
@@ -116,6 +116,7 @@ import {   runWithRequestInsightsIdentity, } from '../lib/trace/request-insights-identity' import { getTracer, SpanStatusCode } from '../lib/trace/tracer'+import type { Span } from '../lib/trace/tracer' import {   getActiveLocalSpan,   isLocalSpanRecordingEnabled,@@ -4828,6 +4829,8 @@ function runDevValidationInBackground(   validationGeneration: DevValidationGeneration ): void {   const validationAbortSignal = validationGeneration.signal+  // The render's span, active while the render schedules the validation.+  const renderSpanContext = getTracer().getActiveScopeSpan()?.spanContext()    void consoleAsyncStorage     .run({ dim: true }, async () => {@@ -4848,167 +4851,173 @@ function runDevValidationInBackground(         return       } -      return runInstantInsightsWithTracing(ctx, async (runSpan) => {-        // Read whether the streamed render errored only now that it has fully-        // settled.-        const devRenderDidError = getDevRenderDidError()--        const [instantInputs, staticInputs] = await runSpan(-          AppRenderSpan.instantInsightsPrepareValidation,-          'Prepare validation inputs',-          async () => {-            const lazyInputs = await prepareValidationInputs(-              prefetchMode,-              navigationKind,-              result,-              requestStore,-              validationDebugChannel,-              ctx,-              prerenderResumeDataCache,-              createRequestStore,-              getPayload,-              onError,-              validationAbortSignal-            )+      return runInDevValidationTrace(ctx, renderSpanContext, () =>+        runInstantInsightsWithTracing(ctx, async (runSpan) => {+          // Read whether the streamed render errored only now that it has fully+          // settled.+          const devRenderDidError = getDevRenderDidError()++          const [instantInputs, staticInputs] = await runSpan(+            AppRenderSpan.instantInsightsPrepareValidation,+            'Prepare validation inputs',+            async () => {+              const lazyInputs = await prepareValidationInputs(+                prefetchMode,+                navigationKind,+                result,+                requestStore,+                validationDebugChannel,+                ctx,+                prerenderResumeDataCache,+                createRequestStore,+                getPayload,+                onError,+                validationAbortSignal+              ) -            // If we need to do multiple renders, do them in parallel.-            // `runValidationInDev` currently needs `instantInputs` eagerly-            // right before using `staticInputs` for static shell validation,-            // so there's no point delaying one of the renders.-            // We bail out (after logging an error during-            // `resolveLazyDevValidationInputs`) if sync IO or invalid dynamic-            // errors happen in either.-            return Promise.all([-              lazyInputs.instantInputs-                ? resolveLazyDevValidationInputs(lazyInputs.instantInputs, ctx)-                : null,-              resolveLazyDevValidationInputs(lazyInputs.staticInputs, ctx),-            ])+              // If we need to do multiple renders, do them in parallel.+              // `runValidationInDev` currently needs `instantInputs` eagerly+              // right before using `staticInputs` for static shell validation,+              // so there's no point delaying one of the renders.+              // We bail out (after logging an error during+              // `resolveLazyDevValidationInputs`) if sync IO or invalid dynamic+              // errors happen in either.+              return Promise.all([+                lazyInputs.instantInputs+                  ? resolveLazyDevValidationInputs(+                      lazyInputs.instantInputs,+                      ctx+                    )+                  : null,+                resolveLazyDevValidationInputs(lazyInputs.staticInputs, ctx),+              ])+            }+          )+          if (+            instantInputs === VALIDATION_BAILOUT ||+            staticInputs === VALIDATION_BAILOUT+          ) {+            return           }-        )-        if (-          instantInputs === VALIDATION_BAILOUT ||-          staticInputs === VALIDATION_BAILOUT-        ) {-          return-        }--        // A newer render may have superseded this work while we prepared the-        // validation inputs above (which can itself render).-        if (validationAbortSignal.aborted) {-          logValidationAborted(ctx)-          return-        } -        return runSpan(-          AppRenderSpan.instantInsightsRunValidation,-          'Run validation',-          async () => {-            // Hand the whole validation to the worker when one is installed. It-            // runs on a worker thread (off the main thread), emits its own-            // lifecycle markers, logs code frames on its piped stdio, and-            // returns the overlay Flight bytes for the main thread to forward.-            // The worker is absent when `experimental.devValidationWorker` is-            // false, and validation runs in-process instead.-            const devValidationWorker = getDevValidationWorker()--            if (devValidationWorker) {-              const runValidationSpan = getActiveLocalSpan()-              const runValidationSpanContext = runValidationSpan?.spanContext()-              const requestInsightsIdentity = getRequestInsightsIdentity()-              const snapshot = await buildDevValidationSnapshot(-                ctx,-                instantInputs,-                staticInputs,-                prefetchMode,-                fallbackRouteParams,-                devRenderDidError-              )+          // A newer render may have superseded this work while we prepared the+          // validation inputs above (which can itself render).+          if (validationAbortSignal.aborted) {+            logValidationAborted(ctx)+            return+          } -              const workerResult = await devValidationWorker(-                snapshot,-                validationAbortSignal,-                {-                  captureLocalSpans: Boolean(-                    runValidationSpanContext && requestInsightsIdentity-                  ),-                }-              )+          return runSpan(+            AppRenderSpan.instantInsightsRunValidation,+            'Run validation',+            async () => {+              // Hand the whole validation to the worker when one is installed. It+              // runs on a worker thread (off the main thread), emits its own+              // lifecycle markers, logs code frames on its piped stdio, and+              // returns the overlay Flight bytes for the main thread to forward.+              // The worker is absent when `experimental.devValidationWorker` is+              // false, and validation runs in-process instead.+              const devValidationWorker = getDevValidationWorker()++              if (devValidationWorker) {+                const runValidationSpan = getActiveLocalSpan()+                const runValidationSpanContext =+                  runValidationSpan?.spanContext()+                const requestInsightsIdentity = getRequestInsightsIdentity()+                const snapshot = await buildDevValidationSnapshot(+                  ctx,+                  instantInputs,+                  staticInputs,+                  prefetchMode,+                  fallbackRouteParams,+                  devRenderDidError+                ) -              // A newer navigation may have superseded this validation while-              // the worker ran; don't surface stale insights for a page the user-              // left.-              if (!validationAbortSignal.aborted) {-                if (-                  workerResult.localSpans &&-                  runValidationSpanContext &&-                  requestInsightsIdentity-                ) {-                  importRequestInsightSpans(-                    requestInsightsIdentity,-                    runValidationSpanContext,-                    workerResult.localSpans-                  )-                  if (workerResult.localSpans.droppedSpanCount > 0) {-                    runValidationSpan?.setAttribute(-                      'next.request_insights.omitted_spans',-                      workerResult.localSpans.droppedSpanCount-                    )+                const workerResult = await devValidationWorker(+                  snapshot,+                  validationAbortSignal,+                  {+                    captureLocalSpans: Boolean(+                      runValidationSpanContext && requestInsightsIdentity+                    ),                   }-                }--                const chunks = workerResult.chunks-                if (!chunks) {-                  return-                }-                const { sendErrorsToBrowser } = ctx.renderOpts-                if (!sendErrorsToBrowser) {-                  throw new InvariantError(-                    'Expected `sendErrorsToBrowser` to be defined in renderOpts.'-                  )-                }-                sendErrorsToBrowser(-                  createNodeStreamFromChunks(chunks),-                  ctx.htmlRequestId                 )-              }-            } else {-              // In-process path, taken when `experimental.devValidationWorker`-              // is false or no worker is installed (e.g. during a build).-              // Validation computes the errors; the caller delivers them to the-              // dev overlay. `runWithDevValidationLogging` encloses both the-              // render and the delivery in the test-mode lifecycle markers so-              // tests that assert the delivered error between-              // `validation_start` and `validation_end` capture it.-              await runWithDevValidationLogging(-                ctx,-                validationAbortSignal,-                async () => {-                  const validationErrors = await runValidationInDev(-                    prefetchMode,-                    instantInputs,-                    staticInputs,-                    toValidationRenderContext(ctx),-                    fallbackRouteParams,-                    devRenderDidError,-                    validationAbortSignal-                  ) +                // A newer navigation may have superseded this validation while+                // the worker ran; don't surface stale insights for a page the user+                // left.+                if (!validationAbortSignal.aborted) {                   if (-                    validationErrors !== undefined &&-                    !validationAbortSignal.aborted+                    workerResult.localSpans &&+                    runValidationSpanContext &&+                    requestInsightsIdentity                   ) {-                    await logMessagesAndSendErrorsToBrowser(-                      validationErrors,-                      ctx+                    importRequestInsightSpans(+                      requestInsightsIdentity,+                      runValidationSpanContext,+                      workerResult.localSpans                     )+                    if (workerResult.localSpans.droppedSpanCount > 0) {+                      runValidationSpan?.setAttribute(+                        'next.request_insights.omitted_spans',+                        workerResult.localSpans.droppedSpanCount+                      )+                    }                   }++                  const chunks = workerResult.chunks+                  if (!chunks) {+                    return+                  }+                  const { sendErrorsToBrowser } = ctx.renderOpts+                  if (!sendErrorsToBrowser) {+                    throw new InvariantError(+                      'Expected `sendErrorsToBrowser` to be defined in renderOpts.'+                    )+                  }+                  sendErrorsToBrowser(+                    createNodeStreamFromChunks(chunks),+                    ctx.htmlRequestId+                  )                 }-              )+              } else {+                // In-process path, taken when `experimental.devValidationWorker`+                // is false or no worker is installed (e.g. during a build).+                // Validation computes the errors; the caller delivers them to the+                // dev overlay. `runWithDevValidationLogging` encloses both the+                // render and the delivery in the test-mode lifecycle markers so+                // tests that assert the delivered error between+                // `validation_start` and `validation_end` capture it.+                await runWithDevValidationLogging(+                  ctx,+                  validationAbortSignal,+                  async () => {+                    const validationErrors = await runValidationInDev(+                      prefetchMode,+                      instantInputs,+                      staticInputs,+                      toValidationRenderContext(ctx),+                      fallbackRouteParams,+                      devRenderDidError,+                      validationAbortSignal+                    )++                    if (+                      validationErrors !== undefined &&+                      !validationAbortSignal.aborted+                    ) {+                      await logMessagesAndSendErrorsToBrowser(+                        validationErrors,+                        ctx+                      )+                    }+                  }+                )+              }             }-          }-        )-      })+          )+        })+      )     })     // The catch keeps a failed render, or anything thrown inside validation,     // from surfacing as an unhandled rejection.@@ -5059,6 +5068,38 @@ function runWithoutInstantInsightsSpan<T>(   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>(   ctx: AppRenderContext,   fn: (runSpan: RunInstantInsightsSpan) => Promise<T>
packages/next/src/server/lib/trace/constants.ts2 + / 0 −
@@ -100,6 +100,7 @@ enum AppRenderSpan {   instantInsightsWarmup = 'AppRender.instantInsights.warmup',   instantInsightsStaticShell = 'AppRender.instantInsights.staticShell',   instantInsightsValidate = 'AppRender.instantInsights.validate',+  devValidation = 'AppRender.devValidation', }  enum DevBundlerServiceSpan {@@ -170,6 +171,7 @@ export const NextVanillaSpanAllowlist = new Set([   RenderSpan.getStaticProps,   AppRenderSpan.fetch,   AppRenderSpan.getBodyResult,+  AppRenderSpan.devValidation,   LoadComponentsSpan.loadRouteModule,   RenderSpan.renderDocument,   NodeSpan.runHandler,
test/e2e/app-dir/otel-middleware-trace/otel-middleware-trace.test.ts61 + / 6 −
@@ -3,6 +3,7 @@ import { randomBytes } from 'crypto' import { isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils' import type { NextInstance } from 'e2e-utils' import cheerio from 'cheerio'+import { retry } from 'next-test-utils' import {   isOneTimeSpan,   printSpanTree,@@ -12,6 +13,7 @@ import { import {   collectSpanGroups,   collectSpans,+  parseSpanEvents,   type SpanGroup,   type SpanGroupResult, } from 'otel-span-capture'@@ -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 app runs (`start`, `dev`, or `deploy`, deployed with the adapter or // without it, `(no adapter)`), the bundler (Turbopack, or ` (webpack)`),@@ -1119,18 +1164,14 @@ describe.each(VARIANTS)(         ) {           expect(tree).toMatchInlineSnapshot(`           "[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           │  ├─ prepare route module (RouteModule.prepare)-          │  ├─ render route (app) /isr (AppRender.getBodyResult) {next.route=/isr} [error: doesn't cover descendants]-          │  │  ├─ build component tree (NextNodeServer.createComponentTree)-          │  │  │  ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)-          │  │  │  └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)+          │  ├─ render route (app) /isr (AppRender.getBodyResult) {next.route=/isr}           │  │  ├─ build component tree (NextNodeServer.createComponentTree)           │  │  │  ├─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)           │  │  │  └─ resolve segment modules (NextNodeServer.getLayoutOrPageModule)           │  │  ├─ generateMetadata /layout (ResolveMetadata.generateMetadata)-          │  │  ├─ generateMetadata /layout (ResolveMetadata.generateMetadata)           │  │  └─ start response (NextNodeServer.startResponse)           │  └─ resolve page components (NextNodeServer.findPageComponents) {next.route=/isr}           │     └─ load route module (LoadComponents.loadRouteModule)@@ -1158,6 +1199,20 @@ describe.each(VARIANTS)(           // Not observed yet (filled from CI).           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)"+          `)+        }       }     )