Commit 20f5a79c authored by Janka Uryga's avatar Janka Uryga

fix: don't memory-leak promises passed to `waitUntil` (#75041)

### Overview

`next start` stores pending promises passed to `waitUntil` so that we
can await them before a (graceful) server shutdown and avoid
interrupting work that's still running.
The problem here was that this set lives a long time (the whole lifetime
of the server), but we weren't removing resolved promises from this set,
so we'd end up holding onto them forever and leaking memory.

This bug would be triggered by any code using `waitUntil` in `next
start` (notably, a recent change:
https://github.com/vercel/next.js/pull/74164)

### Details 
The bug here is that `AwaiterMulti` would hold onto resolved promises
indefinitely. `AwaiterMulti` ends up being used by
`NextNodeServer.getInternalWaitUntil`, which is what provides
`waitUntil` in `next start`.

The code was already attempting to clean up promises to avoid leaks. But
the problem was that we weren't adding `promise` to `this.promises`, we
were adding `promise.then(...)` which is a completely different object.
So the `this.promises.delete(promise)` that `cleanup` did was
effectively doing nothing, and `this.promises` would keep growing.
parent 47102cae
...@@ -15,24 +15,25 @@ export class AwaiterMulti { ...@@ -15,24 +15,25 @@ export class AwaiterMulti {
} }
public waitUntil = (promise: Promise<unknown>): void => { public waitUntil = (promise: Promise<unknown>): void => {
// if a promise settles before we await it, we can drop it. // if a promise settles before we await it, we should drop it --
// storing them indefinitely could result in a memory leak.
const cleanup = () => { const cleanup = () => {
this.promises.delete(promise) this.promises.delete(promise)
} }
this.promises.add( promise.then(cleanup, (err) => {
promise.then(cleanup, (err) => { cleanup()
cleanup() this.onError(err)
this.onError(err) })
})
) this.promises.add(promise)
} }
public async awaiting(): Promise<void> { public async awaiting(): Promise<void> {
while (this.promises.size > 0) { while (this.promises.size > 0) {
const promises = Array.from(this.promises) const promises = Array.from(this.promises)
this.promises.clear() this.promises.clear()
await Promise.all(promises) await Promise.allSettled(promises)
} }
} }
} }
......
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