@orkestrel/pool 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/core/index.cjs +25 -15
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.js +25 -15
- package/dist/src/core/index.js.map +1 -1
- package/package.json +17 -14
package/dist/src/core/index.cjs
CHANGED
|
@@ -57,8 +57,8 @@ var Pool = class {
|
|
|
57
57
|
this.#validate = options.validate;
|
|
58
58
|
this.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY);
|
|
59
59
|
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
60
|
-
on: options
|
|
61
|
-
error: options
|
|
60
|
+
...options.on !== void 0 ? { on: options.on } : {},
|
|
61
|
+
...options.error !== void 0 ? { error: options.error } : {}
|
|
62
62
|
});
|
|
63
63
|
}
|
|
64
64
|
get emitter() {
|
|
@@ -137,29 +137,39 @@ var Pool = class {
|
|
|
137
137
|
const waiter = {
|
|
138
138
|
resolve,
|
|
139
139
|
reject,
|
|
140
|
-
clear:
|
|
140
|
+
clear: this.#ignore
|
|
141
141
|
};
|
|
142
142
|
this.#waiters.push(waiter);
|
|
143
143
|
if (signal !== void 0) {
|
|
144
|
-
const onAbort = ()
|
|
145
|
-
const index = this.#waiters.indexOf(waiter);
|
|
146
|
-
if (index >= 0) this.#waiters.splice(index, 1);
|
|
147
|
-
reject(signal.reason);
|
|
148
|
-
};
|
|
144
|
+
const onAbort = this.#createAbort(signal, waiter);
|
|
149
145
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
150
|
-
waiter.clear = (
|
|
146
|
+
waiter.clear = this.#createClear(signal, onAbort);
|
|
151
147
|
}
|
|
152
148
|
});
|
|
153
149
|
}
|
|
154
150
|
#token(resource) {
|
|
155
|
-
let released = false;
|
|
156
151
|
return {
|
|
157
152
|
value: resource,
|
|
158
|
-
release: ()
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
153
|
+
release: this.#createRelease(resource)
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
#ignore() {}
|
|
157
|
+
#createAbort(signal, waiter) {
|
|
158
|
+
return () => {
|
|
159
|
+
const index = this.#waiters.indexOf(waiter);
|
|
160
|
+
if (index >= 0) this.#waiters.splice(index, 1);
|
|
161
|
+
waiter.reject(signal.reason);
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
#createClear(signal, onAbort) {
|
|
165
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
166
|
+
}
|
|
167
|
+
#createRelease(resource) {
|
|
168
|
+
let released = false;
|
|
169
|
+
return () => {
|
|
170
|
+
if (released) return;
|
|
171
|
+
released = true;
|
|
172
|
+
this.#return(resource);
|
|
163
173
|
};
|
|
164
174
|
}
|
|
165
175
|
#return(resource) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#create","#destroy","#validate","#max","#emitter","#idle","#waiters","#active","#destroyed","#reuse","#grow","#wait","#release","#valid","#token","#return","#handoff","#serve"],"sources":["../../../src/core/Pool.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { PoolEventMap, PoolInterface, PoolOptions, PoolToken, PoolWaiter } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\n\n/**\n * A bounded resource pool with idle reuse + FIFO waiting.\n *\n * @remarks\n * - **Idle reuse.** `acquire` first takes an idle resource (validating it when a\n * `validate` hook is set — an invalid one is destroyed and the next idle / a fresh\n * one is tried). When no usable idle resource exists and the pool is below `max`, it\n * `create`s a new one. At `max` with none idle, the acquire PARKS on a FIFO waiter\n * list until a `release` hands it a resource.\n * - **FIFO handoff (validated).** `release` (on the token) hands the resource to the next\n * parked waiter (oldest first) — the resource stays leased, the lessee just changes —\n * or returns it to idle when no one is waiting. With a waiter parked the resource is\n * re-validated first (the same `validate` hook the idle path uses), so a resource that\n * went invalid WHILE leased (e.g. a terminated worker thread) is destroyed and the\n * waiter is served a fresh/valid one instead — a dead resource is never handed on. The\n * no-waiter path stays synchronous; releasing the same token twice is a no-op (an\n * idempotent token guard).\n * - **`validate` is total.** A `validate` hook that THROWS is treated exactly like one\n * returning `false` — the resource is \"not usable\", so it is destroyed and replaced —\n * rather than escaping. This holds on both the idle reuse and the FIFO handoff paths, so\n * a throwing validator can never strand a parked waiter on an unhandled rejection.\n * - **Abort-cancellable waiting.** A parked `acquire` given an `AbortSignal` rejects\n * when that signal fires and removes its waiter from the queue — no leaked waiter, so\n * a later `release` still serves the next live waiter. The signal is supplied by the\n * caller (a worker, for example, passes its per-attempt execution signal); the pool adds no abort\n * of its own.\n * - **Counts.** `size` = idle + leased; `idle` = available now; `active` = leased out.\n * - **Teardown.** `clear` destroys every IDLE resource (leased ones keep running);\n * `destroy` destroys ALL resources and rejects any parked waiters. Both await the\n * `destroy` hook.\n * - **Observable (§13).** The owned {@link emitter} ({@link PoolEventMap}) carries the\n * resource lifecycle — `create` / `acquire` / `release` / `destroy` — for fire-and-forget\n * observers. Every event is emitted directly, strictly AFTER the relevant transition —\n * OUTSIDE the `#handoff` / `#serve` await-chain, never across a waiter's resolve; the\n * emitter isolates a listener throw and routes it to its `error` handler (the `error`\n * option), so a buggy observer can NEVER corrupt the validated FIFO handoff-eviction\n * machinery (it cannot strand a parked waiter or unbalance the lease count). Observation is\n * purely a side-channel.\n * - **De-bloated.** No warm-floor / `min`, no eviction timers — lean.\n */\nexport class Pool<T> implements PoolInterface<T> {\n\treadonly #create: () => Promise<T> | T\n\treadonly #destroy: ((value: T) => Promise<void> | void) | undefined\n\treadonly #validate: ((value: T) => Promise<boolean> | boolean) | undefined\n\treadonly #max: number\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// validated FIFO handoff-eviction path.\n\treadonly #emitter: Emitter<PoolEventMap>\n\n\treadonly #idle: T[] = []\n\treadonly #waiters: PoolWaiter<T>[] = []\n\t#active = 0\n\t#destroyed = false\n\n\tconstructor(options: PoolOptions<T>) {\n\t\tthis.#create = options.create\n\t\tthis.#destroy = options.destroy\n\t\tthis.#validate = options.validate\n\t\tthis.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY)\n\t\tthis.#emitter = new Emitter<PoolEventMap>({ on: options?.on, error: options?.error })\n\t}\n\n\tget emitter(): EmitterInterface<PoolEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\treturn this.#idle.length + this.#active\n\t}\n\n\tget idle(): number {\n\t\treturn this.#idle.length\n\t}\n\n\tget active(): number {\n\t\treturn this.#active\n\t}\n\n\tasync acquire(signal?: AbortSignal): Promise<PoolToken<T>> {\n\t\tif (this.#destroyed) throw new Error('pool is destroyed')\n\t\tif (signal?.aborted === true) throw signal.reason\n\t\t// Reuse a validated idle resource if one is available.\n\t\tconst reused = await this.#reuse()\n\t\tif (reused !== undefined) {\n\t\t\t// Observe the lease — AFTER `#reuse` resolved the token (the resource is already\n\t\t\t// leased; emit only OBSERVES it).\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn reused\n\t\t}\n\t\t// Otherwise grow the pool when below the cap.\n\t\tif (this.size < this.#max) {\n\t\t\tconst grown = await this.#grow()\n\t\t\t// Observe the lease — AFTER `#grow` resolved the fresh token.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn grown\n\t\t}\n\t\t// At capacity with nothing idle — park until a release hands us a resource. The\n\t\t// `acquire` for THIS lease is emitted by `#serve` once a `release` hands it a resource\n\t\t// (after `waiter.resolve`), NOT here — so a served waiter emits `acquire` exactly once.\n\t\treturn await this.#wait(signal)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tconst waiters = this.#waiters.splice(0)\n\t\tconst error = new Error('pool is destroyed')\n\t\tfor (const waiter of waiters) {\n\t\t\twaiter.clear()\n\t\t\twaiter.reject(error)\n\t\t}\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\t// Take + validate the next idle resource; destroy + skip invalid ones. Returns a\n\t// token for the first valid idle resource, or `undefined` when none is usable.\n\tasync #reuse(): Promise<PoolToken<T> | undefined> {\n\t\twhile (this.#idle.length > 0) {\n\t\t\tconst resource = this.#idle.shift()\n\t\t\tif (resource === undefined) continue\n\t\t\tif (await this.#valid(resource)) {\n\t\t\t\tthis.#active += 1\n\t\t\t\treturn this.#token(resource)\n\t\t\t}\n\t\t\tawait this.#release(resource)\n\t\t}\n\t\treturn undefined\n\t}\n\n\t// Create a fresh resource and lease it. Reserve the active slot before awaiting\n\t// `create` so a concurrent acquire sees the pool at capacity (no overshoot of `max`).\n\tasync #grow(): Promise<PoolToken<T>> {\n\t\tthis.#active += 1\n\t\tlet resource: T\n\t\ttry {\n\t\t\tresource = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\tthis.#active -= 1\n\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t}\n\t\t// The pool may have been destroyed during `create` — never hand a live resource into\n\t\t// a torn-down pool. Free the active slot, destroy the just-created resource, and throw.\n\t\tif (this.#destroyed) {\n\t\t\tthis.#active -= 1\n\t\t\tawait this.#release(resource)\n\t\t\tthrow new Error('pool is destroyed')\n\t\t}\n\t\t// Observe the fresh resource — AFTER `create` resolved and the not-destroyed re-check\n\t\t// passed (the resource is here to stay), BEFORE the token is built.\n\t\tthis.#emitter.emit('create')\n\t\treturn this.#token(resource)\n\t}\n\n\t// Park a resolver on the FIFO waiter list until a release hands it a resource; an\n\t// abort on `signal` rejects the acquire and removes its waiter (no leak).\n\t#wait(signal: AbortSignal | undefined): Promise<PoolToken<T>> {\n\t\treturn new Promise<PoolToken<T>>((resolve, reject) => {\n\t\t\tconst waiter: PoolWaiter<T> = { resolve, reject, clear: () => {} }\n\t\t\tthis.#waiters.push(waiter)\n\t\t\tif (signal !== undefined) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tconst index = this.#waiters.indexOf(waiter)\n\t\t\t\t\tif (index >= 0) this.#waiters.splice(index, 1)\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t}\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\twaiter.clear = (): void => signal.removeEventListener('abort', onAbort)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Build an idempotent token; its `release` returns the resource exactly once.\n\t#token(resource: T): PoolToken<T> {\n\t\tlet released = false\n\t\treturn {\n\t\t\tvalue: resource,\n\t\t\trelease: (): void => {\n\t\t\t\tif (released) return\n\t\t\t\treleased = true\n\t\t\t\tthis.#return(resource)\n\t\t\t},\n\t\t}\n\t}\n\n\t// Return a leased resource. No waiter parked → synchronously drop it to idle (or destroy\n\t// it if torn down), `#active -= 1`. A waiter IS parked → hand off asynchronously, after\n\t// re-validating the resource so an invalid one (e.g. a terminated thread) is never served.\n\t#return(resource: T): void {\n\t\tif (this.#waiters.length === 0) {\n\t\t\tthis.#active -= 1\n\t\t\tif (this.#destroyed) {\n\t\t\t\tvoid this.#release(resource)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#idle.push(resource)\n\t\t\t// Observe the resource dropping to idle — AFTER `#active` was balanced down and it\n\t\t\t// is back on the idle list (the synchronous no-waiter path). A waiter-handoff\n\t\t\t// instead keeps the resource LEASED, so it emits no `release` here.\n\t\t\tthis.#emitter.emit('release')\n\t\t\treturn\n\t\t}\n\t\tvoid this.#handoff(resource)\n\t}\n\n\t// Hand a released resource to the oldest parked waiter, re-validating it first. A VALID\n\t// resource is served as-is (it stays leased — `#active` unchanged). An INVALID one is\n\t// destroyed and the waiter is served a fresh resource that REUSES the dead one's `#active`\n\t// slot (the count never dips below the lease, so a concurrent acquire can't overshoot\n\t// `max`). The waiter is re-shifted after every `await` (the queue can change underneath\n\t// us), and the pool is re-checked for teardown — so no waiter is leaked or double-settled\n\t// and no resource is handed into a destroyed pool.\n\tasync #handoff(resource: T): Promise<void> {\n\t\t// VALID release → serve the released resource directly (the common, unchanged path).\n\t\tif (await this.#valid(resource)) {\n\t\t\tthis.#serve(resource)\n\t\t\treturn\n\t\t}\n\t\t// INVALID release → destroy it and replace it, holding its `#active` slot steady.\n\t\tvoid this.#release(resource)\n\t\tlet replacement: T\n\t\ttry {\n\t\t\treplacement = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\t// The dead resource cannot be replaced — free its slot and reject the oldest waiter\n\t\t\t// (it can't be served), or drop the error if the queue raced empty.\n\t\t\tthis.#active -= 1\n\t\t\tconst waiter = this.#waiters.shift()\n\t\t\twaiter?.clear()\n\t\t\twaiter?.reject(error instanceof Error ? error : new Error(String(error)))\n\t\t\treturn\n\t\t}\n\t\t// Observe the fresh replacement — AFTER `create` resolved, BEFORE it is served.\n\t\tthis.#emitter.emit('create')\n\t\tthis.#serve(replacement)\n\t}\n\n\t// Hand a validated resource (the released one, or its fresh replacement) to the oldest\n\t// live waiter, holding its `#active` slot. If the queue raced empty across the awaits, the\n\t// resource is idle (or destroyed when torn down) and its slot is freed.\n\t#serve(resource: T): void {\n\t\tconst waiter = this.#destroyed ? undefined : this.#waiters.shift()\n\t\tif (waiter !== undefined) {\n\t\t\twaiter.clear()\n\t\t\twaiter.resolve(this.#token(resource))\n\t\t\t// Observe the served-waiter lease — strictly AFTER `waiter.resolve(...)` (the token\n\t\t\t// is already handed off; the emit only OBSERVES it and cannot sit across the resolve\n\t\t\t// or perturb the served acquirer's continuation). This is the `acquire` for a parked\n\t\t\t// `acquire`, so the public `acquire` deliberately does NOT emit on its `#wait` branch.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn\n\t\t}\n\t\tthis.#active -= 1\n\t\tif (this.#destroyed) {\n\t\t\tvoid this.#release(resource)\n\t\t\treturn\n\t\t}\n\t\tthis.#idle.push(resource)\n\t\t// The waiter queue raced empty across the handoff awaits — the resource lands back on\n\t\t// idle instead of being leased. Observe that as a `release` (the return-to-idle that\n\t\t// `#return` would have emitted had no waiter been parked when the token was released).\n\t\tthis.#emitter.emit('release')\n\t}\n\n\t// Is this resource usable? No validator trusts it; otherwise run the hook. A validator\n\t// that THROWS is treated exactly like one returning `false` — the resource is \"not\n\t// usable\", so it is destroyed + replaced rather than escaping as an unhandled rejection\n\t// that would strand a parked waiter on the handoff path (the same total-function spirit\n\t// as a guard, AGENTS §12 / §14). The single gate for both the idle (`#reuse`) and the\n\t// handoff (`#handoff`) validation, so the two paths can never diverge.\n\tasync #valid(resource: T): Promise<boolean> {\n\t\tif (this.#validate === undefined) return true\n\t\ttry {\n\t\t\treturn await this.#validate(resource)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Destroy one resource via the optional hook, swallowing destruction failures. Observe the\n\t// drop with a `destroy` event AFTER the hook ran (or after the no-hook drop) — the resource\n\t// is gone from the pool either way; a swallowed `destroy`-hook failure still emits (the pool\n\t// abandoned it). The emit is the LAST thing here, strictly after the teardown transition.\n\tasync #release(resource: T): Promise<void> {\n\t\tif (this.#destroy === undefined) {\n\t\t\tthis.#emitter.emit('destroy')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.#destroy(resource)\n\t\t} catch {\n\t\t\t// A destroy failure abandons the resource — there is nothing to recover.\n\t\t}\n\t\tthis.#emitter.emit('destroy')\n\t}\n}\n","import type { PoolInterface, PoolOptions } from './types.js'\nimport { Pool } from './Pool.js'\n\n/**\n * Create a bounded resource pool with idle reuse and FIFO waiting — `acquire` leases a\n * resource (reusing a validated idle one, growing up to `max`, or parking until a\n * `release` frees one) and the returned token's `release` returns it for reuse.\n *\n * @remarks\n * A parked `acquire` given an `AbortSignal` rejects + de-queues itself when the signal\n * fires (no leaked waiter). `clear` destroys idle resources (leased ones keep running);\n * `destroy` destroys all and rejects waiters. The pool is lean — no warm-floor (`min`),\n * no eviction timers — and observable (§13): a typed `emitter` surfaces\n * `create` / `acquire` / `release` / `destroy`.\n *\n * @typeParam T - The pooled resource type\n * @param options - The `create` hook plus optional `destroy` / `validate` / `max`\n * @returns A working {@link PoolInterface}\n *\n * @example\n * ```ts\n * import { createPool } from '@src/core'\n *\n * const pool = createPool<Connection>({\n * \tcreate: () => connect(),\n * \tdestroy: (connection) => connection.close(),\n * \tvalidate: (connection) => connection.alive,\n * \tmax: 8,\n * })\n *\n * const token = await pool.acquire()\n * try {\n * \tawait token.value.query('select 1')\n * } finally {\n * \ttoken.release()\n * }\n * ```\n */\nexport function createPool<T>(options: PoolOptions<T>): PoolInterface<T> {\n\treturn new Pool(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,OAAb,MAAiD;CAChD;CACA;CACA;CACA;CAIA;CAEA,QAAsB,CAAC;CACvB,WAAqC,CAAC;CACtC,UAAU;CACV,aAAa;CAEb,YAAY,SAAyB;EACpC,KAAKA,UAAU,QAAQ;EACvB,KAAKC,WAAW,QAAQ;EACxB,KAAKC,YAAY,QAAQ;EACzB,KAAKC,OAAO,KAAK,IAAI,GAAG,QAAQ,OAAO,OAAO,iBAAiB;EAC/D,KAAKC,WAAW,IAAI,mBAAA,QAAsB;GAAE,IAAI,SAAS;GAAI,OAAO,SAAS;EAAM,CAAC;CACrF;CAEA,IAAI,UAA0C;EAC7C,OAAO,KAAKA;CACb;CAEA,IAAI,OAAe;EAClB,OAAO,KAAKC,MAAM,SAAS,KAAKE;CACjC;CAEA,IAAI,OAAe;EAClB,OAAO,KAAKF,MAAM;CACnB;CAEA,IAAI,SAAiB;EACpB,OAAO,KAAKE;CACb;CAEA,MAAM,QAAQ,QAA6C;EAC1D,IAAI,KAAKC,YAAY,MAAM,IAAI,MAAM,mBAAmB;EACxD,IAAI,QAAQ,YAAY,MAAM,MAAM,OAAO;EAE3C,MAAM,SAAS,MAAM,KAAKC,OAAO;EACjC,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,SAAS,OAAgB;GAGxB,KAAKO,WAAW;GAChB,MAAM,SAAS,KAAKD,SAAS,MAAM;GACnC,QAAQ,MAAM;GACd,QAAQ,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;GACxE;EACD;EAEA,KAAKF,SAAS,KAAK,QAAQ;EAC3B,KAAKa,OAAO,WAAW;CACxB;CAKA,OAAO,UAAmB;EACzB,MAAM,SAAS,KAAKT,aAAa,KAAA,IAAY,KAAKF,SAAS,MAAM;EACjE,IAAI,WAAW,KAAA,GAAW;GACzB,OAAO,MAAM;GACb,OAAO,QAAQ,KAAKQ,OAAO,QAAQ,CAAC;GAKpC,KAAKV,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,KAAKG,WAAW;EAChB,IAAI,KAAKC,YAAY;GACpB,KAAUI,SAAS,QAAQ;GAC3B;EACD;EACA,KAAKP,MAAM,KAAK,QAAQ;EAIxB,KAAKD,SAAS,KAAK,SAAS;CAC7B;CAQA,MAAMS,OAAO,UAA+B;EAC3C,IAAI,KAAKX,cAAc,KAAA,GAAW,OAAO;EACzC,IAAI;GACH,OAAO,MAAM,KAAKA,UAAU,QAAQ;EACrC,QAAQ;GACP,OAAO;EACR;CACD;CAMA,MAAMU,SAAS,UAA4B;EAC1C,IAAI,KAAKX,aAAa,KAAA,GAAW;GAChC,KAAKG,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,IAAI;GACH,MAAM,KAAKH,SAAS,QAAQ;EAC7B,QAAQ,CAER;EACA,KAAKG,SAAS,KAAK,SAAS;CAC7B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3QA,SAAgB,WAAc,SAA2C;CACxE,OAAO,IAAI,KAAK,OAAO;AACxB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#create","#destroy","#validate","#max","#emitter","#idle","#waiters","#active","#destroyed","#reuse","#grow","#wait","#release","#valid","#token","#ignore","#createAbort","#createClear","#createRelease","#return","#handoff","#serve"],"sources":["../../../src/core/Pool.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { PoolEventMap, PoolInterface, PoolOptions, PoolToken, PoolWaiter } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\n\n/**\n * A bounded resource pool with idle reuse + FIFO waiting.\n *\n * @remarks\n * - **Idle reuse.** `acquire` first takes an idle resource (validating it when a\n * `validate` hook is set — an invalid one is destroyed and the next idle / a fresh\n * one is tried). When no usable idle resource exists and the pool is below `max`, it\n * `create`s a new one. At `max` with none idle, the acquire PARKS on a FIFO waiter\n * list until a `release` hands it a resource.\n * - **FIFO handoff (validated).** `release` (on the token) hands the resource to the next\n * parked waiter (oldest first) — the resource stays leased, the lessee just changes —\n * or returns it to idle when no one is waiting. With a waiter parked the resource is\n * re-validated first (the same `validate` hook the idle path uses), so a resource that\n * went invalid WHILE leased (e.g. a terminated worker thread) is destroyed and the\n * waiter is served a fresh/valid one instead — a dead resource is never handed on. The\n * no-waiter path stays synchronous; releasing the same token twice is a no-op (an\n * idempotent token guard).\n * - **`validate` is total.** A `validate` hook that THROWS is treated exactly like one\n * returning `false` — the resource is \"not usable\", so it is destroyed and replaced —\n * rather than escaping. This holds on both the idle reuse and the FIFO handoff paths, so\n * a throwing validator can never strand a parked waiter on an unhandled rejection.\n * - **Abort-cancellable waiting.** A parked `acquire` given an `AbortSignal` rejects\n * when that signal fires and removes its waiter from the queue — no leaked waiter, so\n * a later `release` still serves the next live waiter. The signal is supplied by the\n * caller (a worker, for example, passes its per-attempt execution signal); the pool adds no abort\n * of its own.\n * - **Counts.** `size` = idle + leased; `idle` = available now; `active` = leased out.\n * - **Teardown.** `clear` destroys every IDLE resource (leased ones keep running);\n * `destroy` destroys ALL resources and rejects any parked waiters. Both await the\n * `destroy` hook.\n * - **Observable (§13).** The owned {@link emitter} ({@link PoolEventMap}) carries the\n * resource lifecycle — `create` / `acquire` / `release` / `destroy` — for fire-and-forget\n * observers. Every event is emitted directly, strictly AFTER the relevant transition —\n * OUTSIDE the `#handoff` / `#serve` await-chain, never across a waiter's resolve; the\n * emitter isolates a listener throw and routes it to its `error` handler (the `error`\n * option), so a buggy observer can NEVER corrupt the validated FIFO handoff-eviction\n * machinery (it cannot strand a parked waiter or unbalance the lease count). Observation is\n * purely a side-channel.\n * - **De-bloated.** No warm-floor / `min`, no eviction timers — lean.\n */\nexport class Pool<T> implements PoolInterface<T> {\n\treadonly #create: () => Promise<T> | T\n\treadonly #destroy: ((value: T) => Promise<void> | void) | undefined\n\treadonly #validate: ((value: T) => Promise<boolean> | boolean) | undefined\n\treadonly #max: number\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// validated FIFO handoff-eviction path.\n\treadonly #emitter: Emitter<PoolEventMap>\n\n\treadonly #idle: T[] = []\n\treadonly #waiters: PoolWaiter<T>[] = []\n\t#active = 0\n\t#destroyed = false\n\n\tconstructor(options: PoolOptions<T>) {\n\t\tthis.#create = options.create\n\t\tthis.#destroy = options.destroy\n\t\tthis.#validate = options.validate\n\t\tthis.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY)\n\t\tthis.#emitter = new Emitter<PoolEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<PoolEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\treturn this.#idle.length + this.#active\n\t}\n\n\tget idle(): number {\n\t\treturn this.#idle.length\n\t}\n\n\tget active(): number {\n\t\treturn this.#active\n\t}\n\n\tasync acquire(signal?: AbortSignal): Promise<PoolToken<T>> {\n\t\tif (this.#destroyed) throw new Error('pool is destroyed')\n\t\tif (signal?.aborted === true) throw signal.reason\n\t\t// Reuse a validated idle resource if one is available.\n\t\tconst reused = await this.#reuse()\n\t\tif (reused !== undefined) {\n\t\t\t// Observe the lease — AFTER `#reuse` resolved the token (the resource is already\n\t\t\t// leased; emit only OBSERVES it).\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn reused\n\t\t}\n\t\t// Otherwise grow the pool when below the cap.\n\t\tif (this.size < this.#max) {\n\t\t\tconst grown = await this.#grow()\n\t\t\t// Observe the lease — AFTER `#grow` resolved the fresh token.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn grown\n\t\t}\n\t\t// At capacity with nothing idle — park until a release hands us a resource. The\n\t\t// `acquire` for THIS lease is emitted by `#serve` once a `release` hands it a resource\n\t\t// (after `waiter.resolve`), NOT here — so a served waiter emits `acquire` exactly once.\n\t\treturn await this.#wait(signal)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tconst waiters = this.#waiters.splice(0)\n\t\tconst error = new Error('pool is destroyed')\n\t\tfor (const waiter of waiters) {\n\t\t\twaiter.clear()\n\t\t\twaiter.reject(error)\n\t\t}\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\t// Take + validate the next idle resource; destroy + skip invalid ones. Returns a\n\t// token for the first valid idle resource, or `undefined` when none is usable.\n\tasync #reuse(): Promise<PoolToken<T> | undefined> {\n\t\twhile (this.#idle.length > 0) {\n\t\t\tconst resource = this.#idle.shift()\n\t\t\tif (resource === undefined) continue\n\t\t\tif (await this.#valid(resource)) {\n\t\t\t\tthis.#active += 1\n\t\t\t\treturn this.#token(resource)\n\t\t\t}\n\t\t\tawait this.#release(resource)\n\t\t}\n\t\treturn undefined\n\t}\n\n\t// Create a fresh resource and lease it. Reserve the active slot before awaiting\n\t// `create` so a concurrent acquire sees the pool at capacity (no overshoot of `max`).\n\tasync #grow(): Promise<PoolToken<T>> {\n\t\tthis.#active += 1\n\t\tlet resource: T\n\t\ttry {\n\t\t\tresource = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\tthis.#active -= 1\n\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t}\n\t\t// The pool may have been destroyed during `create` — never hand a live resource into\n\t\t// a torn-down pool. Free the active slot, destroy the just-created resource, and throw.\n\t\tif (this.#destroyed) {\n\t\t\tthis.#active -= 1\n\t\t\tawait this.#release(resource)\n\t\t\tthrow new Error('pool is destroyed')\n\t\t}\n\t\t// Observe the fresh resource — AFTER `create` resolved and the not-destroyed re-check\n\t\t// passed (the resource is here to stay), BEFORE the token is built.\n\t\tthis.#emitter.emit('create')\n\t\treturn this.#token(resource)\n\t}\n\n\t// Park a resolver on the FIFO waiter list until a release hands it a resource; an\n\t// abort on `signal` rejects the acquire and removes its waiter (no leak).\n\t#wait(signal: AbortSignal | undefined): Promise<PoolToken<T>> {\n\t\treturn new Promise<PoolToken<T>>((resolve, reject) => {\n\t\t\tconst waiter: PoolWaiter<T> = { resolve, reject, clear: this.#ignore }\n\t\t\tthis.#waiters.push(waiter)\n\t\t\tif (signal !== undefined) {\n\t\t\t\tconst onAbort = this.#createAbort(signal, waiter)\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\twaiter.clear = this.#createClear(signal, onAbort)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Build an idempotent token; its `release` returns the resource exactly once.\n\t#token(resource: T): PoolToken<T> {\n\t\treturn { value: resource, release: this.#createRelease(resource) }\n\t}\n\n\t#ignore(): void {}\n\n\t#createAbort(signal: AbortSignal, waiter: PoolWaiter<T>): () => void {\n\t\treturn (): void => {\n\t\t\tconst index = this.#waiters.indexOf(waiter)\n\t\t\tif (index >= 0) this.#waiters.splice(index, 1)\n\t\t\twaiter.reject(signal.reason)\n\t\t}\n\t}\n\n\t#createClear(signal: AbortSignal, onAbort: () => void): () => void {\n\t\treturn (): void => signal.removeEventListener('abort', onAbort)\n\t}\n\n\t#createRelease(resource: T): () => void {\n\t\tlet released = false\n\t\treturn (): void => {\n\t\t\tif (released) return\n\t\t\treleased = true\n\t\t\tthis.#return(resource)\n\t\t}\n\t}\n\n\t// Return a leased resource. No waiter parked → synchronously drop it to idle (or destroy\n\t// it if torn down), `#active -= 1`. A waiter IS parked → hand off asynchronously, after\n\t// re-validating the resource so an invalid one (e.g. a terminated thread) is never served.\n\t#return(resource: T): void {\n\t\tif (this.#waiters.length === 0) {\n\t\t\tthis.#active -= 1\n\t\t\tif (this.#destroyed) {\n\t\t\t\tvoid this.#release(resource)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#idle.push(resource)\n\t\t\t// Observe the resource dropping to idle — AFTER `#active` was balanced down and it\n\t\t\t// is back on the idle list (the synchronous no-waiter path). A waiter-handoff\n\t\t\t// instead keeps the resource LEASED, so it emits no `release` here.\n\t\t\tthis.#emitter.emit('release')\n\t\t\treturn\n\t\t}\n\t\tvoid this.#handoff(resource)\n\t}\n\n\t// Hand a released resource to the oldest parked waiter, re-validating it first. A VALID\n\t// resource is served as-is (it stays leased — `#active` unchanged). An INVALID one is\n\t// destroyed and the waiter is served a fresh resource that REUSES the dead one's `#active`\n\t// slot (the count never dips below the lease, so a concurrent acquire can't overshoot\n\t// `max`). The waiter is re-shifted after every `await` (the queue can change underneath\n\t// us), and the pool is re-checked for teardown — so no waiter is leaked or double-settled\n\t// and no resource is handed into a destroyed pool.\n\tasync #handoff(resource: T): Promise<void> {\n\t\t// VALID release → serve the released resource directly (the common, unchanged path).\n\t\tif (await this.#valid(resource)) {\n\t\t\tthis.#serve(resource)\n\t\t\treturn\n\t\t}\n\t\t// INVALID release → destroy it and replace it, holding its `#active` slot steady.\n\t\tvoid this.#release(resource)\n\t\tlet replacement: T\n\t\ttry {\n\t\t\treplacement = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\t// The dead resource cannot be replaced — free its slot and reject the oldest waiter\n\t\t\t// (it can't be served), or drop the error if the queue raced empty.\n\t\t\tthis.#active -= 1\n\t\t\tconst waiter = this.#waiters.shift()\n\t\t\twaiter?.clear()\n\t\t\twaiter?.reject(error instanceof Error ? error : new Error(String(error)))\n\t\t\treturn\n\t\t}\n\t\t// Observe the fresh replacement — AFTER `create` resolved, BEFORE it is served.\n\t\tthis.#emitter.emit('create')\n\t\tthis.#serve(replacement)\n\t}\n\n\t// Hand a validated resource (the released one, or its fresh replacement) to the oldest\n\t// live waiter, holding its `#active` slot. If the queue raced empty across the awaits, the\n\t// resource is idle (or destroyed when torn down) and its slot is freed.\n\t#serve(resource: T): void {\n\t\tconst waiter = this.#destroyed ? undefined : this.#waiters.shift()\n\t\tif (waiter !== undefined) {\n\t\t\twaiter.clear()\n\t\t\twaiter.resolve(this.#token(resource))\n\t\t\t// Observe the served-waiter lease — strictly AFTER `waiter.resolve(...)` (the token\n\t\t\t// is already handed off; the emit only OBSERVES it and cannot sit across the resolve\n\t\t\t// or perturb the served acquirer's continuation). This is the `acquire` for a parked\n\t\t\t// `acquire`, so the public `acquire` deliberately does NOT emit on its `#wait` branch.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn\n\t\t}\n\t\tthis.#active -= 1\n\t\tif (this.#destroyed) {\n\t\t\tvoid this.#release(resource)\n\t\t\treturn\n\t\t}\n\t\tthis.#idle.push(resource)\n\t\t// The waiter queue raced empty across the handoff awaits — the resource lands back on\n\t\t// idle instead of being leased. Observe that as a `release` (the return-to-idle that\n\t\t// `#return` would have emitted had no waiter been parked when the token was released).\n\t\tthis.#emitter.emit('release')\n\t}\n\n\t// Is this resource usable? No validator trusts it; otherwise run the hook. A validator\n\t// that THROWS is treated exactly like one returning `false` — the resource is \"not\n\t// usable\", so it is destroyed + replaced rather than escaping as an unhandled rejection\n\t// that would strand a parked waiter on the handoff path (the same total-function spirit\n\t// as a guard, AGENTS §12 / §14). The single gate for both the idle (`#reuse`) and the\n\t// handoff (`#handoff`) validation, so the two paths can never diverge.\n\tasync #valid(resource: T): Promise<boolean> {\n\t\tif (this.#validate === undefined) return true\n\t\ttry {\n\t\t\treturn await this.#validate(resource)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Destroy one resource via the optional hook, swallowing destruction failures. Observe the\n\t// drop with a `destroy` event AFTER the hook ran (or after the no-hook drop) — the resource\n\t// is gone from the pool either way; a swallowed `destroy`-hook failure still emits (the pool\n\t// abandoned it). The emit is the LAST thing here, strictly after the teardown transition.\n\tasync #release(resource: T): Promise<void> {\n\t\tif (this.#destroy === undefined) {\n\t\t\tthis.#emitter.emit('destroy')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.#destroy(resource)\n\t\t} catch {\n\t\t\t// A destroy failure abandons the resource — there is nothing to recover.\n\t\t}\n\t\tthis.#emitter.emit('destroy')\n\t}\n}\n","import type { PoolInterface, PoolOptions } from './types.js'\nimport { Pool } from './Pool.js'\n\n/**\n * Create a bounded resource pool with idle reuse and FIFO waiting — `acquire` leases a\n * resource (reusing a validated idle one, growing up to `max`, or parking until a\n * `release` frees one) and the returned token's `release` returns it for reuse.\n *\n * @remarks\n * A parked `acquire` given an `AbortSignal` rejects + de-queues itself when the signal\n * fires (no leaked waiter). `clear` destroys idle resources (leased ones keep running);\n * `destroy` destroys all and rejects waiters. The pool is lean — no warm-floor (`min`),\n * no eviction timers — and observable (§13): a typed `emitter` surfaces\n * `create` / `acquire` / `release` / `destroy`.\n *\n * @typeParam T - The pooled resource type\n * @param options - The `create` hook plus optional `destroy` / `validate` / `max`\n * @returns A working {@link PoolInterface}\n *\n * @example\n * ```ts\n * import { createPool } from '@src/core'\n *\n * const pool = createPool<Connection>({\n * \tcreate: () => connect(),\n * \tdestroy: (connection) => connection.close(),\n * \tvalidate: (connection) => connection.alive,\n * \tmax: 8,\n * })\n *\n * const token = await pool.acquire()\n * try {\n * \tawait token.value.query('select 1')\n * } finally {\n * \ttoken.release()\n * }\n * ```\n */\nexport function createPool<T>(options: PoolOptions<T>): PoolInterface<T> {\n\tre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,MAAM;GACnC,QAAQ,MAAM;GACd,QAAQ,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;GACxE;EACD;EAEA,KAAKF,SAAS,KAAK,QAAQ;EAC3B,KAAKiB,OAAO,WAAW;CACxB;CAKA,OAAO,UAAmB;EACzB,MAAM,SAAS,KAAKb,aAAa,KAAA,IAAY,KAAKF,SAAS,MAAM;EACjE,IAAI,WAAW,KAAA,GAAW;GACzB,OAAO,MAAM;GACb,OAAO,QAAQ,KAAKQ,OAAO,QAAQ,CAAC;GAKpC,KAAKV,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,KAAKG,WAAW;EAChB,IAAI,KAAKC,YAAY;GACpB,KAAUI,SAAS,QAAQ;GAC3B;EACD;EACA,KAAKP,MAAM,KAAK,QAAQ;EAIxB,KAAKD,SAAS,KAAK,SAAS;CAC7B;CAQA,MAAMS,OAAO,UAA+B;EAC3C,IAAI,KAAKX,cAAc,KAAA,GAAW,OAAO;EACzC,IAAI;GACH,OAAO,MAAM,KAAKA,UAAU,QAAQ;EACrC,QAAQ;GACP,OAAO;EACR;CACD;CAMA,MAAMU,SAAS,UAA4B;EAC1C,IAAI,KAAKX,aAAa,KAAA,GAAW;GAChC,KAAKG,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,IAAI;GACH,MAAM,KAAKH,SAAS,QAAQ;EAC7B,QAAQ,CAER;EACA,KAAKG,SAAS,KAAK,SAAS;CAC7B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzRA,SAAgB,WAAc,SAA2C;CACxE,OAAO,IAAI,KAAK,OAAO;AACxB"}
|
package/dist/src/core/index.js
CHANGED
|
@@ -56,8 +56,8 @@ var Pool = class {
|
|
|
56
56
|
this.#validate = options.validate;
|
|
57
57
|
this.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY);
|
|
58
58
|
this.#emitter = new Emitter({
|
|
59
|
-
on: options
|
|
60
|
-
error: options
|
|
59
|
+
...options.on !== void 0 ? { on: options.on } : {},
|
|
60
|
+
...options.error !== void 0 ? { error: options.error } : {}
|
|
61
61
|
});
|
|
62
62
|
}
|
|
63
63
|
get emitter() {
|
|
@@ -136,29 +136,39 @@ var Pool = class {
|
|
|
136
136
|
const waiter = {
|
|
137
137
|
resolve,
|
|
138
138
|
reject,
|
|
139
|
-
clear:
|
|
139
|
+
clear: this.#ignore
|
|
140
140
|
};
|
|
141
141
|
this.#waiters.push(waiter);
|
|
142
142
|
if (signal !== void 0) {
|
|
143
|
-
const onAbort = ()
|
|
144
|
-
const index = this.#waiters.indexOf(waiter);
|
|
145
|
-
if (index >= 0) this.#waiters.splice(index, 1);
|
|
146
|
-
reject(signal.reason);
|
|
147
|
-
};
|
|
143
|
+
const onAbort = this.#createAbort(signal, waiter);
|
|
148
144
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
149
|
-
waiter.clear = (
|
|
145
|
+
waiter.clear = this.#createClear(signal, onAbort);
|
|
150
146
|
}
|
|
151
147
|
});
|
|
152
148
|
}
|
|
153
149
|
#token(resource) {
|
|
154
|
-
let released = false;
|
|
155
150
|
return {
|
|
156
151
|
value: resource,
|
|
157
|
-
release: ()
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
152
|
+
release: this.#createRelease(resource)
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
#ignore() {}
|
|
156
|
+
#createAbort(signal, waiter) {
|
|
157
|
+
return () => {
|
|
158
|
+
const index = this.#waiters.indexOf(waiter);
|
|
159
|
+
if (index >= 0) this.#waiters.splice(index, 1);
|
|
160
|
+
waiter.reject(signal.reason);
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
#createClear(signal, onAbort) {
|
|
164
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
165
|
+
}
|
|
166
|
+
#createRelease(resource) {
|
|
167
|
+
let released = false;
|
|
168
|
+
return () => {
|
|
169
|
+
if (released) return;
|
|
170
|
+
released = true;
|
|
171
|
+
this.#return(resource);
|
|
162
172
|
};
|
|
163
173
|
}
|
|
164
174
|
#return(resource) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#create","#destroy","#validate","#max","#emitter","#idle","#waiters","#active","#destroyed","#reuse","#grow","#wait","#release","#valid","#token","#return","#handoff","#serve"],"sources":["../../../src/core/Pool.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { PoolEventMap, PoolInterface, PoolOptions, PoolToken, PoolWaiter } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\n\n/**\n * A bounded resource pool with idle reuse + FIFO waiting.\n *\n * @remarks\n * - **Idle reuse.** `acquire` first takes an idle resource (validating it when a\n * `validate` hook is set — an invalid one is destroyed and the next idle / a fresh\n * one is tried). When no usable idle resource exists and the pool is below `max`, it\n * `create`s a new one. At `max` with none idle, the acquire PARKS on a FIFO waiter\n * list until a `release` hands it a resource.\n * - **FIFO handoff (validated).** `release` (on the token) hands the resource to the next\n * parked waiter (oldest first) — the resource stays leased, the lessee just changes —\n * or returns it to idle when no one is waiting. With a waiter parked the resource is\n * re-validated first (the same `validate` hook the idle path uses), so a resource that\n * went invalid WHILE leased (e.g. a terminated worker thread) is destroyed and the\n * waiter is served a fresh/valid one instead — a dead resource is never handed on. The\n * no-waiter path stays synchronous; releasing the same token twice is a no-op (an\n * idempotent token guard).\n * - **`validate` is total.** A `validate` hook that THROWS is treated exactly like one\n * returning `false` — the resource is \"not usable\", so it is destroyed and replaced —\n * rather than escaping. This holds on both the idle reuse and the FIFO handoff paths, so\n * a throwing validator can never strand a parked waiter on an unhandled rejection.\n * - **Abort-cancellable waiting.** A parked `acquire` given an `AbortSignal` rejects\n * when that signal fires and removes its waiter from the queue — no leaked waiter, so\n * a later `release` still serves the next live waiter. The signal is supplied by the\n * caller (a worker, for example, passes its per-attempt execution signal); the pool adds no abort\n * of its own.\n * - **Counts.** `size` = idle + leased; `idle` = available now; `active` = leased out.\n * - **Teardown.** `clear` destroys every IDLE resource (leased ones keep running);\n * `destroy` destroys ALL resources and rejects any parked waiters. Both await the\n * `destroy` hook.\n * - **Observable (§13).** The owned {@link emitter} ({@link PoolEventMap}) carries the\n * resource lifecycle — `create` / `acquire` / `release` / `destroy` — for fire-and-forget\n * observers. Every event is emitted directly, strictly AFTER the relevant transition —\n * OUTSIDE the `#handoff` / `#serve` await-chain, never across a waiter's resolve; the\n * emitter isolates a listener throw and routes it to its `error` handler (the `error`\n * option), so a buggy observer can NEVER corrupt the validated FIFO handoff-eviction\n * machinery (it cannot strand a parked waiter or unbalance the lease count). Observation is\n * purely a side-channel.\n * - **De-bloated.** No warm-floor / `min`, no eviction timers — lean.\n */\nexport class Pool<T> implements PoolInterface<T> {\n\treadonly #create: () => Promise<T> | T\n\treadonly #destroy: ((value: T) => Promise<void> | void) | undefined\n\treadonly #validate: ((value: T) => Promise<boolean> | boolean) | undefined\n\treadonly #max: number\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// validated FIFO handoff-eviction path.\n\treadonly #emitter: Emitter<PoolEventMap>\n\n\treadonly #idle: T[] = []\n\treadonly #waiters: PoolWaiter<T>[] = []\n\t#active = 0\n\t#destroyed = false\n\n\tconstructor(options: PoolOptions<T>) {\n\t\tthis.#create = options.create\n\t\tthis.#destroy = options.destroy\n\t\tthis.#validate = options.validate\n\t\tthis.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY)\n\t\tthis.#emitter = new Emitter<PoolEventMap>({ on: options?.on, error: options?.error })\n\t}\n\n\tget emitter(): EmitterInterface<PoolEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\treturn this.#idle.length + this.#active\n\t}\n\n\tget idle(): number {\n\t\treturn this.#idle.length\n\t}\n\n\tget active(): number {\n\t\treturn this.#active\n\t}\n\n\tasync acquire(signal?: AbortSignal): Promise<PoolToken<T>> {\n\t\tif (this.#destroyed) throw new Error('pool is destroyed')\n\t\tif (signal?.aborted === true) throw signal.reason\n\t\t// Reuse a validated idle resource if one is available.\n\t\tconst reused = await this.#reuse()\n\t\tif (reused !== undefined) {\n\t\t\t// Observe the lease — AFTER `#reuse` resolved the token (the resource is already\n\t\t\t// leased; emit only OBSERVES it).\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn reused\n\t\t}\n\t\t// Otherwise grow the pool when below the cap.\n\t\tif (this.size < this.#max) {\n\t\t\tconst grown = await this.#grow()\n\t\t\t// Observe the lease — AFTER `#grow` resolved the fresh token.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn grown\n\t\t}\n\t\t// At capacity with nothing idle — park until a release hands us a resource. The\n\t\t// `acquire` for THIS lease is emitted by `#serve` once a `release` hands it a resource\n\t\t// (after `waiter.resolve`), NOT here — so a served waiter emits `acquire` exactly once.\n\t\treturn await this.#wait(signal)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tconst waiters = this.#waiters.splice(0)\n\t\tconst error = new Error('pool is destroyed')\n\t\tfor (const waiter of waiters) {\n\t\t\twaiter.clear()\n\t\t\twaiter.reject(error)\n\t\t}\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\t// Take + validate the next idle resource; destroy + skip invalid ones. Returns a\n\t// token for the first valid idle resource, or `undefined` when none is usable.\n\tasync #reuse(): Promise<PoolToken<T> | undefined> {\n\t\twhile (this.#idle.length > 0) {\n\t\t\tconst resource = this.#idle.shift()\n\t\t\tif (resource === undefined) continue\n\t\t\tif (await this.#valid(resource)) {\n\t\t\t\tthis.#active += 1\n\t\t\t\treturn this.#token(resource)\n\t\t\t}\n\t\t\tawait this.#release(resource)\n\t\t}\n\t\treturn undefined\n\t}\n\n\t// Create a fresh resource and lease it. Reserve the active slot before awaiting\n\t// `create` so a concurrent acquire sees the pool at capacity (no overshoot of `max`).\n\tasync #grow(): Promise<PoolToken<T>> {\n\t\tthis.#active += 1\n\t\tlet resource: T\n\t\ttry {\n\t\t\tresource = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\tthis.#active -= 1\n\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t}\n\t\t// The pool may have been destroyed during `create` — never hand a live resource into\n\t\t// a torn-down pool. Free the active slot, destroy the just-created resource, and throw.\n\t\tif (this.#destroyed) {\n\t\t\tthis.#active -= 1\n\t\t\tawait this.#release(resource)\n\t\t\tthrow new Error('pool is destroyed')\n\t\t}\n\t\t// Observe the fresh resource — AFTER `create` resolved and the not-destroyed re-check\n\t\t// passed (the resource is here to stay), BEFORE the token is built.\n\t\tthis.#emitter.emit('create')\n\t\treturn this.#token(resource)\n\t}\n\n\t// Park a resolver on the FIFO waiter list until a release hands it a resource; an\n\t// abort on `signal` rejects the acquire and removes its waiter (no leak).\n\t#wait(signal: AbortSignal | undefined): Promise<PoolToken<T>> {\n\t\treturn new Promise<PoolToken<T>>((resolve, reject) => {\n\t\t\tconst waiter: PoolWaiter<T> = { resolve, reject, clear: () => {} }\n\t\t\tthis.#waiters.push(waiter)\n\t\t\tif (signal !== undefined) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tconst index = this.#waiters.indexOf(waiter)\n\t\t\t\t\tif (index >= 0) this.#waiters.splice(index, 1)\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t}\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\twaiter.clear = (): void => signal.removeEventListener('abort', onAbort)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Build an idempotent token; its `release` returns the resource exactly once.\n\t#token(resource: T): PoolToken<T> {\n\t\tlet released = false\n\t\treturn {\n\t\t\tvalue: resource,\n\t\t\trelease: (): void => {\n\t\t\t\tif (released) return\n\t\t\t\treleased = true\n\t\t\t\tthis.#return(resource)\n\t\t\t},\n\t\t}\n\t}\n\n\t// Return a leased resource. No waiter parked → synchronously drop it to idle (or destroy\n\t// it if torn down), `#active -= 1`. A waiter IS parked → hand off asynchronously, after\n\t// re-validating the resource so an invalid one (e.g. a terminated thread) is never served.\n\t#return(resource: T): void {\n\t\tif (this.#waiters.length === 0) {\n\t\t\tthis.#active -= 1\n\t\t\tif (this.#destroyed) {\n\t\t\t\tvoid this.#release(resource)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#idle.push(resource)\n\t\t\t// Observe the resource dropping to idle — AFTER `#active` was balanced down and it\n\t\t\t// is back on the idle list (the synchronous no-waiter path). A waiter-handoff\n\t\t\t// instead keeps the resource LEASED, so it emits no `release` here.\n\t\t\tthis.#emitter.emit('release')\n\t\t\treturn\n\t\t}\n\t\tvoid this.#handoff(resource)\n\t}\n\n\t// Hand a released resource to the oldest parked waiter, re-validating it first. A VALID\n\t// resource is served as-is (it stays leased — `#active` unchanged). An INVALID one is\n\t// destroyed and the waiter is served a fresh resource that REUSES the dead one's `#active`\n\t// slot (the count never dips below the lease, so a concurrent acquire can't overshoot\n\t// `max`). The waiter is re-shifted after every `await` (the queue can change underneath\n\t// us), and the pool is re-checked for teardown — so no waiter is leaked or double-settled\n\t// and no resource is handed into a destroyed pool.\n\tasync #handoff(resource: T): Promise<void> {\n\t\t// VALID release → serve the released resource directly (the common, unchanged path).\n\t\tif (await this.#valid(resource)) {\n\t\t\tthis.#serve(resource)\n\t\t\treturn\n\t\t}\n\t\t// INVALID release → destroy it and replace it, holding its `#active` slot steady.\n\t\tvoid this.#release(resource)\n\t\tlet replacement: T\n\t\ttry {\n\t\t\treplacement = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\t// The dead resource cannot be replaced — free its slot and reject the oldest waiter\n\t\t\t// (it can't be served), or drop the error if the queue raced empty.\n\t\t\tthis.#active -= 1\n\t\t\tconst waiter = this.#waiters.shift()\n\t\t\twaiter?.clear()\n\t\t\twaiter?.reject(error instanceof Error ? error : new Error(String(error)))\n\t\t\treturn\n\t\t}\n\t\t// Observe the fresh replacement — AFTER `create` resolved, BEFORE it is served.\n\t\tthis.#emitter.emit('create')\n\t\tthis.#serve(replacement)\n\t}\n\n\t// Hand a validated resource (the released one, or its fresh replacement) to the oldest\n\t// live waiter, holding its `#active` slot. If the queue raced empty across the awaits, the\n\t// resource is idle (or destroyed when torn down) and its slot is freed.\n\t#serve(resource: T): void {\n\t\tconst waiter = this.#destroyed ? undefined : this.#waiters.shift()\n\t\tif (waiter !== undefined) {\n\t\t\twaiter.clear()\n\t\t\twaiter.resolve(this.#token(resource))\n\t\t\t// Observe the served-waiter lease — strictly AFTER `waiter.resolve(...)` (the token\n\t\t\t// is already handed off; the emit only OBSERVES it and cannot sit across the resolve\n\t\t\t// or perturb the served acquirer's continuation). This is the `acquire` for a parked\n\t\t\t// `acquire`, so the public `acquire` deliberately does NOT emit on its `#wait` branch.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn\n\t\t}\n\t\tthis.#active -= 1\n\t\tif (this.#destroyed) {\n\t\t\tvoid this.#release(resource)\n\t\t\treturn\n\t\t}\n\t\tthis.#idle.push(resource)\n\t\t// The waiter queue raced empty across the handoff awaits — the resource lands back on\n\t\t// idle instead of being leased. Observe that as a `release` (the return-to-idle that\n\t\t// `#return` would have emitted had no waiter been parked when the token was released).\n\t\tthis.#emitter.emit('release')\n\t}\n\n\t// Is this resource usable? No validator trusts it; otherwise run the hook. A validator\n\t// that THROWS is treated exactly like one returning `false` — the resource is \"not\n\t// usable\", so it is destroyed + replaced rather than escaping as an unhandled rejection\n\t// that would strand a parked waiter on the handoff path (the same total-function spirit\n\t// as a guard, AGENTS §12 / §14). The single gate for both the idle (`#reuse`) and the\n\t// handoff (`#handoff`) validation, so the two paths can never diverge.\n\tasync #valid(resource: T): Promise<boolean> {\n\t\tif (this.#validate === undefined) return true\n\t\ttry {\n\t\t\treturn await this.#validate(resource)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Destroy one resource via the optional hook, swallowing destruction failures. Observe the\n\t// drop with a `destroy` event AFTER the hook ran (or after the no-hook drop) — the resource\n\t// is gone from the pool either way; a swallowed `destroy`-hook failure still emits (the pool\n\t// abandoned it). The emit is the LAST thing here, strictly after the teardown transition.\n\tasync #release(resource: T): Promise<void> {\n\t\tif (this.#destroy === undefined) {\n\t\t\tthis.#emitter.emit('destroy')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.#destroy(resource)\n\t\t} catch {\n\t\t\t// A destroy failure abandons the resource — there is nothing to recover.\n\t\t}\n\t\tthis.#emitter.emit('destroy')\n\t}\n}\n","import type { PoolInterface, PoolOptions } from './types.js'\nimport { Pool } from './Pool.js'\n\n/**\n * Create a bounded resource pool with idle reuse and FIFO waiting — `acquire` leases a\n * resource (reusing a validated idle one, growing up to `max`, or parking until a\n * `release` frees one) and the returned token's `release` returns it for reuse.\n *\n * @remarks\n * A parked `acquire` given an `AbortSignal` rejects + de-queues itself when the signal\n * fires (no leaked waiter). `clear` destroys idle resources (leased ones keep running);\n * `destroy` destroys all and rejects waiters. The pool is lean — no warm-floor (`min`),\n * no eviction timers — and observable (§13): a typed `emitter` surfaces\n * `create` / `acquire` / `release` / `destroy`.\n *\n * @typeParam T - The pooled resource type\n * @param options - The `create` hook plus optional `destroy` / `validate` / `max`\n * @returns A working {@link PoolInterface}\n *\n * @example\n * ```ts\n * import { createPool } from '@src/core'\n *\n * const pool = createPool<Connection>({\n * \tcreate: () => connect(),\n * \tdestroy: (connection) => connection.close(),\n * \tvalidate: (connection) => connection.alive,\n * \tmax: 8,\n * })\n *\n * const token = await pool.acquire()\n * try {\n * \tawait token.value.query('select 1')\n * } finally {\n * \ttoken.release()\n * }\n * ```\n */\nexport function createPool<T>(options: PoolOptions<T>): PoolInterface<T> {\n\treturn new Pool(options)\n}\n"],"mappings":";;;;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AC5B;EACD;EACA,KAAKG,WAAW;EAChB,IAAI,KAAKC,YAAY;GACpB,KAAUI,SAAS,QAAQ;GAC3B;EACD;EACA,KAAKP,MAAM,KAAK,QAAQ;EAIxB,KAAKD,SAAS,KAAK,SAAS;CAC7B;CAQA,MAAMS,OAAO,UAA+B;EAC3C,IAAI,KAAKX,cAAc,KAAA,GAAW,OAAO;EACzC,IAAI;GACH,OAAO,MAAM,KAAKA,UAAU,QAAQ;EACrC,QAAQ;GACP,OAAO;EACR;CACD;CAMA,MAAMU,SAAS,UAA4B;EAC1C,IAAI,KAAKX,aAAa,KAAA,GAAW;GAChC,KAAKG,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,IAAI;GACH,MAAM,KAAKH,SAAS,QAAQ;EAC7B,QAAQ,CAER;EACA,KAAKG,SAAS,KAAK,SAAS;CAC7B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3QA,SAAgB,WAAc,SAA2C;CACxE,OAAO,IAAI,KAAK,OAAO;AACxB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#create","#destroy","#validate","#max","#emitter","#idle","#waiters","#active","#destroyed","#reuse","#grow","#wait","#release","#valid","#token","#ignore","#createAbort","#createClear","#createRelease","#return","#handoff","#serve"],"sources":["../../../src/core/Pool.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { PoolEventMap, PoolInterface, PoolOptions, PoolToken, PoolWaiter } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\n\n/**\n * A bounded resource pool with idle reuse + FIFO waiting.\n *\n * @remarks\n * - **Idle reuse.** `acquire` first takes an idle resource (validating it when a\n * `validate` hook is set — an invalid one is destroyed and the next idle / a fresh\n * one is tried). When no usable idle resource exists and the pool is below `max`, it\n * `create`s a new one. At `max` with none idle, the acquire PARKS on a FIFO waiter\n * list until a `release` hands it a resource.\n * - **FIFO handoff (validated).** `release` (on the token) hands the resource to the next\n * parked waiter (oldest first) — the resource stays leased, the lessee just changes —\n * or returns it to idle when no one is waiting. With a waiter parked the resource is\n * re-validated first (the same `validate` hook the idle path uses), so a resource that\n * went invalid WHILE leased (e.g. a terminated worker thread) is destroyed and the\n * waiter is served a fresh/valid one instead — a dead resource is never handed on. The\n * no-waiter path stays synchronous; releasing the same token twice is a no-op (an\n * idempotent token guard).\n * - **`validate` is total.** A `validate` hook that THROWS is treated exactly like one\n * returning `false` — the resource is \"not usable\", so it is destroyed and replaced —\n * rather than escaping. This holds on both the idle reuse and the FIFO handoff paths, so\n * a throwing validator can never strand a parked waiter on an unhandled rejection.\n * - **Abort-cancellable waiting.** A parked `acquire` given an `AbortSignal` rejects\n * when that signal fires and removes its waiter from the queue — no leaked waiter, so\n * a later `release` still serves the next live waiter. The signal is supplied by the\n * caller (a worker, for example, passes its per-attempt execution signal); the pool adds no abort\n * of its own.\n * - **Counts.** `size` = idle + leased; `idle` = available now; `active` = leased out.\n * - **Teardown.** `clear` destroys every IDLE resource (leased ones keep running);\n * `destroy` destroys ALL resources and rejects any parked waiters. Both await the\n * `destroy` hook.\n * - **Observable (§13).** The owned {@link emitter} ({@link PoolEventMap}) carries the\n * resource lifecycle — `create` / `acquire` / `release` / `destroy` — for fire-and-forget\n * observers. Every event is emitted directly, strictly AFTER the relevant transition —\n * OUTSIDE the `#handoff` / `#serve` await-chain, never across a waiter's resolve; the\n * emitter isolates a listener throw and routes it to its `error` handler (the `error`\n * option), so a buggy observer can NEVER corrupt the validated FIFO handoff-eviction\n * machinery (it cannot strand a parked waiter or unbalance the lease count). Observation is\n * purely a side-channel.\n * - **De-bloated.** No warm-floor / `min`, no eviction timers — lean.\n */\nexport class Pool<T> implements PoolInterface<T> {\n\treadonly #create: () => Promise<T> | T\n\treadonly #destroy: ((value: T) => Promise<void> | void) | undefined\n\treadonly #validate: ((value: T) => Promise<boolean> | boolean) | undefined\n\treadonly #max: number\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// validated FIFO handoff-eviction path.\n\treadonly #emitter: Emitter<PoolEventMap>\n\n\treadonly #idle: T[] = []\n\treadonly #waiters: PoolWaiter<T>[] = []\n\t#active = 0\n\t#destroyed = false\n\n\tconstructor(options: PoolOptions<T>) {\n\t\tthis.#create = options.create\n\t\tthis.#destroy = options.destroy\n\t\tthis.#validate = options.validate\n\t\tthis.#max = Math.max(1, options.max ?? Number.POSITIVE_INFINITY)\n\t\tthis.#emitter = new Emitter<PoolEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<PoolEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\treturn this.#idle.length + this.#active\n\t}\n\n\tget idle(): number {\n\t\treturn this.#idle.length\n\t}\n\n\tget active(): number {\n\t\treturn this.#active\n\t}\n\n\tasync acquire(signal?: AbortSignal): Promise<PoolToken<T>> {\n\t\tif (this.#destroyed) throw new Error('pool is destroyed')\n\t\tif (signal?.aborted === true) throw signal.reason\n\t\t// Reuse a validated idle resource if one is available.\n\t\tconst reused = await this.#reuse()\n\t\tif (reused !== undefined) {\n\t\t\t// Observe the lease — AFTER `#reuse` resolved the token (the resource is already\n\t\t\t// leased; emit only OBSERVES it).\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn reused\n\t\t}\n\t\t// Otherwise grow the pool when below the cap.\n\t\tif (this.size < this.#max) {\n\t\t\tconst grown = await this.#grow()\n\t\t\t// Observe the lease — AFTER `#grow` resolved the fresh token.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn grown\n\t\t}\n\t\t// At capacity with nothing idle — park until a release hands us a resource. The\n\t\t// `acquire` for THIS lease is emitted by `#serve` once a `release` hands it a resource\n\t\t// (after `waiter.resolve`), NOT here — so a served waiter emits `acquire` exactly once.\n\t\treturn await this.#wait(signal)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tconst waiters = this.#waiters.splice(0)\n\t\tconst error = new Error('pool is destroyed')\n\t\tfor (const waiter of waiters) {\n\t\t\twaiter.clear()\n\t\t\twaiter.reject(error)\n\t\t}\n\t\tconst resources = this.#idle.splice(0)\n\t\tawait Promise.all(resources.map((resource) => this.#release(resource)))\n\t}\n\n\t// Take + validate the next idle resource; destroy + skip invalid ones. Returns a\n\t// token for the first valid idle resource, or `undefined` when none is usable.\n\tasync #reuse(): Promise<PoolToken<T> | undefined> {\n\t\twhile (this.#idle.length > 0) {\n\t\t\tconst resource = this.#idle.shift()\n\t\t\tif (resource === undefined) continue\n\t\t\tif (await this.#valid(resource)) {\n\t\t\t\tthis.#active += 1\n\t\t\t\treturn this.#token(resource)\n\t\t\t}\n\t\t\tawait this.#release(resource)\n\t\t}\n\t\treturn undefined\n\t}\n\n\t// Create a fresh resource and lease it. Reserve the active slot before awaiting\n\t// `create` so a concurrent acquire sees the pool at capacity (no overshoot of `max`).\n\tasync #grow(): Promise<PoolToken<T>> {\n\t\tthis.#active += 1\n\t\tlet resource: T\n\t\ttry {\n\t\t\tresource = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\tthis.#active -= 1\n\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t}\n\t\t// The pool may have been destroyed during `create` — never hand a live resource into\n\t\t// a torn-down pool. Free the active slot, destroy the just-created resource, and throw.\n\t\tif (this.#destroyed) {\n\t\t\tthis.#active -= 1\n\t\t\tawait this.#release(resource)\n\t\t\tthrow new Error('pool is destroyed')\n\t\t}\n\t\t// Observe the fresh resource — AFTER `create` resolved and the not-destroyed re-check\n\t\t// passed (the resource is here to stay), BEFORE the token is built.\n\t\tthis.#emitter.emit('create')\n\t\treturn this.#token(resource)\n\t}\n\n\t// Park a resolver on the FIFO waiter list until a release hands it a resource; an\n\t// abort on `signal` rejects the acquire and removes its waiter (no leak).\n\t#wait(signal: AbortSignal | undefined): Promise<PoolToken<T>> {\n\t\treturn new Promise<PoolToken<T>>((resolve, reject) => {\n\t\t\tconst waiter: PoolWaiter<T> = { resolve, reject, clear: this.#ignore }\n\t\t\tthis.#waiters.push(waiter)\n\t\t\tif (signal !== undefined) {\n\t\t\t\tconst onAbort = this.#createAbort(signal, waiter)\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\twaiter.clear = this.#createClear(signal, onAbort)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Build an idempotent token; its `release` returns the resource exactly once.\n\t#token(resource: T): PoolToken<T> {\n\t\treturn { value: resource, release: this.#createRelease(resource) }\n\t}\n\n\t#ignore(): void {}\n\n\t#createAbort(signal: AbortSignal, waiter: PoolWaiter<T>): () => void {\n\t\treturn (): void => {\n\t\t\tconst index = this.#waiters.indexOf(waiter)\n\t\t\tif (index >= 0) this.#waiters.splice(index, 1)\n\t\t\twaiter.reject(signal.reason)\n\t\t}\n\t}\n\n\t#createClear(signal: AbortSignal, onAbort: () => void): () => void {\n\t\treturn (): void => signal.removeEventListener('abort', onAbort)\n\t}\n\n\t#createRelease(resource: T): () => void {\n\t\tlet released = false\n\t\treturn (): void => {\n\t\t\tif (released) return\n\t\t\treleased = true\n\t\t\tthis.#return(resource)\n\t\t}\n\t}\n\n\t// Return a leased resource. No waiter parked → synchronously drop it to idle (or destroy\n\t// it if torn down), `#active -= 1`. A waiter IS parked → hand off asynchronously, after\n\t// re-validating the resource so an invalid one (e.g. a terminated thread) is never served.\n\t#return(resource: T): void {\n\t\tif (this.#waiters.length === 0) {\n\t\t\tthis.#active -= 1\n\t\t\tif (this.#destroyed) {\n\t\t\t\tvoid this.#release(resource)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#idle.push(resource)\n\t\t\t// Observe the resource dropping to idle — AFTER `#active` was balanced down and it\n\t\t\t// is back on the idle list (the synchronous no-waiter path). A waiter-handoff\n\t\t\t// instead keeps the resource LEASED, so it emits no `release` here.\n\t\t\tthis.#emitter.emit('release')\n\t\t\treturn\n\t\t}\n\t\tvoid this.#handoff(resource)\n\t}\n\n\t// Hand a released resource to the oldest parked waiter, re-validating it first. A VALID\n\t// resource is served as-is (it stays leased — `#active` unchanged). An INVALID one is\n\t// destroyed and the waiter is served a fresh resource that REUSES the dead one's `#active`\n\t// slot (the count never dips below the lease, so a concurrent acquire can't overshoot\n\t// `max`). The waiter is re-shifted after every `await` (the queue can change underneath\n\t// us), and the pool is re-checked for teardown — so no waiter is leaked or double-settled\n\t// and no resource is handed into a destroyed pool.\n\tasync #handoff(resource: T): Promise<void> {\n\t\t// VALID release → serve the released resource directly (the common, unchanged path).\n\t\tif (await this.#valid(resource)) {\n\t\t\tthis.#serve(resource)\n\t\t\treturn\n\t\t}\n\t\t// INVALID release → destroy it and replace it, holding its `#active` slot steady.\n\t\tvoid this.#release(resource)\n\t\tlet replacement: T\n\t\ttry {\n\t\t\treplacement = await this.#create()\n\t\t} catch (error: unknown) {\n\t\t\t// The dead resource cannot be replaced — free its slot and reject the oldest waiter\n\t\t\t// (it can't be served), or drop the error if the queue raced empty.\n\t\t\tthis.#active -= 1\n\t\t\tconst waiter = this.#waiters.shift()\n\t\t\twaiter?.clear()\n\t\t\twaiter?.reject(error instanceof Error ? error : new Error(String(error)))\n\t\t\treturn\n\t\t}\n\t\t// Observe the fresh replacement — AFTER `create` resolved, BEFORE it is served.\n\t\tthis.#emitter.emit('create')\n\t\tthis.#serve(replacement)\n\t}\n\n\t// Hand a validated resource (the released one, or its fresh replacement) to the oldest\n\t// live waiter, holding its `#active` slot. If the queue raced empty across the awaits, the\n\t// resource is idle (or destroyed when torn down) and its slot is freed.\n\t#serve(resource: T): void {\n\t\tconst waiter = this.#destroyed ? undefined : this.#waiters.shift()\n\t\tif (waiter !== undefined) {\n\t\t\twaiter.clear()\n\t\t\twaiter.resolve(this.#token(resource))\n\t\t\t// Observe the served-waiter lease — strictly AFTER `waiter.resolve(...)` (the token\n\t\t\t// is already handed off; the emit only OBSERVES it and cannot sit across the resolve\n\t\t\t// or perturb the served acquirer's continuation). This is the `acquire` for a parked\n\t\t\t// `acquire`, so the public `acquire` deliberately does NOT emit on its `#wait` branch.\n\t\t\tthis.#emitter.emit('acquire')\n\t\t\treturn\n\t\t}\n\t\tthis.#active -= 1\n\t\tif (this.#destroyed) {\n\t\t\tvoid this.#release(resource)\n\t\t\treturn\n\t\t}\n\t\tthis.#idle.push(resource)\n\t\t// The waiter queue raced empty across the handoff awaits — the resource lands back on\n\t\t// idle instead of being leased. Observe that as a `release` (the return-to-idle that\n\t\t// `#return` would have emitted had no waiter been parked when the token was released).\n\t\tthis.#emitter.emit('release')\n\t}\n\n\t// Is this resource usable? No validator trusts it; otherwise run the hook. A validator\n\t// that THROWS is treated exactly like one returning `false` — the resource is \"not\n\t// usable\", so it is destroyed + replaced rather than escaping as an unhandled rejection\n\t// that would strand a parked waiter on the handoff path (the same total-function spirit\n\t// as a guard, AGENTS §12 / §14). The single gate for both the idle (`#reuse`) and the\n\t// handoff (`#handoff`) validation, so the two paths can never diverge.\n\tasync #valid(resource: T): Promise<boolean> {\n\t\tif (this.#validate === undefined) return true\n\t\ttry {\n\t\t\treturn await this.#validate(resource)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Destroy one resource via the optional hook, swallowing destruction failures. Observe the\n\t// drop with a `destroy` event AFTER the hook ran (or after the no-hook drop) — the resource\n\t// is gone from the pool either way; a swallowed `destroy`-hook failure still emits (the pool\n\t// abandoned it). The emit is the LAST thing here, strictly after the teardown transition.\n\tasync #release(resource: T): Promise<void> {\n\t\tif (this.#destroy === undefined) {\n\t\t\tthis.#emitter.emit('destroy')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.#destroy(resource)\n\t\t} catch {\n\t\t\t// A destroy failure abandons the resource — there is nothing to recover.\n\t\t}\n\t\tthis.#emitter.emit('destroy')\n\t}\n}\n","import type { PoolInterface, PoolOptions } from './types.js'\nimport { Pool } from './Pool.js'\n\n/**\n * Create a bounded resource pool with idle reuse and FIFO waiting — `acquire` leases a\n * resource (reusing a validated idle one, growing up to `max`, or parking until a\n * `release` frees one) and the returned token's `release` returns it for reuse.\n *\n * @remarks\n * A parked `acquire` given an `AbortSignal` rejects + de-queues itself when the signal\n * fires (no leaked waiter). `clear` destroys idle resources (leased ones keep running);\n * `destroy` destroys all and rejects waiters. The pool is lean — no warm-floor (`min`),\n * no eviction timers — and observable (§13): a typed `emitter` surfaces\n * `create` / `acquire` / `release` / `destroy`.\n *\n * @typeParam T - The pooled resource type\n * @param options - The `create` hook plus optional `destroy` / `validate` / `max`\n * @returns A working {@link PoolInterface}\n *\n * @example\n * ```ts\n * import { createPool } from '@src/core'\n *\n * const pool = createPool<Connection>({\n * \tcreate: () => connect(),\n * \tdestroy: (connection) => connection.close(),\n * \tvalidate: (connection) => connection.alive,\n * \tmax: 8,\n * })\n *\n * const token = await pool.acquire()\n * try {\n * \tawait token.value.query('select 1')\n * } finally {\n * \ttoken.release()\n * }\n * ```\n */\nexport function createPool<T>(options: PoolOptions<T>): PoolInterface<T> {\n\treturn new Pool(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,OAAb,MAAiD;CAChD;CACA;CACA;CACA;CAIA;CAEA,QAAsB,CAAC;CACvB,WAAqC,CAAC;CACtC,UAAU;CACV,aAAa;CAEb,YAAY,SAAyB;EACpC,KAAKA,UAAU,QAAQ;EACvB,KAAKC,WAAW,QAAQ;EACxB,KAAKC,YAAY,QAAQ;EACzB,KAAKC,OAAO,KAAK,IAAI,GAAG,QAAQ,OAAO,OAAO,iBAAiB;EAC/D,KAAKC,WAAW,IAAI,QAAsB;GACzC,GAAI,QAAQ,OAAO,KAAA,IAAY,EAAE,IAAI,QAAQ,GAAG,IAAI,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AAQ;GAC3B;EACD;EACA,KAAKP,MAAM,KAAK,QAAQ;EAIxB,KAAKD,SAAS,KAAK,SAAS;CAC7B;CAQA,MAAMS,OAAO,UAA+B;EAC3C,IAAI,KAAKX,cAAc,KAAA,GAAW,OAAO;EACzC,IAAI;GACH,OAAO,MAAM,KAAKA,UAAU,QAAQ;EACrC,QAAQ;GACP,OAAO;EACR;CACD;CAMA,MAAMU,SAAS,UAA4B;EAC1C,IAAI,KAAKX,aAAa,KAAA,GAAW;GAChC,KAAKG,SAAS,KAAK,SAAS;GAC5B;EACD;EACA,IAAI;GACH,MAAM,KAAKH,SAAS,QAAQ;EAC7B,QAAQ,CAER;EACA,KAAKG,SAAS,KAAK,SAAS;CAC7B;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzRA,SAAgB,WAAc,SAA2C;CACxE,OAAO,IAAI,KAAK,OAAO;AACxB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orkestrel/pool",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "A bounded, typed resource pool — idle reuse, max backpressure, FIFO abort-cancellable waiting, and an observable lifecycle emitter. Part of the @orkestrel line.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"connection-pool",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"url": "git+https://github.com/orkestrel/pool.git"
|
|
18
18
|
},
|
|
19
19
|
"files": [
|
|
20
|
-
"dist",
|
|
20
|
+
"dist/src",
|
|
21
21
|
"README.md"
|
|
22
22
|
],
|
|
23
23
|
"type": "module",
|
|
@@ -42,19 +42,20 @@
|
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
44
|
"scripts": {
|
|
45
|
-
"clean": "node -e \"
|
|
45
|
+
"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
46
46
|
"copy": "node -e \"const fs=require('node:fs'),p=require('node:path'),a=process.argv[1],b=process.argv[2];fs.mkdirSync(p.dirname(b),{recursive:true});fs.cpSync(a,b,{force:true});console.log('Copied: '+a+' to '+b)\"",
|
|
47
|
-
"
|
|
48
|
-
"lint": "oxlint --config .oxlintrc.json --fix .",
|
|
47
|
+
"scaffold": "scaffold",
|
|
48
|
+
"lint": "oxlint --config .oxlintrc.json --fix --deny-warnings .",
|
|
49
49
|
"check": "tsc --noEmit --project tsconfig.json && npm run check:src",
|
|
50
50
|
"check:src": "npm run check:src:core",
|
|
51
51
|
"check:src:core": "tsc --noEmit -p configs/src/tsconfig.core.json",
|
|
52
52
|
"format": "oxfmt --config .oxfmtrc.json --write .",
|
|
53
53
|
"format:check": "oxfmt --config .oxfmtrc.json --check .",
|
|
54
|
-
"lint:check": "oxlint --config .oxlintrc.json .",
|
|
55
|
-
"test": "npm run test:src && npm run test:guides",
|
|
54
|
+
"lint:check": "oxlint --config .oxlintrc.json --deny-warnings .",
|
|
55
|
+
"test": "npm run test:src && npm run test:policy && npm run test:guides",
|
|
56
56
|
"test:src": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core",
|
|
57
57
|
"test:src:core": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core",
|
|
58
|
+
"test:policy": "vitest run --config vite.config.ts --no-cache --reporter=dot --project policy",
|
|
58
59
|
"test:guides": "vitest run --config vite.config.ts --reporter=dot --project guides",
|
|
59
60
|
"build": "npm run clean && npm run build:src",
|
|
60
61
|
"build:src": "npm run build:src:core",
|
|
@@ -62,20 +63,22 @@
|
|
|
62
63
|
"prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test"
|
|
63
64
|
},
|
|
64
65
|
"dependencies": {
|
|
65
|
-
"@orkestrel/emitter": "^0.0.
|
|
66
|
+
"@orkestrel/emitter": "^0.0.4"
|
|
66
67
|
},
|
|
67
68
|
"devDependencies": {
|
|
68
|
-
"@microsoft/api-extractor": "^7.58.
|
|
69
|
-
"@orkestrel/guide": "^0.0.
|
|
70
|
-
"@
|
|
71
|
-
"
|
|
72
|
-
"
|
|
69
|
+
"@microsoft/api-extractor": "^7.58.12",
|
|
70
|
+
"@orkestrel/guide": "^0.0.6",
|
|
71
|
+
"@orkestrel/scaffold": "^0.0.6",
|
|
72
|
+
"@types/node": "^26.1.2",
|
|
73
|
+
"@vitest/browser-playwright": "^4.1.10",
|
|
74
|
+
"oxfmt": "^0.61.0",
|
|
75
|
+
"oxlint": "^1.76.0",
|
|
73
76
|
"typescript": "^6.0.3",
|
|
74
77
|
"vite": "^8.1.5",
|
|
75
78
|
"vite-plugin-dts": "^5.0.3",
|
|
76
79
|
"vitest": "^4.1.10"
|
|
77
80
|
},
|
|
78
81
|
"engines": {
|
|
79
|
-
"node": ">=22"
|
|
82
|
+
"node": ">=22.12.0"
|
|
80
83
|
}
|
|
81
84
|
}
|