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