Unverified Commit dd76599c authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Scaffolding for concurrentRouterQueue flag (#97413)

Sets up the scaffolding for a rewrite of the client router's queue.

I've named the new module concurrent-router-queue.ts and the existing
module sequential-router-queue.ts, since the main goal of the new one is
to improve the router's integration with React's concurrent rendering
model. The experimental flag is likewise named `concurrentRouterQueue`.

There's no implementation yet; all router operations throw an error when
the flag is enabled.

The main entry point into the router is navigator.ts. The flag swaps
between implementations at the module level to ensure the inactive code
is eliminated from the final bundle.
parent 5a3a3d19
......@@ -165,11 +165,13 @@ pub async fn get_client_resolve_options_context(
|| *next_config
.enable_expose_testing_api_in_production_build()
.await?;
let concurrent_router_queue = *next_config.enable_concurrent_router_queue().await?;
let next_client_resolved_map = get_next_client_resolved_map(
project_path.clone(),
project_path.clone(),
*mode.await?,
expose_testing_api,
concurrent_router_queue,
)
.await?
.to_resolved()
......
......@@ -1378,6 +1378,9 @@ pub struct ExperimentalConfig {
swc_trace_profiling: Option<bool>,
transition_indicator: Option<bool>,
gesture_transition: Option<bool>,
/// Forks the client router's entry-point modules to the experimental
/// concurrent router queue implementation via the import map.
concurrent_router_queue: Option<bool>,
// `rename_all = "camelCase"` would lowercase the acronym to `blockingSsr`;
// rename explicitly so it deserializes from the public `blockingSSR` field.
#[serde(rename = "blockingSSR")]
......@@ -2428,6 +2431,11 @@ impl NextConfig {
)
}
#[turbo_tasks::function]
pub fn enable_concurrent_router_queue(&self) -> Vc<bool> {
Vc::cell(self.experimental.concurrent_router_queue.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn enable_cache_components(&self) -> Vc<bool> {
Vc::cell(self.cache_components.unwrap_or(false))
......
......@@ -578,6 +578,7 @@ pub async fn get_next_client_resolved_map(
root: FileSystemPath,
_mode: NextMode,
expose_testing_api: bool,
concurrent_router_queue: bool,
) -> Result<Vc<ResolvedMap>> {
// In the browser bundle, swap every module that has a `.browser` sibling (see
// BROWSER_VARIANT_MODULES, generated from the filesystem) for that sibling. The default
......@@ -613,7 +614,7 @@ pub async fn get_next_client_resolved_map(
// alias in `create-compiler-aliases.ts`.
if !expose_testing_api {
glob_mappings.push((
fs_root,
fs_root.clone(),
Glob::new(
rcstr!("**/next/dist/client/components/segment-cache/navigation-testing-lock.js"),
GlobOptions::default(),
......@@ -629,6 +630,40 @@ pub async fn get_next_client_resolved_map(
));
}
// When `experimental.concurrentRouterQueue` is enabled, resolve the
// router's forked entry-point modules (the navigator interface and the
// callServer action door) to the concurrent implementations. Neither the
// interface module nor the sequential implementation is bundled at all.
// This mirrors the webpack alias in `create-compiler-aliases.ts`.
if concurrent_router_queue {
glob_mappings.push((
fs_root.clone(),
Glob::new(
rcstr!("**/next/dist/client/components/navigator.js"),
GlobOptions::default(),
)
.to_resolved()
.await?,
request_to_import_mapping(
context_path.clone(),
rcstr!("next/dist/client/components/concurrent-router-queue"),
),
));
glob_mappings.push((
fs_root,
Glob::new(
rcstr!("**/next/dist/client/app-call-server.js"),
GlobOptions::default(),
)
.to_resolved()
.await?,
request_to_import_mapping(
context_path.clone(),
rcstr!("next/dist/client/concurrent-call-server"),
),
));
}
Ok(ResolvedMap {
by_glob: glob_mappings,
}
......
......@@ -1473,5 +1473,6 @@
"1472": "Cannot convert a server response with no transport data and no base tree.",
"1473": "Invariant: image cache entry \"%s\" is empty",
"1474": "Invariant: cannot write an empty buffer to the image cache",
"1475": "Invariant: no direct app page entry found for %s"
"1475": "Invariant: no direct app page entry found for %s",
"1476": "Not implemented: this behavior is not yet supported when `experimental.concurrentRouterQueue` is enabled."
}
......@@ -64,6 +64,8 @@ export function createWebpackAliases({
const isInstantNavigationTestingEnabled =
config.cacheComponents === true &&
(dev || config.experimental.exposeTestingApiInProductionBuild === true)
const isConcurrentRouterQueueEnabled =
config.experimental.concurrentRouterQueue === true
// tell webpack where to look for _app and _document
// using aliases to allow falling back to the default
......@@ -199,6 +201,24 @@ export function createWebpackAliases({
'next/dist/client/components/segment-cache/navigation-testing-lock.disabled',
}
: {}),
// When `experimental.concurrentRouterQueue` is enabled, resolve the
// router's forked entry-point modules (the navigator interface and
// the callServer action door) to the concurrent implementations.
// Neither the interface module nor the sequential implementation is
// bundled at all. Same resolved-path matching as the swaps above.
...(isConcurrentRouterQueueEnabled
? {
[path.join(
NEXT_PROJECT_ROOT_DIST,
'client/components/navigator.js'
) + '$']: 'next/dist/client/components/concurrent-router-queue',
[path.join(
NEXT_PROJECT_ROOT_DIST,
'client/app-call-server.js'
) + '$']: 'next/dist/client/concurrent-call-server',
}
: {}),
}
: {}),
......
......@@ -384,6 +384,8 @@ export function getDefineEnv({
config.experimental.gestureTransition ?? false,
'process.env.__NEXT_OPTIMISTIC_ROUTING':
config.experimental.optimisticRouting ?? false,
'process.env.__NEXT_CONCURRENT_ROUTER_QUEUE':
config.experimental.concurrentRouterQueue ?? false,
'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':
config.experimental.instrumentationClientRouterTransitionEvents ?? false,
'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,
......
import { startTransition } from 'react'
import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'
import { dispatchAppRouterAction } from './components/use-action-queue'
// The entry point for Server Actions: the "action door" into the router.
// Server Actions are deliberately not a navigator operation (navigator.ts) —
// the action queue is semantically separate from the router state queue —
// but this module forks the same way: by default it re-exports the
// sequential implementation, and when `experimental.concurrentRouterQueue`
// is enabled, imports of this module resolve to './concurrent-call-server'
// instead at the bundler level (see create-compiler-aliases.ts and
// next_import_map.rs). Both implementations expose exactly this surface.
/**
* Invoke a Server Action. The returned promise resolves with the action's
......@@ -8,16 +13,4 @@ import { dispatchAppRouterAction } from './components/use-action-queue'
* revalidation side effects of the action are handled by the router; they are
* not observable through the returned promise.
*/
export async function callServer(actionId: string, actionArgs: any[]) {
return new Promise((resolve, reject) => {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_SERVER_ACTION,
actionId,
actionArgs,
resolve,
reject,
})
})
})
}
export { callServer } from './sequential-call-server'
// The concurrent-router-queue implementation of the navigator interface
// (navigator.ts). Callers must never import this module directly; when
// `experimental.concurrentRouterQueue` is enabled, imports of './navigator'
// resolve here at the bundler level (see create-compiler-aliases.ts and
// next_import_map.rs), and neither navigator.ts nor the sequential
// implementation is bundled at all.
//
// This module must remain free of side effects at module scope: in addition
// to the browser bundle, the navigator module graph is also compiled into
// the pre-compiled app-page runtime bundles (via app-render.tsx), where the
// bundler alias cannot reach. Only the browser copy's operations ever run.
//
// TODO: This is currently a stub. Every operation throws so that enabling
// the flag fails loudly instead of silently running the old implementation.
import type {
AppHistoryState,
NavigateAction,
ScrollBehavior,
} from './router-reducer/router-reducer-types'
import type { NavigateOptions } from '../../shared/lib/app-router-context.shared-runtime'
import type { LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
// Keep in sync with the identical message in concurrent-call-server.ts, so
// all unimplemented behavior shares a single error (and error code).
function notImplemented(): never {
throw new Error(
'Not implemented: this behavior is not yet supported when ' +
'`experimental.concurrentRouterQueue` is enabled.'
)
}
export function navigate(
_href: string,
_navigateType: NavigateAction['navigateType'],
_scrollBehavior: ScrollBehavior,
_linkInstanceRef: LinkInstance | null,
_transitionTypes: string[] | undefined,
_prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
notImplemented()
}
export function push(_href: string, _options?: NavigateOptions): void {
notImplemented()
}
export function replace(_href: string, _options?: NavigateOptions): void {
notImplemented()
}
export function traverse(
_href: string,
_historyState: AppHistoryState | undefined
): void {
notImplemented()
}
export function restore(
_url: URL,
_historyState: AppHistoryState | undefined
): void {
notImplemented()
}
// Never implemented, on purpose. This op exists only because the sequential
// queue expresses an MPA navigation as state (`pushRef.mpaNavigation`)
// consumed by a render-phase side effect, so a bfcache-restored page must
// reset that state with an urgent update before any other render can observe
// it and re-fire the navigation — urgency as a defense. The concurrent
// machine has no such hazard to defend against, and its single
// history/location owner handles the `pageshow` event itself, feeding it in
// as an ordinary restore — so this entry point won't be called at all once
// the shared callers are ported, and it dies with the sequential queue.
export function legacyUrgentBFCacheRestore(
_url: URL,
_historyState: AppHistoryState | undefined
): void {
notImplemented()
}
export function refresh(): void {
notImplemented()
}
// Development only.
export function hmrRefresh(): void {
notImplemented()
}
// Type-only conformance check: this module must expose exactly the surface of
// the navigator interface. Fails to typecheck if a signature drifts. Compiles
// to `const _conformance = null` — no runtime effect.
const _conformance: typeof import('./navigator') =
null as unknown as typeof import('./concurrent-router-queue')
......@@ -8,215 +8,26 @@
//
// Server Actions are not a navigator operation: the action queue is
// semantically separate from the router state queue. Its entry point is
// callServer (app-call-server.ts).
// callServer (app-call-server.ts), which forks the same way.
//
// The legacy reducer action objects are an implementation detail of the
// current action queue; they are constructed here and never by callers.
//
// This is also the seam where an experimental rewrite of the router state
// machine will fork from the existing implementation, so nothing above this
// interface may depend on how the operations are processed.
import { addTransitionType, startTransition } from 'react'
import {
ACTION_HMR_REFRESH,
ACTION_NAVIGATE,
ACTION_REFRESH,
ACTION_RESTORE,
type AppHistoryState,
type AppRouterState,
type NavigateAction,
ScrollBehavior,
} from './router-reducer/router-reducer-types'
import type { NavigateOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { dispatchAppRouterAction } from './use-action-queue'
import { getCurrentAppRouterState } from './app-router-instance'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import { startRouterTransition } from './router-transition'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
function getRequiredAppRouterState(): AppRouterState {
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return state
}
export function navigate(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getRequiredAppRouterState().tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
})
}
export function push(href: string, options?: NavigateOptions): void {
navigate(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function replace(href: string, options?: NavigateOptions): void {
navigate(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function traverse(
href: string,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
startRouterTransition(
href,
'traverse',
getRequiredAppRouterState().tree,
null
)
restore(new URL(href), historyState)
})
}
/**
* Sync the router state to a history entry that was written by something
* other than a router navigation (a userland pushState/replaceState, or a
* bfcache restore). Unlike a traversal, this does not represent a transition
* between routes.
*/
export function restore(
url: URL,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
})
}
/**
* The bfcache `pageshow` restore (see the pageshow handler in app-router.tsx).
* Unlike every other navigator operation, this dispatches as a deliberately
* urgent (non-transition) update: the restored state reset must render before
* anything else can observe the stale mpaNavigation state and re-fire the MPA
* navigation the restore exists to prevent. As a transition it would be
* interruptible, and an intervening urgent render could commit against the
* stale state first.
*
* This is a preserved legacy special case. It will not be carried into the
* concurrent router queue, which handles bfcache restore through its own
* design.
*/
export function legacyUrgentBFCacheRestore(
url: URL,
historyState: AppHistoryState | undefined
): void {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
}
export function refresh(): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
}
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
// Development only.
export function hmrRefresh(): void {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
}
// This is the seam where the experimental rewrite of the router state
// machine forks from the existing implementation, so nothing above this
// interface may depend on how the operations are processed. The fork happens
// at the bundler level: by default this module re-exports the sequential
// router queue, but when `experimental.concurrentRouterQueue` is enabled,
// imports of this module resolve to './concurrent-router-queue' instead —
// neither this module nor the sequential implementation is bundled at all.
// The aliases live in create-compiler-aliases.ts (webpack/rspack) and
// next_import_map.rs (Turbopack). The export list below is the interface;
// both implementations expose exactly this surface.
export {
navigate,
push,
replace,
traverse,
restore,
legacyUrgentBFCacheRestore,
refresh,
hmrRefresh,
} from './sequential-router-queue'
// The sequential-router-queue implementation of the navigator interface
// (navigator.ts). Callers must never import this module directly; they import
// './navigator', which resolves here unless `experimental.
// concurrentRouterQueue` swaps in `./concurrent-router-queue` at the bundler
// level (see create-compiler-aliases.ts and next_import_map.rs).
//
// The legacy reducer action objects are an implementation detail of the
// sequential action queue; they are constructed here and never by callers.
//
// This module must remain free of side effects at module scope: in addition
// to the browser bundle, a statically-resolved copy is compiled into the
// pre-compiled app-page runtime bundles (via app-render.tsx), where the
// bundler alias cannot reach. Only the browser copy's operations ever run.
import { addTransitionType, startTransition } from 'react'
import {
ACTION_HMR_REFRESH,
ACTION_NAVIGATE,
ACTION_REFRESH,
ACTION_RESTORE,
type AppHistoryState,
type AppRouterState,
type NavigateAction,
ScrollBehavior,
} from './router-reducer/router-reducer-types'
import type { NavigateOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { dispatchAppRouterAction } from './use-action-queue'
import { getCurrentAppRouterState } from './app-router-instance'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import { startRouterTransition } from './router-transition'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
function getRequiredAppRouterState(): AppRouterState {
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return state
}
export function navigate(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getRequiredAppRouterState().tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
})
}
export function push(href: string, options?: NavigateOptions): void {
navigate(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function replace(href: string, options?: NavigateOptions): void {
navigate(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function traverse(
href: string,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
startRouterTransition(
href,
'traverse',
getRequiredAppRouterState().tree,
null
)
restore(new URL(href), historyState)
})
}
/**
* Sync the router state to a history entry that was written by something
* other than a router navigation (a userland pushState/replaceState, or a
* bfcache restore). Unlike a traversal, this does not represent a transition
* between routes.
*/
export function restore(
url: URL,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
})
}
/**
* The bfcache `pageshow` restore (see the pageshow handler in app-router.tsx).
* Unlike every other navigator operation, this dispatches as a deliberately
* urgent (non-transition) update: the restored state reset must render before
* anything else can observe the stale mpaNavigation state and re-fire the MPA
* navigation the restore exists to prevent. As a transition it would be
* interruptible, and an intervening urgent render could commit against the
* stale state first.
*
* This is a preserved legacy special case. It will not be carried into the
* concurrent router queue, which handles bfcache restore through its own
* design.
*/
export function legacyUrgentBFCacheRestore(
url: URL,
historyState: AppHistoryState | undefined
): void {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
}
export function refresh(): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
}
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
// Development only.
export function hmrRefresh(): void {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
}
// The concurrent implementation of callServer (app-call-server.ts). Callers
// must never import this module directly; when
// `experimental.concurrentRouterQueue` is enabled, imports of
// './app-call-server' resolve here at the bundler level (see
// create-compiler-aliases.ts and next_import_map.rs), and neither
// app-call-server.ts nor the sequential implementation is bundled at all.
//
// This module must remain free of side effects at module scope; see the note
// in concurrent-router-queue.ts.
//
// TODO: This is currently a stub. It throws so that enabling the flag fails
// loudly instead of silently running the old implementation.
export async function callServer(
_actionId: string,
_actionArgs: any[]
): Promise<unknown> {
// Keep in sync with the identical message in concurrent-router-queue.ts, so
// all unimplemented behavior shares a single error (and error code).
throw new Error(
'Not implemented: this behavior is not yet supported when ' +
'`experimental.concurrentRouterQueue` is enabled.'
)
}
// Type-only conformance check: this module must expose exactly the surface of
// the app-call-server interface. Fails to typecheck if a signature drifts.
// Compiles to `const _conformance = null` — no runtime effect.
const _conformance: typeof import('./app-call-server') =
null as unknown as typeof import('./concurrent-call-server')
// The sequential implementation of callServer (app-call-server.ts): Server
// Actions are dispatched into the sequential router action queue. Callers
// must never import this module directly; they import './app-call-server',
// which resolves here unless `experimental.concurrentRouterQueue` swaps in
// './concurrent-call-server' at the bundler level (see
// create-compiler-aliases.ts and next_import_map.rs).
//
// This module must remain free of side effects at module scope: in addition
// to the browser bundle, a statically-resolved copy may be compiled into the
// pre-compiled app-page runtime bundles, where the bundler alias cannot
// reach. Only the browser copy ever runs.
import { startTransition } from 'react'
import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'
import { dispatchAppRouterAction } from './components/use-action-queue'
export async function callServer(actionId: string, actionArgs: any[]) {
return new Promise((resolve, reject) => {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_SERVER_ACTION,
actionId,
actionArgs,
resolve,
reject,
})
})
})
}
......@@ -227,6 +227,7 @@ export const experimentalSchema = {
dynamicOnHover: z.boolean().optional(),
useOffline: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
concurrentRouterQueue: z.boolean().optional(),
instrumentationClientRouterTransitionEvents: z.boolean().optional(),
varyParams: z.boolean().optional(),
prefetchInlining: z
......
......@@ -521,6 +521,12 @@ export interface ExperimentalConfig {
dynamicOnHover?: boolean
useOffline?: boolean
optimisticRouting?: boolean
/**
* Replaces the client router's sequential action queue with a rewritten
* concurrent implementation. The implementations are swapped at the module
* level by the bundler; the inactive one is not included in the bundle.
*/
concurrentRouterQueue?: boolean
instrumentationClientRouterTransitionEvents?: boolean
varyParams?: boolean
prefetchInlining?:
......@@ -2234,6 +2240,7 @@ export const defaultConfig = Object.freeze({
useOffline: false,
varyParams: true,
optimisticRouting: true,
concurrentRouterQueue: false,
instrumentationClientRouterTransitionEvents: false,
prefetchInlining: true,
preloadEntriesOnStart: true,
......
'use server'
export async function greet(): Promise<string> {
return 'hello from the server'
}
'use client'
import { useState } from 'react'
// Invokes a Server Action and renders the settled result, the way an app
// would observe its own action's returned promise.
export function ActionButton({ action }: { action: () => Promise<string> }) {
const [result, setResult] = useState('')
return (
<>
<button
id="invoke-action"
onClick={() => {
action().then(
(value) => setResult(`fulfilled: ${value}`),
(error) => setResult(`rejected: ${error.message}`)
)
}}
>
Invoke server action
</button>
<p id="action-result">{result}</p>
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
import { greet } from './actions'
import { ActionButton } from './client-components'
export default function Page() {
return (
<>
<p id="home">home</p>
<Link href="/target-page" id="to-target-page">
Go to target page
</Link>
<ActionButton action={greet} />
</>
)
}
export default function TargetPage() {
return <p id="target-page">target page</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const NOT_IMPLEMENTED_ERROR =
'Not implemented: this behavior is not yet supported when ' +
'`experimental.concurrentRouterQueue` is enabled.'
// `experimental.concurrentRouterQueue` swaps the router's entry-point modules
// (the navigator and the callServer action door) for the concurrent
// implementations at the bundler level. The concurrent implementations are
// currently stubs that throw a single distinctive error from every operation,
// so this suite verifies the fork wiring: the app boots on the concurrent
// modules without touching them, and every old-world entry point fails
// loudly instead of silently running the sequential implementation.
describe('concurrent-router-queue', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('hydrates cleanly without invoking the forked entry points', async () => {
// `pushErrorAsConsoleLog` records uncaught page errors into the console
// log capture, which works in both dev and start modes.
const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
expect(await browser.elementByCss('#home').text()).toBe('home')
// Hydration is complete once the client components are interactive.
await browser.waitForElementByCss('#invoke-action')
// Nothing at boot may call into the stubs (or fail in any other way).
const errors = (await browser.log()).filter((log) => log.source === 'error')
expect(errors).toEqual([])
})
it('fails loudly on link navigation', async () => {
const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
await browser.waitForElementByCss('#invoke-action')
await browser.elementByCss('#to-target-page').click()
// The stub throws synchronously inside the click handler, which surfaces
// as an uncaught page error. Wait for it to confirm the click was
// processed.
await retry(async () => {
const errors = (await browser.log()).filter(
(log) =>
log.source === 'error' && log.message.includes(NOT_IMPLEMENTED_ERROR)
)
expect(errors.length).toBeGreaterThan(0)
})
// No navigation happened, soft or hard: Link calls preventDefault()
// before dispatching, and the stub throws before any router state or
// pending-URL bookkeeping, so there is no fallback hard navigation.
expect(new URL(await browser.url()).pathname).toBe('/')
// The home page is still rendered; the target page never appears.
expect(await browser.elementByCss('#home').text()).toBe('home')
expect(await browser.hasElementByCssSelector('#target-page')).toBe(false)
})
it('fails loudly on server action invocation', async () => {
const browser = await next.browser('/')
await browser.waitForElementByCss('#invoke-action')
await browser.elementByCss('#invoke-action').click()
// callServer is async, so the stub surfaces as a rejection of the promise
// returned to the action caller, which the fixture renders. The result
// element is empty (and hidden) until the rejection renders, so
// elementByCss waits for it to appear.
expect(await browser.elementByCss('#action-result').text()).toBe(
`rejected: ${NOT_IMPLEMENTED_ERROR}`
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
concurrentRouterQueue: true,
},
}
module.exports = 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