@orkestrel/worker 0.0.3 → 0.0.5
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/README.md +3 -2
- package/dist/src/core/index.cjs +65 -31
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +47 -22
- package/dist/src/core/index.d.ts +47 -22
- package/dist/src/core/index.js +65 -31
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +368 -175
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +44 -58
- package/dist/src/server/index.d.ts +44 -58
- package/dist/src/server/index.js +368 -175
- package/dist/src/server/index.js.map +1 -1
- package/package.json +22 -19
package/dist/src/core/index.js
CHANGED
|
@@ -11,16 +11,23 @@ import { Queue } from "@orkestrel/queue";
|
|
|
11
11
|
* `options.pool`) and a `Queue` whose handler ACQUIRES a pooled resource, runs the
|
|
12
12
|
* user handler against it, and RELEASES it in a `finally`. All concurrency, retries,
|
|
13
13
|
* timeout, and lifecycle are the Queue's — the Worker adds only the resource pairing.
|
|
14
|
-
* - **Resource ↔ concurrency.** The
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* - **Resource ↔ concurrency.** The queue strictly validates `concurrency` as a positive
|
|
15
|
+
* safe integer after caller options are captured once. Only `undefined` defaults
|
|
16
|
+
* `concurrency` to `1` or pool `max` to that value; runtime `null` reaches the owning
|
|
17
|
+
* validator. The queue validates before the pool option is read; every declared pool member
|
|
18
|
+
* is then captured once by direct access, preserving inherited and non-enumerable structural
|
|
19
|
+
* options. At most one resource exists per in-flight job by default, and idle resources are
|
|
20
|
+
* reused across jobs.
|
|
17
21
|
* - **Acquire over the attempt signal.** Each job acquires using the attempt's
|
|
18
22
|
* `execution.signal`, so an `abort` / `timeout` while waiting for a resource rejects
|
|
19
23
|
* the acquire — the Queue then handles retry / rejection, and there is no token to
|
|
20
24
|
* release (the resource was never leased).
|
|
21
25
|
* - **Lifecycle (§10).** `enqueue` / `restore` / `start` / `stop` / `pause` / `resume` /
|
|
22
26
|
* `abort` / `clear` delegate to the queue; `count` / `active` / `paused` / `stopped`
|
|
23
|
-
* read it. `
|
|
27
|
+
* read it. `stop` / `abort` / `clear` return the queue's own cleanup barriers.
|
|
28
|
+
* `destroy` returns one stable barrier while it tears down the queue, then the pool,
|
|
29
|
+
* and destroys the worker emitter last. A sole cleanup failure is preserved by
|
|
30
|
+
* identity; failures from both layers become an ordered `AggregateError`.
|
|
24
31
|
* - **Durability.** An optional `store` is passed straight through to the queue, so the
|
|
25
32
|
* worker's outstanding jobs persist; `restore` re-runs them (delegated to the queue).
|
|
26
33
|
* - **Observable (§13).** The owned {@link emitter} ({@link WorkerEventMap}) RE-EXPOSES the
|
|
@@ -38,30 +45,31 @@ var Worker = class {
|
|
|
38
45
|
#queue;
|
|
39
46
|
#pool;
|
|
40
47
|
#emitter;
|
|
41
|
-
#
|
|
48
|
+
#handler;
|
|
49
|
+
#ending;
|
|
42
50
|
constructor(options) {
|
|
43
|
-
const concurrency
|
|
51
|
+
const { concurrency: capturedConcurrency, handler, on, error, retries, timeout, store } = options;
|
|
52
|
+
const concurrency = capturedConcurrency === void 0 ? 1 : capturedConcurrency;
|
|
53
|
+
this.#handler = handler;
|
|
44
54
|
this.#emitter = new Emitter({
|
|
45
|
-
on:
|
|
46
|
-
error:
|
|
47
|
-
});
|
|
48
|
-
this.#pool = new Pool({
|
|
49
|
-
...options.pool,
|
|
50
|
-
max: options.pool.max ?? concurrency
|
|
55
|
+
...on !== void 0 ? { on } : {},
|
|
56
|
+
...error !== void 0 ? { error } : {}
|
|
51
57
|
});
|
|
52
58
|
this.#queue = new Queue({
|
|
53
|
-
handler:
|
|
54
|
-
const token = await this.#pool.acquire(execution.signal);
|
|
55
|
-
try {
|
|
56
|
-
return await options.handler(input, token.value, execution);
|
|
57
|
-
} finally {
|
|
58
|
-
token.release();
|
|
59
|
-
}
|
|
60
|
-
},
|
|
59
|
+
handler: this.#handle.bind(this),
|
|
61
60
|
concurrency,
|
|
62
|
-
retries:
|
|
63
|
-
timeout:
|
|
64
|
-
store:
|
|
61
|
+
...retries !== void 0 ? { retries } : {},
|
|
62
|
+
...timeout !== void 0 ? { timeout } : {},
|
|
63
|
+
...store !== void 0 ? { store } : {}
|
|
64
|
+
});
|
|
65
|
+
const { max, on: poolOn, error: poolError, create, destroy, validate } = options.pool;
|
|
66
|
+
this.#pool = new Pool({
|
|
67
|
+
create,
|
|
68
|
+
max: max === void 0 ? concurrency : max,
|
|
69
|
+
...poolOn !== void 0 ? { on: poolOn } : {},
|
|
70
|
+
...poolError !== void 0 ? { error: poolError } : {},
|
|
71
|
+
...destroy !== void 0 ? { destroy } : {},
|
|
72
|
+
...validate !== void 0 ? { validate } : {}
|
|
65
73
|
});
|
|
66
74
|
this.#bridge();
|
|
67
75
|
}
|
|
@@ -90,7 +98,7 @@ var Worker = class {
|
|
|
90
98
|
this.#queue.start();
|
|
91
99
|
}
|
|
92
100
|
stop() {
|
|
93
|
-
this.#queue.stop();
|
|
101
|
+
return this.#queue.stop();
|
|
94
102
|
}
|
|
95
103
|
pause() {
|
|
96
104
|
this.#queue.pause();
|
|
@@ -99,16 +107,42 @@ var Worker = class {
|
|
|
99
107
|
this.#queue.resume();
|
|
100
108
|
}
|
|
101
109
|
abort(reason) {
|
|
102
|
-
this.#queue.abort(reason);
|
|
110
|
+
return this.#queue.abort(reason);
|
|
103
111
|
}
|
|
104
112
|
clear() {
|
|
105
|
-
this.#queue.clear();
|
|
113
|
+
return this.#queue.clear();
|
|
106
114
|
}
|
|
107
115
|
destroy() {
|
|
108
|
-
if (this.#
|
|
109
|
-
|
|
110
|
-
this.#
|
|
111
|
-
this.#
|
|
116
|
+
if (this.#ending !== void 0) return this.#ending.promise;
|
|
117
|
+
const ending = Promise.withResolvers();
|
|
118
|
+
this.#ending = ending;
|
|
119
|
+
this.#teardown(ending);
|
|
120
|
+
return ending.promise;
|
|
121
|
+
}
|
|
122
|
+
async #handle(input, execution) {
|
|
123
|
+
const token = await this.#pool.acquire(execution.signal);
|
|
124
|
+
try {
|
|
125
|
+
return await this.#handler(input, token.value, execution);
|
|
126
|
+
} finally {
|
|
127
|
+
token.release();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async #teardown(ending) {
|
|
131
|
+
const failures = [];
|
|
132
|
+
try {
|
|
133
|
+
await this.#queue.destroy();
|
|
134
|
+
} catch (error) {
|
|
135
|
+
failures.push(error);
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
await this.#pool.destroy();
|
|
139
|
+
} catch (error) {
|
|
140
|
+
failures.push(error);
|
|
141
|
+
}
|
|
142
|
+
this.#emitter.destroy();
|
|
143
|
+
if (failures.length === 0) ending.resolve();
|
|
144
|
+
else if (failures.length === 1) ending.reject(failures[0]);
|
|
145
|
+
else ending.reject(new AggregateError(failures, "worker destroy cleanup failed"));
|
|
112
146
|
}
|
|
113
147
|
#bridge() {
|
|
114
148
|
const queue = this.#queue.emitter;
|
|
@@ -146,7 +180,7 @@ var Worker = class {
|
|
|
146
180
|
*
|
|
147
181
|
* @example
|
|
148
182
|
* ```ts
|
|
149
|
-
* import { createWorker } from '@
|
|
183
|
+
* import { createWorker } from '@orkestrel/worker'
|
|
150
184
|
*
|
|
151
185
|
* const worker = createWorker<Query, Connection, Rows>({
|
|
152
186
|
* pool: { create: () => connect(), destroy: (connection) => connection.close() },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#queue","#pool","#emitter","#bridge","#destroyed"],"sources":["../../../src/core/Worker.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QueueEntryOptions } from '@orkestrel/queue'\nimport type { WorkerEventMap, WorkerInterface, WorkerOptions } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Pool } from '@orkestrel/pool'\nimport { Queue } from '@orkestrel/queue'\n\n/**\n * A resource-backed job worker — a thin facade composing a `Queue` (`@orkestrel/queue`)\n * with a `Pool` (`@orkestrel/pool`).\n *\n * @remarks\n * - **Composition, not reimplementation.** The Worker owns a `Pool` (built from\n * `options.pool`) and a `Queue` whose handler ACQUIRES a pooled resource, runs the\n * user handler against it, and RELEASES it in a `finally`. All concurrency, retries,\n * timeout, and lifecycle are the Queue's — the Worker adds only the resource pairing.\n * - **Resource ↔ concurrency.** The pool's `max` defaults to the worker's\n * `concurrency` (default `1`), so at most one resource exists per in-flight job and\n * idle resources are reused across jobs.\n * - **Acquire over the attempt signal.** Each job acquires using the attempt's\n * `execution.signal`, so an `abort` / `timeout` while waiting for a resource rejects\n * the acquire — the Queue then handles retry / rejection, and there is no token to\n * release (the resource was never leased).\n * - **Lifecycle (§10).** `enqueue` / `restore` / `start` / `stop` / `pause` / `resume` /\n * `abort` / `clear` delegate to the queue; `count` / `active` / `paused` / `stopped`\n * read it. `destroy` destroys the queue then tears the pool down, idempotently.\n * - **Durability.** An optional `store` is passed straight through to the queue, so the\n * worker's outstanding jobs persist; `restore` re-runs them (delegated to the queue).\n * - **Observable (§13).** The owned {@link emitter} ({@link WorkerEventMap}) RE-EXPOSES the\n * underlying queue's job lifecycle (`enqueue` / `start` / `retry` / `success` / `failure` /\n * `abort` / `drain`) as the worker's OWN events — bridged from the inner queue's emitter at\n * construction — so a consumer observes the worker without reaching through to internals.\n * The bridge re-emits directly on the worker's own emitter; the worker emitter isolates a\n * listener throw and routes it to its `error` handler (the `error` option), so a buggy\n * worker observer can never corrupt the inner queue or pool — the bridge listener never\n * throws, so the inner queue's own emit stays balanced. The pool's create / acquire /\n * release events stay the pool's internal concern (a Worker manages its own resources);\n * observe a `Pool` directly for those.\n */\nexport class Worker<TInput, TResource, TResult> implements WorkerInterface<TInput, TResult> {\n\treadonly #queue: Queue<TInput, TResult>\n\treadonly #pool: Pool<TResource>\n\t// The PUSH observation surface (§13) — the worker's OWN emitter, fed by the queue→worker\n\t// bridge. The emitter isolates a worker observer's throw (routing it to the `error`\n\t// handler), so it never escapes into queue or pool.\n\treadonly #emitter: Emitter<WorkerEventMap<TResult>>\n\t#destroyed = false\n\n\tconstructor(options: WorkerOptions<TInput, TResource, TResult>) {\n\t\tconst concurrency = Math.max(1, options.concurrency ?? 1)\n\t\tthis.#emitter = new Emitter<WorkerEventMap<TResult>>({ on: options?.on, error: options?.error })\n\t\tthis.#pool = new Pool<TResource>({\n\t\t\t...options.pool,\n\t\t\tmax: options.pool.max ?? concurrency,\n\t\t})\n\t\tthis.#queue = new Queue<TInput, TResult>({\n\t\t\thandler: async (input, execution) => {\n\t\t\t\tconst token = await this.#pool.acquire(execution.signal)\n\t\t\t\ttry {\n\t\t\t\t\treturn await options.handler(input, token.value, execution)\n\t\t\t\t} finally {\n\t\t\t\t\ttoken.release()\n\t\t\t\t}\n\t\t\t},\n\t\t\tconcurrency,\n\t\t\tretries: options.retries,\n\t\t\ttimeout: options.timeout,\n\t\t\tstore: options.store,\n\t\t})\n\t\tthis.#bridge()\n\t}\n\n\tget emitter(): EmitterInterface<WorkerEventMap<TResult>> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#queue.count\n\t}\n\n\tget active(): number {\n\t\treturn this.#queue.active\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#queue.paused\n\t}\n\n\tget stopped(): boolean {\n\t\treturn this.#queue.stopped\n\t}\n\n\tenqueue(input: TInput, options?: QueueEntryOptions): Promise<TResult> {\n\t\treturn this.#queue.enqueue(input, options)\n\t}\n\n\trestore(): Promise<void> {\n\t\treturn this.#queue.restore()\n\t}\n\n\tstart(): void {\n\t\tthis.#queue.start()\n\t}\n\n\tstop(): void {\n\t\tthis.#queue.stop()\n\t}\n\n\tpause(): void {\n\t\tthis.#queue.pause()\n\t}\n\n\tresume(): void {\n\t\tthis.#queue.resume()\n\t}\n\n\tabort(reason?: unknown): void {\n\t\tthis.#queue.abort(reason)\n\t}\n\n\tclear(): void {\n\t\tthis.#queue.clear()\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#queue.destroy()\n\t\tvoid this.#pool.destroy()\n\t}\n\n\t// Bridge the inner queue's lifecycle onto the worker's OWN emitter, once at construction.\n\t// Each listener re-emits the queue event directly on the worker's emitter, which isolates a\n\t// worker observer's throw (routing it to the worker's `error` handler). Because the bridge\n\t// listener itself never throws, the queue's own `#emitter.emit` — which invoked this\n\t// listener — sees no throw, so the inner queue's engine stays balanced regardless of what a\n\t// worker observer does. The events are already post-transition (they fire from the queue's\n\t// own post-settle / post-wake emits), so this stays observation.\n\t#bridge(): void {\n\t\tconst queue = this.#queue.emitter\n\t\tqueue.on('enqueue', (id) => this.#emitter.emit('enqueue', id))\n\t\tqueue.on('start', (id) => this.#emitter.emit('start', id))\n\t\tqueue.on('retry', (id, attempt) => this.#emitter.emit('retry', id, attempt))\n\t\tqueue.on('success', (id, result) => this.#emitter.emit('success', id, result))\n\t\tqueue.on('failure', (id, error) => this.#emitter.emit('failure', id, error))\n\t\tqueue.on('abort', (reason) => this.#emitter.emit('abort', reason))\n\t\tqueue.on('drain', () => this.#emitter.emit('drain'))\n\t}\n}\n","import type { WorkerInterface, WorkerOptions } from './types.js'\nimport { Worker } from './Worker.js'\n\n/**\n * Create a resource-backed job worker — a `Queue` (`@orkestrel/queue`) marrying a `Pool`\n * (`@orkestrel/pool`). Each enqueued input runs through the handler against an\n * automatically acquired pooled resource (released when the job settles), with the\n * queue's bounded concurrency, retries, and per-attempt timeout / abort.\n *\n * @remarks\n * The pool's `max` defaults to `concurrency`, so resources match the jobs in flight and\n * are reused across jobs. A handler that throws still releases its resource (the\n * acquire/release pair brackets the call in a `finally`), so a later job reuses it. The\n * lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)\n * delegates to the queue; `destroy` also tears the pool down. Observable (§13): a typed\n * `emitter` surfaces the queue lifecycle (`enqueue` / `start` / `success` / `failure` / …).\n *\n * @typeParam TInput - The work input each job carries\n * @typeParam TResource - The pooled resource each job runs against\n * @typeParam TResult - The value the handler resolves for a job\n * @param options - The `handler` and `pool` plus optional `concurrency` (default `1`),\n * `retries` (default `0`), and a default per-attempt `timeout` in milliseconds\n * @returns A working {@link WorkerInterface}\n *\n * @example\n * ```ts\n * import { createWorker } from '@src/core'\n *\n * const worker = createWorker<Query, Connection, Rows>({\n * \tpool: { create: () => connect(), destroy: (connection) => connection.close() },\n * \thandler: (query, connection, { signal }) => connection.run(query, signal),\n * \tconcurrency: 4,\n * \tretries: 1,\n * })\n *\n * const rows = await worker.enqueue(query)\n * ```\n */\nexport function createWorker<TInput, TResource, TResult>(\n\toptions: WorkerOptions<TInput, TResource, TResult>,\n): WorkerInterface<TInput, TResult> {\n\treturn new Worker(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,SAAb,MAA4F;CAC3F;CACA;CAIA;CACA,aAAa;CAEb,YAAY,SAAoD;EAC/D,MAAM,cAAc,KAAK,IAAI,GAAG,QAAQ,eAAe,CAAC;EACxD,KAAKE,WAAW,IAAI,QAAiC;GAAE,IAAI,SAAS;GAAI,OAAO,SAAS;EAAM,CAAC;EAC/F,KAAKD,QAAQ,IAAI,KAAgB;GAChC,GAAG,QAAQ;GACX,KAAK,QAAQ,KAAK,OAAO;EAC1B,CAAC;EACD,KAAKD,SAAS,IAAI,MAAuB;GACxC,SAAS,OAAO,OAAO,cAAc;IACpC,MAAM,QAAQ,MAAM,KAAKC,MAAM,QAAQ,UAAU,MAAM;IACvD,IAAI;KACH,OAAO,MAAM,QAAQ,QAAQ,OAAO,MAAM,OAAO,SAAS;IAC3D,UAAU;KACT,MAAM,QAAQ;IACf;GACD;GACA;GACA,SAAS,QAAQ;GACjB,SAAS,QAAQ;GACjB,OAAO,QAAQ;EAChB,CAAC;EACD,KAAKE,QAAQ;CACd;CAEA,IAAI,UAAqD;EACxD,OAAO,KAAKD;CACb;CAEA,IAAI,QAAgB;EACnB,OAAO,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;CACpD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9GA,SAAgB,aACf,SACmC;CACnC,OAAO,IAAI,OAAO,OAAO;AAC1B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#queue","#pool","#emitter","#handler","#handle","#bridge","#ending","#teardown"],"sources":["../../../src/core/Worker.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QueueEntryOptions, QueueExecution } from '@orkestrel/queue'\nimport type { WorkerEventMap, WorkerHandler, WorkerInterface, WorkerOptions } from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Pool } from '@orkestrel/pool'\nimport { Queue } from '@orkestrel/queue'\n\n/**\n * A resource-backed job worker — a thin facade composing a `Queue` (`@orkestrel/queue`)\n * with a `Pool` (`@orkestrel/pool`).\n *\n * @remarks\n * - **Composition, not reimplementation.** The Worker owns a `Pool` (built from\n * `options.pool`) and a `Queue` whose handler ACQUIRES a pooled resource, runs the\n * user handler against it, and RELEASES it in a `finally`. All concurrency, retries,\n * timeout, and lifecycle are the Queue's — the Worker adds only the resource pairing.\n * - **Resource ↔ concurrency.** The queue strictly validates `concurrency` as a positive\n * safe integer after caller options are captured once. Only `undefined` defaults\n * `concurrency` to `1` or pool `max` to that value; runtime `null` reaches the owning\n * validator. The queue validates before the pool option is read; every declared pool member\n * is then captured once by direct access, preserving inherited and non-enumerable structural\n * options. At most one resource exists per in-flight job by default, and idle resources are\n * reused across jobs.\n * - **Acquire over the attempt signal.** Each job acquires using the attempt's\n * `execution.signal`, so an `abort` / `timeout` while waiting for a resource rejects\n * the acquire — the Queue then handles retry / rejection, and there is no token to\n * release (the resource was never leased).\n * - **Lifecycle (§10).** `enqueue` / `restore` / `start` / `stop` / `pause` / `resume` /\n * `abort` / `clear` delegate to the queue; `count` / `active` / `paused` / `stopped`\n * read it. `stop` / `abort` / `clear` return the queue's own cleanup barriers.\n * `destroy` returns one stable barrier while it tears down the queue, then the pool,\n * and destroys the worker emitter last. A sole cleanup failure is preserved by\n * identity; failures from both layers become an ordered `AggregateError`.\n * - **Durability.** An optional `store` is passed straight through to the queue, so the\n * worker's outstanding jobs persist; `restore` re-runs them (delegated to the queue).\n * - **Observable (§13).** The owned {@link emitter} ({@link WorkerEventMap}) RE-EXPOSES the\n * underlying queue's job lifecycle (`enqueue` / `start` / `retry` / `success` / `failure` /\n * `abort` / `drain`) as the worker's OWN events — bridged from the inner queue's emitter at\n * construction — so a consumer observes the worker without reaching through to internals.\n * The bridge re-emits directly on the worker's own emitter; the worker emitter isolates a\n * listener throw and routes it to its `error` handler (the `error` option), so a buggy\n * worker observer can never corrupt the inner queue or pool — the bridge listener never\n * throws, so the inner queue's own emit stays balanced. The pool's create / acquire /\n * release events stay the pool's internal concern (a Worker manages its own resources);\n * observe a `Pool` directly for those.\n */\nexport class Worker<TInput, TResource, TResult> implements WorkerInterface<TInput, TResult> {\n\treadonly #queue: Queue<TInput, TResult>\n\treadonly #pool: Pool<TResource>\n\t// The PUSH observation surface (§13) — the worker's OWN emitter, fed by the queue→worker\n\t// bridge. The emitter isolates a worker observer's throw (routing it to the `error`\n\t// handler), so it never escapes into queue or pool.\n\treadonly #emitter: Emitter<WorkerEventMap<TResult>>\n\treadonly #handler: WorkerHandler<TInput, TResource, TResult>\n\t#ending: PromiseWithResolvers<void> | undefined\n\n\tconstructor(options: WorkerOptions<TInput, TResource, TResult>) {\n\t\tconst {\n\t\t\tconcurrency: capturedConcurrency,\n\t\t\thandler,\n\t\t\ton,\n\t\t\terror,\n\t\t\tretries,\n\t\t\ttimeout,\n\t\t\tstore,\n\t\t} = options\n\t\tconst concurrency = capturedConcurrency === undefined ? 1 : capturedConcurrency\n\t\tthis.#handler = handler\n\t\tthis.#emitter = new Emitter<WorkerEventMap<TResult>>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t\tthis.#queue = new Queue<TInput, TResult>({\n\t\t\thandler: this.#handle.bind(this),\n\t\t\tconcurrency,\n\t\t\t...(retries !== undefined ? { retries } : {}),\n\t\t\t...(timeout !== undefined ? { timeout } : {}),\n\t\t\t...(store !== undefined ? { store } : {}),\n\t\t})\n\t\tconst pool = options.pool\n\t\tconst { max, on: poolOn, error: poolError, create, destroy, validate } = pool\n\t\tthis.#pool = new Pool<TResource>({\n\t\t\tcreate,\n\t\t\tmax: max === undefined ? concurrency : max,\n\t\t\t...(poolOn !== undefined ? { on: poolOn } : {}),\n\t\t\t...(poolError !== undefined ? { error: poolError } : {}),\n\t\t\t...(destroy !== undefined ? { destroy } : {}),\n\t\t\t...(validate !== undefined ? { validate } : {}),\n\t\t})\n\t\tthis.#bridge()\n\t}\n\n\tget emitter(): EmitterInterface<WorkerEventMap<TResult>> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#queue.count\n\t}\n\n\tget active(): number {\n\t\treturn this.#queue.active\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#queue.paused\n\t}\n\n\tget stopped(): boolean {\n\t\treturn this.#queue.stopped\n\t}\n\n\tenqueue(input: TInput, options?: QueueEntryOptions): Promise<TResult> {\n\t\treturn this.#queue.enqueue(input, options)\n\t}\n\n\trestore(): Promise<void> {\n\t\treturn this.#queue.restore()\n\t}\n\n\tstart(): void {\n\t\tthis.#queue.start()\n\t}\n\n\tstop(): Promise<void> {\n\t\treturn this.#queue.stop()\n\t}\n\n\tpause(): void {\n\t\tthis.#queue.pause()\n\t}\n\n\tresume(): void {\n\t\tthis.#queue.resume()\n\t}\n\n\tabort(reason?: unknown): Promise<void> {\n\t\treturn this.#queue.abort(reason)\n\t}\n\n\tclear(): Promise<void> {\n\t\treturn this.#queue.clear()\n\t}\n\n\tdestroy(): Promise<void> {\n\t\tif (this.#ending !== undefined) return this.#ending.promise\n\t\tconst ending = Promise.withResolvers<void>()\n\t\tthis.#ending = ending\n\t\tvoid this.#teardown(ending)\n\t\treturn ending.promise\n\t}\n\n\tasync #handle(input: TInput, execution: QueueExecution): Promise<TResult> {\n\t\tconst token = await this.#pool.acquire(execution.signal)\n\t\ttry {\n\t\t\treturn await this.#handler(input, token.value, execution)\n\t\t} finally {\n\t\t\ttoken.release()\n\t\t}\n\t}\n\n\tasync #teardown(ending: PromiseWithResolvers<void>): Promise<void> {\n\t\tconst failures: unknown[] = []\n\t\ttry {\n\t\t\tawait this.#queue.destroy()\n\t\t} catch (error) {\n\t\t\tfailures.push(error)\n\t\t}\n\t\ttry {\n\t\t\tawait this.#pool.destroy()\n\t\t} catch (error) {\n\t\t\tfailures.push(error)\n\t\t}\n\t\tthis.#emitter.destroy()\n\t\tif (failures.length === 0) ending.resolve()\n\t\telse if (failures.length === 1) ending.reject(failures[0])\n\t\telse ending.reject(new AggregateError(failures, 'worker destroy cleanup failed'))\n\t}\n\n\t// Bridge the inner queue's lifecycle onto the worker's OWN emitter, once at construction.\n\t// Each listener re-emits the queue event directly on the worker's emitter, which isolates a\n\t// worker observer's throw (routing it to the worker's `error` handler). Because the bridge\n\t// listener itself never throws, the queue's own `#emitter.emit` — which invoked this\n\t// listener — sees no throw, so the inner queue's engine stays balanced regardless of what a\n\t// worker observer does. The events are already post-transition (they fire from the queue's\n\t// own post-settle / post-wake emits), so this stays observation.\n\t#bridge(): void {\n\t\tconst queue = this.#queue.emitter\n\t\tqueue.on('enqueue', (id) => this.#emitter.emit('enqueue', id))\n\t\tqueue.on('start', (id) => this.#emitter.emit('start', id))\n\t\tqueue.on('retry', (id, attempt) => this.#emitter.emit('retry', id, attempt))\n\t\tqueue.on('success', (id, result) => this.#emitter.emit('success', id, result))\n\t\tqueue.on('failure', (id, error) => this.#emitter.emit('failure', id, error))\n\t\tqueue.on('abort', (reason) => this.#emitter.emit('abort', reason))\n\t\tqueue.on('drain', () => this.#emitter.emit('drain'))\n\t}\n}\n","import type { WorkerInterface, WorkerOptions } from './types.js'\nimport { Worker } from './Worker.js'\n\n/**\n * Create a resource-backed job worker — a `Queue` (`@orkestrel/queue`) marrying a `Pool`\n * (`@orkestrel/pool`). Each enqueued input runs through the handler against an\n * automatically acquired pooled resource (released when the job settles), with the\n * queue's bounded concurrency, retries, and per-attempt timeout / abort.\n *\n * @remarks\n * The pool's `max` defaults to `concurrency`, so resources match the jobs in flight and\n * are reused across jobs. A handler that throws still releases its resource (the\n * acquire/release pair brackets the call in a `finally`), so a later job reuses it. The\n * lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)\n * delegates to the queue; `destroy` also tears the pool down. Observable (§13): a typed\n * `emitter` surfaces the queue lifecycle (`enqueue` / `start` / `success` / `failure` / …).\n *\n * @typeParam TInput - The work input each job carries\n * @typeParam TResource - The pooled resource each job runs against\n * @typeParam TResult - The value the handler resolves for a job\n * @param options - The `handler` and `pool` plus optional `concurrency` (default `1`),\n * `retries` (default `0`), and a default per-attempt `timeout` in milliseconds\n * @returns A working {@link WorkerInterface}\n *\n * @example\n * ```ts\n * import { createWorker } from '@orkestrel/worker'\n *\n * const worker = createWorker<Query, Connection, Rows>({\n * \tpool: { create: () => connect(), destroy: (connection) => connection.close() },\n * \thandler: (query, connection, { signal }) => connection.run(query, signal),\n * \tconcurrency: 4,\n * \tretries: 1,\n * })\n *\n * const rows = await worker.enqueue(query)\n * ```\n */\nexport function createWorker<TInput, TResource, TResult>(\n\toptions: WorkerOptions<TInput, TResource, TResult>,\n): WorkerInterface<TInput, TResult> {\n\treturn new Worker(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,SAAb,MAA4F;CAC3F;CACA;CAIA;CACA;CACA;CAEA,YAAY,SAAoD;EAC/D,MAAM,EACL,aAAa,qBACb,SACA,IACA,OACA,SACA,SACA,UACG;EACJ,MAAM,cAAc,wBAAwB,KAAA,IAAY,IAAI;EAC5D,KAAKG,WAAW;EAChB,KAAKD,WAAW,IAAI,QAAiC;GACpD,GAAI,OAAO,KAAA,IAAY,EAAE,GA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