Commit afe9d0d1 authored by Janka Uryga's avatar Janka Uryga

fixing hanging cache deadlock

parent c6ff4d0a
...@@ -2782,7 +2782,7 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2782,7 +2782,7 @@ async function renderWithRestartOnCacheMissInDev(
initialRequestStore: RequestStore, initialRequestStore: RequestStore,
createRequestStore: () => RequestStore, createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void onError: (err: unknown) => string | undefined
) { ) {
const { const {
htmlRequestId, htmlRequestId,
...@@ -2842,9 +2842,9 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2842,9 +2842,9 @@ async function renderWithRestartOnCacheMissInDev(
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
const initialReactController = new AbortController() const initialReactController = new AbortController()
const initialDataController = new AbortController() // Controls hanging promises we create const initialHangingPromiseController = new AbortController()
const initialStageController = new StagedRenderingController( const initialStageController = new StagedRenderingController(
initialDataController.signal initialHangingPromiseController.signal
) )
requestStore.prerenderResumeDataCache = prerenderResumeDataCache requestStore.prerenderResumeDataCache = prerenderResumeDataCache
...@@ -2873,7 +2873,13 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2873,7 +2873,13 @@ async function renderWithRestartOnCacheMissInDev(
initialRscPayload, initialRscPayload,
clientReferenceManifest.clientModules, clientReferenceManifest.clientModules,
{ {
onError, onError: (err) => {
if (initialReactController.signal.aborted) {
return undefined
} else {
return onError(err)
}
},
environmentName, environmentName,
filterStackFrame, filterStackFrame,
debugChannel: debugChannel?.serverSide, debugChannel: debugChannel?.serverSide,
...@@ -2884,7 +2890,8 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2884,7 +2890,8 @@ async function renderWithRestartOnCacheMissInDev(
// Note that we want to install this listener after the render is started // Note that we want to install this listener after the render is started
// so that it runs after react is finished running its abort code. // so that it runs after react is finished running its abort code.
initialReactController.signal.addEventListener('abort', () => { initialReactController.signal.addEventListener('abort', () => {
initialDataController.abort(initialReactController.signal.reason) const { reason } = initialReactController.signal
initialHangingPromiseController.abort(reason)
}) })
return stream return stream
}, },
......
...@@ -42,7 +42,7 @@ export function makeHangingPromise<T>( ...@@ -42,7 +42,7 @@ export function makeHangingPromise<T>(
expression: string expression: string
): Promise<T> { ): Promise<T> {
if (signal.aborted) { if (signal.aborted) {
return Promise.reject(new HangingPromiseRejectionError(route, expression)) return makeRejectedHangingPromise(route, expression)
} else { } else {
const hangingPromise = new Promise<T>((_, reject) => { const hangingPromise = new Promise<T>((_, reject) => {
const boundRejection = reject.bind( const boundRejection = reject.bind(
...@@ -74,6 +74,13 @@ export function makeHangingPromise<T>( ...@@ -74,6 +74,13 @@ export function makeHangingPromise<T>(
} }
} }
export function makeRejectedHangingPromise(
route: string,
expression: string
): Promise<never> {
return Promise.reject(new HangingPromiseRejectionError(route, expression))
}
function ignoreReject() {} function ignoreReject() {}
export function makeDevtoolsIOAwarePromise<T>( export function makeDevtoolsIOAwarePromise<T>(
......
...@@ -38,8 +38,8 @@ import { ...@@ -38,8 +38,8 @@ import {
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
makeRejectedHangingPromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import type { ClientReferenceManifestForRsc } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifestForRsc } from '../../build/webpack/plugins/flight-manifest-plugin'
...@@ -71,7 +71,10 @@ import { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result' ...@@ -71,7 +71,10 @@ import { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external' import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import { isReactLargeShellError } from '../app-render/react-large-shell-error' import { isReactLargeShellError } from '../app-render/react-large-shell-error'
import type { CacheLife } from './cache-life' import type { CacheLife } from './cache-life'
import { RenderStage } from '../app-render/staged-rendering' import {
RenderStage,
type NonStaticRenderStage,
} from '../app-render/staged-rendering'
interface PrivateCacheContext { interface PrivateCacheContext {
readonly kind: 'private' readonly kind: 'private'
...@@ -1015,10 +1018,9 @@ export function cache( ...@@ -1015,10 +1018,9 @@ export function cache(
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Similar to runtime prerenders, private caches should not resolve in the static stage // Similar to runtime prerenders, private caches should not resolve in the static stage
// of a dev request, so we delay them. // of a dev request, so we delay them.
await makeDevtoolsIOAwarePromise( await delayBeforeCacheReadStartInDev(
undefined, RenderStage.Runtime,
outerWorkUnitStore, outerWorkUnitStore
RenderStage.Runtime
) )
} }
break break
...@@ -1280,14 +1282,19 @@ export function cache( ...@@ -1280,14 +1282,19 @@ export function cache(
// We delay the cache here so that it doesn't resolve in the static task -- // We delay the cache here so that it doesn't resolve in the static task --
// in a regular static prerender, it'd be a hanging promise, and we need to reflect that, // in a regular static prerender, it'd be a hanging promise, and we need to reflect that,
// so it has to resolve later. // so it has to resolve later.
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. // TODO(restart-on-cache-miss): This can fallthrough to the `RUNTIME_PREFETCH_DYNAMIC_STALE`
// We don't end the cache read here, so this will always appear as a cache miss in the static stage, // check below, and try to delay again. This is not incorrect, but it's unnecessary.
// and thus will cause a restart even if all caches are filled. // refactor this to avoid it.
await makeDevtoolsIOAwarePromise( const hang = await delayOrHangStartedCacheReadInDev(
undefined, RenderStage.Runtime,
workUnitStore, workUnitStore,
RenderStage.Runtime cacheSignal,
workStore.route,
'dynamic "use cache"'
) )
if (hang) {
return hang.hangingPromise
}
} }
break break
} }
...@@ -1322,14 +1329,16 @@ export function cache( ...@@ -1322,14 +1329,16 @@ export function cache(
// We delay the cache here so that it doesn't resolve in the runtime phase -- // We delay the cache here so that it doesn't resolve in the runtime phase --
// in a regular runtime prerender, it'd be a hanging promise, and we need to reflect that, // in a regular runtime prerender, it'd be a hanging promise, and we need to reflect that,
// so it has to resolve later. // so it has to resolve later.
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. const hang = await delayOrHangStartedCacheReadInDev(
// We don't end the cache read here, so this will always appear as a cache miss in the runtime stage, RenderStage.Dynamic,
// and thus will cause a restart even if all caches are filled.
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore, workUnitStore,
RenderStage.Dynamic cacheSignal,
workStore.route,
'dynamic "use cache"'
) )
if (hang) {
return hang.hangingPromise
}
} }
break break
} }
...@@ -1496,14 +1505,16 @@ export function cache( ...@@ -1496,14 +1505,16 @@ export function cache(
// We delay the cache here so that it doesn't resolve in the static task -- // We delay the cache here so that it doesn't resolve in the static task --
// in a regular static prerender, it'd be a hanging promise, and we need to reflect that, // in a regular static prerender, it'd be a hanging promise, and we need to reflect that,
// so it has to resolve later. // so it has to resolve later.
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. const hang = await delayOrHangStartedCacheReadInDev(
// We don't end the cache read here, so this will always appear as a cache miss in the static stage, RenderStage.Dynamic,
// and thus will cause a restart even if all caches are filled.
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore, workUnitStore,
RenderStage.Runtime cacheSignal,
workStore.route,
'dynamic "use cache"'
) )
if (hang) {
return hang.hangingPromise
}
} }
break break
} }
...@@ -1848,3 +1859,75 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean { ...@@ -1848,3 +1859,75 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean {
return false return false
} }
async function delayBeforeCacheReadStartInDev(
stage: NonStaticRenderStage,
requestStore: RequestStore
): Promise<void> {
const { stagedRendering } = requestStore
if (stagedRendering && stagedRendering.currentStage < stage) {
await stagedRendering.waitForStage(stage)
}
}
/** Note: Only call this after a `cacheSignal.beginRead()`. */
async function delayOrHangStartedCacheReadInDev(
stage: NonStaticRenderStage,
requestStore: RequestStore,
cacheSignal: CacheSignal | null,
route: string,
expression: string
): Promise<{ hangingPromise: Promise<never> } | null> {
const { stagedRendering } = requestStore
// No staging, so we don't need to delay.
if (!stagedRendering) {
return null
}
// We're already at or beyond the target stage, so we shouldn't hang or delay.
if (stagedRendering.currentStage >= stage) {
return null
}
// We've got an ongoing cache read that can only resolve in a future stage.
if (cacheSignal) {
// We're filling caches, and might need to omit this one if we can't reach its target stage.
// This can happen e.g. if a cache only resolves in the Dynamic stage --
// we never advance to it in a cache filling render.
// Hide the cache read.
// It won't resolve in the current stage anyway,
// so we don't want it to show up when we check if there's pending reads
// (i.e. cache misses) at the beginning of the next stage.
// Otherwise, the render might be bailed out and used as a warmup,
// and we'd stop advancing stages (e.g. we would never reach Dynamic)
// so this read would never end, and `cacheSignal.cacheReady()` would deadlock.
cacheSignal.endRead()
// We haven't reached the target stage yet, so we wait for one of these two things:
try {
await stagedRendering.waitForStage(stage)
// 1. We reach the target stage, and we can unblock the cacke
// We need to restart the read that we hid before, since it hasn't actually finished.
cacheSignal.beginRead()
return null
} catch {
// 2. The render is aborted before we reached the target stage.
// The render was already aborted, so we can just return a rejected promise instead of a hanging one.
const hangingPromise = makeRejectedHangingPromise(route, expression)
// Wrapped in an object so that we can return it without it being awaited by the runtime.
return { hangingPromise }
}
}
cacheSignal satisfies null
// Otherwise, we're in the restarted render, after caches have been filled.
// This render should finish completely, without aborting, so we should only delay.
await stagedRendering.waitForStage(stage)
return null
}
...@@ -246,7 +246,8 @@ describe.each([ ...@@ -246,7 +246,8 @@ describe.each([
assertLog(logs, 'after cache read - page', 'Prerender') assertLog(logs, 'after cache read - page', 'Prerender')
// Short lived caches are dynamic holes in static prerenders, // Short lived caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage. // so they shouldn't resolve in the static stage,
// but they should resolve in the runtime stage.
assertLog(logs, 'after short-lived cache read - page', RUNTIME_ENV) assertLog(logs, 'after short-lived cache read - page', RUNTIME_ENV)
assertLog( assertLog(
logs, logs,
...@@ -254,6 +255,11 @@ describe.each([ ...@@ -254,6 +255,11 @@ describe.each([
RUNTIME_ENV RUNTIME_ENV
) )
// Dynamic caches are holes in static and runtime prerenders,
// so they should only resolve in the dynamic stage.
assertLog(logs, 'after dynamic cache read - layout', 'Server')
assertLog(logs, 'after dynamic cache read - page', 'Server')
assertLog(logs, 'after uncached fetch - layout', 'Server') assertLog(logs, 'after uncached fetch - layout', 'Server')
assertLog(logs, 'after uncached fetch - page', 'Server') assertLog(logs, 'after uncached fetch - page', 'Server')
} }
......
...@@ -23,3 +23,31 @@ async function getShortLivedCachedData(_key: string) { ...@@ -23,3 +23,31 @@ async function getShortLivedCachedData(_key: string) {
await new Promise((r) => setTimeout(r)) await new Promise((r) => setTimeout(r))
return Math.random() return Math.random()
} }
export async function DynamicCache({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getDynamicCachedData(cacheKey)
console.log(`after dynamic cache read - ${label}`)
return (
<dl>
<dt>Dynamic Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
async function getDynamicCachedData(_key: string) {
'use cache'
cacheLife({
stale: 20, // < DYNAMIC_STALE (excluded from runtime prerenders)
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE (excluded from static prerenders)
})
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react' import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching' import { UncachedFetch, CachedData } from '../data-fetching'
import { ShortLivedCache } from './data-fetching' import { DynamicCache, ShortLivedCache } from './data-fetching'
export const unstable_prefetch = { mode: 'runtime', samples: [{}] } export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
...@@ -20,6 +20,10 @@ export default function Layout({ children }: { children: React.ReactNode }) { ...@@ -20,6 +20,10 @@ export default function Layout({ children }: { children: React.ReactNode }) {
<ShortLivedCache label="layout" cacheKey={CACHE_KEY} /> <ShortLivedCache label="layout" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
<Suspense fallback="Loading dynamic cache...">
<DynamicCache label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch..."> <Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} /> <UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching' import { CachedData, UncachedFetch } from '../data-fetching'
import { ShortLivedCache } from './data-fetching' import { DynamicCache, ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__' const CACHE_KEY = __dirname + '/__PAGE__'
...@@ -15,6 +15,10 @@ export default async function Page() { ...@@ -15,6 +15,10 @@ export default async function Page() {
<ShortLivedCache label="page" cacheKey={CACHE_KEY} /> <ShortLivedCache label="page" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
<Suspense fallback="Loading dynamic cache...">
<DynamicCache label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch..."> <Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} /> <UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
......
...@@ -23,3 +23,31 @@ async function getShortLivedCachedData(_key: string) { ...@@ -23,3 +23,31 @@ async function getShortLivedCachedData(_key: string) {
await new Promise((r) => setTimeout(r)) await new Promise((r) => setTimeout(r))
return Math.random() return Math.random()
} }
export async function DynamicCache({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getDynamicCachedData(cacheKey)
console.log(`after dynamic cache read - ${label}`)
return (
<dl>
<dt>Dynamic Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
async function getDynamicCachedData(_key: string) {
'use cache'
cacheLife({
stale: 20, // < DYNAMIC_STALE (excluded from runtime prerenders)
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE (excluded from static prerenders)
})
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react' import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching' import { UncachedFetch, CachedData } from '../data-fetching'
import { ShortLivedCache } from './data-fetching' import { DynamicCache, ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__LAYOUT__' const CACHE_KEY = __dirname + '/__LAYOUT__'
...@@ -18,6 +18,10 @@ export default function Layout({ children }: { children: React.ReactNode }) { ...@@ -18,6 +18,10 @@ export default function Layout({ children }: { children: React.ReactNode }) {
<ShortLivedCache label="layout" cacheKey={CACHE_KEY} /> <ShortLivedCache label="layout" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
<Suspense fallback="Loading dynamic cache...">
<DynamicCache label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch..."> <Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} /> <UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching' import { CachedData, UncachedFetch } from '../data-fetching'
import { ShortLivedCache } from './data-fetching' import { DynamicCache, ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__' const CACHE_KEY = __dirname + '/__PAGE__'
...@@ -15,6 +15,10 @@ export default async function Page() { ...@@ -15,6 +15,10 @@ export default async function Page() {
<ShortLivedCache label="page" cacheKey={CACHE_KEY} /> <ShortLivedCache label="page" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
<Suspense fallback="Loading dynamic cache...">
<DynamicCache label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch..."> <Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} /> <UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense> </Suspense>
......
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