@orkestrel/pool 0.0.4 → 0.0.6

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.
@@ -3,24 +3,20 @@ import { EmitterHooks } from '@orkestrel/emitter';
3
3
  import { EmitterInterface } from '@orkestrel/emitter';
4
4
 
5
5
  /**
6
- * Create a bounded resource pool with idle reuse and FIFO waiting `acquire` leases a
7
- * resource (reusing a validated idle one, growing up to `max`, or parking until a
8
- * `release` frees one) and the returned token's `release` returns it for reuse.
6
+ * Create a resource pool with optional bounded capacity, unique ownership, and FIFO settlement.
9
7
  *
10
8
  * @remarks
11
- * A parked `acquire` given an `AbortSignal` rejects + de-queues itself when the signal
12
- * fires (no leaked waiter). `clear` destroys idle resources (leased ones keep running);
13
- * `destroy` destroys all and rejects waiters. The pool is lean no warm-floor (`min`),
14
- * no eviction timers — and observable (§13): a typed `emitter` surfaces
15
- * `create` / `acquire` / `release` / `destroy`.
9
+ * Concurrent create and validation hooks may overlap, while acquire promises settle in
10
+ * request order. `clear` owns its idle snapshot; `destroy` returns one stable barrier and
11
+ * waits for every in-flight hook and cleanup before destroying the emitter last.
16
12
  *
17
13
  * @typeParam T - The pooled resource type
18
- * @param options - The `create` hook plus optional `destroy` / `validate` / `max`
14
+ * @param options - Lifecycle hooks, optional positive safe `max`, and observation hooks
19
15
  * @returns A working {@link PoolInterface}
20
16
  *
21
17
  * @example
22
18
  * ```ts
23
- * import { createPool } from '@src/core'
19
+ * import { createPool } from '@orkestrel/pool'
24
20
  *
25
21
  * const pool = createPool<Connection>({
26
22
  * create: () => connect(),
@@ -40,120 +36,206 @@ import { EmitterInterface } from '@orkestrel/emitter';
40
36
  export declare function createPool<T>(options: PoolOptions<T>): PoolInterface<T>;
41
37
 
42
38
  /**
43
- * A bounded resource pool with idle reuse + FIFO waiting.
39
+ * Test whether an unknown value is a {@link PoolError}, returning `false` for hostile proxies.
44
40
  *
45
- * @remarks
46
- * - **Idle reuse.** `acquire` first takes an idle resource (validating it when a
47
- * `validate` hook is set — an invalid one is destroyed and the next idle / a fresh
48
- * one is tried). When no usable idle resource exists and the pool is below `max`, it
49
- * `create`s a new one. At `max` with none idle, the acquire PARKS on a FIFO waiter
50
- * list until a `release` hands it a resource.
51
- * - **FIFO handoff (validated).** `release` (on the token) hands the resource to the next
52
- * parked waiter (oldest first) — the resource stays leased, the lessee just changes —
53
- * or returns it to idle when no one is waiting. With a waiter parked the resource is
54
- * re-validated first (the same `validate` hook the idle path uses), so a resource that
55
- * went invalid WHILE leased (e.g. a terminated worker thread) is destroyed and the
56
- * waiter is served a fresh/valid one instead — a dead resource is never handed on. The
57
- * no-waiter path stays synchronous; releasing the same token twice is a no-op (an
58
- * idempotent token guard).
59
- * - **`validate` is total.** A `validate` hook that THROWS is treated exactly like one
60
- * returning `false` the resource is "not usable", so it is destroyed and replaced —
61
- * rather than escaping. This holds on both the idle reuse and the FIFO handoff paths, so
62
- * a throwing validator can never strand a parked waiter on an unhandled rejection.
63
- * - **Abort-cancellable waiting.** A parked `acquire` given an `AbortSignal` rejects
64
- * when that signal fires and removes its waiter from the queue — no leaked waiter, so
65
- * a later `release` still serves the next live waiter. The signal is supplied by the
66
- * caller (a worker, for example, passes its per-attempt execution signal); the pool adds no abort
67
- * of its own.
68
- * - **Counts.** `size` = idle + leased; `idle` = available now; `active` = leased out.
69
- * - **Teardown.** `clear` destroys every IDLE resource (leased ones keep running);
70
- * `destroy` destroys ALL resources and rejects any parked waiters. Both await the
71
- * `destroy` hook.
72
- * - **Observable (§13).** The owned {@link emitter} ({@link PoolEventMap}) carries the
73
- * resource lifecycle `create` / `acquire` / `release` / `destroy` — for fire-and-forget
74
- * observers. Every event is emitted directly, strictly AFTER the relevant transition —
75
- * OUTSIDE the `#handoff` / `#serve` await-chain, never across a waiter's resolve; the
76
- * emitter isolates a listener throw and routes it to its `error` handler (the `error`
77
- * option), so a buggy observer can NEVER corrupt the validated FIFO handoff-eviction
78
- * machinery (it cannot strand a parked waiter or unbalance the lease count). Observation is
79
- * purely a side-channel.
80
- * - **De-bloated.** No warm-floor / `min`, no eviction timers — lean.
41
+ * @param value - The unknown boundary value
42
+ * @returns Whether the value is a real `PoolError` instance
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * isPoolError(new PoolError({ code: 'destroyed' })) // true
47
+ * isPoolError(new Error('other')) // false
48
+ * ```
49
+ */
50
+ export declare function isPoolError(value: unknown): value is PoolError;
51
+
52
+ /**
53
+ * Test whether a value is a valid finite pool maximum.
54
+ *
55
+ * @param value - The unknown maximum candidate
56
+ * @returns Whether the value is a positive safe integer
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * isPoolMax(8) // true
61
+ * isPoolMax(Infinity) // false
62
+ * ```
63
+ */
64
+ export declare function isPoolMax(value: unknown): value is number;
65
+
66
+ /**
67
+ * Test whether a value is a native `AbortSignal`, returning `false` for hostile proxies.
68
+ *
69
+ * @param value - The unknown signal candidate
70
+ * @returns Whether the value is a native `AbortSignal`
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * isPoolSignal(new AbortController().signal) // true
75
+ * isPoolSignal({ aborted: false }) // false
76
+ * ```
77
+ */
78
+ export declare function isPoolSignal(value: unknown): value is AbortSignal;
79
+
80
+ /**
81
+ * A capacity-aware resource pool whose opaque ownership records preserve FIFO settlement,
82
+ * cancellation, exact lease release, and deterministic teardown under concurrent hooks.
83
+ *
84
+ * @typeParam T - The pooled resource value
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * import { Pool } from '@orkestrel/pool'
89
+ *
90
+ * const pool = new Pool({ create: () => new Uint8Array(64), max: 2 })
91
+ * const token = await pool.acquire()
92
+ * try {
93
+ * consume(token.value)
94
+ * } finally {
95
+ * token.release()
96
+ * }
97
+ * await pool.destroy()
98
+ * ```
81
99
  */
