Open History to see the last commit
1/**
2 * Resources one plugin owns for one lifetime (a session or a turn).
3 *
4 * - `acquire(open, close)` registers `close` only after `open` succeeds.
5 * - If the scope closes while `open` is still running, the late resource is
6 * closed as soon as it arrives.
7 * - `dispose()` closes resources newest first, runs every closer even when
8 * one throws, and returns the same promise to every caller.
9 */
10export class ResourceScope {
11 private readonly controller = new AbortController()
12 readonly signal: AbortSignal = this.controller.signal
13 private readonly closers: Array<() => unknown> = []
14 private closing?: Promise<void>
15 private closed = false
16
17 async acquire<T>(
18 open: () => T | Promise<T>,
19 close: (resource: T) => unknown,
20 ): Promise<T> {
21 this.signal.throwIfAborted()
22 const resource = await open()
23 if (this.closed) {
24 await close(resource)
25 throw this.signal.reason
26 }
27 this.closers.push(() => close(resource))
28 return resource
29 }
30
31 dispose(): Promise<void> {
32 if (this.closing) return this.closing
33 this.closed = true
34 this.controller.abort(new Error('Resource scope disposed'))
35 // Defer, so a closer that calls dispose() again gets the same promise.
36 // An `open` still running is not awaited: `acquire` closes its resource
37 // when it arrives, so an `open` that ignores `signal` cannot hang this.
38 this.closing = Promise.resolve().then(async () => {
39 const errors: Array<unknown> = []
40 for (const close of this.closers.reverse()) {
41 try {
42 await close()
43 } catch (error) {
44 errors.push(error)
45 }
46 }
47 this.closers.length = 0
48 if (errors.length > 0) {
49 throw new AggregateError(errors, 'Resource cleanup failed')
50 }
51 })
52 return this.closing
53 }
54}
55
56/**
57 * Dispose scopes newest first. Every scope is disposed even when one fails.
58 * Throws an `AggregateError` with every failure, after all scopes ran.
59 */
60export async function disposeAll(
61 scopes: ReadonlyArray<ResourceScope>,
62): Promise<void> {
63 const errors: Array<unknown> = []
64 for (const scope of [...scopes].reverse()) {
65 try {
66 await scope.dispose()
67 } catch (error) {
68 errors.push(error)
69 }
70 }
71 if (errors.length > 0) {
72 throw new AggregateError(errors, 'Plugin cleanup failed')
73 }
74}