Unverified Commit 6541ab5b authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Improve error stacks for dynamic API usage in `"use cache"` (#92736)

When `cookies()`, `headers()`, `draftMode()`, or `connection()` are
called inside `"use cache"` from third-party (ignore-listed) code, the
error stacks previously had no usable frames. The redbox showed no
source location and an empty call stack, and the build output only
showed `at ignore-listed frames`. This made it difficult to trace which
component was responsible for the invalid API usage.

This PR fixes the issue by calling React's `captureOwnerStack()` at the
`"use cache"` boundary (in `use-cache-wrapper.ts`) before entering the
cache scope, and storing the result on the cache work unit store as
`outerOwnerStack`. When an error is later thrown inside the cache scope
(e.g. from `cookies()`), `applyOwnerStack()` concatenates the inner
owner stack (from within the cache scope) with the stored outer owner
stack to reconstruct the full component tree across cache boundaries.
This also correctly handles nested `"use cache"` scopes by chaining the
outer owner stacks.

The `applyOwnerStack` function was extracted from `io-utils.tsx` into
`dynamic-rendering-utils.ts` so it can be reused by both the request API
files (`cookies.ts`, `headers.ts`, `draft-mode.ts`, `connection.ts`) and
the sync IO error handling in `io-utils.tsx`.

New test cases cover both first-party and third-party usage of all four
APIs, including a previously missing `connection()` in `"use cache"`
test case.
parent d1418740
......@@ -346,6 +346,7 @@ export interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {
readonly isHmrRefresh: boolean
readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined
readonly forceRevalidate: boolean
readonly outerOwnerStack: string | undefined
}
export interface PublicUseCacheStore extends CommonUseCacheStore {
......
......@@ -7,6 +7,8 @@ import type {
PrerenderStoreModernRuntime,
RequestStore,
} from './app-render/work-unit-async-storage.external'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
import { getServerReact, getClientReact } from './runtime-reacts.external'
export function isHangingPromiseRejectionError(
err: unknown
......@@ -148,3 +150,64 @@ export function delayUntilRuntimeStage<T>(
.waitForStage(getRuntimeStage(stagedRendering))
.then(() => result)
}
export function applyOwnerStack(error: Error): Error {
if (process.env.NODE_ENV !== 'production') {
let ownerStack: string | undefined | null
const workUnitStore = workUnitAsyncStorage.getStore()
// captureOwnerStack() returns the owner stack for the current React
// rendering context. Inside a cache scope this only includes the inner
// component tree. The outer owner stack (captured before entering the
// cache boundary in use-cache-wrapper.ts) is stored on the cache store.
// We concatenate both to get the full component tree.
const innerOwnerStack =
getClientReact()?.captureOwnerStack?.() ??
getServerReact()?.captureOwnerStack?.()
switch (workUnitStore?.type) {
case 'cache':
case 'private-cache':
ownerStack =
(innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||
undefined
break
case 'unstable-cache':
case 'request':
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
case 'generate-static-params':
case undefined:
ownerStack = innerOwnerStack
break
default:
workUnitStore satisfies never
}
if (ownerStack) {
let stack = ownerStack
if (error.stack) {
const frames: string[] = []
for (const frame of error.stack.split('\n').slice(1)) {
if (frame.includes('react_stack_bottom_frame')) {
break
}
frames.push(frame)
}
stack = '\n' + frames.join('\n') + stack
}
error.stack = error.name + ': ' + error.message + stack
}
}
return error
}
......@@ -3,8 +3,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
import { getServerReact, getClientReact } from '../runtime-reacts.external'
import { applyOwnerStack } from '../dynamic-rendering-utils'
type ApiType = 'time' | 'random' | 'crypto'
......@@ -167,37 +166,3 @@ export function io(expression: string, type: ApiType) {
workUnitStore satisfies never
}
}
function applyOwnerStack(error: Error) {
// TODO: Instead of stitching the stacks here, we should log the original
// error as-is when it occurs, and let `patchErrorInspect` handle adding the
// owner stack, instead of logging it deferred in the `LogSafely` component
// via `throwIfDisallowedDynamic`.
if (process.env.NODE_ENV !== 'production') {
const ownerStack =
getClientReact()?.captureOwnerStack?.() ??
getServerReact()?.captureOwnerStack?.()
if (ownerStack) {
let stack = ownerStack
if (error.stack) {
const frames: string[] = []
for (const frame of error.stack.split('\n').slice(1)) {
if (frame.includes('react_stack_bottom_frame')) {
break
}
frames.push(frame)
}
stack = '\n' + frames.join('\n') + stack
}
error.stack = error.name + ': ' + error.message + stack
}
}
return error
}
......@@ -14,6 +14,7 @@ import {
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils'
import { isRequestAPICallableInsideAfter } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -57,6 +58,7 @@ export function connection(): Promise<void> {
`Route ${workStore.route} used \`connection()\` inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, connection)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
......@@ -68,6 +70,7 @@ export function connection(): Promise<void> {
`Route ${workStore.route} used \`connection()\` inside "use cache: private". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, connection)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
......
......@@ -28,6 +28,7 @@ import {
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -68,6 +69,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
`Route ${workStore.route} used \`cookies()\` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`cookies()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, cookies)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
case 'unstable-cache':
......
......@@ -21,6 +21,7 @@ import { DynamicServerError } from '../../client/components/hooks-server-context
import { InvariantError } from '../../shared/lib/invariant-error'
import { delayUntilRuntimeStage } from '../dynamic-rendering-utils'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { applyOwnerStack } from '../dynamic-rendering-utils'
export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode'
......@@ -206,6 +207,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
`Route ${workStore.route} used "${expression}" inside "use cache". The enabled status of \`draftMode()\` can be read in caches but you must not enable or disable \`draftMode()\` inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, constructorOpt)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
......
......@@ -26,6 +26,7 @@ import {
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -68,6 +69,7 @@ export function headers(): Promise<ReadonlyHeaders> {
`Route ${workStore.route} used \`headers()\` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`headers()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, headers)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
......
......@@ -75,6 +75,7 @@ import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-st
import type { CacheLife } from './cache-life'
import { RenderStage } from '../app-render/staged-rendering'
import * as Log from '../../build/output/log'
import { getServerReact, getClientReact } from '../runtime-reacts.external'
interface PrivateCacheContext {
readonly kind: 'private'
......@@ -83,6 +84,7 @@ interface PrivateCacheContext {
| PrivateUseCacheStore
| PrerenderStoreModernRuntime
readonly skipPropagation: boolean
readonly outerOwnerStack: string | undefined
}
interface PublicCacheContext {
......@@ -93,6 +95,7 @@ interface PublicCacheContext {
PrerenderStoreModernClient | ValidationStoreClient
>
readonly skipPropagation: boolean
readonly outerOwnerStack: string | undefined
}
type CacheContext = PrivateCacheContext | PublicCacheContext
......@@ -360,6 +363,7 @@ function createUseCacheStore(
rootParams: outerWorkUnitStore.rootParams,
headers: outerWorkUnitStore.headers,
cookies: outerWorkUnitStore.cookies,
outerOwnerStack: cacheContext.outerOwnerStack,
}
} else {
let useCacheOrRequestStore: RequestStore | UseCacheStore | undefined
......@@ -404,10 +408,48 @@ function createUseCacheStore(
),
rootParams: outerWorkUnitStore.rootParams,
readRootParamNames: new Set<string>(),
outerOwnerStack: cacheContext.outerOwnerStack,
}
}
}
/**
* Captures the owner stack from the outer component tree before entering a
* cache boundary. When nested inside another cache scope, the parent's
* outerOwnerStack is concatenated so that the full component tree is preserved
* across multiple cache boundaries.
*/
function captureOuterOwnerStack(
workUnitStore: WorkUnitStore
): string | undefined {
const capturedOwnerStack =
(getClientReact()?.captureOwnerStack?.() ??
getServerReact()?.captureOwnerStack?.()) ||
''
let parentOuterOwnerStack: string | undefined
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
parentOuterOwnerStack = workUnitStore.outerOwnerStack
break
case 'unstable-cache':
case 'request':
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
return capturedOwnerStack + (parentOuterOwnerStack || '') || undefined
}
function assertDefaultCacheLife(
defaultCacheLife: CacheLife | undefined
): asserts defaultCacheLife is Required<CacheLife> {
......@@ -1125,6 +1167,11 @@ export async function cache(
)
}
const outerOwnerStack =
process.env.NODE_ENV !== 'production'
? captureOuterOwnerStack(workUnitStore)
: undefined
const name = originalFn.name
let fn = originalFn
let cacheContext: CacheContext
......@@ -1182,6 +1229,7 @@ export async function cache(
kind: 'private',
outerWorkUnitStore: workUnitStore,
skipPropagation: false,
outerOwnerStack,
}
break
case 'generate-static-params':
......@@ -1221,6 +1269,7 @@ export async function cache(
kind: 'public',
outerWorkUnitStore: workUnitStore,
skipPropagation: false,
outerOwnerStack,
}
break
default:
......@@ -2048,6 +2097,7 @@ export async function cache(
kind: cacheContext.kind,
outerWorkUnitStore: cacheContext.outerWorkUnitStore,
skipPropagation: true,
outerOwnerStack: cacheContext.outerOwnerStack,
},
clientReferenceManifest,
encodedCacheKeyParts,
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { CachedConnectionCaller } from 'third-party-pkg'
export default async function Page() {
return (
<>
<p>
This page calls `connection()` in `'use cache'` from third-party code,
which triggers an error.
</p>
<CachedConnectionCaller />
</>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { connection } from 'next/server'
export default async function Page() {
return (
<>
<p>
This page calls `connection()` in `'use cache'`, which triggers an
error.
</p>
<ConnectionCallingComponent />
</>
)
}
async function ConnectionCallingComponent() {
'use cache'
// Calling connection() in a cache context is not allowed. We're try/catching
// here to ensure that this error is shown even when it's caught in userland.
try {
await connection()
} catch {}
return null
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { CachedCookiesReader } from 'third-party-pkg'
export default async function Page() {
return (
<>
<p>
This page accesses `cookies()` in `'use cache'` from third-party code,
which triggers an error.
</p>
<CachedCookiesReader />
</>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { CachedDraftModeEnabler } from 'third-party-pkg'
export default async function Page() {
return (
<>
<p>
This page enables draft mode in `'use cache'` from third-party code,
which triggers an error.
</p>
<CachedDraftModeEnabler />
</>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { CachedHeadersReader } from 'third-party-pkg'
export default async function Page() {
return (
<>
<p>
This page accesses `headers()` in `'use cache'` from third-party code,
which triggers an error.
</p>
<CachedHeadersReader />
</>
)
}
import { cookies, headers, draftMode } from 'next/headers'
import { connection } from 'next/server'
export async function CachedCookiesReader() {
'use cache'
try {
await cookies()
} catch {}
return null
}
export async function CachedHeadersReader() {
'use cache'
try {
await headers()
} catch {}
return null
}
export async function CachedDraftModeEnabler() {
'use cache'
try {
;(await draftMode()).enable()
} catch {}
return null
}
export async function CachedConnectionCaller() {
'use cache'
try {
await connection()
} catch {}
return null
}
{
"name": "third-party-pkg",
"type": "module",
"exports": {
".": "./index.js"
}
}
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