Skip to content

Commit

Permalink
unstable_after: support nested unstable_after calls (#65950)
Browse files Browse the repository at this point in the history
Adds support for nested `unstable_after()`.

This pattern previously threw a "Not supported yet" error, but works
now:

```js
function MyComponent() {
  after(() => asyncWork());
  return <div>...</div>
}

async function asyncWork() {
  after(() => { /* look ma, nesting!*/ })
  // more stuff...
}
```

### Implementation notes
Switched `AfterContext` to use a proper promise queue
([`p-queue`](https://www.npmjs.com/package/p-queue)) instead of plain a
callback array to support adding more callbacks as we execute (i.e. from
nested `after`s). Used a package because I didn't want to reinvent the
wheel here.

As a nice bonus, `p-queue` lets us limit the concurrency of running
tasks if we're worried about resource consumption. **This PR doesn't do
that**, but it's very easy to add. That could be controlled via
`process.env.NEXT_AFTER_MAX_CONCURRENT_TASKS`, a next.config.js option
(`unstable_after: { maxConcurrentTasks: 5 }`), or something like that.
  • Loading branch information
lubieowoce authored May 20, 2024
1 parent a142012 commit 663488c
Show file tree
Hide file tree
Showing 11 changed files with 192 additions and 33 deletions.
1 change: 1 addition & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@
"ora": "4.0.4",
"os-browserify": "0.3.0",
"p-limit": "3.1.0",
"p-queue": "6.6.2",
"path-browserify": "1.0.1",
"path-to-regexp": "6.1.0",
"picomatch": "4.0.1",
Expand Down
9 changes: 9 additions & 0 deletions packages/next/src/compiled/p-queue/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 change: 1 addition & 0 deletions packages/next/src/compiled/p-queue/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/next/src/compiled/p-queue/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"p-queue","main":"index.js","license":"MIT"}
61 changes: 61 additions & 0 deletions packages/next/src/server/after/after-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,67 @@ describe('createAfterContext', () => {
expect(results).toEqual([undefined])
})

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 afterContext = createAfterContext({
waitUntil,
onClose,
cacheScope: undefined,
})

const requestStore = createMockRequestStore(afterContext)
const run = createRun(afterContext, requestStore)

// ==================================

const promise1 = new DetachedPromise<string>()
const afterCallback1 = jest.fn(async () => {
await promise1.promise
after(afterCallback2)
})

const promise2 = new DetachedPromise<string>()
const afterCallback2 = jest.fn(() => promise2.promise)

await run(async () => {
after(afterCallback1)
expect(onClose).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1) // just runCallbacksOnClose
})

expect(onClose).toHaveBeenCalledTimes(1)
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()

// the response is done.
onCloseCallback!()
await Promise.resolve(null)

expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(0)
expect(waitUntil).toHaveBeenCalledTimes(1)

promise1.resolve('1')
await Promise.resolve(null)

expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1)
promise2.resolve('2')

const results = await Promise.all(waitUntilPromises)
expect(results).toEqual([
undefined, // callbacks all get collected into a big void promise
])
})

