File size: 2,441 Bytes
b2cad4f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | diff --git a/packages/next/src/server/web/sandbox/resource-managers.ts b/packages/next/src/server/web/sandbox/resource-managers.ts
index fb5096b4bf..91874d3a30 100644
--- a/packages/next/src/server/web/sandbox/resource-managers.ts
+++ b/packages/next/src/server/web/sandbox/resource-managers.ts
@@ -1,23 +1,34 @@
abstract class ResourceManager<T, Args> {
- private resources: T[] = []
+ private resources = new Set<T>()
abstract create(resourceArgs: Args): T
abstract destroy(resource: T): void
add(resourceArgs: Args) {
const resource = this.create(resourceArgs)
- this.resources.push(resource)
+ this.resources.add(resource)
return resource
}
remove(resource: T) {
- this.resources = this.resources.filter((r) => r !== resource)
+ this.untrack(resource)
this.destroy(resource)
}
+ /**
+ * Stop tracking a resource without destroying it. Used when a resource has
+ * already been released by other means (e.g. a one-shot timeout that ran to
+ * completion) so it should no longer be retained by this manager.
+ */
+ protected untrack(resource: T) {
+ this.resources.delete(resource)
+ }
+
removeAll() {
- this.resources.forEach(this.destroy)
- this.resources = []
+ for (const resource of this.resources) {
+ this.destroy(resource)
+ }
+ this.resources.clear()
}
}
@@ -41,7 +52,29 @@ class TimeoutsManager extends ResourceManager<
> {
create(args: Parameters<typeof webSetTimeoutPolyfill>) {
// TODO: use the edge runtime provided `setTimeout` instead
- return webSetTimeoutPolyfill(...args)
+ const [globalObject, callback, ms, ...rest] = args
+
+ // A one-shot timeout releases itself from tracking once its callback has
+ // run. Otherwise fire-and-forget timeouts (whose ids user code never
+ // passes to `clearTimeout`) would accumulate for the lifetime of the
+ // module context and leak memory in long-lived server processes.
+ // See: https://github.com/vercel/next.js/issues/95094
+ let timeoutId: number
+ const callbackWithRelease = (...callbackArgs: typeof rest) => {
+ try {
+ return callback.apply(globalObject, callbackArgs)
+ } finally {
+ this.untrack(timeoutId)
+ }
+ }
+
+ timeoutId = webSetTimeoutPolyfill(
+ globalObject,
+ callbackWithRelease,
+ ms,
+ ...rest
+ )
+ return timeoutId
}
destroy(timeout: number) {
|