Unverified Commit 004fea03 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

optimize server action refresh logic (#82674)

When a server action is in-flight and the user kicks off a navigation,
the router has handling to prioritize that navigation and "discard" the
action that was pending. This only discards it from the router state
perspective: the action is still run to completion and not aborted.

To account for the case where your action might have performed a data
mutation + revalidation, we'd eagerly refresh the router state after the
discarded action completes. However this isn't zero-cost:
`router.refresh` wipes the full router cache, which is wasteful if the
action you ran wasn't a mutation (ie, maybe it was just a GET).

Since actions already pass information to the reducer about when/if they
performed some sort of revalidation, we can use this to pass information
to the action queue, and it can use this to determine that a refresh is
needed, rather than always eagerly executing it.

While making this change, I noticed the original test case for it wasn't
actually working as expected. The random number in the root layout was a
`Math.random()` without any caching, so a navigation would have resulted
in a new random number, regardless of calling `router.refresh()`.
parent 527a238d
......@@ -69,24 +69,25 @@ function runRemainingActions(
if (actionQueue.pending !== null) {
actionQueue.pending = actionQueue.pending.next
if (actionQueue.pending !== null) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
runAction({
actionQueue,
action: actionQueue.pending,
setState,
})
} else {
// No more actions are pending, check if a refresh is needed
if (actionQueue.needsRefresh) {
actionQueue.needsRefresh = false
actionQueue.dispatch(
{
type: ACTION_REFRESH,
origin: window.location.origin,
},
setState
)
}
}
} else {
// Check for refresh when pending is already null
// This handles the case where a discarded server action completes
// after the navigation has already finished and the queue is empty
if (actionQueue.needsRefresh) {
actionQueue.needsRefresh = false
actionQueue.dispatch(
{
type: ACTION_REFRESH,
origin: window.location.origin,
},
setState
)
}
}
}
......@@ -110,6 +111,18 @@ async function runAction({
function handleResult(nextState: AppRouterState) {
// if we discarded this action, the state should also be discarded
if (action.discarded) {
// Check if the discarded server action revalidated data
if (
action.payload.type === ACTION_SERVER_ACTION &&
action.payload.didRevalidate
) {
// The server action was discarded but it revalidated data,
// mark that we need to refresh after all actions complete
actionQueue.needsRefresh = true
}
// Still need to run remaining actions even for discarded actions
// to potentially trigger the refresh
runRemainingActions(actionQueue, setState)
return
}
......@@ -187,11 +200,6 @@ function dispatchAction(
// (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)
newAction.next = actionQueue.pending.next
// if the pending action was a server action, mark the queue as needing a refresh once events are processed
if (actionQueue.pending.payload.type === ACTION_SERVER_ACTION) {
actionQueue.needsRefresh = true
}
runAction({
actionQueue,
action: newAction,
......
......@@ -290,6 +290,14 @@ export function serverActionReducer(
revalidatedParts.tag ||
revalidatedParts.cookie
// Store whether this action triggered any revalidation
// The action queue will use this information to potentially
// trigger a refresh action if the action was discarded
// (ie, due to a navigation, before the action completed)
if (actionRevalidated) {
action.didRevalidate = true
}
for (const normalizedFlightData of flightData) {
const {
tree: treePatch,
......
......@@ -69,6 +69,7 @@ export interface ServerActionAction {
actionArgs: any[]
resolve: (value: any) => void
reject: (reason?: any) => void
didRevalidate?: boolean
}
/**
......
......@@ -261,11 +261,27 @@ async function createForwardedActionResponse(
function getAppRelativeRedirectUrl(
basePath: string,
host: Host,
redirectUrl: string
redirectUrl: string,
currentPathname?: string
): URL | null {
if (redirectUrl.startsWith('/') || redirectUrl.startsWith('.')) {
// Make sure we are appending the basePath to relative URLS
if (redirectUrl.startsWith('/')) {
// Absolute path - just add basePath
return new URL(`${basePath}${redirectUrl}`, 'http://n')
} else if (redirectUrl.startsWith('.')) {
// Relative path - resolve relative to current pathname
let base = currentPathname || '/'
// Ensure the base path ends with a slash so relative resolution works correctly
// e.g., "./subpage" from "/subdir" should resolve to "/subdir/subpage"
// not "/subpage"
if (!base.endsWith('/')) {
base = base + '/'
}
const resolved = new URL(redirectUrl, `http://n${base}`)
// Include basePath in the final URL
return new URL(
`${basePath}${resolved.pathname}${resolved.search}${resolved.hash}`,
'http://n'
)
}
const parsedRedirectUrl = new URL(redirectUrl)
......@@ -288,7 +304,8 @@ async function createRedirectRenderResult(
redirectUrl: string,
redirectType: RedirectType,
basePath: string,
workStore: WorkStore
workStore: WorkStore,
currentPathname?: string
) {
res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`)
......@@ -300,7 +317,8 @@ async function createRedirectRenderResult(
const appRelativeRedirectUrl = getAppRelativeRedirectUrl(
basePath,
originalHost,
redirectUrl
redirectUrl,
currentPathname
)
if (appRelativeRedirectUrl) {
......@@ -1052,7 +1070,8 @@ export async function handleAction({
redirectUrl,
redirectType,
ctx.renderOpts.basePath,
workStore
workStore,
requestStore.url.pathname
),
}
}
......
......@@ -553,27 +553,6 @@ describe('app-dir action handling', () => {
await check(() => browser.url(), `${next.url}/`, true, 2)
})
it('should trigger a refresh for a server action that gets discarded due to a navigation', async () => {
let browser = await next.browser('/client')
const initialRandomNumber = await browser
.elementByCss('#random-number')
.text()
await browser.elementByCss('#slow-inc').click()
// navigate to server
await browser.elementByCss('#navigate-server').click()
// wait for the action to be completed
await retry(async () => {
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
expect(newRandomNumber).not.toBe(initialRandomNumber)
})
})
it('should trigger a refresh for a server action that also dispatches a navigation event', async () => {
let browser = await next.browser('/revalidate')
let initialJustPutit = await browser.elementById('justputit').text()
......@@ -1926,4 +1905,54 @@ describe('app-dir action handling', () => {
}
)
})
describe('action discarding', () => {
it('should not trigger a refresh for a server action that gets discarded due to a navigation (without revalidation)', async () => {
let browser = await next.browser('/action-discarding')
await browser.waitForIdleNetwork()
const initialRandomNumber = await browser
.elementByCss('#cached-random')
.text()
await browser.elementByCss('#slow-action').click()
// navigate to destination
await browser.elementByCss('#navigate-destination').click()
// wait for the 2s action to finish
await waitFor(2000)
await retry(async () => {
const newRandomNumber = await browser
.elementByCss('#cached-random')
.text()
expect(newRandomNumber).toBe(initialRandomNumber)
})
})
it('should trigger a refresh for a server action that gets discarded due to a navigation (with revalidation)', async () => {
let browser = await next.browser('/action-discarding')
await browser.waitForIdleNetwork()
const initialRandomNumber = await browser
.elementByCss('#cached-random')
.text()
await browser.elementByCss('#slow-action-revalidate').click()
// navigate to destination
await browser.elementByCss('#navigate-destination').click()
// wait for the 2s action to finish
await waitFor(2000)
await retry(async () => {
const newRandomNumber = await browser
.elementByCss('#cached-random')
.text()
expect(newRandomNumber).not.toBe(initialRandomNumber)
})
})
})
})
'use server'
import { revalidateTag } from 'next/cache'
export async function slowAction() {
await new Promise((resolve) => setTimeout(resolve, 2000))
return 'slow action completed'
}
export async function slowActionWithRevalidation() {
await new Promise((resolve) => setTimeout(resolve, 2000))
revalidateTag('cached-random')
return 'slow action with revalidation completed'
}
export default function DestinationPage() {
return (
<div>
<h1 id="destination-page">Destination Page</h1>
<p>You have navigated to the destination.</p>
</div>
)
}
import Link from 'next/link'
import { connection } from 'next/server'
export default async function Layout({ children }) {
await connection()
const cachedRandom = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?key=cached-random',
{ next: { tags: ['cached-random'] } }
).then((res) => res.text())
return (
<div>
<div>
Cached Random: <span id="cached-random">{cachedRandom}</span>
</div>
<div>
<Link id="navigate-destination" href="/action-discarding/destination">
Navigate to Destination
</Link>
</div>
{children}
</div>
)
}
'use client'
import { slowAction, slowActionWithRevalidation } from './actions'
export default function Page() {
return (
<div>
<h1>Action Discarding Test</h1>
<button
id="slow-action"
onClick={async () => {
await slowAction()
}}
>
Slow Action (No Revalidation)
</button>
<button
id="slow-action-revalidate"
onClick={async () => {
await slowActionWithRevalidation()
}}
>
Slow Action (With Revalidation)
</button>
</div>
)
}
......@@ -15,7 +15,7 @@ export async function inc(value) {
}
export async function slowInc(value) {
await new Promise((resolve) => setTimeout(resolve, 10000))
await new Promise((resolve) => setTimeout(resolve, 2000))
return value + 1
}
......
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