82
100
  export declare class Pool<T> implements PoolInterface<T> {
83
101
  #private;
102
+ /**
103
+ * Construct a pool and synchronously validate its capacity contract.
104
+ *
105
+ * @param options - Resource hooks, observation hooks, and optional positive safe `max`
106
+ */
84
107
  constructor(options: PoolOptions<T>);
108
+ /** The typed synchronous lifecycle observation surface. */
85
109
  get emitter(): EmitterInterface<PoolEventMap>;
110
+ /** All owned records, including records validating or destroying. */
86
111
  get size(): number;
112
+ /** Records immediately available without validation work. */
87
113
  get idle(): number;
114
+ /** Records represented by unsettled released-once lease tokens. */
88
115
  get active(): number;
116
+ /**
117
+ * Queue and lease one resource in FIFO settlement order.
118
+ *
119
+ * @param signal - Optional native cancellation signal
120
+ * @returns A promise for the unique resource lease
121
+ */
89
122
  acquire(signal?: AbortSignal): Promise<PoolToken<T>>;
123
+ /**
124
+ * Destroy the records that are idle at this call's synchronous snapshot.
125
+ *
126
+ * @returns A promise that settles after every snapshot cleanup attempt
127
+ */
90
128
  clear(): Promise<void>;
129
+ /**
130
+ * Permanently tear down the pool and return its stable completion barrier.
131
+ *
132
+ * @returns The exact promise shared by every destroy call
133
+ */
91
134
  destroy(): Promise<void>;
92
135
  }
93
136
 
