Unverified Commit 6137b367 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix Server Actions hanging after navigation to PPR pages (#99252)

Adopts #99229. Closes #99229.

A Server Action can hang on Vercel when the client navigates from `/a`
to a PPR `/b` page and then calls an action owned by `/a`. The `/b` POST
can carry postponed state. `app-page-runtime.ts` consumes the request
stream to separate that state and saves the remaining action body as
`actionBody`. The forwarding path reads `req.stream()` again, so its
fetch waits on an exhausted stream until the function times out.

The forwarding path now sends `actionBody` when it is present. It
removes the source route's resume headers because the forwarded body no
longer contains that state; the platform can attach the target route's
state on the new request. Requests without a saved action body still use
the request stream.

The E2E test uses `connection()` to make `/b` PPR, warms its shell,
navigates from `/a` to `/b`, and invokes an action imported only by
`/a`. On a fresh Vercel deployment, it stays pending without this change
and returns `pong` with it. The same test passes under `next start`,
which does not receive the platform's prepended state.

Fixes #99153

---------
Co-authored-by: 's avatarDmitrii Troitskii <jsleitor@gmail.com>
parent 36e51187
...@@ -44,6 +44,8 @@ import { ...@@ -44,6 +44,8 @@ import {
JSON_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
NEXT_RESUME_HEADER,
NEXT_RESUME_STATE_LENGTH_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta' import { getServerActionRequestMetadata } from '../lib/server-action-request-meta'
import { isCsrfOriginAllowed } from './csrf-protection' import { isCsrfOriginAllowed } from './csrf-protection'
...@@ -278,7 +280,24 @@ async function createForwardedActionResponse( ...@@ -278,7 +280,24 @@ async function createForwardedActionResponse(
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req) isNodeNextRequest(req)
) { ) {
body = req.stream() // If the action body was already stashed (and consumed from the
// request stream) so it could be replayed for the local action
// handler (e.g. when resume state was read from the body first),
// forward that stashed body instead of re-reading the now-exhausted
// stream, which would otherwise hang forever. Since the forwarded
// body no longer starts with the postponed state, the resume headers
// no longer apply and must be dropped so the receiving worker doesn't
// try to read postponed state from it.
// The platform can attach the target page's postponed state, including
// its RDC, to the forwarded request independently of these headers.
const actionBody = getRequestMeta(req, 'actionBody')
if (actionBody) {
body = new Uint8Array(actionBody)
forwardedHeaders.delete(NEXT_RESUME_HEADER)
forwardedHeaders.delete(NEXT_RESUME_STATE_LENGTH_HEADER)
} else {
body = req.stream()
}
} else { } else {
throw new Error('Invariant: Unknown request type.') throw new Error('Invariant: Unknown request type.')
} }
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('forwarding an action from a PPR route', () => {
const { next } = nextTestSetup({ files: __dirname })
it('completes an action after navigating to a PPR page', async () => {
expect((await next.fetch('/b')).status).toBe(200)
const browser = await next.browser('/a')
await browser.waitForElementByCss('#go-to-b')
await browser.elementById('go-to-b').click()
await browser.waitForElementByCss('#forward-action')
expect(new URL(await browser.url()).pathname).toBe('/b')
let actionResponseStatus: number | undefined
browser.on('response', (response) => {
if (
new URL(response.url()).pathname === '/b' &&
response.request().method() === 'POST'
) {
actionResponseStatus = response.status()
}
})
await browser.elementById('forward-action').click()
await retry(async () => {
expect(
await browser.eval('sessionStorage.getItem("action-status")')
).toBe('pong')
expect(actionResponseStatus).toBe(200)
}, 15_000)
})
})
'use server'
export async function ping() {
return 'pong'
}
'use client'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { useActionReference } from '../action-context'
import { ping } from './actions'
export function Client() {
const { setAction } = useActionReference()
const [ready, setReady] = useState(false)
useEffect(() => {
setAction(() => ping)
setReady(true)
}, [setAction])
return ready ? (
<Link id="go-to-b" href="/b">
Go to /b
</Link>
) : null
}
import { Client } from './client'
export default function Page() {
return <Client />
}
'use client'
import {
createContext,
useContext,
useState,
type Dispatch,
type ReactNode,
type SetStateAction,
} from 'react'
type Action = () => Promise<string>
const ActionContext = createContext<{
action: Action | null
setAction: Dispatch<SetStateAction<Action | null>>
} | null>(null)
export function ActionProvider({ children }: { children: ReactNode }) {
const [action, setAction] = useState<Action | null>(null)
return (
<ActionContext.Provider value={{ action, setAction }}>
{children}
</ActionContext.Provider>
)
}
export function useActionReference() {
const context = useContext(ActionContext)
if (!context) {
throw new Error('Missing action provider')
}
return context
}
'use client'
import { useActionReference } from '../action-context'
export function ActionButton() {
const { action } = useActionReference()
return action ? (
<button
id="forward-action"
type="button"
onClick={async () => {
sessionStorage.setItem('action-status', 'started')
try {
sessionStorage.setItem('action-status', await action())
} catch (error) {
sessionStorage.setItem('action-status', `error: ${error}`)
}
}}
>
Ping
</button>
) : null
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { ActionButton } from './action-button'
export const maxDuration = 30
async function Dynamic() {
await connection()
return <p id="dynamic">ready</p>
}
export default function Page() {
return (
<main>
<ActionButton />
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
</main>
)
}
import type { ReactNode } from 'react'
import { ActionProvider } from './action-context'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<ActionProvider>{children}</ActionProvider>
</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default 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