Unverified Commit 10b0db32 authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Preserve resume data cache for MPA actions

parent 3cbf2916
...@@ -41,7 +41,7 @@ import { ...@@ -41,7 +41,7 @@ import {
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' } import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' }
import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' } import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' }
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' } import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' }
import { getServerActionRequestMetadata } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' } import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' }
import { import {
RSC_HEADER, RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
...@@ -291,8 +291,7 @@ export function createAppPageEntrypoint({ ...@@ -291,8 +291,7 @@ export function createAppPageEntrypoint({
getRequestMeta(req, 'isRSCRequest') ?? getRequestMeta(req, 'isRSCRequest') ??
isRSCRequestHeader(req.headers[RSC_HEADER]) isRSCRequestHeader(req.headers[RSC_HEADER])
const { isFetchAction, isPossibleServerAction } = const isPossibleServerAction = getIsPossibleServerAction(req)
getServerActionRequestMetadata(req)
// For subresource requests (e.g. images or fonts), return plain text 404 // For subresource requests (e.g. images or fonts), return plain text 404
// instead of rendering the not-found route. // instead of rendering the not-found route.
...@@ -319,9 +318,8 @@ export function createAppPageEntrypoint({ ...@@ -319,9 +318,8 @@ export function createAppPageEntrypoint({
*/ */
const couldSupportPPR: boolean = Boolean(nextConfig.cacheComponents) const couldSupportPPR: boolean = Boolean(nextConfig.cacheComponents)
// Split postponed state from Server Action bodies in minimal mode. Fetch // Stash postponed state for server actions when in minimal mode.
// actions resume with that state, while MPA actions only reuse the extracted // We extract it here so the RDC is available for the re-render after the action completes.
// action body because their response must include the complete page.
const resumeStateLengthHeader = req.headers[NEXT_RESUME_STATE_LENGTH_HEADER] const resumeStateLengthHeader = req.headers[NEXT_RESUME_STATE_LENGTH_HEADER]
if ( if (
!getRequestMeta(req, 'postponed') && !getRequestMeta(req, 'postponed') &&
...@@ -372,12 +370,10 @@ export function createAppPageEntrypoint({ ...@@ -372,12 +370,10 @@ export function createAppPageEntrypoint({
if (fullBody.length >= stateLength) { if (fullBody.length >= stateLength) {
// Extract postponed state from the beginning // Extract postponed state from the beginning
if (isFetchAction) { const postponedState = fullBody
const postponedState = fullBody .subarray(0, stateLength)
.subarray(0, stateLength) .toString('utf8')
.toString('utf8') addRequestMeta(req, 'postponed', postponedState)
addRequestMeta(req, 'postponed', postponedState)
}
// Store the remaining action body for the action handler // Store the remaining action body for the action handler
const actionBody = fullBody.subarray(stateLength) const actionBody = fullBody.subarray(stateLength)
...@@ -1352,16 +1348,19 @@ export function createAppPageEntrypoint({ ...@@ -1352,16 +1348,19 @@ export function createAppPageEntrypoint({
: undefined : undefined
if ( if (
// Dynamic RSC requests and fetch actions should use the postponed data // If this is a dynamic RSC request or a server action request, we should
// from the static render (if available). This keeps the resume data // use the postponed data from the static render (if available). This
// cache consistent between the static and dynamic renders. MPA actions // ensures that we can utilize the resume data cache (RDC) from the static
// need a complete HTML document, so they must not resume here. // render to ensure that the data is consistent between the static and
// dynamic renders (for navigations) or when re-rendering after a server
// action.
// Only enable RDC for Navigations if the feature is enabled. // Only enable RDC for Navigations if the feature is enabled.
supportsRDCForNavigations && supportsRDCForNavigations &&
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
!isMinimalMode && !isMinimalMode &&
incrementalCache && incrementalCache &&
(isDynamicRSCRequest || isFetchAction) && // Include both dynamic RSC requests (navigations) and server actions
(isDynamicRSCRequest || isPossibleServerAction) &&
// We don't typically trigger an on-demand revalidation for dynamic RSC // We don't typically trigger an on-demand revalidation for dynamic RSC
// requests, as we're typically revalidating the page in the background // requests, as we're typically revalidating the page in the background
// instead. However, if the cache entry is stale, we should trigger a // instead. However, if the cache entry is stale, we should trigger a
......
...@@ -170,7 +170,10 @@ import { ...@@ -170,7 +170,10 @@ import {
getPostponedFromState, getPostponedFromState,
} from './postponed-state' } from './postponed-state'
import { isDynamicServerError } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta' import {
getIsPossibleServerAction,
getServerActionRequestMetadata,
} from '../lib/server-action-request-meta'
import { getFlightStream } from './use-flight-response' import { getFlightStream } from './use-flight-response'
import { import {
StaticGenBailoutError, StaticGenBailoutError,
...@@ -221,7 +224,6 @@ import { ...@@ -221,7 +224,6 @@ import {
import AppRouter from '../../client/components/app-router' import AppRouter from '../../client/components/app-router'
import type { ServerComponentsHmrCache } from '../response-cache' import type { ServerComponentsHmrCache } from '../response-cache'
import type { RequestErrorContext } from '../instrumentation/types' import type { RequestErrorContext } from '../instrumentation/types'
import { getIsPossibleServerAction } from '../lib/server-action-request-meta'
import { createInitialRouterState } from '../../client/components/router-reducer/create-initial-router-state' import { createInitialRouterState } from '../../client/components/router-reducer/create-initial-router-state'
import { createMutableActionQueue } from '../../client/components/app-router-instance' import { createMutableActionQueue } from '../../client/components/app-router-instance'
import { getRevalidateReason } from '../instrumentation/utils' import { getRevalidateReason } from '../instrumentation/utils'
...@@ -3321,12 +3323,15 @@ function prepareAppPage( ...@@ -3321,12 +3323,15 @@ function prepareAppPage(
fallbackRouteParams fallbackRouteParams
) )
// If provided, the postpone state should be parsed so it can be provided to // If provided, parse the postponed state so its RDC is available to the
// React. // render. Keep the React state only for requests that can resume it.
let postponedState: PostponedState | null = null let postponedState: PostponedState | null = null
if (typeof renderOpts.postponed === 'string') { if (typeof renderOpts.postponed === 'string') {
const { isFetchAction, isPossibleMPAAction } =
getServerActionRequestMetadata(req)
if (fallbackRouteParams) { if (fallbackRouteParams) {
if (!getServerActionRequestMetadata(req).isFetchAction) { if (!isFetchAction) {
throw new InvariantError( throw new InvariantError(
'postponed state should not be provided when fallback params are provided' 'postponed state should not be provided when fallback params are provided'
) )
...@@ -3343,6 +3348,18 @@ function prepareAppPage( ...@@ -3343,6 +3348,18 @@ function prepareAppPage(
renderOpts.experimental.disableResumeDataCacheCompression renderOpts.experimental.disableResumeDataCacheCompression
), ),
} }
} else if (isPossibleMPAAction) {
// An MPA action needs a complete HTML document, so it cannot resume the
// React render. Its RDC is still needed to keep cached values consistent
// with the static shell when the action did not invalidate them.
postponedState = {
type: DynamicState.DATA,
renderResumeDataCache: parseResumeDataCacheFromPostponedState(
renderOpts.postponed,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
),
}
} else { } else {
postponedState = parsePostponedState( postponedState = parsePostponedState(
renderOpts.postponed, renderOpts.postponed,
...@@ -3531,6 +3548,8 @@ async function renderToStream( ...@@ -3531,6 +3548,8 @@ async function renderToStream(
): Promise<AnyStream> { ): Promise<AnyStream> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ /* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
// MARK: renderToStream setup // MARK: renderToStream setup
const { isPossibleMPAAction } = getServerActionRequestMetadata(req)
const { const {
assetPrefix, assetPrefix,
htmlRequestId, htmlRequestId,
...@@ -3540,6 +3559,10 @@ async function renderToStream( ...@@ -3540,6 +3559,10 @@ async function renderToStream(
requestId, requestId,
workStore, workStore,
} = ctx } = ctx
// MPA actions reuse the RDC from the postponed state, but their response
// must come from a complete server render rather than a postponed response.
const shouldUsePostponedResponse =
typeof renderOpts.postponed === 'string' && !isPossibleMPAAction
const { const {
basePath, basePath,
...@@ -4068,7 +4091,7 @@ async function renderToStream( ...@@ -4068,7 +4091,7 @@ async function renderToStream(
if (process.env.__NEXT_USE_NODE_STREAMS) { if (process.env.__NEXT_USE_NODE_STREAMS) {
// If provided, the postpone state should be parsed as JSON so it can be // If provided, the postpone state should be parsed as JSON so it can be
// provided to React. // provided to React.
if (typeof renderOpts.postponed === 'string') { if (shouldUsePostponedResponse) {
if (postponedState?.type === DynamicState.DATA) { if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to // We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included // still include the new server component render because it was not included
...@@ -4209,7 +4232,7 @@ async function renderToStream( ...@@ -4209,7 +4232,7 @@ async function renderToStream(
// MARK: webStreams HTML // MARK: webStreams HTML
// If provided, the postpone state should be parsed as JSON so it can be // If provided, the postpone state should be parsed as JSON so it can be
// provided to React. // provided to React.
if (typeof renderOpts.postponed === 'string') { if (shouldUsePostponedResponse) {
if (postponedState?.type === DynamicState.DATA) { if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to // We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included // still include the new server component render because it was not included
......
...@@ -10,6 +10,7 @@ export function getServerActionRequestMetadata( ...@@ -10,6 +10,7 @@ export function getServerActionRequestMetadata(
isURLEncodedAction: boolean isURLEncodedAction: boolean
isMultipartAction: boolean isMultipartAction: boolean
isFetchAction: boolean isFetchAction: boolean
isPossibleMPAAction: boolean
isPossibleServerAction: boolean isPossibleServerAction: boolean
} { } {
let actionId: string | null let actionId: string | null
...@@ -37,16 +38,17 @@ export function getServerActionRequestMetadata( ...@@ -37,16 +38,17 @@ export function getServerActionRequestMetadata(
typeof actionId === 'string' && typeof actionId === 'string' &&
req.method === 'POST' req.method === 'POST'
) )
const isPossibleMPAAction =
!isFetchAction && (isURLEncodedAction || isMultipartAction)
const isPossibleServerAction = Boolean( const isPossibleServerAction = Boolean(isFetchAction || isPossibleMPAAction)
isFetchAction || isURLEncodedAction || isMultipartAction
)
return { return {
actionId, actionId,
isURLEncodedAction, isURLEncodedAction,
isMultipartAction, isMultipartAction,
isFetchAction, isFetchAction,
isPossibleMPAAction,
isPossibleServerAction, isPossibleServerAction,
} }
} }
......
'use server' 'use server'
import { revalidatePath } from 'next/cache'
export async function action() { export async function action() {
return 'result' return 'result'
} }
export async function revalidatingAction() {
revalidatePath('/server-action-mpa-partial')
return 'revalidated'
}
'use client' 'use client'
import { useActionState } from 'react' import { useActionState } from 'react'
import { action } from './action' import { action, revalidatingAction } from './action'
export function ActionForm() { export function ActionForm() {
const [result, formAction] = useActionState(action, 'initial') const [result, formAction] = useActionState(action, 'initial')
const [revalidationResult, revalidationFormAction] = useActionState(
revalidatingAction,
'initial'
)
return ( return (
<form action={formAction}> <>
<button>Submit</button> <form action={formAction}>
<p id="action-state">{result}</p> <button id="submit-button">Submit</button>
</form> <p id="action-state">{result}</p>
</form>
<form action={revalidationFormAction}>
<button id="revalidate-button">Revalidate</button>
<p id="revalidation-state">{revalidationResult}</p>
</form>
</>
) )
} }
...@@ -2,10 +2,13 @@ import { connection } from 'next/server' ...@@ -2,10 +2,13 @@ import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
import { ActionForm } from './form' import { ActionForm } from './form'
export default function Page() { export default async function Page() {
const cachedTimestamp = await getCachedTimestamp()
return ( return (
<main> <main>
<h1>Server Action on a partial page</h1> <h1>Server Action on a partial page</h1>
<p id="cached-timestamp">{cachedTimestamp}</p>
<ActionForm /> <ActionForm />
<Suspense fallback={<p>Loading request data</p>}> <Suspense fallback={<p>Loading request data</p>}>
<RequestData /> <RequestData />
...@@ -14,6 +17,12 @@ export default function Page() { ...@@ -14,6 +17,12 @@ export default function Page() {
) )
} }
async function getCachedTimestamp() {
'use cache'
return Date.now()
}
async function RequestData() { async function RequestData() {
await connection() await connection()
return <p>Request data ready</p> return <p>Request data ready</p>
......
...@@ -22,10 +22,36 @@ describe('cache-components', () => { ...@@ -22,10 +22,36 @@ describe('cache-components', () => {
}) })
expect(await browser.elementByCss('#action-state').text()).toBe('initial') expect(await browser.elementByCss('#action-state').text()).toBe('initial')
await browser.elementByCss('button').click() const cachedTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
await browser.elementByCss('#submit-button').click()
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('#action-state').text()).toBe('result') expect(await browser.elementByCss('#action-state').text()).toBe('result')
expect(await browser.elementByCss('#cached-timestamp').text()).toBe(
cachedTimestamp
)
})
})
it('should revalidate cached data in a complete MPA response', async () => {
const browser = await next.browser('/server-action-mpa-partial', {
disableJavaScript: true,
})
const cachedTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
await browser.elementByCss('#revalidate-button').click()
await retry(async () => {
expect(await browser.elementByCss('#revalidation-state').text()).toBe(
'revalidated'
)
expect(await browser.elementByCss('#cached-timestamp').text()).not.toBe(
cachedTimestamp
)
}) })
}) })
......
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