137
+ /** Machine-readable failure codes produced by {@link PoolError}. */
138
+ export declare type PoolCode = 'invalid' | 'destroyed' | 'create' | 'cleanup';
139
+
140
+ /** Structured context attached to a {@link PoolError}. */
141
+ export declare interface PoolContext {
142
+ /** The rejected public input, when the failure is an input-validation error. */
143
+ readonly value?: unknown;
144
+ /** Distinct cleanup failures collected by `clear()` or `destroy()`. */
145
+ readonly failures?: readonly unknown[];
146
+ }
147
+
94
148
  /**
95
- * The push observation surface of a {@link PoolInterface} (AGENTS §13) the resource
96
- * lifecycle moments a fire-and-forget observer subscribes to.
149
+ * A stable, machine-readable pool failure with the original cause and structured context.
97
150
  *
98
- * @remarks
99
- * Pure signals (no `T` payload — `Pool<T>` carries no resource value on its events, so a
100
- * non-generic map stays lean). Listener isolation is the emitter's (AGENTS §13): every event
101
- * is emitted directly and a listener throw is routed to the emitter's `error` handler (the
102
- * `error` option), never onto this map, and sits AFTER the relevant create / acquire /
103
- * release / destroy transition — so a throwing observer can never corrupt the FIFO
104
- * handoff-eviction machinery (it cannot strand a parked waiter or unbalance the lease count).
105
- * Subscribe via `pool.emitter.on(...)`. Declared as a `type` alias (§4.5 — `EventMap` is a
106
- * `type` kind).
151
+ * @example
152
+ * ```ts
153
+ * import { PoolError, isPoolError } from '@orkestrel/pool'
154
+ *
155
+ * try {
156
+ * await pool.acquire()
157
+ * } catch (error: unknown) {
158
+ * if (isPoolError(error)) console.error(error.code, error.cause)
159
+ * }
160
+ * ```
107
161
  */
162
+ export declare class PoolError extends Error {
163
+ /** Stable machine-readable failure category. */
164
+ readonly code: PoolCode;
165
+ /** Optional structured input or aggregate-cleanup details. */
166
+ readonly context: PoolContext | undefined;
167
+ /**
168
+ * Create a pool failure without coercing a hostile thrown value.
169
+ *
170
+ * @param options - Stable code plus optional cause and structured context
171
+ */
172
+ constructor(options: PoolErrorOptions);
173
+ }
174
+
175
+ /** Construction options for {@link PoolError}. */
176
+ export declare interface PoolErrorOptions {
177
+ /** The stable machine-readable failure category. */
178
+ readonly code: PoolCode;
179
+ /** The original thrown value, retained without unsafe string coercion. */
180
+ readonly cause?: unknown;
181
+ /** Optional structured failure details. */
182
+ readonly context?: PoolContext;
183
+ }
184
+
185
+ /** Observable resource lifecycle events emitted by a {@link PoolInterface}. */
108
186
  export declare type PoolEventMap = {
109
- /** A fresh resource was created (`create` resolved) and leased. */
187
+ /** A created resource entered pool ownership. */
110
188
  readonly create: readonly [];
111
- /** A token was handed to a lessee (a reused idle one, a fresh one, or a served waiter). */
189
+ /** A token settled successfully and its exact resource became leased. */
112
190
  readonly acquire: readonly [];
113
- /** A leased resource returned to idle (no waiter was parked). */
191
+ /** A released resource became immediately idle. */
114
192
  readonly release: readonly [];
115
- /** A resource was destroyed (`clear` / `destroy`, or a failed `validate`). */
193
+ /** A resource cleanup hook completed or was attempted when absent. */
116
194
  readonly destroy: readonly [];
117
195
  };
118
196
 
119
- /**
120
- * A bounded resource pool with idle reuse + FIFO waiting.
121
- *
122
- * @remarks
123
- * Exposes a typed {@link emitter} (AGENTS §13) carrying its resource lifecycle moments
124
- * ({@link PoolEventMap}) for fire-and-forget observers. Emitting is observation-only —
125
- * every event fires AFTER the relevant create / acquire / release / destroy transition, so a
126
- * buggy observer can never corrupt the FIFO handoff-eviction machinery: the emitter isolates
127
- * a listener throw and routes it to its `error` handler (the `error` option), never the pool.
128
- */
197
+ /** A FIFO resource pool with optional bounded capacity and deterministic teardown. */
129
198
  export declare interface PoolInterface<T> {
199
+ /** The typed synchronous lifecycle observation surface. */
130
200
  readonly emitter: EmitterInterface<PoolEventMap>;
201
+ /** All owned records, including records validating or destroying. */
131
202
  readonly size: number;
203
+ /** Records immediately available without validation work. */
132
204
  readonly idle: number;
205
+ /** Records represented by unsettled released-once lease tokens. */
133
206
  readonly active: number;
207
+ /**
208
+ * Queue and lease one resource in FIFO settlement order.
209
+ *
210
+ * @param signal - Optional native cancellation signal
211
+ * @returns A promise for the unique resource lease
212
+ */
134
213
  acquire(signal?: AbortSignal): Promise<PoolToken<T>>;
214
+ /**
215
+ * Destroy the records that are idle at this call's synchronous snapshot.
216
+ *
217
+ * @returns A promise that settles after every snapshot cleanup attempt
218
+ */
135
219
  clear(): Promise<void>;
220
+ /**
221
+ * Permanently tear down the pool and return its stable completion barrier.
222
+ *
223
+ * @returns The exact promise shared by every destroy call
224
+ */
136
225
  destroy(): Promise<void>;
137
226
  }
