Unverified Commit 892839ff authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix: server actions blocking navigation events (#54307)

A long-running server action shouldn't block page navigation. This makes use of a global mutable to detect when a navigation event occurs -- this change will unblock other reducers (such as navigation).

If we bailed on the action, we trigger a `router.refresh()` to ensure any side effects from the action are refetched.

Closes NEXT-1131
Fixes #49425
parent 36c14da3
......@@ -38,6 +38,7 @@ import {
RouterChangeByServerResponse,
RouterNavigate,
ServerActionDispatcher,
ServerActionMutable,
} from './router-reducer/router-reducer-types'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import {
......@@ -59,7 +60,6 @@ import { createInfinitePromise } from './infinite-promise'
import { NEXT_RSC_UNION_QUERY } from './app-router-headers'
import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path'
const isServer = typeof window === 'undefined'
// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
......@@ -73,6 +73,10 @@ export function getServerActionDispatcher() {
return globalServerActionDispatcher
}
let globalServerActionMutable: ServerActionMutable['globalMutable'] = {
refresh: () => {}, // noop until the router is initialized
}
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin)
urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)
......@@ -141,7 +145,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
dispatch({
...actionPayload,
type: ACTION_SERVER_ACTION,
mutable: {},
mutable: { globalMutable: globalServerActionMutable },
cache: createEmptyCacheNode(),
})
})
......@@ -182,6 +186,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
return useCallback(
(href, navigateType, forceOptimisticNavigation, shouldScroll) => {
const url = new URL(addBasePath(href), location.href)
globalServerActionMutable.pendingNavigatePath = href
return dispatch({
type: ACTION_NAVIGATE,
......@@ -351,6 +356,10 @@ function Router({
}
}, [appRouter])
useEffect(() => {
globalServerActionMutable.refresh = appRouter.refresh
}, [appRouter.refresh])
if (process.env.NODE_ENV !== 'production') {
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
// eslint-disable-next-line react-hooks/rules-of-hooks
......
......@@ -5,6 +5,7 @@ import {
} from '../../../../server/app-render/types'
import { callServer } from '../../../app-call-server'
import {
ACTION,
NEXT_ROUTER_STATE_TREE,
NEXT_URL,
RSC_CONTENT_TYPE_HEADER,
......@@ -51,7 +52,7 @@ async function fetchServerAction(
method: 'POST',
headers: {
Accept: RSC_CONTENT_TYPE_HEADER,
'Next-Action': actionId,
[ACTION]: actionId,
[NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)),
...(process.env.__NEXT_ACTIONS_DEPLOYMENT_ID &&
process.env.NEXT_DEPLOYMENT_ID
......@@ -147,9 +148,28 @@ export function serverActionReducer(
return handleMutable(state, mutable)
}
if (!action.mutable.inFlightServerAction) {
action.mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action)
if (mutable.inFlightServerAction) {
// unblock if a navigation event comes through
// while we've suspended on an action
if (
mutable.globalMutable.pendingNavigatePath &&
mutable.globalMutable.pendingNavigatePath !== href
) {
return state
}
} else {
mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action).then((result) => {
// if the server action resolves after a navigation took place,
// reset ServerActionMutable values & trigger a refresh so that any stale data gets updated
if (mutable.globalMutable.pendingNavigatePath) {
mutable.inFlightServerAction = null
mutable.globalMutable.pendingNavigatePath = undefined
mutable.globalMutable.refresh()
} else {
return result
}
})
)
}
......
......@@ -42,6 +42,7 @@ export interface Mutable {
export interface ServerActionMutable extends Mutable {
inFlightServerAction?: Promise<any> | null
globalMutable: { pendingNavigatePath?: string; refresh: () => void }
actionResultResolved?: boolean
}
......
......@@ -258,6 +258,26 @@ createNextDescribe(
await check(() => browser.elementByCss('#value').text(), 'Value = 2')
})
it('should not block navigation events while a server action is in flight', async () => {
let browser = await next.browser('/client')
await browser.elementByCss('#slow-inc').click()
// navigate to server
await browser.elementByCss('#navigate-server').click()
// intentionally bailing after 2 retries so we don't retry to the point where the async function resolves
await check(() => browser.url(), `${next.url}/server`, true, 2)
browser = await next.browser('/server')
await browser.elementByCss('#slow-inc').click()
// navigate to client
await browser.elementByCss('#navigate-client').click()
// intentionally bailing after 2 retries so we don't retry to the point where the async function resolves
await check(() => browser.url(), `${next.url}/client`, true, 2)
})
if (isNextStart) {
it('should not expose action content in sourcemaps', async () => {
const sourcemap = (
......
......@@ -14,6 +14,11 @@ export async function inc(value) {
return value + 1
}
export async function slowInc(value) {
await new Promise((resolve) => setTimeout(resolve, 10000))
return value + 1
}
export async function dec(value) {
return value - 1
}
......
......@@ -8,6 +8,7 @@ import double, {
redirectAction,
getHeaders,
renamed,
slowInc,
} from './actions'
import { test } from './actions-lib'
......@@ -19,7 +20,6 @@ export default function Counter() {
<button
id="inc"
onClick={async () => {
console.log(inc)
const newCount = await inc(count)
setCount(newCount)
......@@ -29,6 +29,15 @@ export default function Counter() {
>
+1
</button>
<button
id="slow-inc"
onClick={async () => {
const newCount = await slowInc(count)
setCount(newCount)
}}
>
+1 (Slow)
</button>
<button
id="dec"
onClick={async () => {
......
......@@ -6,6 +6,11 @@ export async function inc(value) {
return value + 1
}
export async function slowInc(value) {
await new Promise((resolve) => setTimeout(resolve, 10000))
return value + 1
}
export default async function dec(value) {
return value - 1
}
......
......@@ -2,7 +2,7 @@
import { useState } from 'react'
export default function Counter({ inc, dec, double }) {
export default function Counter({ inc, dec, double, slowInc }) {
const [count, setCount] = useState(0)
return (
......@@ -17,6 +17,15 @@ export default function Counter({ inc, dec, double }) {
>
+1
</button>
<button
id="slow-inc"
onClick={async () => {
const newCount = await slowInc(count)
setCount(newCount)
}}
>
+1 (Slow)
</button>
<button
id="dec"
onClick={async () => {
......
......@@ -2,7 +2,7 @@ import Counter from './counter'
import Form from './form'
import ClientForm from './client-form'
import dec, { inc } from './actions'
import dec, { inc, slowInc } from './actions'
import { log } from './actions-2'
export default function Page() {
......@@ -12,6 +12,7 @@ export default function Page() {
<Counter
inc={inc}
dec={dec}
slowInc={slowInc}
double={async (x) => {
'use server'
return x * two.value
......
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