Unverified Commit 85abc48c authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

suspend in render, not in reducers (#56497)

This removes our current convention of throwing promises in reducers in
favor of returning promises that can be consumed by `use` instead. This
will help unblock some future improvements (batching, PPR)

Reducers that would typically throw a promise now return their promise.
This gets maintained by a mutable queue (initialized in hydrate) to
ensure actions are processed in-order. The queue is also responsible for
mutating state and passing it as an input to subsequent actions.

This PR does not modify reducer behavior to keep changes minimal, but
there's more cleanup that we can do in a follow-up PR to remove things
that previously assumed reducers would be replayed.

(I recommend reviewing with whitespace turned off)

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent be618048
...@@ -12,6 +12,10 @@ import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context.shar ...@@ -12,6 +12,10 @@ import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context.shar
import onRecoverableError from './on-recoverable-error' import onRecoverableError from './on-recoverable-error'
import { callServer } from './app-call-server' import { callServer } from './app-call-server'
import { isNextRouterError } from './components/is-next-router-error' import { isNextRouterError } from './components/is-next-router-error'
import {
ActionQueueContext,
createMutableActionQueue,
} from '../shared/lib/router/action-queue'
// Since React doesn't call onerror for errors caught in error boundaries. // Since React doesn't call onerror for errors caught in error boundaries.
const origConsoleError = window.console.error const origConsoleError = window.console.error
...@@ -222,6 +226,8 @@ export function hydrate() { ...@@ -222,6 +226,8 @@ export function hydrate() {
} }
} }
const actionQueue = createMutableActionQueue()
const reactEl = ( const reactEl = (
<StrictModeIfEnabled> <StrictModeIfEnabled>
<HeadManagerContext.Provider <HeadManagerContext.Provider
...@@ -229,9 +235,11 @@ export function hydrate() { ...@@ -229,9 +235,11 @@ export function hydrate() {
appDir: true, appDir: true,
}} }}
> >
<ActionQueueContext.Provider value={actionQueue}>
<Root> <Root>
<RSCComponent /> <RSCComponent />
</Root> </Root>
</ActionQueueContext.Provider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</StrictModeIfEnabled> </StrictModeIfEnabled>
) )
......
...@@ -24,7 +24,6 @@ import type { ...@@ -24,7 +24,6 @@ import type {
FlightData, FlightData,
} from '../../server/app-render/types' } from '../../server/app-render/types'
import type { ErrorComponent } from './error-boundary' import type { ErrorComponent } from './error-boundary'
import { reducer } from './router-reducer/router-reducer'
import { import {
ACTION_FAST_REFRESH, ACTION_FAST_REFRESH,
ACTION_NAVIGATE, ACTION_NAVIGATE,
...@@ -36,7 +35,6 @@ import { ...@@ -36,7 +35,6 @@ import {
PrefetchKind, PrefetchKind,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import type { import type {
Mutable,
ReducerActions, ReducerActions,
RouterChangeByServerResponse, RouterChangeByServerResponse,
RouterNavigate, RouterNavigate,
...@@ -47,7 +45,10 @@ import { ...@@ -47,7 +45,10 @@ import {
SearchParamsContext, SearchParamsContext,
PathnameContext, PathnameContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import {
useReducerWithReduxDevtools,
useUnwrapState,
} from './use-reducer-with-devtools'
import { ErrorBoundary } from './error-boundary' import { ErrorBoundary } from './error-boundary'
import { createInitialRouterState } from './router-reducer/create-initial-router-state' import { createInitialRouterState } from './router-reducer/create-initial-router-state'
import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state' import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state'
...@@ -73,9 +74,9 @@ export function getServerActionDispatcher() { ...@@ -73,9 +74,9 @@ export function getServerActionDispatcher() {
return globalServerActionDispatcher return globalServerActionDispatcher
} }
let globalMutable: Mutable['globalMutable'] = { const globalMutable: {
refresh: () => {}, // noop until the router is initialized pendingMpaPath?: string
} } = {}
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)
...@@ -131,7 +132,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) { ...@@ -131,7 +132,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) {
return null return null
} }
const createEmptyCacheNode = () => ({ export const createEmptyCacheNode = () => ({
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
subTreeData: null, subTreeData: null,
...@@ -145,7 +146,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) { ...@@ -145,7 +146,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
dispatch({ dispatch({
...actionPayload, ...actionPayload,
type: ACTION_SERVER_ACTION, type: ACTION_SERVER_ACTION,
mutable: { globalMutable }, mutable: {},
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
}) })
}) })
...@@ -174,7 +175,7 @@ function useChangeByServerResponse( ...@@ -174,7 +175,7 @@ function useChangeByServerResponse(
previousTree, previousTree,
overrideCanonicalUrl, overrideCanonicalUrl,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
}) })
}) })
}, },
...@@ -186,7 +187,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -186,7 +187,6 @@ 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)
globalMutable.pendingNavigatePath = createHrefFromUrl(url)
return dispatch({ return dispatch({
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
...@@ -197,7 +197,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -197,7 +197,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
shouldScroll: shouldScroll ?? true, shouldScroll: shouldScroll ?? true,
navigateType, navigateType,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
}) })
}, },
[dispatch] [dispatch]
...@@ -229,25 +229,15 @@ function Router({ ...@@ -229,25 +229,15 @@ function Router({
}), }),
[buildId, children, initialCanonicalUrl, initialTree, initialHead] [buildId, children, initialCanonicalUrl, initialTree, initialHead]
) )
const [ const [reducerState, dispatch, sync] =
{ useReducerWithReduxDevtools(initialState)
tree,
cache,
prefetchCache,
pushRef,
focusAndScrollRef,
canonicalUrl,
nextUrl,
},
dispatch,
sync,
] = useReducerWithReduxDevtools(reducer, initialState)
useEffect(() => { useEffect(() => {
// Ensure initialParallelRoutes is cleaned up from memory once it's used. // Ensure initialParallelRoutes is cleaned up from memory once it's used.
initialParallelRoutes = null! initialParallelRoutes = null!
}, []) }, [])
const { canonicalUrl } = useUnwrapState(reducerState)
// Add memoized pathname/query for useSearchParams and usePathname. // Add memoized pathname/query for useSearchParams and usePathname.
const { searchParams, pathname } = useMemo(() => { const { searchParams, pathname } = useMemo(() => {
const url = new URL( const url = new URL(
...@@ -322,7 +312,7 @@ function Router({ ...@@ -322,7 +312,7 @@ function Router({
dispatch({ dispatch({
type: ACTION_REFRESH, type: ACTION_REFRESH,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
...@@ -338,7 +328,7 @@ function Router({ ...@@ -338,7 +328,7 @@ function Router({
dispatch({ dispatch({
type: ACTION_FAST_REFRESH, type: ACTION_FAST_REFRESH,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
...@@ -356,11 +346,10 @@ function Router({ ...@@ -356,11 +346,10 @@ function Router({
} }
}, [appRouter]) }, [appRouter])
useEffect(() => {
globalMutable.refresh = appRouter.refresh
}, [appRouter.refresh])
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { cache, prefetchCache, tree } = useUnwrapState(reducerState)
// 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
useEffect(() => { useEffect(() => {
...@@ -408,6 +397,7 @@ function Router({ ...@@ -408,6 +397,7 @@ function Router({
// probably safe because we know this is a singleton component and it's never // probably safe because we know this is a singleton component and it's never
// in <Offscreen>. At least I hope so. (It will run twice in dev strict mode, // in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,
// but that's... fine?) // but that's... fine?)
const { pushRef } = useUnwrapState(reducerState)
if (pushRef.mpaNavigation) { if (pushRef.mpaNavigation) {
// if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL // if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL
if (globalMutable.pendingMpaPath !== canonicalUrl) { if (globalMutable.pendingMpaPath !== canonicalUrl) {
...@@ -466,6 +456,9 @@ function Router({ ...@@ -466,6 +456,9 @@ function Router({
} }
}, [onPopState]) }, [onPopState])
const { cache, tree, nextUrl, focusAndScrollRef } =
useUnwrapState(reducerState)
const head = useMemo(() => { const head = useMemo(() => {
return findHeadInCache(cache, tree[1]) return findHeadInCache(cache, tree[1])
}, [cache, tree]) }, [cache, tree])
...@@ -513,7 +506,7 @@ function Router({ ...@@ -513,7 +506,7 @@ function Router({
<LayoutRouterContext.Provider <LayoutRouterContext.Provider
value={{ value={{
childNodes: cache.parallelRoutes, childNodes: cache.parallelRoutes,
tree: tree, tree,
// Root node always has `url` // Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl, url: canonicalUrl,
......
import { readRecordValue } from './read-record-value'
import { createRecordFromThenable } from './create-record-from-thenable'
describe('readRecordValue', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable
expect(readRecordValue(record)).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('failed')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable.catch(() => {})
expect(() => readRecordValue(record)).toThrow()
const result: any = (() => {
try {
return readRecordValue(record)
} catch (err) {
return err
}
})()
expect(result.status).toBe('rejected')
expect(result.reason).toBe('failed')
})
})
import type { ThenableRecord } from './router-reducer-types'
/**
* Read record value or throw Promise if it's not resolved yet.
*/
export function readRecordValue<T>(thenable: ThenableRecord<T>): T {
if (thenable.status === 'fulfilled') {
return thenable.value
} else {
throw thenable
}
}
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
...@@ -40,8 +39,9 @@ function fastRefreshReducerImpl( ...@@ -40,8 +39,9 @@ function fastRefreshReducerImpl(
) )
) )
} }
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
return cache.data.then(
([flightData, canonicalUrlOverride]) => {
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
return handleExternalUrl( return handleExternalUrl(
...@@ -80,7 +80,12 @@ function fastRefreshReducerImpl( ...@@ -80,7 +80,12 @@ function fastRefreshReducerImpl(
} }
if (isNavigatingToNewRootLayout(currentTree, newTree)) { if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush) return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
} }
const canonicalUrlOverrideHref = canonicalUrlOverride const canonicalUrlOverrideHref = canonicalUrlOverride
...@@ -104,6 +109,9 @@ function fastRefreshReducerImpl( ...@@ -104,6 +109,9 @@ function fastRefreshReducerImpl(
currentTree = newTree currentTree = newTree
} }
return handleMutable(state, mutable) return handleMutable(state, mutable)
},
() => state
)
} }
function fastRefreshReducerNoop( function fastRefreshReducerNoop(
......
...@@ -102,10 +102,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [ ...@@ -102,10 +102,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true, true,
] ]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> { async function runPromiseThrowChain(fn: any): Promise<any> {
try { try {
return await fn() return await fn()
...@@ -194,7 +190,7 @@ describe('navigateReducer', () => { ...@@ -194,7 +190,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
...@@ -438,7 +434,7 @@ describe('navigateReducer', () => { ...@@ -438,7 +434,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -633,7 +629,7 @@ describe('navigateReducer', () => { ...@@ -633,7 +629,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -792,7 +788,7 @@ describe('navigateReducer', () => { ...@@ -792,7 +788,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -948,7 +944,7 @@ describe('navigateReducer', () => { ...@@ -948,7 +944,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1147,7 +1143,7 @@ describe('navigateReducer', () => { ...@@ -1147,7 +1143,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1317,7 +1313,7 @@ describe('navigateReducer', () => { ...@@ -1317,7 +1313,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1630,7 +1626,7 @@ describe('navigateReducer', () => { ...@@ -1630,7 +1626,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1841,7 +1837,6 @@ describe('navigateReducer', () => { ...@@ -1841,7 +1837,6 @@ describe('navigateReducer', () => {
hashFragment: '#hash', hashFragment: '#hash',
pendingPush: true, pendingPush: true,
shouldScroll: true, shouldScroll: true,
globalMutable,
}, },
} }
...@@ -1984,7 +1979,7 @@ describe('navigateReducer', () => { ...@@ -1984,7 +1979,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
......
...@@ -7,7 +7,6 @@ import type { ...@@ -7,7 +7,6 @@ import type {
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import type { FetchServerResponseResult } from '../fetch-server-response' import type { FetchServerResponseResult } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath' import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property' import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
...@@ -248,11 +247,10 @@ export function navigateReducer( ...@@ -248,11 +247,10 @@ export function navigateReducer(
prefetchQueue.bump(data!) prefetchQueue.bump(data!)
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves. return data!.then(
const [flightData, canonicalUrlOverride, postponed] = readRecordValue(data!) ([flightData, canonicalUrlOverride, postponed]) => {
// we only want to mark this once // we only want to mark this once
if (!prefetchValues.lastUsedTime) { if (prefetchValues && !prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above // important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now() prefetchValues.lastUsedTime = Date.now()
} }
...@@ -300,21 +298,20 @@ export function navigateReducer( ...@@ -300,21 +298,20 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, href, pendingPush) return handleExternalUrl(state, mutable, href, pendingPush)
} }
// TODO-APP: If the prefetch was postponed, we don't want to apply it let applied = applyFlightData(
// until we land router changes to handle the postponed case.
let applied = postponed
? false
: applyFlightData(
currentCache, currentCache,
cache, cache,
flightDataPath, flightDataPath,
prefetchValues.kind === 'auto' && prefetchValues?.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
) )
if ( if (
!applied && (!applied &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale) ||
// TODO-APP: If the prefetch was postponed, we don't want to apply it
// until we land router changes to handle the postponed case.
postponed
) { ) {
applied = addRefetchToLeafSegments( applied = addRefetchToLeafSegments(
cache, cache,
...@@ -383,4 +380,7 @@ export function navigateReducer( ...@@ -383,4 +380,7 @@ export function navigateReducer(
mutable.shouldScroll = shouldScroll mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable) return handleMutable(state, mutable)
},
() => state
)
} }
import type { ReducerState } from '../router-reducer-types' import type { AppRouterState } from '../router-reducer-types'
import { import {
PrefetchCacheEntryStatus, PrefetchCacheEntryStatus,
getPrefetchEntryCacheStatus, getPrefetchEntryCacheStatus,
} from '../get-prefetch-cache-entry-status' } from '../get-prefetch-cache-entry-status'
export function prunePrefetchCache( export function prunePrefetchCache(
prefetchCache: ReducerState['prefetchCache'] prefetchCache: AppRouterState['prefetchCache']
) { ) {
for (const [href, prefetchCacheEntry] of prefetchCache) { for (const [href, prefetchCacheEntry] of prefetchCache) {
if ( if (
......
...@@ -64,10 +64,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [ ...@@ -64,10 +64,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true, true,
] ]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> { async function runPromiseThrowChain(fn: any): Promise<any> {
try { try {
return await fn() return await fn()
...@@ -141,7 +137,7 @@ describe('refreshReducer', () => { ...@@ -141,7 +137,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -302,7 +298,7 @@ describe('refreshReducer', () => { ...@@ -302,7 +298,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -489,7 +485,7 @@ describe('refreshReducer', () => { ...@@ -489,7 +485,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -725,7 +721,7 @@ describe('refreshReducer', () => { ...@@ -725,7 +721,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
......
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
...@@ -42,8 +41,9 @@ export function refreshReducer( ...@@ -42,8 +41,9 @@ export function refreshReducer(
) )
) )
} }
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
return cache.data.then(
([flightData, canonicalUrlOverride]) => {
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
return handleExternalUrl( return handleExternalUrl(
...@@ -79,7 +79,12 @@ export function refreshReducer( ...@@ -79,7 +79,12 @@ export function refreshReducer(
} }
if (isNavigatingToNewRootLayout(currentTree, newTree)) { if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush) return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
} }
const canonicalUrlOverrideHref = canonicalUrlOverride const canonicalUrlOverrideHref = canonicalUrlOverride
...@@ -116,4 +121,7 @@ export function refreshReducer( ...@@ -116,4 +121,7 @@ export function refreshReducer(
} }
return handleMutable(state, mutable) return handleMutable(state, mutable)
},
() => state
)
} }
...@@ -11,7 +11,6 @@ import { ...@@ -11,7 +11,6 @@ import {
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers' } from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client' // import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -159,48 +158,14 @@ export function serverActionReducer( ...@@ -159,48 +158,14 @@ export function serverActionReducer(
return handleMutable(state, mutable) return handleMutable(state, mutable)
} }
if (mutable.inFlightServerAction) {
// unblock if a navigation event comes through
// while we've suspended on an action
if (
mutable.inFlightServerAction.status !== 'fulfilled' &&
mutable.globalMutable.pendingNavigatePath &&
mutable.globalMutable.pendingNavigatePath !== href
) {
mutable.inFlightServerAction.then(
() => {
if (mutable.actionResultResolved) return
// if the server action resolves after a navigation took place,
// reset ServerActionMutable values & trigger a refresh so that any stale data gets updated
mutable.inFlightServerAction = null
mutable.globalMutable.pendingNavigatePath = undefined
mutable.globalMutable.refresh()
mutable.actionResultResolved = true
},
() => {}
)
return state
}
} else {
mutable.inFlightServerAction = createRecordFromThenable( mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action) fetchServerAction(state, action)
) )
}
// TODO-APP: Make try/catch wrap only readRecordValue so that other errors bubble up through the reducer instead.
try {
// suspends until the server action is resolved. // suspends until the server action is resolved.
const {
actionResult,
actionFlightData: flightData,
redirectLocation,
// revalidatedParts,
} = readRecordValue(
mutable.inFlightServerAction!
) as Awaited<FetchServerActionResult>
return mutable.inFlightServerAction.then(
({ actionResult, actionFlightData: flightData, redirectLocation }) => {
// Make sure the redirection is a push instead of a replace. // Make sure the redirection is a push instead of a replace.
// Issue: https://github.com/vercel/next.js/issues/53911 // Issue: https://github.com/vercel/next.js/issues/53911
if (redirectLocation) { if (redirectLocation) {
...@@ -306,7 +271,8 @@ export function serverActionReducer( ...@@ -306,7 +271,8 @@ export function serverActionReducer(
mutable.actionResultResolved = true mutable.actionResultResolved = true
} }
return handleMutable(state, mutable) return handleMutable(state, mutable)
} catch (e: any) { },
(e: any) => {
if (e.status === 'rejected') { if (e.status === 'rejected') {
if (!mutable.actionResultResolved) { if (!mutable.actionResultResolved) {
reject(e.reason) reject(e.reason)
...@@ -319,4 +285,5 @@ export function serverActionReducer( ...@@ -319,4 +285,5 @@ export function serverActionReducer(
throw e throw e
} }
)
} }
...@@ -13,10 +13,6 @@ import { navigateReducer } from './navigate-reducer' ...@@ -13,10 +13,6 @@ import { navigateReducer } from './navigate-reducer'
import { serverPatchReducer } from './server-patch-reducer' import { serverPatchReducer } from './server-patch-reducer'
const buildId = 'development' const buildId = 'development'
const globalMutable = {
refresh: () => {},
}
jest.mock('../fetch-server-response', () => { jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [ const flightData: FlightData = [
[ [
...@@ -181,7 +177,7 @@ describe('serverPatchReducer', () => { ...@@ -181,7 +177,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
...@@ -372,7 +368,7 @@ describe('serverPatchReducer', () => { ...@@ -372,7 +368,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => serverPatchReducer(state, action)) await runPromiseThrowChain(() => serverPatchReducer(state, action))
...@@ -511,7 +507,7 @@ describe('serverPatchReducer', () => { ...@@ -511,7 +507,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const state = createInitialRouterState({ const state = createInitialRouterState({
...@@ -553,7 +549,7 @@ describe('serverPatchReducer', () => { ...@@ -553,7 +549,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
......
...@@ -4,11 +4,6 @@ import type { ...@@ -4,11 +4,6 @@ import type {
FlightData, FlightData,
FlightSegmentPath, FlightSegmentPath,
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import type {
FulfilledThenable,
PendingThenable,
RejectedThenable,
} from 'react'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
export const ACTION_REFRESH = 'refresh' export const ACTION_REFRESH = 'refresh'
...@@ -43,11 +38,6 @@ export interface Mutable { ...@@ -43,11 +38,6 @@ export interface Mutable {
prefetchCache?: AppRouterState['prefetchCache'] prefetchCache?: AppRouterState['prefetchCache']
hashFragment?: string hashFragment?: string
shouldScroll?: boolean shouldScroll?: boolean
globalMutable: {
pendingNavigatePath?: string
pendingMpaPath?: string
refresh: () => void
}
} }
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
...@@ -273,7 +263,7 @@ export type AppRouterState = { ...@@ -273,7 +263,7 @@ export type AppRouterState = {
} }
export type ReadonlyReducerState = Readonly<AppRouterState> export type ReadonlyReducerState = Readonly<AppRouterState>
export type ReducerState = AppRouterState export type ReducerState = Promise<AppRouterState> | AppRouterState
export type ReducerActions = Readonly< export type ReducerActions = Readonly<
| RefreshAction | RefreshAction
| NavigateAction | NavigateAction
...@@ -284,7 +274,36 @@ export type ReducerActions = Readonly< ...@@ -284,7 +274,36 @@ export type ReducerActions = Readonly<
| ServerActionAction | ServerActionAction
> >
export interface PendingThenable<T> extends ThenableImpl<T> {
status: 'pending'
}
export interface FulfilledThenable<T> extends ThenableImpl<T> {
status: 'fulfilled'
value: T
}
export interface RejectedThenable<T> extends ThenableImpl<T> {
status: 'rejected'
reason: unknown
}
interface ThenableImpl<T> {
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>
}
export type ThenableRecord<T> = export type ThenableRecord<T> =
| PendingThenable<T> | PendingThenable<T>
| RejectedThenable<T> | RejectedThenable<T>
| FulfilledThenable<T> | FulfilledThenable<T>
export function isThenable(value: any): value is Promise<AppRouterState> {
return (
value &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function'
)
}
import type { reducer } from './router-reducer/router-reducer' import type { Dispatch } from 'react'
import type { import React, { use, useContext } from 'react'
ReducerState, import { useRef, useEffect, useCallback } from 'react'
ReducerAction, import {
MutableRefObject, isThenable,
Dispatch, type AppRouterState,
} from 'react' type ReducerActions,
import { useRef, useReducer, useEffect, useCallback } from 'react' type ReducerState,
} from './router-reducer/router-reducer-types'
import { ActionQueueContext } from '../../shared/lib/router/action-queue'
function normalizeRouterState(val: any): any { function normalizeRouterState(val: any): any {
if (val instanceof Map) { if (val instanceof Map) {
...@@ -61,70 +63,44 @@ function normalizeRouterState(val: any): any { ...@@ -61,70 +63,44 @@ function normalizeRouterState(val: any): any {
return val return val
} }
// Log router state when actions are triggered.
// function logReducer(fn: typeof reducer) {
// return (
// state: ReducerState<typeof reducer>,
// action: ReducerAction<typeof reducer>
// ) => {
// console.groupCollapsed(action.type)
// console.log('action', action)
// console.log('old', state)
// const res = fn(state, action)
// console.log('new', res)
// console.groupEnd()
// return res
// }
// }
declare global { declare global {
interface Window { interface Window {
__REDUX_DEVTOOLS_EXTENSION__: any __REDUX_DEVTOOLS_EXTENSION__: any
} }
} }
interface ReduxDevToolsInstance { export interface ReduxDevToolsInstance {
send(action: any, state: any): void send(action: any, state: any): void
init(initialState: any): void init(initialState: any): void
} }
function devToolReducer( export function useUnwrapState(state: ReducerState) {
fn: typeof reducer, // reducer actions can be async, so sometimes we need to suspend until the state is resolved
ref: MutableRefObject<ReduxDevToolsInstance | undefined> if (isThenable(state)) {
) { const result = use(state)
return ( return result
state: ReducerState<typeof reducer>,
action: ReducerAction<typeof reducer>
) => {
const res = fn(state, action)
if (ref.current) {
ref.current.send(action, normalizeRouterState(res))
}
return res
} }
return state
} }
function useReducerWithReduxDevtoolsNoop( function useReducerWithReduxDevtoolsNoop(
fn: typeof reducer, initialState: AppRouterState
initialState: ReturnType<typeof reducer> ): [ReducerState, Dispatch<ReducerActions>, () => void] {
): [ return [initialState, () => {}, () => {}]
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>,
() => void
] {
const [state, dispatch] = useReducer(fn, initialState)
return [state, dispatch, () => {}]
} }
function useReducerWithReduxDevtoolsImpl( function useReducerWithReduxDevtoolsImpl(
fn: typeof reducer, initialState: AppRouterState
initialState: ReturnType<typeof reducer> ): [ReducerState, Dispatch<ReducerActions>, () => void] {
): [ const [state, setState] = React.useState<ReducerState>(initialState)
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>, const actionQueue = useContext(ActionQueueContext)
() => void
] { if (!actionQueue) {
throw new Error('Invariant: Missing ActionQueueContext')
}
const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>() const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>()
const enabledRef = useRef<boolean>() const enabledRef = useRef<boolean>()
...@@ -149,16 +125,28 @@ function useReducerWithReduxDevtoolsImpl( ...@@ -149,16 +125,28 @@ function useReducerWithReduxDevtoolsImpl(
) )
if (devtoolsConnectionRef.current) { if (devtoolsConnectionRef.current) {
devtoolsConnectionRef.current.init(normalizeRouterState(initialState)) devtoolsConnectionRef.current.init(normalizeRouterState(initialState))
if (actionQueue) {
actionQueue.devToolsInstance = devtoolsConnectionRef.current
}
} }
return () => { return () => {
devtoolsConnectionRef.current = undefined devtoolsConnectionRef.current = undefined
} }
}, [initialState]) }, [initialState, actionQueue])
const [state, dispatch] = useReducer( const dispatch = useCallback(
devToolReducer(/* logReducer( */ fn /*)*/, devtoolsConnectionRef), (action: ReducerActions) => {
initialState if (!actionQueue.state) {
// we lazy initialize the mutable action queue state since the data needed
// to generate the state is not available when the actionQueue context is created
actionQueue.state = initialState
}
actionQueue.dispatch(action, setState)
},
[actionQueue, initialState]
) )
const sync = useCallback(() => { const sync = useCallback(() => {
...@@ -169,6 +157,7 @@ function useReducerWithReduxDevtoolsImpl( ...@@ -169,6 +157,7 @@ function useReducerWithReduxDevtoolsImpl(
) )
} }
}, [state]) }, [state])
return [state, dispatch, sync] return [state, dispatch, sync]
} }
......
import {
isThenable,
type AppRouterState,
type ReducerActions,
type ReducerState,
ACTION_REFRESH,
ACTION_SERVER_ACTION,
ACTION_NAVIGATE,
} from '../../../client/components/router-reducer/router-reducer-types'
import type { ReduxDevToolsInstance } from '../../../client/components/use-reducer-with-devtools'
import { reducer } from '../../../client/components/router-reducer/router-reducer'
import React, { startTransition } from 'react'
import { createEmptyCacheNode } from '../../../client/components/app-router'
export type DispatchStatePromise = React.Dispatch<ReducerState>
export type AppRouterActionQueue = {
state: AppRouterState | null
devToolsInstance?: ReduxDevToolsInstance
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void
action: (state: AppRouterState, action: ReducerActions) => ReducerState
pending: ActionQueueNode | null
needsRefresh?: boolean
last: ActionQueueNode | null
}
export type ActionQueueNode = {
payload: ReducerActions
next: ActionQueueNode | null
resolve: (value: PromiseLike<AppRouterState> | AppRouterState) => void
reject: (err: Error) => void
discarded?: boolean
}
export const ActionQueueContext =
React.createContext<AppRouterActionQueue | null>(null)
function runRemainingActions(
actionQueue: AppRouterActionQueue,
setState: DispatchStatePromise
) {
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,
})
}
}
}
async function runAction({
actionQueue,
action,
setState,
}: {
actionQueue: AppRouterActionQueue
action: ActionQueueNode
setState: DispatchStatePromise
}) {
const prevState = actionQueue.state
if (!prevState) {
// This shouldn't happen as the state is initialized in the dispatcher if it's not set
throw new Error('Invariant: Router state not initialized')
}
actionQueue.pending = action
actionQueue.last = action
const payload = action.payload
const actionResult = actionQueue.action(prevState, payload)
function handleResult(nextState: AppRouterState) {
// if we discarded this action, the state should also be discarded
if (action.discarded) {
// if a refresh is needed, we only want to trigger it once the action queue is empty
if (actionQueue.needsRefresh && actionQueue.pending === null) {
actionQueue.needsRefresh = false
actionQueue.dispatch(
{
type: ACTION_REFRESH,
cache: createEmptyCacheNode(),
mutable: {},
origin: window.location.origin,
},
setState
)
}
return
}
actionQueue.state = nextState
if (actionQueue.devToolsInstance) {
actionQueue.devToolsInstance.send(payload, nextState)
}
runRemainingActions(actionQueue, setState)
action.resolve(nextState)
}
// if the action is a promise, set up a callback to resolve it
if (isThenable(actionResult)) {
actionResult.then(handleResult, (err) => {
runRemainingActions(actionQueue, setState)
action.reject(err)
})
} else {
handleResult(actionResult)
}
}
function dispatchAction(
actionQueue: AppRouterActionQueue,
payload: ReducerActions,
setState: DispatchStatePromise
) {
let resolvers: {
resolve: (value: AppRouterState | PromiseLike<AppRouterState>) => void
reject: (reason: any) => void
}
// Create the promise and assign the resolvers to the object.
const deferredPromise = new Promise<AppRouterState>((resolve, reject) => {
resolvers = { resolve, reject }
})
const newAction: ActionQueueNode = {
payload,
next: null,
resolve: resolvers!.resolve,
reject: resolvers!.reject,
}
startTransition(() => {
// we immediately notify React of the pending promise -- the resolver is attached to the action node
// and will be called when the associated action promise resolves
setState(deferredPromise)
})
// Check if the queue is empty
if (actionQueue.pending === null) {
// The queue is empty, so add the action and start it immediately
runAction({
actionQueue,
action: newAction,
setState,
})
} else if (payload.type === ACTION_NAVIGATE) {
// Navigations take priority over any pending actions.
// Mark the pending action as discarded (so the state is never applied) and start the navigation action immediately.
actionQueue.pending.discarded = true
// 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,
setState,
})
} else {
// The queue is not empty, so add the action to the end of the queue
// It will be started by finishRunningAction after the previous action finishes
if (actionQueue.last !== null) {
actionQueue.last.next = newAction
}
actionQueue.last = newAction
}
}
export function createMutableActionQueue(): AppRouterActionQueue {
const actionQueue: AppRouterActionQueue = {
state: null,
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) =>
dispatchAction(actionQueue, payload, setState),
action: async (state: AppRouterState, action: ReducerActions) => {
if (state === null) {
throw new Error('Invariant: Router state not initialized')
}
const result = reducer(state, action)
return result
},
pending: null,
last: null,
}
return actionQueue
}
...@@ -288,6 +288,27 @@ createNextDescribe( ...@@ -288,6 +288,27 @@ createNextDescribe(
await check(() => browser.url(), `${next.url}/client`, true, 2) await check(() => browser.url(), `${next.url}/client`, 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 check(async () => {
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
return newRandomNumber === initialRandomNumber ? 'fail' : 'success'
}, 'success')
})
it('should support next/dynamic with ssr: false', async () => { it('should support next/dynamic with ssr: false', async () => {
const browser = await next.browser('/dynamic-csr') const browser = await next.browser('/dynamic-csr')
......
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