Unverified Commit d538cfb7 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

fix: after(callback) called after response end (#94974)

Fixes a bug where if `after(callback)`was called after the response
ended, and no `after(callback)` calls occurred earlier, the callback
would never run.

Implementation-wise, what happens is:
1. when the first callback is scheduled, we do `runCallbacksOnClose()`,
which waits until `onClose` fires and starts the callback queue
2. but if no `after(callback)` calls occurred before the response ended,
then by the time we got to `runCallbacksOnClose()`, `onClose` has
already fired, so we'd wait forever

We now start listening for `onClose` when the context is initialized and
track the state (`isRequestClosed`), which avoids this.

I also did another drive-by fix here: if we only had `after(promise)`
calls, we wouldn't switch the workUnitStore's phase to `'after'`,
because we were only doing that in the `after(callback)` codepath. This
is relevant in #94964 which fixes some bugs around `after(promise)`.
parent 34759c3e
......@@ -1365,5 +1365,6 @@
"1364": "\\`experimental.turbopackRustReactCompiler\\` requires \\`reactCompiler\\` to be enabled. Please add \\`reactCompiler: true\\` in %s.",
"1365": "Expected a dev tiered cache handler for kind \"%s\".",
"1366": "Turbopack build failed with %s %s:\\n%s",
"1367": "createServerParamsForRoute should not be called in runtime prerenders."
"1367": "createServerParamsForRoute should not be called in runtime prerenders.",
"1368": "An onClose call failed, which means after() can't work correctly."
}
......@@ -36,30 +36,34 @@ describe('AfterContext', () => {
})
const createRun =
(_afterContext: AfterContext, workStore: WorkStore) =>
(
_afterContext: AfterContext,
workStore: WorkStore,
workUnitStore: WorkUnitStore
) =>
<T>(cb: () => T): T => {
return workAsyncStorage.run(workStore, () =>
workUnitAsyncStorage.run(createMockWorkUnitStore(), cb)
workUnitAsyncStorage.run(workUnitStore, cb)
)
}
it('runs after() callbacks from a run() callback that resolves', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1) // called once when initializing
const workStore = createMockWorkStore(afterContext)
const run = createRun(afterContext, workStore)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -72,29 +76,32 @@ describe('AfterContext', () => {
const afterCallback2 = jest.fn(() => promise2.promise)
await run(async () => {
expect(waitUntil).toHaveBeenCalledTimes(0)
after(promise0.promise)
expect(onClose).not.toHaveBeenCalled() // we don't need onClose for bare promises
expect(waitUntil).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1) // bump: called for promises
expect(onClose).toHaveBeenCalledTimes(1) // unchanged
await Promise.resolve(null)
after(afterCallback1)
expect(waitUntil).toHaveBeenCalledTimes(2) // just runCallbacksOnClose
expect(onClose).toHaveBeenCalledTimes(2) // bump: runCallbacksOnClose
expect(waitUntil).toHaveBeenCalledTimes(2) // bump: runCallbacksOnClose
await Promise.resolve(null)
after(afterCallback2)
expect(waitUntil).toHaveBeenCalledTimes(2) // should only `waitUntil(this.runCallbacksOnClose())` once for all callbacks
expect(waitUntil).toHaveBeenCalledTimes(2) // unchanged: should only `waitUntil(this.runCallbacksOnClose())` once for all callbacks
})
expect(onClose).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(2)
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
triggerOnClose()
await waitForCallbackQueue()
expect(workUnitStore.phase).toBe('after')
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(2)
......@@ -105,29 +112,29 @@ describe('AfterContext', () => {
const results = await Promise.all(waitUntilPromises)
expect(results).toEqual([
'0', // promises are passed to waitUntil as is
undefined, // the results of promises are dropped
undefined, // callbacks all get collected into a big void promise
])
expect(taskErrors).toEqual([])
})
it('runs after() callbacks from a run() callback that throws', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1)
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore)
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -141,14 +148,15 @@ describe('AfterContext', () => {
// runCallbacksOnClose
expect(waitUntil).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(2)
expect(afterCallback1).not.toHaveBeenCalled()
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
triggerOnClose()
await waitForCallbackQueue()
expect(workUnitStore.phase).toBe('after')
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1)
......@@ -156,26 +164,26 @@ describe('AfterContext', () => {
const results = await Promise.all(waitUntilPromises)
expect(results).toEqual([undefined])
expect(taskErrors).toEqual([])
})
it('runs after() callbacks from a run() callback that streams', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1)
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore)
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -211,7 +219,7 @@ describe('AfterContext', () => {
})
})
expect(onClose).not.toHaveBeenCalled() // no after()s executed yet
expect(onClose).toHaveBeenCalledTimes(1) // unchanged: no after()s executed yet
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
......@@ -228,16 +236,17 @@ describe('AfterContext', () => {
}
// runCallbacksOnClose
expect(onClose).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(2)
expect(waitUntil).toHaveBeenCalledTimes(1)
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
triggerOnClose()
await waitForCallbackQueue()
expect(workUnitStore.phase).toBe('after')
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1)
......@@ -247,25 +256,25 @@ describe('AfterContext', () => {
const results = await Promise.all(waitUntilPromises)
expect(results).toEqual([undefined])
expect(taskErrors).toEqual([])
})
it('runs after() callbacks added within an after()', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1)
const workStore = createMockWorkStore(afterContext)
const run = createRun(afterContext, workStore)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -280,18 +289,19 @@ describe('AfterContext', () => {
await run(async () => {
after(afterCallback1)
expect(onClose).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1) // just runCallbacksOnClose
expect(onClose).toHaveBeenCalledTimes(2) // bump: runCallbacksOnClose
expect(waitUntil).toHaveBeenCalledTimes(1) // bump: runCallbacksOnClose
})
expect(onClose).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(2) // bump: runCallbacksOnClose
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
triggerOnClose()
await waitForCallbackQueue()
expect(workUnitStore.phase).toBe('after')
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(0)
expect(waitUntil).toHaveBeenCalledTimes(1)
......@@ -308,14 +318,16 @@ describe('AfterContext', () => {
expect(results).toEqual([
undefined, // callbacks all get collected into a big void promise
])
expect(taskErrors).toEqual([])
})
it('does not hang forever if onClose failed', async () => {
it('waits for promises added via after(promise)', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
const onClose = jest.fn(() => {
throw new Error('onClose is broken for some reason')
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const afterContext = new AfterContext({
......@@ -325,37 +337,148 @@ describe('AfterContext', () => {
})
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
const promise = new DetachedPromise<void>()
let promiseDidResolve = false
promise.promise.then(() => {
promiseDidResolve = true
})
await run(() => {
afterContext.after(promise.promise, workUnitStore)
expect(onClose).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1) // just runCallbacksOnClose
})
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
const run = createRun(afterContext, workStore)
expect(workUnitStore.phase).toBe('after')
setTimeout(() => promise.resolve(), 50)
await Promise.all(waitUntilPromises)
expect(promiseDidResolve).toBe(true)
})
it('runs after() callbacks added from after(promise) after onClose', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: taskErrors.push.bind(taskErrors),
})
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
const afterCallback1 = jest.fn()
const promise1 = new DetachedPromise<void>()
const promise2 = new DetachedPromise<void>()
let afterCallback2DidFinish = false
const afterCallback2 = jest.fn(async () => {
await promise2.promise
afterCallback2DidFinish = true
})
await run(async () => {
after(afterCallback1)
const afterPromise1 = (async () => {
await promise1.promise
after(afterCallback2)
await waitForCallbackQueue()
expect(afterCallback2).toHaveBeenCalledTimes(1)
})()
// only `after()` a promise, no callbacks
after(afterPromise1)
})
expect(waitUntil).toHaveBeenCalledTimes(1) // runCallbacksOnClose
expect(onClose).toHaveBeenCalledTimes(1)
expect(afterCallback1).not.toHaveBeenCalled()
expect(onClose).toHaveBeenCalledTimes(1) // unchanged
expect(waitUntil).toHaveBeenCalledTimes(1) // promise
// the response is done.
triggerOnClose()
expect(workUnitStore.phase).toBe('after')
promise1.resolve() // unblock the promise, leading to an `after(callback)`
// if we didn't properly reject the runCallbacksOnClose promise, this should hang forever, and get killed by jest.
const results = await Promise.allSettled(waitUntilPromises)
await waitForCallbackQueue()
expect(afterCallback2).toHaveBeenCalledTimes(1)
promise2.resolve() // unblock the callback
const results = await Promise.all(waitUntilPromises)
await Promise.resolve(null)
expect(afterCallback2DidFinish).toBe(true)
expect(waitUntil).toHaveBeenCalledTimes(2)
expect(results).toEqual([
{ status: 'rejected', value: undefined, reason: expect.anything() },
undefined, // callbacks all get collected into a big void promise
])
expect(taskErrors).toEqual([])
})
it('runs all after() callbacks even if some of them threw', async () => {
it('reports onClose failures', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
const taskErrors: unknown[] = []
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
const onClose = jest.fn(() => {
throw new Error('onClose is broken for some reason')
})
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1)
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
const afterCallback1 = jest.fn()
await expect(
run(async () => {
after(afterCallback1)
})
).rejects.toEqual(
expect.objectContaining({
message: expect.stringContaining(
`An onClose call failed, which means after() can't work correctly.`
),
})
)
expect(waitUntil).toHaveBeenCalledTimes(0)
expect(afterCallback1).not.toHaveBeenCalled()
expect(taskErrors).toEqual([])
})
it('runs all after() callbacks even if some of them threw', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
const { onClose, triggerOnClose } = createOnClose()
const onTaskError = jest.fn()
const afterContext = new AfterContext({
......@@ -365,6 +488,8 @@ describe('AfterContext', () => {
})
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -382,14 +507,12 @@ describe('AfterContext', () => {
const thrownFromPromise4 = new Error('4')
const promise4 = Promise.reject(thrownFromPromise4)
workAsyncStorage.run(workStore, () =>
workUnitAsyncStorage.run(createMockWorkUnitStore(), () => {
after(afterCallback1)
after(afterCallback2)
after(afterCallback3)
after(promise4)
})
)
run(() => {
after(afterCallback1)
after(afterCallback2)
after(afterCallback3)
after(promise4)
})
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
......@@ -397,9 +520,10 @@ describe('AfterContext', () => {
expect(waitUntil).toHaveBeenCalledTimes(1 + 1) // once for callbacks, once for the promise
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
triggerOnClose()
await waitForCallbackQueue()
expect(workUnitStore.phase).toBe('after')
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(1)
expect(afterCallback3).toHaveBeenCalledTimes(1)
......@@ -419,17 +543,21 @@ describe('AfterContext', () => {
it('throws from after() if waitUntil is not provided', async () => {
const waitUntil = undefined
const taskErrors: unknown[] = []
const onClose = jest.fn()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
expect(onClose).toHaveBeenCalledTimes(1)
const workStore = createMockWorkStore(afterContext)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore)
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -441,71 +569,84 @@ describe('AfterContext', () => {
})
).toThrow(/`waitUntil` is not available in the current environment/)
expect(onClose).not.toHaveBeenCalled()
expect(onClose).toHaveBeenCalledTimes(1) // unchanged
expect(afterCallback1).not.toHaveBeenCalled()
expect(taskErrors).toEqual([])
})
it('does NOT shadow workAsyncStorage within after callbacks', async () => {
it('does NOT shadow workAsyncStorage or workUnitAsyncStorage within after callbacks', async () => {
const waitUntil = jest.fn()
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
const workStore = createMockWorkStore(afterContext)
const run = createRun(afterContext, workStore)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
const stores = new DetachedPromise<
[WorkStore | undefined, WorkStore | undefined]
>()
type Stores = {
workStore: WorkStore | undefined
workUnitStore: WorkUnitStore | undefined
}
const stores = new DetachedPromise<[Stores, Stores]>()
await run(async () => {
const store1 = workAsyncStorage.getStore()
const stores1 = {
workStore: workAsyncStorage.getStore(),
workUnitStore: workUnitAsyncStorage.getStore(),
}
after(() => {
const store2 = workAsyncStorage.getStore()
stores.resolve([store1, store2])
const stores2 = {
workStore: workAsyncStorage.getStore(),
workUnitStore: workUnitAsyncStorage.getStore(),
}
stores.resolve([stores1, stores2])
})
})
// the response is done.
onCloseCallback!()
triggerOnClose()
const [store1, store2] = await stores.promise
await Promise.resolve(null)
expect(workUnitStore.phase).toBe('after')
const [stores1, stores2] = await stores.promise
expect(stores1.workStore).toBeTruthy()
expect(stores1.workUnitStore).toBeTruthy()
expect(stores2.workStore).toBeTruthy()
expect(stores2.workUnitStore).toBeTruthy()
// if we use .toBe, the proxy from createMockWorkStore throws because jest checks '$$typeof'
expect(store1).toBeTruthy()
expect(store2).toBeTruthy()
expect(store1 === workStore).toBe(true)
expect(store2 === store1).toBe(true)
expect(stores1.workStore === workStore).toBe(true)
expect(stores1.workUnitStore === workUnitStore).toBe(true)
expect(stores2.workStore === workStore).toBe(true)
expect(stores2.workUnitStore === workUnitStore).toBe(true)
expect(taskErrors).toEqual([])
})
it('preserves the ALS context the callback was created in', async () => {
type TestStore = string
const testStorage = new AsyncLocalStorage<TestStore>()
const waitUntil = jest.fn()
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const taskErrors: unknown[] = []
const { onClose, triggerOnClose } = createOnClose()
const afterContext = new AfterContext({
waitUntil,
onClose,
onTaskError: undefined,
onTaskError: taskErrors.push.bind(taskErrors),
})
const workStore = createMockWorkStore(afterContext)
const run = createRun(afterContext, workStore)
const workUnitStore = createMockWorkUnitStore()
const run = createRun(afterContext, workStore, workUnitStore)
// ==================================
......@@ -524,7 +665,10 @@ describe('AfterContext', () => {
)
// the response is done.
onCloseCallback!()
triggerOnClose()
await Promise.resolve(null)
expect(workUnitStore.phase).toBe('after')
const [store1, store2] = await stores.promise
// if we use .toBe, the proxy from createMockWorkStore throws because jest checks '$$typeof'
......@@ -532,9 +676,30 @@ describe('AfterContext', () => {
expect(store2).toBeDefined()
expect(store1 === 'value').toBe(true)
expect(store2 === store1).toBe(true)
expect(taskErrors).toEqual([])
})
})
function createOnClose() {
const callbacks: (() => void)[] = []
const onClose = jest.fn((cb) => {
callbacks.push(cb)
})
const triggerOnClose = () => {
for (const callback of callbacks) {
try {
callback()
} catch {}
}
callbacks.length = 0
}
return { onClose, triggerOnClose }
}
function waitForCallbackQueue() {
return new Promise((resolve) => setImmediate(() => setImmediate(resolve)))
}
const createMockWorkStore = (afterContext: AfterContext): WorkStore => {
const partialStore: Partial<WorkStore> = {
afterContext: afterContext,
......
......@@ -6,11 +6,9 @@ import { isThenable } from '../../shared/lib/is-thenable'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { withExecuteRevalidates } from '../revalidation-utils'
import { bindSnapshot } from '../app-render/async-local-storage'
import {
workUnitAsyncStorage,
type WorkUnitStore,
} from '../app-render/work-unit-async-storage.external'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import { scheduleImmediate } from '../../lib/scheduler'
export type AfterContextOpts = {
waitUntil: RequestLifecycleOpts['waitUntil'] | undefined
......@@ -23,6 +21,9 @@ export class AfterContext {
private onClose: RequestLifecycleOpts['onClose']
private onTaskError: RequestLifecycleOpts['onAfterTaskError'] | undefined
private isRequestClosed: boolean = false
private initialOnCloseError: null | { error: unknown } = null
private runCallbacksOnClosePromise: Promise<void> | undefined
private callbackQueue: PromiseQueue
private workUnitStores = new Set<WorkUnitStore>()
......@@ -34,33 +35,67 @@ export class AfterContext {
this.callbackQueue = new PromiseQueue()
this.callbackQueue.pause()
try {
onClose(() => {
this.isRequestClosed = true
// TODO(after): it's not ideal that we'll only switch the `phase` of a WorkUnitStore
// if `after()` was called inside it. We should probably track this whenever a store is created
for (const workUnitStore of this.workUnitStores) {
workUnitStore.phase = 'after'
}
})
} catch (err) {
// If onClose is broken, report errors lazily, when after() is called.
this.initialOnCloseError = { error: err }
}
}
public after(task: AfterTask): void {
if (isThenable(task)) {
if (!this.waitUntil) {
errorWaitUntilNotAvailable()
}
this.waitUntil(
task.catch((error) => this.reportTaskError('promise', error))
public after(task: AfterTask, workUnitStore: WorkUnitStore): void {
if (this.initialOnCloseError) {
throw new InvariantError(
`An onClose call failed, which means after() can't work correctly.`,
{ cause: this.initialOnCloseError.error }
)
}
// Save the workUnitStore so we can switch its phase later.
this.workUnitStores.add(workUnitStore)
if (isThenable(task)) {
this.addThenable(task)
} else if (typeof task === 'function') {
// TODO(after): implement tracing
this.addCallback(task)
this.addCallback(task, workUnitStore)
} else {
throw new Error('`after()`: Argument must be a promise or a function')
}
}
private addCallback(callback: AfterCallback) {
// if something is wrong, throw synchronously, bubbling up to the `after` callsite.
private addThenable(thenable: PromiseLike<any>) {
if (!this.waitUntil) {
errorWaitUntilNotAvailable()
}
this.waitUntil(
new Promise<void>((resolve) => {
thenable.then(
() => {
resolve()
},
(error) => {
resolve()
this.reportTaskError('promise', error)
}
)
})
)
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
this.workUnitStores.add(workUnitStore)
private addCallback(callback: AfterCallback, workUnitStore: WorkUnitStore) {
// if something is wrong, throw synchronously, bubbling up to the `after` callsite.
if (!this.waitUntil) {
errorWaitUntilNotAvailable()
}
const afterTaskStore = afterTaskAsyncStorage.getStore()
......@@ -71,7 +106,7 @@ export class AfterContext {
// Otherwise, we might allow `after(() => headers())`, but not `after(() => after(() => headers()))`.
const rootTaskSpawnPhase = afterTaskStore
? afterTaskStore.rootTaskSpawnPhase // nested after
: workUnitStore?.phase // topmost after
: workUnitStore.phase // topmost after
// this should only happen once.
if (!this.runCallbacksOnClosePromise) {
......@@ -102,17 +137,20 @@ export class AfterContext {
}
private async runCallbacksOnClose() {
await new Promise<void>((resolve) => this.onClose!(resolve))
if (!this.isRequestClosed) {
await new Promise<void>((resolve) => this.onClose(resolve))
} else {
// The request is already closed.
// Avoid running the callbacks too quickly to prevent userspace from
// e.g. relying on `after` being microtasky somewhere.
await new Promise<void>((resolve) => scheduleImmediate(resolve))
}
return this.runCallbacks()
}
private async runCallbacks(): Promise<void> {
if (this.callbackQueue.size === 0) return
for (const workUnitStore of this.workUnitStores) {
workUnitStore.phase = 'after'
}
const workStore = workAsyncStorage.getStore()
if (!workStore) {
throw new InvariantError('Missing workStore in AfterContext.runCallbacks')
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
export type AfterTask<T = unknown> = Promise<T> | AfterCallback<T>
export type AfterCallback<T = unknown> = () => T | Promise<T>
......@@ -8,8 +9,9 @@ export type AfterCallback<T = unknown> = () => T | Promise<T>
*/
export function after<T>(task: AfterTask<T>): void {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore) {
if (!workStore || !workUnitStore) {
// TODO(after): the linked docs page talks about *dynamic* APIs, which after soon won't be anymore
throw new Error(
'`after` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
......@@ -17,5 +19,5 @@ export function after<T>(task: AfterTask<T>): void {
}
const { afterContext } = workStore
return afterContext.after(task)
return afterContext.after(task, workUnitStore)
}
export { default } from '../../nodejs/nested-after-from-slow-promise/page'
import { after, connection } from 'next/server'
import { cliLog } from '../../../utils/log'
export default async function Page() {
await connection()
// This test checks if `after` callbacks scheduled from `after(promise)` are executed if
// - the promise resolves after the response ended
// - no `after(callback)` calls occurred before the response ended
// We had a bug where the after callback queue wouldn't start if no `after(callback)` calls occured during the response,
// so the callback scheduled from the promise would never run.
const promise = (async () => {
// hackily wait for the response to finish
await new Promise((resolve) => setTimeout(resolve, 500))
after(() => {
cliLog({
source: '[page] /nested-after-from-slow-promise',
})
})
})()
after(promise)
return <div>Page with nested after() called from a slow promise</div>
}
......@@ -96,6 +96,16 @@ describe.each(runtimes)('after() in %s runtime', (runtimeValue) => {
})
})
it('runs callbacks from nested after calls that happened within a slow promise', async () => {
await next.browser(pathPrefix + '/nested-after-from-slow-promise')
await retry(() => {
expect(getLogs()).toContainEqual({
source: `[page] /nested-after-from-slow-promise`,
})
})
})
describe('interrupted RSC renders', () => {
// This is currently broken with Turbopack.
// https://github.com/vercel/next.js/pull/75989
......
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