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."
}
......@@ -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