138
227
 
139
228
  /**
140
- * Options for `createPool` the resource lifecycle hooks.
229
+ * Resource lifecycle options for {@link Pool} and `createPool`.
141
230
  *
142
231
  * @remarks
143
- * - `create` make a fresh resource; called when no idle resource is reusable and
144
- * the pool is below `max`. May be async.
145
- * - `destroy` tear a resource down when the pool drops it (`clear` / `destroy`, or
146
- * a failed `validate`); optional and awaited.
147
- * - `validate` — check an idle resource is still usable before leasing it; an invalid
148
- * resource is destroyed and replaced. Optional (an absent validator trusts idle).
149
- * - `max` — the most resources that may exist at once (idle + leased); defaults to
150
- * unbounded. A surplus `acquire` waits (FIFO) for a `release`.
151
- * - `on` — the reserved {@link EmitterHooks} key (§8): initial listeners for the pool's
152
- * {@link PoolEventMap}, wired at construction (e.g. `{ create: () => count() }`).
232
+ * `create` lazily produces resources. `destroy` tears down a claimed resource.
233
+ * `validate` checks a previously owned resource before reuse. `max` is a positive
234
+ * safe integer; omission is the only unbounded form. `on` installs initial emitter
235
+ * listeners and `error` receives isolated listener failures.
153
236
  */
154
237
  export declare interface PoolOptions<T> {
155
238
  readonly on?: EmitterHooks<PoolEventMap>;
156
- /** The emitter's listener-error handler (AGENTS §13) — a listener throw routes here, not to a domain event. */
157
239
  readonly error?: EmitterErrorHandler;
158
240
  readonly create: () => Promise<T> | T;
159
241
  readonly destroy?: (value: T) => Promise<void> | void;
@@ -161,34 +243,12 @@ export declare interface PoolOptions<T> {
161
243
  readonly max?: number;
162
244
  }
163
245
 
164
- /**
165
- * A leased resource from a {@link PoolInterface} — `value` is the live resource and
166
- * `release()` returns it to the pool for reuse (or hands it to the next waiter).
167
- */
246
+ /** A unique lease over one pool-owned resource record. */
168
247
  export declare interface PoolToken<T> {
169
- /** The leased resource. */
248
+ /** The leased value. Duplicate values still belong to independent records. */
170
249
  readonly value: T;
171
- /** Return the resource to the pool; calling more than once is a no-op. */
250
+ /** Return this exact lease once; subsequent calls are no-ops. */
172
251
  release(): void;
173
252
  }
174
253
 
175
- /**
176
- * A parked acquirer on a {@link PoolInterface}'s FIFO waiter list — its promise resolvers
177
- * plus the cleanup that detaches its abort listener.
178
- *
179
- * @remarks
180
- * Held only inside the {@link PoolInterface} engine (a resource at `max` parks the acquirer
181
- * here until a `release` hands it a token); not part of the public call surface, but
182
- * centralized here per AGENTS §5. `resolve` hands the waiter its leased {@link PoolToken};
183
- * `reject` fails its `acquire` (a teardown or an aborted wait); `clear` detaches the abort
184
- * listener so a settled waiter leaks nothing.
185
- *
186
- * @typeParam T - The resource the pool leases
187
- */
188
- export declare interface PoolWaiter<T> {
189
- readonly resolve: (token: PoolToken<T>) => void;
190
- readonly reject: (error: unknown) => void;
191
- clear(): void;
192
- }
193
-
194
254
  export { }