Unverified Commit 1ab0f1ad authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Handle Server Actions on dynamic PPR fallback routes (#96932)

## Summary

A fetch action can be dispatched to a parameterized route fallback
without concrete route params. When the deployment adapter also supplies
that route’s postponed state, Next.js throws because postponed state and
fallback params are present together.

These requests only need to execute the action and cannot safely render
the fallback route. This change preserves the Resume Data Cache for
cached reads, discards the React postponed state that cannot be resumed
without concrete params, and consistently skips fallback-route rendering
for successful and failed actions.

## Verification

- Added a `next start` integration test that synthesizes an action-only
fallback request and fails without the fix.
- Added coverage for access fallback errors and direct Resume Data Cache
extraction.
- Added a deployment test using a public browser interaction where an
action is retained across navigation to a route that does not bundle it.

<!-- NEXT_JS_LLM -->
parent 5e8f31f7
......@@ -741,6 +741,14 @@ export async function handleAction({
)
const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
// A fetch action targeting a fallback route has no concrete params with
// which to resume the destination page.
const isActionOnlyFallbackRequest =
isFetchAction &&
requestStore.fallbackParams != null &&
typeof ctx.renderOpts.postponed === 'string'
const shouldSkipPageRendering =
actionWasForwarded || isActionOnlyFallbackRequest
// Only attempt to forward if this request has not already been forwarded.
// Otherwise middleware that rewrites the action POST can cause the receiving
......@@ -1216,7 +1224,7 @@ export async function handleAction({
boundActionArguments,
workStore,
requestStore,
actionWasForwarded
shouldSkipPageRendering
).finally(() => {
addRevalidationHeader(res, { workStore, requestStore })
if (logInfo) {
......@@ -1314,7 +1322,7 @@ export async function handleAction({
return {
type: 'done',
result: await generateFlight(req, ctx, requestStore, {
skipPageRendering: false,
skipPageRendering: shouldSkipPageRendering,
actionResult: promise,
temporaryReferences,
}),
......@@ -1351,12 +1359,12 @@ export async function handleAction({
type: 'done',
result: await generateFlight(req, ctx, requestStore, {
actionResult: promise,
// If the page was not revalidated, or if the action was forwarded
// from another worker, we can skip rendering the page.
// If the page was not revalidated, or if this is an action-only
// request, we can skip rendering the page.
skipPageRendering:
workStore.pathWasRevalidated === undefined ||
workStore.pathWasRevalidated === ActionDidNotRevalidate ||
actionWasForwarded,
shouldSkipPageRendering,
temporaryReferences,
}),
}
......@@ -1380,13 +1388,13 @@ async function executeActionAndPrepareForRender<
args: Parameters<TFn>,
workStore: WorkStore,
requestStore: RequestStore,
actionWasForwarded: boolean
shouldSkipPageRendering: boolean
): Promise<{
actionResult: Awaited<ReturnType<TFn>>
skipPageRendering: boolean
}> {
requestStore.phase = 'action'
let skipPageRendering = actionWasForwarded
let skipPageRendering = shouldSkipPageRendering
if (args.length > SERVER_ACTION_ARGS_LIMIT) {
throw new Error(
......@@ -1399,8 +1407,8 @@ async function executeActionAndPrepareForRender<
action.apply(null, args)
)
// If the page was not revalidated, or if the action was forwarded from
// another worker, we can skip rendering the page.
// If the page was not revalidated, or if this is an action-only request,
// we can skip rendering the page.
skipPageRendering ||=
workStore.pathWasRevalidated === undefined ||
workStore.pathWasRevalidated === ActionDidNotRevalidate
......
......@@ -161,6 +161,7 @@ import {
type PostponedState,
DynamicHTMLPreludeState,
parsePostponedState,
parseResumeDataCacheFromPostponedState,
} from './postponed-state'
import {
getDynamicDataPostponedState,
......@@ -168,6 +169,7 @@ import {
getPostponedFromState,
} from './postponed-state'
import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta'
import { getFlightStream } from './use-flight-response'
import {
StaticGenBailoutError,
......@@ -3304,16 +3306,29 @@ function prepareAppPage(
let postponedState: PostponedState | null = null
if (typeof renderOpts.postponed === 'string') {
if (fallbackRouteParams) {
throw new InvariantError(
'postponed state should not be provided when fallback params are provided'
if (!getServerActionRequestMetadata(req).isFetchAction) {
throw new InvariantError(
'postponed state should not be provided when fallback params are provided'
)
}
// A fetch action with fallback params cannot render this page, so its
// React postponed state cannot be resumed. The RDC is still useful while
// executing cached functions in the action.
postponedState = {
type: DynamicState.DATA,
renderResumeDataCache: parseResumeDataCacheFromPostponedState(
renderOpts.postponed,
renderOpts.experimental.maxPostponedStateSizeBytes
),
}
} else {
postponedState = parsePostponedState(
renderOpts.postponed,
interpolatedParams,
renderOpts.experimental.maxPostponedStateSizeBytes
)
}
postponedState = parsePostponedState(
renderOpts.postponed,
interpolatedParams,
renderOpts.experimental.maxPostponedStateSizeBytes
)
}
if (
......
......@@ -7,6 +7,7 @@ import {
DynamicState,
getDynamicDataPostponedState,
getDynamicHTMLPostponedState,
parseResumeDataCacheFromPostponedState,
parsePostponedState,
DynamicHTMLPreludeState,
} from './postponed-state'
......@@ -146,6 +147,53 @@ describe('getDynamicDataPostponedState', () => {
})
})
describe('parseResumeDataCacheFromPostponedState', () => {
it('extracts the resume data cache without parsing the React state', async () => {
const key = '%%drp:slug:e9615126684e5%%'
const fallbackRouteParams = createMockOpaqueFallbackRouteParams({
slug: [key, 'd'],
})
const prerenderResumeDataCache = createPrerenderResumeDataCache()
prerenderResumeDataCache.cache.set(
'cache-key',
Promise.resolve({
entry: {
value: streamFromString('cached value'),
tags: [],
stale: 0,
timestamp: 0,
expire: 300,
revalidate: 1,
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
dynamicNestedCacheError: undefined,
})
)
const state = await getDynamicHTMLPostponedState(
{ [key]: key } as any,
DynamicHTMLPreludeState.Full,
fallbackRouteParams,
prerenderResumeDataCache,
isCacheComponentsEnabled
)
const resumeDataCache = parseResumeDataCacheFromPostponedState(
state,
undefined
)
const value = await resumeDataCache.cache.get('cache-key')
expect(value).toBeDefined()
await expect(streamToString(value!.entry.value)).resolves.toBe(
'cached value'
)
})
})
describe('parsePostponedState', () => {
it('parses a HTML postponed state with fallback params', () => {
const state = `2593:39[["slug","%%drp:slug:e9615126684e5%%"]][1,{"t":2,"d":{"nextSegmentId":2,"rootFormatContext":{"insertionMode":0,"selectedValue":null,"tagScope":0},"progressiveChunkSize":12800,"resumableState":{"idPrefix":"","nextFormID":0,"streamingFormat":0,"instructions":0,"hasBody":true,"hasHtml":true,"unknownResources":{},"dnsResources":{},"connectResources":{"default":{},"anonymous":{},"credentials":{}},"imageResources":{},"styleResources":{},"scriptResources":{"/_next/static/chunks/webpack-6b2534a6458c6fe5.js":null,"/_next/static/chunks/f5e865f6-5e04edf75402c5e9.js":null,"/_next/static/chunks/9440-26a4cfbb73347735.js":null,"/_next/static/chunks/main-app-315ef55d588dbeeb.js":null,"/_next/static/chunks/8630-8e01a4bea783c651.js":null,"/_next/static/chunks/app/layout-1b900e1a3caf3737.js":null},"moduleUnknownResources":{},"moduleScriptResources":{"/_next/static/chunks/webpack-6b2534a6458c6fe5.js":null}},"replayNodes":[["oR",0,[["Context.Provider",0,[["ServerInsertedHTMLProvider",0,[["Context.Provider",0,[["n7",0,[["nU",0,[["nF",0,[["n9",0,[["Fragment",0,[["Context.Provider",2,[["Context.Provider",0,[["Context.Provider",0,[["Context.Provider",0,[["Context.Provider",0,[["Context.Provider",0,[["nY",0,[["nX",0,[["Fragment","c",[["Fragment",0,[["html",1,[["body",0,[["main",3,[["j",0,[["Fragment",0,[["Context.Provider","validation",[["i",2,[["Fragment",0,[["E",0,[["R",0,[["h",0,[["Fragment",0,[["O",0,[["Fragment",0,[["s",0,[["c",0,[["s",0,[["c",0,[["v",0,[["Context.Provider",0,[["Fragment","c",[["j",1,[["Fragment",0,[["Context.Provider","slug|%%drp:slug:e9615126684e5%%|d",[["i",2,[["Fragment",0,[["E",0,[["R",0,[["h",0,[["Fragment",0,[["O",0,[["Fragment",0,[["s",0,[["Fragment",0,[["s",0,[["c",0,[["v",0,[["Context.Provider",0,[["Fragment","c",[["j",1,[["Fragment",0,[["Context.Provider","__PAGE__",[["i",2,[["Fragment",0,[["E",0,[["R",0,[["h",0,[["Fragment",0,[["O",0,[["Suspense",0,[["s",0,[["Fragment",0,[["s",0,[["c",0,[["v",0,[["Context.Provider",0,[["Fragment","c",[["Fragment",0,[],{"1":1}]],null]],null]],null]],null]],null]],null]],null]],null,["Suspense Fallback",0,[],null],0]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],null]],"replaySlots":null}}]null`
......
......@@ -114,34 +114,60 @@ export async function getDynamicDataPostponedState(
return `4:null${await stringifyResumeDataCache(createRenderResumeDataCache(resumeDataCache), isCacheComponentsEnabled)}`
}
export function parsePostponedState(
function parsePostponedStateParts(
state: string,
interpolatedParams: Params,
maxPostponedStateSizeBytes: number | undefined
): PostponedState {
try {
const postponedStringLengthMatch = state.match(/^([0-9]*):/)?.[1]
if (!postponedStringLengthMatch) {
// Do not include the raw state in the message: it can be large and may
// contain sensitive serialized data.
throw new Error(
'Invariant: invalid postponed state: missing length prefix'
)
}
): {
postponedString: string
renderResumeDataCache: RenderResumeDataCache
} {
const postponedStringLengthMatch = state.match(/^([0-9]*):/)?.[1]
if (!postponedStringLengthMatch) {
// Do not include the raw state in the message: it can be large and may
// contain sensitive serialized data.
throw new Error('Invariant: invalid postponed state: missing length prefix')
}
const postponedStringLength = parseInt(postponedStringLengthMatch)
const postponedStringLength = parseInt(postponedStringLengthMatch)
const tailStart =
postponedStringLengthMatch.length + postponedStringLength + 1
// We add a `:` to the end of the length as the first character of the
// postponed string is the length of the replacement entries.
const postponedString = state.slice(
return {
postponedString: state.slice(
postponedStringLengthMatch.length + 1,
postponedStringLengthMatch.length + postponedStringLength + 1
tailStart
),
renderResumeDataCache: createRenderResumeDataCache(
state.slice(tailStart),
maxPostponedStateSizeBytes
),
}
}
export function parseResumeDataCacheFromPostponedState(
state: string,
maxPostponedStateSizeBytes: number | undefined
): RenderResumeDataCache {
try {
return parsePostponedStateParts(state, maxPostponedStateSizeBytes)
.renderResumeDataCache
} catch (err) {
console.error(
'Failed to parse postponed state',
describePostponedStateParseFailure(state, err)
)
return createRenderResumeDataCache(createPrerenderResumeDataCache())
}
}
const renderResumeDataCache = createRenderResumeDataCache(
state.slice(
postponedStringLengthMatch.length + postponedStringLength + 1
),
export function parsePostponedState(
state: string,
interpolatedParams: Params,
maxPostponedStateSizeBytes: number | undefined
): PostponedState {
try {
const { postponedString, renderResumeDataCache } = parsePostponedStateParts(
state,
maxPostponedStateSizeBytes
)
......
import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('action-only fallback resume data cache', () => {
const { next } = nextTestSetup({
files: __dirname,
env: isNextDeploy
? {}
: {
NEXT_PRIVATE_TEST_HEADERS: '1',
NEXT_PRIVATE_MINIMAL_MODE: '1',
},
})
if (isNextDeploy) {
it('executes an action that is not bundled by the current route', async () => {
const browser = await next.browser('/events/foo/group')
await retry(async () => {
expect(await browser.elementByCss('#action-ready').text()).toBe('ready')
})
await browser.elementByCss('#navigate-home').click()
await retry(async () => {
expect(await browser.eval('window.location.pathname')).toBe('/')
})
await browser.elementByCss('#call-retained-action').click()
await retry(async () => {
expect(await browser.elementByCss('#action-result').text()).toBe(
'cached value'
)
})
expect(await browser.elementByCss('body').text()).not.toContain(
'destination page rendered'
)
})
} else {
async function invokeAction(exportedName: string) {
const metadata = await next.readJSON(
'.next/server/app/events/[id]/group.meta'
)
const postponed = metadata.postponed as string
expect(postponed).toEqual(expect.any(String))
const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json'
)
const actionId = Object.keys(manifest.node).find(
(id) => manifest.node[id].exportedName === exportedName
)
expect(actionId).toEqual(expect.any(String))
// Simulate the request received by the action worker after the platform
// has selected the dynamic route's fallback and prepended its postponed
// state to the action body.
const actionBody = Buffer.from('[]')
const postponedBody = Buffer.from(postponed)
return next.fetch('/events/[id]/group', {
method: 'POST',
headers: {
'content-type': 'text/plain;charset=UTF-8',
'next-action': actionId!,
'x-matched-path': '/events/[id]/group',
'x-next-resume-state-length': String(postponedBody.byteLength),
},
body: Buffer.concat([postponedBody, actionBody]),
})
}
it('handles postponed state on an action-only fallback request', async () => {
const response = await invokeAction('readCachedValue')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/x-component')
const responseBody = await response.text()
expect(responseBody).toContain('cached value')
expect(responseBody).not.toContain('destination page rendered')
})
it('does not render the fallback route when the action calls notFound', async () => {
const response = await invokeAction('notFoundAfterRevalidation')
expect(response.status).toBe(404)
expect(response.headers.get('content-type')).toContain('text/x-component')
const responseBody = await response.text()
expect(responseBody).not.toContain('destination page rendered')
})
}
})
'use server'
import { revalidatePath } from 'next/cache'
import { notFound } from 'next/navigation'
import { getCachedValue } from './cached-value'
export async function readCachedValue() {
const value = await getCachedValue()
revalidatePath('/events/foo/group')
return value
}
export async function notFoundAfterRevalidation() {
revalidatePath('/events/foo/group')
notFound()
}
'use client'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { notFoundAfterRevalidation, readCachedValue } from './actions'
declare global {
interface Window {
retainedAction?: () => Promise<string>
retainedNotFoundAction?: () => Promise<void>
}
}
export function Button() {
const [ready, setReady] = useState(false)
useEffect(() => {
window.retainedAction = readCachedValue
window.retainedNotFoundAction = notFoundAfterRevalidation
setReady(true)
}, [])
return (
<>
<p id="action-ready">{ready ? 'ready' : 'loading'}</p>
<Link id="navigate-home" href="/">
navigate home
</Link>
</>
)
}
export async function getCachedValue() {
'use cache'
return 'cached value'
}
import { Suspense } from 'react'
import { Button } from './button'
import { getCachedValue } from './cached-value'
async function CachedValue() {
return <p id="cached-value">{await getCachedValue()}</p>
}
async function EventId({ params }: { params: Promise<{ id: string }> }) {
return <p id="event-id">{(await params).id}</p>
}
export default function Page({ params }: { params: Promise<{ id: string }> }) {
return (
<>
<p>destination page rendered</p>
<CachedValue />
<Suspense fallback={<p>loading event</p>}>
<EventId params={params} />
</Suspense>
<Button />
</>
)
}
'use client'
import { useState } from 'react'
declare global {
interface Window {
retainedAction?: () => Promise<string>
}
}
export function HomeButton() {
const [result, setResult] = useState('not called')
return (
<>
<button
id="call-retained-action"
onClick={async () => {
const action = window.retainedAction
setResult(action ? await action() : 'missing action')
}}
>
call retained action
</button>
<p id="action-result">{result}</p>
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { HomeButton } from './home-button'
export default function Page() {
return <HomeButton />
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
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