Simplify prefetch suppression in draft mode

This change rejects new prefetches and cancels queued or resumed work
while draft mode is enabled. It restores the ordinary processing loop
and preserves foreground navigation-testing tasks.
parent edae2ac4
...@@ -867,6 +867,11 @@ async function ensurePrefetchThenNavigate( ...@@ -867,6 +867,11 @@ async function ensurePrefetchThenNavigate(
null, // onInvalidate null, // onInvalidate
navigationLockPrefetch navigationLockPrefetch
) )
if (prefetchTask === null) {
throw new Error(
'Internal Next.js error: Prefetch for a locked navigation was not scheduled.'
)
}
if (navigationLockPrefetch !== null) { if (navigationLockPrefetch !== null) {
await navigationLockPrefetch.promise await navigationLockPrefetch.promise
} }
......
...@@ -2475,7 +2475,14 @@ async function retryUpgradeableFallbackPrefetch( ...@@ -2475,7 +2475,14 @@ async function retryUpgradeableFallbackPrefetch(
await new Promise<void>((resolve) => await new Promise<void>((resolve) =>
setTimeout(resolve, FALLBACK_RETRY_DELAY_MS) setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)
) )
if (task.isCanceled || !isPrefetchingAllowed(task)) { if (
task.isCanceled ||
!isPrefetchingAllowed(
process.env.__NEXT_EXPOSE_TESTING_API
? task._navigationLockPrefetch
: null
)
) {
break break
} }
......
...@@ -294,16 +294,46 @@ export function startRevalidationCooldown(): void { ...@@ -294,16 +294,46 @@ export function startRevalidationCooldown(): void {
}, REVALIDATION_COOLDOWN_MS) }, REVALIDATION_COOLDOWN_MS)
} }
// Whether the browser session is in draft mode. Prefetching pauses while it is, // Draft mode prevents ordinary prefetch tasks from entering the queue. The
// because a draft response must not be stored as speculative data. Null until // state is separate from router state because an action can change its cookie
// hydration reports the initial state; a Server Action that writes the draft // even when the router discards the action's render result.
// cookie updates it from its response headers. The state lives here, not in the
// router state, because the cookie still changes when a navigation discards the
// action's render result.
let isDraftMode: boolean | null = null let isDraftMode: boolean | null = null
export function setIsDraftMode(value: boolean): void { export function setIsDraftMode(value: boolean): void {
if (isDraftMode === value) {
return
}
isDraftMode = value isDraftMode = value
if (!value || taskHeap.length === 0) {
return
}
// Cancel queued prefetches at the transition. Blocked tasks must pass the
// same policy when their responses requeue them through pingPrefetchTask.
let navigationTasks: PrefetchTask[] | null = null
let task = heapPop(taskHeap)
while (task !== null) {
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
task._navigationLockPrefetch != null
) {
if (navigationTasks === null) {
navigationTasks = []
}
navigationTasks.push(task)
} else {
cancelPrefetchTask(task)
}
task = heapPop(taskHeap)
}
if (navigationTasks !== null) {
for (const navigationTask of navigationTasks) {
heapPush(taskHeap, navigationTask)
}
}
pingPrefetchScheduler()
} }
export type IncludeDynamicData = null | 'full' | 'dynamic' export type IncludeDynamicData = null | 'full' | 'dynamic'
...@@ -313,7 +343,8 @@ export type IncludeDynamicData = null | 'full' | 'dynamic' ...@@ -313,7 +343,8 @@ export type IncludeDynamicData = null | 'full' | 'dynamic'
* is already in progress, this will bump it to the top of the queue. * is already in progress, this will bump it to the top of the queue.
* *
* This is not a user-facing function. By the time this is called, the href is * This is not a user-facing function. By the time this is called, the href is
* expected to be validated and normalized. * expected to be validated and normalized. Returns null when prefetching is
* disabled, unless the task drives a locked navigation.
* *
* @param key The RouteCacheKey to prefetch. * @param key The RouteCacheKey to prefetch.
* @param renderTreeAtTimeOfPrefetch The active render tree and head, and * @param renderTreeAtTimeOfPrefetch The active render tree and head, and
...@@ -331,7 +362,11 @@ export function schedulePrefetchTask( ...@@ -331,7 +362,11 @@ export function schedulePrefetchTask(
priority: PrefetchPriority, priority: PrefetchPriority,
onInvalidate: null | (() => void), onInvalidate: null | (() => void),
navigationLockPrefetch: NavigationLockPrefetch | null navigationLockPrefetch: NavigationLockPrefetch | null
): PrefetchTask { ): PrefetchTask | null {
if (!isPrefetchingAllowed(navigationLockPrefetch)) {
return null
}
// Bind the task to the segment cache map that is active right now: the // Bind the task to the segment cache map that is active right now: the
// shared map, unless the Instant Navigation Testing lock is held, in which // shared map, unless the Instant Navigation Testing lock is held, in which
// case the task gets the lock scope's private map. This is the single // case the task gets the lock scope's private map. This is the single
...@@ -404,6 +439,17 @@ export function reschedulePrefetchTask( ...@@ -404,6 +439,17 @@ export function reschedulePrefetchTask(
fetchStrategy: PrefetchTaskFetchStrategy, fetchStrategy: PrefetchTaskFetchStrategy,
priority: PrefetchPriority priority: PrefetchPriority
): void { ): void {
if (
!isPrefetchingAllowed(
process.env.__NEXT_EXPOSE_TESTING_API
? task._navigationLockPrefetch
: null
)
) {
cancelPrefetchTask(task)
return
}
// Bump the prefetch task to the top of the queue, as if it were a fresh // Bump the prefetch task to the top of the queue, as if it were a fresh
// task. This is essentially the same as canceling the task and scheduling // task. This is essentially the same as canceling the task and scheduling
// a new one, except it reuses the original object. // a new one, except it reuses the original object.
...@@ -487,11 +533,10 @@ export function pingPrefetchScheduler() { ...@@ -487,11 +533,10 @@ export function pingPrefetchScheduler() {
scheduleMicrotask(processQueueInMicrotask) scheduleMicrotask(processQueueInMicrotask)
} }
export function isPrefetchingAllowed(task: PrefetchTask): boolean { export function isPrefetchingAllowed(
if ( navigationLockPrefetch: NavigationLockPrefetch | null | undefined
process.env.__NEXT_EXPOSE_TESTING_API && ): boolean {
task._navigationLockPrefetch != null if (process.env.__NEXT_EXPOSE_TESTING_API && navigationLockPrefetch != null) {
) {
// The testing API uses this task to fulfill a navigation, not to fetch // The testing API uses this task to fulfill a navigation, not to fetch
// speculative data. Blocking it would leave that navigation waiting // speculative data. Blocking it would leave that navigation waiting
// forever. // forever.
...@@ -604,6 +649,16 @@ export function pingPrefetchTask(task: PrefetchTask) { ...@@ -604,6 +649,16 @@ export function pingPrefetchTask(task: PrefetchTask) {
) { ) {
return return
} }
if (
!isPrefetchingAllowed(
process.env.__NEXT_EXPOSE_TESTING_API
? task._navigationLockPrefetch
: null
)
) {
cancelPrefetchTask(task)
return
}
// Add the task back to the queue. // Add the task back to the queue.
heapPush(taskHeap, task) heapPush(taskHeap, task)
pingPrefetchScheduler() pingPrefetchScheduler()
...@@ -618,27 +673,8 @@ function processQueueInMicrotask() { ...@@ -618,27 +673,8 @@ function processQueueInMicrotask() {
const now = Date.now() const now = Date.now()
// Process the task queue until we run out of network bandwidth. // Process the task queue until we run out of network bandwidth.
let pausedTasks: PrefetchTask[] | null = null
let task = heapPeek(taskHeap) let task = heapPeek(taskHeap)
processTasks: while (task !== null) { while (task !== null && hasNetworkBandwidth(task)) {
if (!isPrefetchingAllowed(task)) {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// A navigation-testing task may be behind a paused Link prefetch. Keep
// the paused tasks out of this pass so they cannot block the
// navigation.
heapPop(taskHeap)
if (pausedTasks === null) {
pausedTasks = []
}
pausedTasks.push(task)
task = heapPeek(taskHeap)
continue
}
break
}
if (!hasNetworkBandwidth(task)) {
break
}
task.routeCacheVersion = getCurrentRouteCacheVersion() task.routeCacheVersion = getCurrentRouteCacheVersion()
task.segmentCacheVersion = getCurrentSegmentCacheVersion() task.segmentCacheVersion = getCurrentSegmentCacheVersion()
...@@ -657,7 +693,7 @@ function processQueueInMicrotask() { ...@@ -657,7 +693,7 @@ function processQueueInMicrotask() {
case PrefetchTaskExitStatus.InProgress: case PrefetchTaskExitStatus.InProgress:
// The task yielded because there are too many requests in progress. // The task yielded because there are too many requests in progress.
// Stop processing tasks until we have more bandwidth. // Stop processing tasks until we have more bandwidth.
break processTasks return
case PrefetchTaskExitStatus.Blocked: case PrefetchTaskExitStatus.Blocked:
// The task is blocked. It needs more data before it can proceed. // The task is blocked. It needs more data before it can proceed.
// Keep the task out of the queue until the server responds. // Keep the task out of the queue until the server responds.
...@@ -740,21 +776,11 @@ function processQueueInMicrotask() { ...@@ -740,21 +776,11 @@ function processQueueInMicrotask() {
} }
} }
if (pausedTasks !== null) { // Run LRU cleanup only when the scheduler is fully idle: no queued tasks and
for (const pausedTask of pausedTasks) { // no in-progress requests. At that point, all active prefetch tasks have
heapPush(taskHeap, pausedTask)
}
task = heapPeek(taskHeap)
}
// Run LRU cleanup only when the scheduler is fully idle: no runnable tasks
// and no in-progress requests. At that point, all active prefetch tasks have
// finished reading from the cache (moving recently used entries to the front // finished reading from the cache (moving recently used entries to the front
// of the list), so only genuinely stale data gets evicted. // of the list), so only genuinely stale data gets evicted.
if ( if (task === null && inProgressRequests === 0) {
inProgressRequests === 0 &&
(task === null || !isPrefetchingAllowed(task))
) {
cleanup() cleanup()
} }
} }
......
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