it('does not hang forever if onClose failed', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
Expand Down
62 changes: 29 additions & 33 deletions packages/next/src/server/after/after-context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import PromiseQueue from 'next/dist/compiled/p-queue'
import {
requestAsyncStorage,
type RequestStore,
Expand Down Expand Up @@ -30,12 +31,16 @@ export class AfterContextImpl implements AfterContext {

private requestStore: RequestStore | undefined

private afterCallbacks: AfterCallback[] = []
private runCallbacksOnClosePromise: Promise<void> | undefined
private callbackQueue: PromiseQueue

constructor({ waitUntil, onClose, cacheScope }: AfterContextOpts) {
this.waitUntil = waitUntil
this.onClose = onClose
this.cacheScope = cacheScope

this.callbackQueue = new PromiseQueue()
this.callbackQueue.pause()
}

public run<T>(requestStore: RequestStore, callback: () => T): T {
Expand Down Expand Up @@ -79,10 +84,26 @@ export class AfterContextImpl implements AfterContext {
'unstable_after: Missing `onClose` implementation'
)
}
if (this.afterCallbacks.length === 0) {
this.waitUntil(this.runCallbacksOnClose())

// this should only happen once.
if (!this.runCallbacksOnClosePromise) {
this.runCallbacksOnClosePromise = this.runCallbacksOnClose()
this.waitUntil(this.runCallbacksOnClosePromise)
}

const wrappedCallback = async () => {
try {
await callback()
} catch (err) {
// TODO(after): this is fine for now, but will need better intergration with our error reporting.
console.error(
'An error occurred in a function passed to `unstable_after()`:',
err
)
}
}
this.afterCallbacks.push(callback)

this.callbackQueue.add(wrappedCallback)
}

private async runCallbacksOnClose() {
Expand All @@ -91,24 +112,11 @@ export class AfterContextImpl implements AfterContext {
}

private async runCallbacks(requestStore: RequestStore): Promise<void> {
if (this.afterCallbacks.length === 0) return
if (this.callbackQueue.size === 0) return

const runCallbacksImpl = async () => {
// TODO(after): we should consider limiting the parallelism here via something like `p-queue`.
// (having a queue will also be needed for after-within-after, so this'd solve two problems at once).
await Promise.all(
this.afterCallbacks.map(async (afterCallback) => {
try {
await afterCallback()
} catch (err) {
// TODO(after): this is fine for now, but will need better intergration with our error reporting.
console.error(
'An error occurred in a function passed to `unstable_after()`:',
err
)
}
})
)
this.callbackQueue.start()
return this.callbackQueue.onIdle()
}

const readonlyRequestStore: RequestStore =
Expand Down Expand Up @@ -148,19 +156,7 @@ function wrapRequestStoreForAfterCallbacks(
mutableCookies: new ResponseCookies(new Headers()),
assetPrefix: requestStore.assetPrefix,
reactLoadableManifest: requestStore.reactLoadableManifest,

afterContext: {
after: () => {
throw new Error(
'Calling `unstable_after()` from within `unstable_after()` is not supported yet.'
)
},
run: () => {
throw new InvariantError(
'unstable_after: Cannot call `AfterContext.run()` from within an `unstable_after()` callback'
)
},
},
afterContext: requestStore.afterContext,
}
}

Expand Down
10 changes: 10 additions & 0 deletions packages/next/taskfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,15 @@ export async function ncc_p_limit(task, opts) {
.target('src/compiled/p-limit')
}

// eslint-disable-next-line camelcase
externals['p-queue'] = 'next/dist/compiled/p-queue'
export async function ncc_p_queue(task, opts) {
await task
.source(relative(__dirname, require.resolve('p-queue')))
.ncc({ packageName: 'p-queue', externals })
.target('src/compiled/p-queue')
}

// eslint-disable-next-line camelcase
externals['raw-body'] = 'next/dist/compiled/raw-body'
export async function ncc_raw_body(task, opts) {
Expand Down Expand Up @@ -2171,6 +2180,7 @@ export async function ncc(task, opts) {
'ncc_node_html_parser',
'ncc_napirs_triples',
'ncc_p_limit',
'ncc_p_queue',
'ncc_raw_body',
'ncc_image_size',
'ncc_hapi_accept',
Expand Down
5 changes: 5 additions & 0 deletions packages/next/types/$$compiled.internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ declare module 'next/dist/compiled/p-limit' {
export = m
}

declare module 'next/dist/compiled/p-queue' {
import m from 'p-queue'
export = m
}

declare module 'next/dist/compiled/raw-body' {
import m from 'raw-body'
export = m
Expand Down
5 changes: 5 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 663488c

Please sign in to comment.