@orkestrel/worker 0.0.4 → 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 +55 -24
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +38 -15
- package/dist/src/core/index.d.ts +38 -15
- package/dist/src/core/index.js +55 -24
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +140 -67
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +39 -50
- package/dist/src/server/index.d.ts +39 -50
- package/dist/src/server/index.js +140 -67
- package/dist/src/server/index.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#queue","#pool","#emitter","#handler","#handle","#bridge","#destroyed"],"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 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\treadonly #handler: WorkerHandler<TInput, TResource, 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.#handler = options.handler\n\t\tthis.#emitter = new Emitter<WorkerEventMap<TResult>>({\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\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: this.#handle.bind(this),\n\t\t\tconcurrency,\n\t\t\t...(options.retries !== undefined ? { retries: options.retries } : {}),\n\t\t\t...(options.timeout !== undefined ? { timeout: options.timeout } : {}),\n\t\t\t...(options.store !== undefined ? { store: 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\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\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;CACA,aAAa;CAEb,YAAY,SAAoD;EAC/D,MAAM,cAAc,KAAK,IAAI,GAAG,QAAQ,eAAe,CAAC;EACxD,KAAKG,WAAW,QAAQ;EACxB,KAAKD,WAAW,IAAI,QAAiC;GACpD,GAAI,QAAQ,OAAO,KAAA,IAAY,EAAE,IAAI,QAAQ,GAAG,IAAI,CAAC;GACrD,GAAI,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;EAC/D,CAAC;EACD,KAAKD,QAAQ,IAAI,KAAgB;GAChC,GAAG,QAAQ;GACX,KAAK,QAAQ,KAAK,OAAO;EAC1B,CAAC;EACD,KAAKD,SAAS,IAAI,MAAuB;GACxC,SAAS,KAAKI,QAAQ,KAAK,IAAI;GAC/B;GACA,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;GACpE,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;GACpE,GAAI,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;EAC/D,CAAC;EACD,KAAKC,QAAQ;CACd;CAEA,IAAI,UAAqD;EACxD,OAAO,KAAKH;CACb;CAEA,IAAI,QAAgB;EACnB,OAAO,KAAKF,OAAO;CACpB;CAEA,IAAI,SAAiB;EACpB,OA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K,WAAW,IAAI,KAAK,CAAC;EAC3E,MAAM,GAAG,UAAU,WAAW,KAAKA,SAAS,KAAK,SAAS,MAAM,CAAC;EACjE,MAAM,GAAG,eAAe,KAAKA,SAAS,KAAK,OAAO,CAAC;CACpD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrHA,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,S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CAAC;EAC7D,MAAM,GAAG,UAAU,OAAO,KAAKA,SAAS,KAAK,SAAS,EAAE,CAAC;EACzD,MAAM,GAAG,UAAU,IAAI,YAAY,KAAKA,SAAS,KAAK,SAAS,IAAI,OAAO,CAAC;EAC3E,MAAM,GAAG,YAAY,IAAI,WAAW,KAAKA,SAAS,KAAK,WAAW,IAAI,MAAM,CAAC;EAC7E,MAAM,GAAG,YAAY,IAAI,UAAU,KAAKA,SAAS,KAAK,WAAW,IAAI,KAAK,CAAC;EAC3E,MAAM,GAAG,UAAU,WAAW,KAAKA,SAAS,KAAK,SAAS,MAAM,CAAC;EACjE,MAAM,GAAG,eAAe,KAAKA,SAAS,KAAK,OAAO,CAAC;CACpD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9JA,SAAgB,aACf,SACmC;CACnC,OAAO,IAAI,OAAO,OAAO;AAC1B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
let node_worker_threads = require("node:worker_threads");
|
|
3
2
|
let _orkestrel_contract = require("@orkestrel/contract");
|
|
3
|
+
let node_worker_threads = require("node:worker_threads");
|
|
4
4
|
let _orkestrel_database_server = require("@orkestrel/database/server");
|
|
5
5
|
let _orkestrel_queue = require("@orkestrel/queue");
|
|
6
6
|
let _src_core = require("../core/index.cjs");
|
|
@@ -9,16 +9,16 @@ let _src_core = require("../core/index.cjs");
|
|
|
9
9
|
* Internal mutable implementation of the readonly {@link NodeThread} observation contract.
|
|
10
10
|
*
|
|
11
11
|
* @remarks
|
|
12
|
-
* Liveness and the first terminal error live behind runtime-private fields.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* Liveness and the first terminal error live behind runtime-private fields. Thread `error`,
|
|
13
|
+
* `messageerror`, and `exit` all latch death, so pool validation cannot reuse a thread whose
|
|
14
|
+
* inbound message could not be deserialized.
|
|
15
15
|
*/
|
|
16
16
|
var Thread = class {
|
|
17
17
|
#worker;
|
|
18
18
|
#promise;
|
|
19
19
|
#resolve;
|
|
20
20
|
#reject;
|
|
21
|
-
#
|
|
21
|
+
#recordHandler;
|
|
22
22
|
#recordExitHandler;
|
|
23
23
|
#onlineHandler;
|
|
24
24
|
#spawnErrorHandler;
|
|
@@ -31,12 +31,13 @@ var Thread = class {
|
|
|
31
31
|
this.#promise = readiness.promise;
|
|
32
32
|
this.#resolve = readiness.resolve;
|
|
33
33
|
this.#reject = readiness.reject;
|
|
34
|
-
this.#
|
|
34
|
+
this.#recordHandler = this.#record.bind(this);
|
|
35
35
|
this.#recordExitHandler = this.#recordExit.bind(this);
|
|
36
36
|
this.#onlineHandler = this.#online.bind(this);
|
|
37
37
|
this.#spawnErrorHandler = this.#spawnError.bind(this);
|
|
38
38
|
this.#spawnExitHandler = this.#spawnExit.bind(this);
|
|
39
|
-
this.#worker.on("error", this.#
|
|
39
|
+
this.#worker.on("error", this.#recordHandler);
|
|
40
|
+
this.#worker.on("messageerror", this.#recordHandler);
|
|
40
41
|
this.#worker.on("exit", this.#recordExitHandler);
|
|
41
42
|
this.#worker.once("online", this.#onlineHandler);
|
|
42
43
|
this.#worker.once("error", this.#spawnErrorHandler);
|
|
@@ -57,7 +58,7 @@ var Thread = class {
|
|
|
57
58
|
evict() {
|
|
58
59
|
this.#alive = false;
|
|
59
60
|
}
|
|
60
|
-
#
|
|
61
|
+
#record(error) {
|
|
61
62
|
this.#alive = false;
|
|
62
63
|
if (this.#death === void 0) this.#death = error;
|
|
63
64
|
}
|
|
@@ -109,9 +110,10 @@ function isReply(value, id) {
|
|
|
109
110
|
* Internal lifecycle entity for one dispatched worker-thread job.
|
|
110
111
|
*
|
|
111
112
|
* @remarks
|
|
112
|
-
* Owns
|
|
113
|
-
* eviction for one dispatch.
|
|
114
|
-
*
|
|
113
|
+
* Owns stable `message` / `messageerror` / death listener identities, settlement, result-guard
|
|
114
|
+
* containment, and abort eviction for one dispatch. Deserialization failure, a matching-id
|
|
115
|
+
* malformed reply, and abort each evict and terminate the thread before rejecting, with
|
|
116
|
+
* termination failure preserved. Non-record, id-less, hostile-id, and foreign-id chatter is ignored.
|
|
115
117
|
*/
|
|
116
118
|
var Dispatch = class {
|
|
117
119
|
#thread;
|
|
@@ -124,6 +126,7 @@ var Dispatch = class {
|
|
|
124
126
|
#fulfill;
|
|
125
127
|
#reject;
|
|
126
128
|
#messageHandler;
|
|
129
|
+
#messageErrorHandler;
|
|
127
130
|
#errorHandler;
|
|
128
131
|
#exitHandler;
|
|
129
132
|
#abortHandler;
|
|
@@ -139,6 +142,7 @@ var Dispatch = class {
|
|
|
139
142
|
this.#fulfill = settlement.resolve;
|
|
140
143
|
this.#reject = settlement.reject;
|
|
141
144
|
this.#messageHandler = this.#message.bind(this);
|
|
145
|
+
this.#messageErrorHandler = this.#messageError.bind(this);
|
|
142
146
|
this.#errorHandler = this.#error.bind(this);
|
|
143
147
|
this.#exitHandler = this.#exit.bind(this);
|
|
144
148
|
this.#abortHandler = this.#abort.bind(this);
|
|
@@ -153,6 +157,7 @@ var Dispatch = class {
|
|
|
153
157
|
return;
|
|
154
158
|
}
|
|
155
159
|
this.#worker.on("message", this.#messageHandler);
|
|
160
|
+
this.#worker.on("messageerror", this.#messageErrorHandler);
|
|
156
161
|
this.#worker.on("error", this.#errorHandler);
|
|
157
162
|
this.#worker.on("exit", this.#exitHandler);
|
|
158
163
|
if (this.#execution.signal.aborted) {
|
|
@@ -171,29 +176,70 @@ var Dispatch = class {
|
|
|
171
176
|
}
|
|
172
177
|
}
|
|
173
178
|
#message(value) {
|
|
174
|
-
if (!
|
|
179
|
+
if (!(0, _orkestrel_contract.isRecord)(value)) return;
|
|
180
|
+
const id = (0, _orkestrel_contract.attempt)(() => value.id);
|
|
181
|
+
if (!id.success || id.value !== this.#id) return;
|
|
182
|
+
if (!isReply(value, this.#id)) {
|
|
183
|
+
this.#terminate(/* @__PURE__ */ new Error("worker reply was malformed"));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
175
186
|
if (value.ok) {
|
|
176
187
|
const reply = value.value;
|
|
177
|
-
|
|
178
|
-
|
|
188
|
+
try {
|
|
189
|
+
if (this.#result(reply)) this.#succeed(reply);
|
|
190
|
+
else this.#fail(/* @__PURE__ */ new Error("reply did not satisfy result guard"));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
this.#fail(error);
|
|
193
|
+
}
|
|
179
194
|
return;
|
|
180
195
|
}
|
|
181
196
|
this.#fail(new Error(value.error));
|
|
182
197
|
}
|
|
198
|
+
#messageError(error) {
|
|
199
|
+
this.#terminate(error);
|
|
200
|
+
}
|
|
183
201
|
#error(error) {
|
|
184
202
|
this.#fail(error);
|
|
185
203
|
}
|
|
186
204
|
#exit() {
|
|
187
|
-
this.#fail(/* @__PURE__ */ new Error("worker thread exited"));
|
|
205
|
+
this.#fail(this.#thread.death ?? /* @__PURE__ */ new Error("worker thread exited"));
|
|
188
206
|
}
|
|
189
207
|
#abort() {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
208
|
+
const notification = [];
|
|
209
|
+
try {
|
|
210
|
+
this.#worker.postMessage({
|
|
211
|
+
id: this.#id,
|
|
212
|
+
command: "abort"
|
|
213
|
+
});
|
|
214
|
+
} catch (cause) {
|
|
215
|
+
notification.push(cause);
|
|
216
|
+
}
|
|
217
|
+
this.#terminate(this.#execution.signal.reason, notification);
|
|
218
|
+
}
|
|
219
|
+
#terminate(error, notification = []) {
|
|
220
|
+
if (this.#settled) return;
|
|
221
|
+
this.#settled = true;
|
|
222
|
+
this.#detach();
|
|
194
223
|
if (this.#thread instanceof Thread) this.#thread.evict();
|
|
195
|
-
|
|
196
|
-
|
|
224
|
+
let termination;
|
|
225
|
+
try {
|
|
226
|
+
termination = this.#worker.terminate();
|
|
227
|
+
} catch (cause) {
|
|
228
|
+
this.#reject(new AggregateError([
|
|
229
|
+
error,
|
|
230
|
+
...notification,
|
|
231
|
+
cause
|
|
232
|
+
], "worker termination failed"));
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
termination.then(() => {
|
|
236
|
+
if (notification.length === 0) this.#reject(error);
|
|
237
|
+
else this.#reject(new AggregateError([error, ...notification], "worker abort notification failed"));
|
|
238
|
+
}, (cause) => this.#reject(new AggregateError([
|
|
239
|
+
error,
|
|
240
|
+
...notification,
|
|
241
|
+
cause
|
|
242
|
+
], "worker termination failed")));
|
|
197
243
|
}
|
|
198
244
|
#succeed(value) {
|
|
199
245
|
if (this.#settled) return;
|
|
@@ -209,6 +255,7 @@ var Dispatch = class {
|
|
|
209
255
|
}
|
|
210
256
|
#detach() {
|
|
211
257
|
this.#worker.off("message", this.#messageHandler);
|
|
258
|
+
this.#worker.off("messageerror", this.#messageErrorHandler);
|
|
212
259
|
this.#worker.off("error", this.#errorHandler);
|
|
213
260
|
this.#worker.off("exit", this.#exitHandler);
|
|
214
261
|
this.#execution.signal.removeEventListener("abort", this.#abortHandler);
|
|
@@ -227,11 +274,11 @@ var Dispatch = class {
|
|
|
227
274
|
* listeners that flip `alive` to `false` AND latch the first terminal event on
|
|
228
275
|
* {@link NodeThread.death}: a crash is observable to an in-flight {@link dispatch} (via
|
|
229
276
|
* its own listeners), to the pool's `validate` (via `alive`), and — crucially — to a
|
|
230
|
-
* dispatch that attaches AFTER the death (via the latch).
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
277
|
+
* dispatch that attaches AFTER the death (via the latch). A `messageerror` is terminal too,
|
|
278
|
+
* so a thread whose inbound payload could not be deserialized is never reused. The latch
|
|
279
|
+
* closes a real race: a thread can become terminal before the readiness promise continuation
|
|
280
|
+
* hands it to `dispatch`, leaving no future death event for that dispatch to observe. Without
|
|
281
|
+
* the latch, that job would wait forever. The pool's `create` hook calls this.
|
|
235
282
|
*
|
|
236
283
|
* @param script - The worker module each thread runs (must call `serveWorker`)
|
|
237
284
|
* @param workerData - Opaque, structured-cloneable data handed to the thread at spawn
|
|
@@ -248,15 +295,15 @@ function spawnThread(script, workerData) {
|
|
|
248
295
|
* that id: a success `value` is narrowed through `result` (a value that fails the guard
|
|
249
296
|
* rejects — the zero-`as` type bridge), a failure rejects with the thread's error string.
|
|
250
297
|
* A thread that ALREADY died rejects synchronously at entry from the latched
|
|
251
|
-
* {@link NodeThread.death} — its death events fired before this dispatch existed
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
* job rejects.
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
298
|
+
* {@link NodeThread.death} — its death events fired before this dispatch existed and will
|
|
299
|
+
* never fire again, so waiting on the listeners below would dangle forever; the latch makes
|
|
300
|
+
* death total across every event ordering. If the thread `error`s / `exit`s mid-flight it is
|
|
301
|
+
* marked dead and the
|
|
302
|
+
* job rejects. An inbound `messageerror` also evicts and terminates the thread before
|
|
303
|
+
* rejection. On `execution.signal` abort it contains the cooperative `abort` post,
|
|
304
|
+
* evicts the thread, and observes `terminate()` settlement because CPU-bound work cannot
|
|
305
|
+
* honour the signal; the freed pool slot then gets a fresh thread. Every per-job listener
|
|
306
|
+
* (`message` / `messageerror` / `error` / `exit` / `abort`) is removed on settle.
|
|
260
307
|
*
|
|
261
308
|
* @typeParam TResult - The reply type the `result` guard narrows to
|
|
262
309
|
* @param thread - The leased thread to run the job on
|
|
@@ -287,7 +334,10 @@ function isAbort(value) {
|
|
|
287
334
|
* run/abort protocol: a `run` message narrows its `input` through `options.input` (an
|
|
288
335
|
* invalid payload replies with an error envelope, never running the handler), then runs
|
|
289
336
|
* `options.handler(input, { signal })` and replies `{ id, ok: true, value }` on success or
|
|
290
|
-
* `{ id, ok: false, error }` on throw.
|
|
337
|
+
* `{ id, ok: false, error }` on throw. Input-guard throws use the same failure envelope. If a
|
|
338
|
+
* success value cannot be cloned, the post is retried as a clone-safe failure; if that post also
|
|
339
|
+
* fails, the parent port closes so the main side observes thread exit instead of waiting forever.
|
|
340
|
+
* Each in-flight job has its own `AbortController`,
|
|
291
341
|
* so an `abort` message for that id fires the handler's `signal` (cooperative — the main
|
|
292
342
|
* side ALSO terminates the thread, so a handler that ignores its signal is still stopped).
|
|
293
343
|
* Every inbound message is narrowed with the inlined guards — no `as`. On the main thread
|
|
@@ -300,7 +350,7 @@ function isAbort(value) {
|
|
|
300
350
|
* @example
|
|
301
351
|
* ```ts
|
|
302
352
|
* // double.ts — a worker script
|
|
303
|
-
* import { serveWorker } from '@
|
|
353
|
+
* import { serveWorker } from '@orkestrel/worker/server'
|
|
304
354
|
*
|
|
305
355
|
* serveWorker<number, number>({
|
|
306
356
|
* input: (value): value is number => typeof value === 'number',
|
|
@@ -311,6 +361,8 @@ function isAbort(value) {
|
|
|
311
361
|
function serveWorker(options) {
|
|
312
362
|
const port = node_worker_threads.parentPort;
|
|
313
363
|
if (port === null) return;
|
|
364
|
+
const input = options.input;
|
|
365
|
+
const handler = options.handler;
|
|
314
366
|
const controllers = /* @__PURE__ */ new Map();
|
|
315
367
|
port.on("message", (raw) => {
|
|
316
368
|
if (isAbort(raw)) {
|
|
@@ -319,31 +371,36 @@ function serveWorker(options) {
|
|
|
319
371
|
}
|
|
320
372
|
if (!isRun(raw)) return;
|
|
321
373
|
const id = raw.id;
|
|
322
|
-
if (!options.input(raw.input)) {
|
|
323
|
-
port.postMessage({
|
|
324
|
-
id,
|
|
325
|
-
ok: false,
|
|
326
|
-
error: "input did not satisfy input guard"
|
|
327
|
-
});
|
|
328
|
-
return;
|
|
329
|
-
}
|
|
330
|
-
const input = raw.input;
|
|
331
374
|
const controller = new AbortController();
|
|
332
375
|
controllers.set(id, controller);
|
|
333
|
-
Promise.resolve().then(() =>
|
|
376
|
+
Promise.resolve().then(() => {
|
|
377
|
+
if (!input(raw.input)) throw new Error("input did not satisfy input guard");
|
|
378
|
+
const value = raw.input;
|
|
379
|
+
return handler(value, { signal: controller.signal });
|
|
380
|
+
}).then((value) => {
|
|
334
381
|
controllers.delete(id);
|
|
335
382
|
port.postMessage({
|
|
336
383
|
id,
|
|
337
384
|
ok: true,
|
|
338
385
|
value
|
|
339
386
|
});
|
|
340
|
-
}
|
|
387
|
+
}).catch((error) => {
|
|
341
388
|
controllers.delete(id);
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
389
|
+
let message = "worker operation failed";
|
|
390
|
+
try {
|
|
391
|
+
message = error instanceof Error ? error.message : String(error);
|
|
392
|
+
} catch {}
|
|
393
|
+
try {
|
|
394
|
+
port.postMessage({
|
|
395
|
+
id,
|
|
396
|
+
ok: false,
|
|
397
|
+
error: message
|
|
398
|
+
});
|
|
399
|
+
} catch {
|
|
400
|
+
try {
|
|
401
|
+
port.close();
|
|
402
|
+
} catch {}
|
|
403
|
+
}
|
|
347
404
|
});
|
|
348
405
|
});
|
|
349
406
|
}
|
|
@@ -357,9 +414,23 @@ function serveWorker(options) {
|
|
|
357
414
|
* public entity remains the plain core {@link WorkerInterface}.
|
|
358
415
|
*/
|
|
359
416
|
var NodeWorker = class {
|
|
360
|
-
#
|
|
417
|
+
#script;
|
|
418
|
+
#input;
|
|
419
|
+
#result;
|
|
420
|
+
#workerData;
|
|
421
|
+
#concurrency;
|
|
422
|
+
#retries;
|
|
423
|
+
#timeout;
|
|
424
|
+
#store;
|
|
361
425
|
constructor(options) {
|
|
362
|
-
this.#
|
|
426
|
+
this.#script = options.script;
|
|
427
|
+
this.#input = options.input;
|
|
428
|
+
this.#result = options.result;
|
|
429
|
+
this.#workerData = options.workerData;
|
|
430
|
+
this.#concurrency = options.concurrency;
|
|
431
|
+
this.#retries = options.retries;
|
|
432
|
+
this.#timeout = options.timeout;
|
|
433
|
+
this.#store = options.store;
|
|
363
434
|
}
|
|
364
435
|
build() {
|
|
365
436
|
return (0, _src_core.createWorker)({
|
|
@@ -367,17 +438,17 @@ var NodeWorker = class {
|
|
|
367
438
|
create: this.#create.bind(this),
|
|
368
439
|
destroy: this.#destroy.bind(this),
|
|
369
440
|
validate: this.#validate.bind(this),
|
|
370
|
-
...this.#
|
|
441
|
+
...this.#concurrency !== void 0 ? { max: this.#concurrency } : {}
|
|
371
442
|
},
|
|
372
443
|
handler: this.#handle.bind(this),
|
|
373
|
-
...this.#
|
|
374
|
-
...this.#
|
|
375
|
-
...this.#
|
|
376
|
-
...this.#
|
|
444
|
+
...this.#concurrency !== void 0 ? { concurrency: this.#concurrency } : {},
|
|
445
|
+
...this.#retries !== void 0 ? { retries: this.#retries } : {},
|
|
446
|
+
...this.#timeout !== void 0 ? { timeout: this.#timeout } : {},
|
|
447
|
+
...this.#store !== void 0 ? { store: this.#store } : {}
|
|
377
448
|
});
|
|
378
449
|
}
|
|
379
450
|
#create() {
|
|
380
|
-
return spawnThread(this.#
|
|
451
|
+
return spawnThread(this.#script, this.#workerData);
|
|
381
452
|
}
|
|
382
453
|
async #destroy(thread) {
|
|
383
454
|
await thread.worker.terminate();
|
|
@@ -386,8 +457,10 @@ var NodeWorker = class {
|
|
|
386
457
|
return thread.alive && thread.worker.threadId > 0;
|
|
387
458
|
}
|
|
388
459
|
#handle(input, thread, execution) {
|
|
389
|
-
|
|
390
|
-
|
|
460
|
+
const outcome = (0, _orkestrel_contract.attempt)(() => this.#input(input));
|
|
461
|
+
if (!outcome.success) return Promise.reject(outcome.error);
|
|
462
|
+
if (!outcome.value) return Promise.reject(/* @__PURE__ */ new Error("input did not satisfy input guard"));
|
|
463
|
+
return dispatch(thread, input, execution, this.#result);
|
|
391
464
|
}
|
|
392
465
|
};
|
|
393
466
|
//#endregion
|
|
@@ -412,8 +485,8 @@ var NodeWorker = class {
|
|
|
412
485
|
*
|
|
413
486
|
* @example
|
|
414
487
|
* ```ts
|
|
415
|
-
* import { stringShape } from '@
|
|
416
|
-
* import { createJSONQueueStore } from '@
|
|
488
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
489
|
+
* import { createJSONQueueStore } from '@orkestrel/worker/server'
|
|
417
490
|
*
|
|
418
491
|
* const store = createJSONQueueStore('data/queue.json', stringShape())
|
|
419
492
|
* await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
|
|
@@ -453,7 +526,7 @@ function createJSONQueueStore(path, input) {
|
|
|
453
526
|
*
|
|
454
527
|
* @example
|
|
455
528
|
* ```ts
|
|
456
|
-
* import { createNodeWorker } from '@
|
|
529
|
+
* import { createNodeWorker } from '@orkestrel/worker/server'
|
|
457
530
|
*
|
|
458
531
|
* const worker = createNodeWorker({
|
|
459
532
|
* script: new URL('./double.js', import.meta.url),
|
|
@@ -463,7 +536,7 @@ function createJSONQueueStore(path, input) {
|
|
|
463
536
|
* })
|
|
464
537
|
*
|
|
465
538
|
* const doubled = await worker.enqueue(21) // 42, computed on a worker thread
|
|
466
|
-
* worker.destroy() // terminates every thread
|
|
539
|
+
* await worker.destroy() // terminates every thread
|
|
467
540
|
* ```
|
|
468
541
|
*/
|
|
469
542
|
function createNodeWorker(options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#worker","#promise","#resolve","#reject","#recordErrorHandler","#recordExitHandler","#onlineHandler","#spawnErrorHandler","#spawnExitHandler","#recordError","#recordExit","#online","#spawnError","#spawnExit","#alive","#death","#thread","#worker","#input","#execution","#result","#id","#promise","#fulfill","#reject","#messageHandler","#errorHandler","#exitHandler","#abortHandler","#message","#error","#exit","#abort","#start","#fail","#succeed","#settled","#detach","#options","#create","#destroy","#validate","#handle"],"sources":["../../../src/server/Thread.ts","../../../src/server/validators.ts","../../../src/server/Dispatch.ts","../../../src/server/helpers.ts","../../../src/server/serve.ts","../../../src/server/NodeWorker.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { NodeThread } from './types.js'\nimport { Worker as ThreadWorker } from 'node:worker_threads'\n\n/**\n * Internal mutable implementation of the readonly {@link NodeThread} observation contract.\n *\n * @remarks\n * Liveness and the first terminal error live behind runtime-private fields. Consumers observe\n * their current values through readonly getters, while the worker lifecycle records transitions\n * through bound instance methods without exposing writable contract properties.\n */\nexport class Thread implements NodeThread {\n\treadonly #worker: ThreadWorker\n\treadonly #promise: Promise<NodeThread>\n\treadonly #resolve: (value: NodeThread | PromiseLike<NodeThread>) => void\n\treadonly #reject: (reason?: unknown) => void\n\treadonly #recordErrorHandler: (error: Error) => void\n\treadonly #recordExitHandler: (code: number) => void\n\treadonly #onlineHandler: () => void\n\treadonly #spawnErrorHandler: (error: Error) => void\n\treadonly #spawnExitHandler: (code: number) => void\n\t#alive = true\n\t#death: Error | undefined\n\n\tconstructor(script: string | URL, workerData: unknown) {\n\t\tthis.#worker = new ThreadWorker(script, {\n\t\t\t...(workerData !== undefined ? { workerData } : {}),\n\t\t})\n\t\tconst readiness = Promise.withResolvers<NodeThread>()\n\t\tthis.#promise = readiness.promise\n\t\tthis.#resolve = readiness.resolve\n\t\tthis.#reject = readiness.reject\n\t\tthis.#recordErrorHandler = this.#recordError.bind(this)\n\t\tthis.#recordExitHandler = this.#recordExit.bind(this)\n\t\tthis.#onlineHandler = this.#online.bind(this)\n\t\tthis.#spawnErrorHandler = this.#spawnError.bind(this)\n\t\tthis.#spawnExitHandler = this.#spawnExit.bind(this)\n\n\t\tthis.#worker.on('error', this.#recordErrorHandler)\n\t\tthis.#worker.on('exit', this.#recordExitHandler)\n\t\tthis.#worker.once('online', this.#onlineHandler)\n\t\tthis.#worker.once('error', this.#spawnErrorHandler)\n\t\tthis.#worker.once('exit', this.#spawnExitHandler)\n\t}\n\n\tget worker(): ThreadWorker {\n\t\treturn this.#worker\n\t}\n\n\tget alive(): boolean {\n\t\treturn this.#alive\n\t}\n\n\tget death(): Error | undefined {\n\t\treturn this.#death\n\t}\n\n\tget promise(): Promise<NodeThread> {\n\t\treturn this.#promise\n\t}\n\n\tevict(): void {\n\t\tthis.#alive = false\n\t}\n\n\t#recordError(error: Error): void {\n\t\tthis.#alive = false\n\t\tif (this.#death === undefined) this.#death = error\n\t}\n\n\t#recordExit(code: number): void {\n\t\tthis.#alive = false\n\t\tif (this.#death === undefined) {\n\t\t\tthis.#death = new Error(`worker thread exited (code ${String(code)})`)\n\t\t}\n\t}\n\n\t#online(): void {\n\t\tthis.#worker.off('error', this.#spawnErrorHandler)\n\t\tthis.#worker.off('exit', this.#spawnExitHandler)\n\t\tthis.#resolve(this)\n\t}\n\n\t#spawnError(error: Error): void {\n\t\tthis.#worker.off('online', this.#onlineHandler)\n\t\tthis.#worker.off('exit', this.#spawnExitHandler)\n\t\tthis.#reject(error)\n\t}\n\n\t#spawnExit(code: number): void {\n\t\tthis.#worker.off('online', this.#onlineHandler)\n\t\tthis.#worker.off('error', this.#spawnErrorHandler)\n\t\tthis.#reject(new Error(`worker thread exited before coming online (code ${String(code)})`))\n\t}\n}\n","import type { Reply } from './types.js'\nimport { attempt, isRecord } from '@orkestrel/contract'\n\n/**\n * Narrow an inbound `message` to a {@link Reply} for a given job `id` — no assertion.\n *\n * @remarks\n * A total predicate: a record whose `id` matches and whose `ok` discriminant is well-formed.\n * Anything else is rejected so a dispatch listener can ignore foreign or malformed messages.\n *\n * @param value - The inbound message to narrow\n * @param id - The job id a matching reply must carry\n * @returns `true` when the value is this job's well-formed reply\n */\nexport function isReply(value: unknown, id: string): value is Reply {\n\tconst outcome = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tif (value.id !== id) return false\n\t\tif (value.ok === true) return 'value' in value\n\t\treturn value.ok === false && typeof value.error === 'string'\n\t})\n\treturn outcome.success && outcome.value\n}\n","import type { QueueExecution } from '@orkestrel/queue'\nimport type { Guard, NodeThread } from './types.js'\nimport type { Worker as ThreadWorker } from 'node:worker_threads'\nimport { Thread } from './Thread.js'\nimport { isReply } from './validators.js'\n\n/**\n * Internal lifecycle entity for one dispatched worker-thread job.\n *\n * @remarks\n * Owns the stable listener identities, settlement guard, cleanup, result narrowing, and abort\n * eviction for one dispatch. The public {@link dispatch} helper constructs this entity and returns\n * its promise.\n */\nexport class Dispatch<TResult> {\n\treadonly #thread: NodeThread\n\treadonly #worker: ThreadWorker\n\treadonly #input: unknown\n\treadonly #execution: QueueExecution\n\treadonly #result: Guard<TResult>\n\treadonly #id = crypto.randomUUID()\n\treadonly #promise: Promise<TResult>\n\treadonly #fulfill: (value: TResult | PromiseLike<TResult>) => void\n\treadonly #reject: (reason?: unknown) => void\n\treadonly #messageHandler: (value: unknown) => void\n\treadonly #errorHandler: (error: Error) => void\n\treadonly #exitHandler: () => void\n\treadonly #abortHandler: () => void\n\t#settled = false\n\n\tconstructor(\n\t\tthread: NodeThread,\n\t\tinput: unknown,\n\t\texecution: QueueExecution,\n\t\tresult: Guard<TResult>,\n\t) {\n\t\tthis.#thread = thread\n\t\tthis.#worker = thread.worker\n\t\tthis.#input = input\n\t\tthis.#execution = execution\n\t\tthis.#result = result\n\t\tconst settlement = Promise.withResolvers<TResult>()\n\t\tthis.#promise = settlement.promise\n\t\tthis.#fulfill = settlement.resolve\n\t\tthis.#reject = settlement.reject\n\t\tthis.#messageHandler = this.#message.bind(this)\n\t\tthis.#errorHandler = this.#error.bind(this)\n\t\tthis.#exitHandler = this.#exit.bind(this)\n\t\tthis.#abortHandler = this.#abort.bind(this)\n\t\tthis.#start()\n\t}\n\n\tget promise(): Promise<TResult> {\n\t\treturn this.#promise\n\t}\n\n\t#start(): void {\n\t\tif (this.#thread.death !== undefined || !this.#thread.alive) {\n\t\t\tthis.#fail(this.#thread.death ?? new Error('worker thread is dead'))\n\t\t\treturn\n\t\t}\n\t\tthis.#worker.on('message', this.#messageHandler)\n\t\tthis.#worker.on('error', this.#errorHandler)\n\t\tthis.#worker.on('exit', this.#exitHandler)\n\t\tif (this.#execution.signal.aborted) {\n\t\t\tthis.#abort()\n\t\t\treturn\n\t\t}\n\t\tthis.#execution.signal.addEventListener('abort', this.#abortHandler, { once: true })\n\t\ttry {\n\t\t\tthis.#worker.postMessage({ id: this.#id, command: 'run', input: this.#input })\n\t\t} catch (error: unknown) {\n\t\t\tthis.#fail(error instanceof Error ? error : new Error(String(error)))\n\t\t}\n\t}\n\n\t#message(value: unknown): void {\n\t\tif (!isReply(value, this.#id)) return\n\t\tif (value.ok) {\n\t\t\tconst reply = value.value\n\t\t\tif (this.#result(reply)) this.#succeed(reply)\n\t\t\telse this.#fail(new Error('reply did not satisfy result guard'))\n\t\t\treturn\n\t\t}\n\t\tthis.#fail(new Error(value.error))\n\t}\n\n\t#error(error: Error): void {\n\t\tthis.#fail(error)\n\t}\n\n\t#exit(): void {\n\t\tthis.#fail(new Error('worker thread exited'))\n\t}\n\n\t#abort(): void {\n\t\tthis.#worker.postMessage({ id: this.#id, command: 'abort' })\n\t\tif (this.#thread instanceof Thread) this.#thread.evict()\n\t\tvoid this.#worker.terminate()\n\t\tthis.#fail(new Error('job aborted'))\n\t}\n\n\t#succeed(value: TResult): void {\n\t\tif (this.#settled) return\n\t\tthis.#settled = true\n\t\tthis.#detach()\n\t\tthis.#fulfill(value)\n\t}\n\n\t#fail(error: unknown): void {\n\t\tif (this.#settled) return\n\t\tthis.#settled = true\n\t\tthis.#detach()\n\t\tthis.#reject(error)\n\t}\n\n\t#detach(): void {\n\t\tthis.#worker.off('message', this.#messageHandler)\n\t\tthis.#worker.off('error', this.#errorHandler)\n\t\tthis.#worker.off('exit', this.#exitHandler)\n\t\tthis.#execution.signal.removeEventListener('abort', this.#abortHandler)\n\t}\n}\n","import type { QueueExecution } from '@orkestrel/queue'\nimport type { Guard, NodeThread } from './types.js'\nimport { Dispatch } from './Dispatch.js'\nimport { Thread } from './Thread.js'\n\n// === The wire protocol (main ↔ thread)\n//\n// The main-side half of the run/abort/reply protocol `serveWorker` answers — spawning a\n// pooled thread, narrowing its replies, and dispatching one job at a time. The envelope\n// types ({@link Reply}, {@link NodeThread}) live in `./types.js` (AGENTS §5); the public\n// bridge across the structured-clone boundary is the `input` / `result` `Guard`s, which\n// narrow the envelopes' opaque `unknown` payloads with no assertion (AGENTS §14).\n\n/**\n * Spawn one worker thread and resolve a live {@link NodeThread} once it comes online.\n *\n * @remarks\n * Constructs the thread with the `script` module and the cloned `workerData`, then\n * resolves on the thread's `online` event (rejecting on an early `error` OR an `exit`\n * that arrives before `online`, so the spawn promise is total — it can never dangle on a\n * thread that died without erroring). The wrapper attaches persistent `error` / `exit`\n * listeners that flip `alive` to `false` AND latch the first terminal event on\n * {@link NodeThread.death}: a crash is observable to an in-flight {@link dispatch} (via\n * its own listeners), to the pool's `validate` (via `alive`), and — crucially — to a\n * dispatch that attaches AFTER the death (via the latch). The latch closes a real race:\n * under event-loop pressure a dead thread's `online` + `error` + `exit` are delivered in\n * ONE synchronous exit-drain batch, so every death event fires before the microtask chain\n * resolving this spawn can hand the thread to `dispatch` — without the latch that job\n * would await events that already fired, forever. The pool's `create` hook calls this.\n *\n * @param script - The worker module each thread runs (must call `serveWorker`)\n * @param workerData - Opaque, structured-cloneable data handed to the thread at spawn\n * @returns A promise resolving the online {@link NodeThread}\n */\nexport function spawnThread(script: string | URL, workerData: unknown): Promise<NodeThread> {\n\treturn new Thread(script, workerData).promise\n}\n\n/**\n * Dispatch one job to a leased {@link NodeThread} and await its narrowed reply.\n *\n * @remarks\n * Mints a fresh `id`, posts a `run` envelope, and resolves when the thread replies for\n * that id: a success `value` is narrowed through `result` (a value that fails the guard\n * rejects — the zero-`as` type bridge), a failure rejects with the thread's error string.\n * A thread that ALREADY died rejects synchronously at entry from the latched\n * {@link NodeThread.death} — its death events fired before this dispatch existed (under\n * load they arrive in one batched exit drain) and will never fire again, so waiting on\n * the listeners below would dangle forever; the latch makes the death total across every\n * event ordering. If the thread `error`s / `exit`s mid-flight it is marked dead and the\n * job rejects. On `execution.signal` abort it posts an `abort` envelope (cooperative) AND\n * evicts the thread — `alive = false` + `terminate()` — because CPU-bound work cannot\n * honour the signal; the freed pool slot then gets a fresh thread. Every listener (the\n * thread's `message` / `error` / `exit` and the signal's `abort`) is removed on settle,\n * and a `settled` guard prevents a double-settle.\n *\n * @typeParam TResult - The reply type the `result` guard narrows to\n * @param thread - The leased thread to run the job on\n * @param input - The work payload (structured-cloned to the thread)\n * @param execution - The per-attempt handle; its `signal` aborts → terminate + evict\n * @param result - The {@link Guard} narrowing the reply value with no assertion\n * @returns A promise resolving the narrowed `TResult`, or rejecting on error / abort\n */\nexport function dispatch<TResult>(\n\tthread: NodeThread,\n\tinput: unknown,\n\texecution: QueueExecution,\n\tresult: Guard<TResult>,\n): Promise<TResult> {\n\treturn new Dispatch(thread, input, execution, result).promise\n}\n","import type { ServeWorkerOptions } from './types.js'\nimport { parentPort } from 'node:worker_threads'\n\n// The worker-side entry. SELF-CONTAINED by necessity: this module loads as RAW `.ts`\n// inside a spawned thread (Node ≥ 23.6 type-stripping), so it imports ONLY\n// `node:worker_threads` at runtime — no `@src/*`, no `.js`-relative value imports (the\n// only non-node import is the type-only `ServeWorkerOptions`, fully erased at runtime).\n// Its guards are inlined for the same reason. A worker script that needs the cloned\n// `workerData` reads it directly from `node:worker_threads` (it is in a thread already).\n\n// Inlined record guard (do NOT import `isRecord` from `@src/core` — see above). Total:\n// adversarial input returns `false`, never throws (AGENTS §14).\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// Narrow an inbound message to a `run` envelope (a string `id` + a `'run'` command + an\n// `input` payload) — no assertion.\nfunction isRun(value: unknown): value is { readonly id: string; readonly input: unknown } {\n\treturn (\n\t\tisRecord(value) && typeof value.id === 'string' && value.command === 'run' && 'input' in value\n\t)\n}\n\n// Narrow an inbound message to an `abort` envelope (a string `id` + an `'abort'` command).\nfunction isAbort(value: unknown): value is { readonly id: string } {\n\treturn isRecord(value) && typeof value.id === 'string' && value.command === 'abort'\n}\n\n/**\n * Register a worker-thread handler — the worker-side half of {@link createNodeWorker}.\n *\n * @remarks\n * Must be the spawned thread's module entry. It listens on the parent port for the\n * run/abort protocol: a `run` message narrows its `input` through `options.input` (an\n * invalid payload replies with an error envelope, never running the handler), then runs\n * `options.handler(input, { signal })` and replies `{ id, ok: true, value }` on success or\n * `{ id, ok: false, error }` on throw. Each in-flight job has its own `AbortController`,\n * so an `abort` message for that id fires the handler's `signal` (cooperative — the main\n * side ALSO terminates the thread, so a handler that ignores its signal is still stopped).\n * Every inbound message is narrowed with the inlined guards — no `as`. On the main thread\n * (`parentPort === null`) it is a no-op.\n *\n * @typeParam TInput - The work payload (inferred from `options.input`)\n * @typeParam TResult - The value the handler resolves (the reply payload)\n * @param options - The `input` guard and the `handler` (see {@link ServeWorkerOptions})\n *\n * @example\n * ```ts\n * // double.ts — a worker script\n * import { serveWorker } from '@src/server'\n *\n * serveWorker<number, number>({\n * \tinput: (value): value is number => typeof value === 'number',\n * \thandler: (value) => value * 2,\n * })\n * ```\n */\nexport function serveWorker<TInput, TResult>(options: ServeWorkerOptions<TInput, TResult>): void {\n\tconst port = parentPort\n\tif (port === null) return\n\tconst controllers = new Map<string, AbortController>()\n\tport.on('message', (raw: unknown) => {\n\t\tif (isAbort(raw)) {\n\t\t\tcontrollers.get(raw.id)?.abort()\n\t\t\treturn\n\t\t}\n\t\tif (!isRun(raw)) return\n\t\tconst id = raw.id\n\t\tif (!options.input(raw.input)) {\n\t\t\tport.postMessage({ id, ok: false, error: 'input did not satisfy input guard' })\n\t\t\treturn\n\t\t}\n\t\tconst input = raw.input\n\t\tconst controller = new AbortController()\n\t\tcontrollers.set(id, controller)\n\t\t// Defer the handler call into the `then` so a SYNCHRONOUS throw becomes a rejection\n\t\t// (not an uncaught thread exception) and is reported as an error reply.\n\t\tPromise.resolve()\n\t\t\t.then(() => options.handler(input, { signal: controller.signal }))\n\t\t\t.then(\n\t\t\t\t(value) => {\n\t\t\t\t\tcontrollers.delete(id)\n\t\t\t\t\tport.postMessage({ id, ok: true, value })\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tcontrollers.delete(id)\n\t\t\t\t\tport.postMessage({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\t})\n}\n","import type { WorkerInterface } from '@src/core'\nimport type { QueueExecution } from '@orkestrel/queue'\nimport type { NodeThread, NodeWorkerOptions } from './types.js'\nimport { createWorker } from '@src/core'\nimport { dispatch, spawnThread } from './helpers.js'\n\n/**\n * Internal composition entity backing {@link createNodeWorker}.\n *\n * @remarks\n * Supplies bound Pool and Queue operations without nested function assignments. The resulting\n * public entity remains the plain core {@link WorkerInterface}.\n */\nexport class NodeWorker<TInput, TResult> {\n\treadonly #options: NodeWorkerOptions<TInput, TResult>\n\n\tconstructor(options: NodeWorkerOptions<TInput, TResult>) {\n\t\tthis.#options = options\n\t}\n\n\tbuild(): WorkerInterface<TInput, TResult> {\n\t\treturn createWorker<TInput, NodeThread, TResult>({\n\t\t\tpool: {\n\t\t\t\tcreate: this.#create.bind(this),\n\t\t\t\tdestroy: this.#destroy.bind(this),\n\t\t\t\tvalidate: this.#validate.bind(this),\n\t\t\t\t...(this.#options.concurrency !== undefined ? { max: this.#options.concurrency } : {}),\n\t\t\t},\n\t\t\thandler: this.#handle.bind(this),\n\t\t\t...(this.#options.concurrency !== undefined\n\t\t\t\t? { concurrency: this.#options.concurrency }\n\t\t\t\t: {}),\n\t\t\t...(this.#options.retries !== undefined ? { retries: this.#options.retries } : {}),\n\t\t\t...(this.#options.timeout !== undefined ? { timeout: this.#options.timeout } : {}),\n\t\t\t...(this.#options.store !== undefined ? { store: this.#options.store } : {}),\n\t\t})\n\t}\n\n\t#create(): Promise<NodeThread> {\n\t\treturn spawnThread(this.#options.script, this.#options.workerData)\n\t}\n\n\tasync #destroy(thread: NodeThread): Promise<void> {\n\t\tawait thread.worker.terminate()\n\t}\n\n\t#validate(thread: NodeThread): boolean {\n\t\treturn thread.alive && thread.worker.threadId > 0\n\t}\n\n\t#handle(input: TInput, thread: NodeThread, execution: QueueExecution): Promise<TResult> {\n\t\tif (!this.#options.input(input)) {\n\t\t\treturn Promise.reject(new Error('input did not satisfy input guard'))\n\t\t}\n\t\treturn dispatch(thread, input, execution, this.#options.result)\n\t}\n}\n","import type { WorkerInterface } from '@src/core'\nimport type { ContractShape, Infer } from '@orkestrel/contract'\nimport type { QueueStoreInterface } from '@orkestrel/queue'\nimport type { NodeWorkerOptions } from './types.js'\nimport { createJSONDriver } from '@orkestrel/database/server'\nimport { createDatabaseQueueStore } from '@orkestrel/queue'\nimport { NodeWorker } from './NodeWorker.js'\n\n/**\n * Create a persistent JSON-file {@link QueueStoreInterface} — the core\n * `createDatabaseQueueStore` over a server {@link createJSONDriver}.\n *\n * @remarks\n * A queue's durable state is just a database table, so JSON persistence reuses the\n * existing JSON-file driver rather than a bespoke store: the entries are written to\n * (and reloaded from) the file at `path`, surviving a process restart. There is no new\n * class — the store engine ({@link createDatabaseQueueStore}) is shared, and only the\n * driver changes where the bytes live. The `input` shape must be JSON-serializable\n * (the JSON driver round-trips it as JSON). Build a second store over the SAME `path` to\n * resume the outstanding entries a prior store persisted.\n *\n * @typeParam TInput - The contract shape of each entry's `input` payload\n * @param path - The JSON file the entries are loaded from and flushed to\n * @param input - The {@link ContractShape} for the work payload (the `input` column)\n * @returns A JSON-file-backed {@link QueueStoreInterface}, typed by `input`\n *\n * @example\n * ```ts\n * import { stringShape } from '@src/core'\n * import { createJSONQueueStore } from '@src/server'\n *\n * const store = createJSONQueueStore('data/queue.json', stringShape())\n * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })\n * // A later process resumes the outstanding work:\n * const resumed = createJSONQueueStore('data/queue.json', stringShape())\n * const outstanding = await resumed.load()\n * ```\n */\nexport function createJSONQueueStore<TInput extends ContractShape>(\n\tpath: string,\n\tinput: TInput,\n): QueueStoreInterface<Infer<TInput>> {\n\treturn createDatabaseQueueStore(input, createJSONDriver(path))\n}\n\n/**\n * Create a CPU-parallel worker over `node:worker_threads` — a thin specialization of the\n * core `createWorker` whose pooled resource is a worker THREAD.\n *\n * @remarks\n * Composition, not reimplementation: all concurrency, retries, per-attempt timeout,\n * lifecycle, and durability are the core `Worker`'s (a `Queue` ⨉ `Pool`). This factory\n * supplies only the thread pairing — the pool `create`s a thread (via `spawnThread`),\n * `destroy`s it with `terminate()`, and `validate`s it by `alive && threadId > 0` (so an\n * evicted / crashed thread is dropped and replaced) — and an internal handler that\n * narrows the input through `options.input` (fail-fast before the structured-clone\n * boundary) then `dispatch`es the job to the leased thread, narrowing the reply through\n * `options.result`. Both generics INFER from the `input` / `result` guards, so call sites\n * need no explicit type arguments. The boundary is crossed with ZERO `as`: the guards\n * reconstruct `TInput` / `TResult` by validation (AGENTS §14). An `abort` / `timeout`\n * TERMINATES the in-flight thread (CPU-bound work can't honour a signal) and evicts it; a\n * subsequent job spawns a fresh thread. The worker script's module must call\n * `serveWorker`. Returns the plain {@link WorkerInterface} — its methods are the Worker's.\n *\n * @typeParam TInput - The work payload each job carries (inferred from `input`)\n * @typeParam TResult - The value a thread resolves for a job (inferred from `result`)\n * @param options - The `script` plus the `input` / `result` guards and optional\n * `workerData` / `concurrency` / `retries` / `timeout` / `store`\n * (see {@link NodeWorkerOptions})\n * @returns A working {@link WorkerInterface} backed by a thread pool\n *\n * @example\n * ```ts\n * import { createNodeWorker } from '@src/server'\n *\n * const worker = createNodeWorker({\n * \tscript: new URL('./double.js', import.meta.url),\n * \tinput: (value): value is number => typeof value === 'number',\n * \tresult: (value): value is number => typeof value === 'number',\n * \tconcurrency: 4,\n * })\n *\n * const doubled = await worker.enqueue(21) // 42, computed on a worker thread\n * worker.destroy() // terminates every thread\n * ```\n */\nexport function createNodeWorker<TInput, TResult>(\n\toptions: NodeWorkerOptions<TInput, TResult>,\n): WorkerInterface<TInput, TResult> {\n\treturn new NodeWorker(options).build()\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAa,SAAb,MAA0C;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,SAAS;CACT;CAEA,YAAY,QAAsB,YAAqB;EACtD,KAAKA,UAAU,IAAI,oBAAA,OAAa,QAAQ,EACvC,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC,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AAA,IAC/B,EAAE,aAAa,KAAKA,SAAS,YAAY,IACzC,CAAC;GACJ,GAAI,KAAKA,SAAS,YAAY,KAAA,IAAY,EAAE,SAAS,KAAKA,SAAS,QAAQ,IAAI,CAAC;GAChF,GAAI,KAAKA,SAAS,YAAY,KAAA,IAAY,EAAE,SAAS,KAAKA,SAAS,QAAQ,IAAI,CAAC;GAChF,GAAI,KAAKA,SAAS,UAAU,KAAA,IAAY,EAAE,OAAO,KAAKA,SAAS,MAAM,IAAI,CAAC;EAC3E,CAAC;CACF;CAEA,UAA+B;EAC9B,OAAO,YAAY,KAAKA,SAAS,QAAQ,KAAKA,SAAS,UAAU;CAClE;CAEA,MAAME,SAAS,QAAmC;EACjD,MAAM,OAAO,OAAO,UAAU;CAC/B;CAEA,UAAU,QAA6B;EACtC,OAAO,OAAO,SAAS,OAAO,OAAO,WAAW;CACjD;CAEA,QAAQ,OAAe,QAAoB,WAA6C;EACvF,IAAI,CAAC,KAAKF,SAAS,MAAM,KAAK,GAC7B,OAAO,QAAQ,uBAAO,IAAI,MAAM,mCAAmC,CAAC;EAErE,OAAO,SAAS,QAAQ,OAAO,WAAW,KAAKA,SAAS,MAAM;CAC/D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClBA,SAAgB,qBACf,MACA,OACqC;CACrC,QAAA,GAAA,iBAAA,yBAAA,CAAgC,QAAA,GAAA,2BAAA,iBAAA,CAAwB,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,iBACf,SACmC;CACnC,OAAO,IAAI,WAAW,OAAO,CAAC,CAAC,MAAM;AACtC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#worker","#promise","#resolve","#reject","#recordHandler","#recordExitHandler","#onlineHandler","#spawnErrorHandler","#spawnExitHandler","#record","#recordExit","#online","#spawnError","#spawnExit","#alive","#death","#thread","#worker","#input","#execution","#result","#id","#promise","#fulfill","#reject","#messageHandler","#messageErrorHandler","#errorHandler","#exitHandler","#abortHandler","#message","#messageError","#error","#exit","#abort","#start","#fail","#terminate","#succeed","#settled","#detach","#script","#input","#result","#workerData","#concurrency","#retries","#timeout","#store","#create","#destroy","#validate","#handle"],"sources":["../../../src/server/Thread.ts","../../../src/server/validators.ts","../../../src/server/Dispatch.ts","../../../src/server/helpers.ts","../../../src/server/serve.ts","../../../src/server/NodeWorker.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { NodeThread } from './types.js'\nimport { Worker as ThreadWorker } from 'node:worker_threads'\n\n/**\n * Internal mutable implementation of the readonly {@link NodeThread} observation contract.\n *\n * @remarks\n * Liveness and the first terminal error live behind runtime-private fields. Thread `error`,\n * `messageerror`, and `exit` all latch death, so pool validation cannot reuse a thread whose\n * inbound message could not be deserialized.\n */\nexport class Thread implements NodeThread {\n\treadonly #worker: ThreadWorker\n\treadonly #promise: Promise<NodeThread>\n\treadonly #resolve: (value: NodeThread | PromiseLike<NodeThread>) => void\n\treadonly #reject: (reason?: unknown) => void\n\treadonly #recordHandler: (error: Error) => void\n\treadonly #recordExitHandler: (code: number) => void\n\treadonly #onlineHandler: () => void\n\treadonly #spawnErrorHandler: (error: Error) => void\n\treadonly #spawnExitHandler: (code: number) => void\n\t#alive = true\n\t#death: Error | undefined\n\n\tconstructor(script: string | URL, workerData: unknown) {\n\t\tthis.#worker = new ThreadWorker(script, {\n\t\t\t...(workerData !== undefined ? { workerData } : {}),\n\t\t})\n\t\tconst readiness = Promise.withResolvers<NodeThread>()\n\t\tthis.#promise = readiness.promise\n\t\tthis.#resolve = readiness.resolve\n\t\tthis.#reject = readiness.reject\n\t\tthis.#recordHandler = this.#record.bind(this)\n\t\tthis.#recordExitHandler = this.#recordExit.bind(this)\n\t\tthis.#onlineHandler = this.#online.bind(this)\n\t\tthis.#spawnErrorHandler = this.#spawnError.bind(this)\n\t\tthis.#spawnExitHandler = this.#spawnExit.bind(this)\n\n\t\tthis.#worker.on('error', this.#recordHandler)\n\t\tthis.#worker.on('messageerror', this.#recordHandler)\n\t\tthis.#worker.on('exit', this.#recordExitHandler)\n\t\tthis.#worker.once('online', this.#onlineHandler)\n\t\tthis.#worker.once('error', this.#spawnErrorHandler)\n\t\tthis.#worker.once('exit', this.#spawnExitHandler)\n\t}\n\n\tget worker(): ThreadWorker {\n\t\treturn this.#worker\n\t}\n\n\tget alive(): boolean {\n\t\treturn this.#alive\n\t}\n\n\tget death(): Error | undefined {\n\t\treturn this.#death\n\t}\n\n\tget promise(): Promise<NodeThread> {\n\t\treturn this.#promise\n\t}\n\n\tevict(): void {\n\t\tthis.#alive = false\n\t}\n\n\t#record(error: Error): void {\n\t\tthis.#alive = false\n\t\tif (this.#death === undefined) this.#death = error\n\t}\n\n\t#recordExit(code: number): void {\n\t\tthis.#alive = false\n\t\tif (this.#death === undefined) {\n\t\t\tthis.#death = new Error(`worker thread exited (code ${String(code)})`)\n\t\t}\n\t}\n\n\t#online(): void {\n\t\tthis.#worker.off('error', this.#spawnErrorHandler)\n\t\tthis.#worker.off('exit', this.#spawnExitHandler)\n\t\tthis.#resolve(this)\n\t}\n\n\t#spawnError(error: Error): void {\n\t\tthis.#worker.off('online', this.#onlineHandler)\n\t\tthis.#worker.off('exit', this.#spawnExitHandler)\n\t\tthis.#reject(error)\n\t}\n\n\t#spawnExit(code: number): void {\n\t\tthis.#worker.off('online', this.#onlineHandler)\n\t\tthis.#worker.off('error', this.#spawnErrorHandler)\n\t\tthis.#reject(new Error(`worker thread exited before coming online (code ${String(code)})`))\n\t}\n}\n","import type { Reply } from './types.js'\nimport { attempt, isRecord } from '@orkestrel/contract'\n\n/**\n * Narrow an inbound `message` to a {@link Reply} for a given job `id` — no assertion.\n *\n * @remarks\n * A total predicate: a record whose `id` matches and whose `ok` discriminant is well-formed.\n * Anything else is rejected so a dispatch listener can ignore foreign or malformed messages.\n *\n * @param value - The inbound message to narrow\n * @param id - The job id a matching reply must carry\n * @returns `true` when the value is this job's well-formed reply\n */\nexport function isReply(value: unknown, id: string): value is Reply {\n\tconst outcome = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tif (value.id !== id) return false\n\t\tif (value.ok === true) return 'value' in value\n\t\treturn value.ok === false && typeof value.error === 'string'\n\t})\n\treturn outcome.success && outcome.value\n}\n","import type { QueueExecution } from '@orkestrel/queue'\nimport type { Guard } from '@orkestrel/contract'\nimport type { NodeThread } from './types.js'\nimport type { Worker as ThreadWorker } from 'node:worker_threads'\nimport { attempt, isRecord } from '@orkestrel/contract'\nimport { Thread } from './Thread.js'\nimport { isReply } from './validators.js'\n\n/**\n * Internal lifecycle entity for one dispatched worker-thread job.\n *\n * @remarks\n * Owns stable `message` / `messageerror` / death listener identities, settlement, result-guard\n * containment, and abort eviction for one dispatch. Deserialization failure, a matching-id\n * malformed reply, and abort each evict and terminate the thread before rejecting, with\n * termination failure preserved. Non-record, id-less, hostile-id, and foreign-id chatter is ignored.\n */\nexport class Dispatch<TResult> {\n\treadonly #thread: NodeThread\n\treadonly #worker: ThreadWorker\n\treadonly #input: unknown\n\treadonly #execution: QueueExecution\n\treadonly #result: Guard<TResult>\n\treadonly #id = crypto.randomUUID()\n\treadonly #promise: Promise<TResult>\n\treadonly #fulfill: (value: TResult | PromiseLike<TResult>) => void\n\treadonly #reject: (reason?: unknown) => void\n\treadonly #messageHandler: (value: unknown) => void\n\treadonly #messageErrorHandler: (error: Error) => void\n\treadonly #errorHandler: (error: Error) => void\n\treadonly #exitHandler: () => void\n\treadonly #abortHandler: () => void\n\t#settled = false\n\n\tconstructor(\n\t\tthread: NodeThread,\n\t\tinput: unknown,\n\t\texecution: QueueExecution,\n\t\tresult: Guard<TResult>,\n\t) {\n\t\tthis.#thread = thread\n\t\tthis.#worker = thread.worker\n\t\tthis.#input = input\n\t\tthis.#execution = execution\n\t\tthis.#result = result\n\t\tconst settlement = Promise.withResolvers<TResult>()\n\t\tthis.#promise = settlement.promise\n\t\tthis.#fulfill = settlement.resolve\n\t\tthis.#reject = settlement.reject\n\t\tthis.#messageHandler = this.#message.bind(this)\n\t\tthis.#messageErrorHandler = this.#messageError.bind(this)\n\t\tthis.#errorHandler = this.#error.bind(this)\n\t\tthis.#exitHandler = this.#exit.bind(this)\n\t\tthis.#abortHandler = this.#abort.bind(this)\n\t\tthis.#start()\n\t}\n\n\tget promise(): Promise<TResult> {\n\t\treturn this.#promise\n\t}\n\n\t#start(): void {\n\t\tif (this.#thread.death !== undefined || !this.#thread.alive) {\n\t\t\tthis.#fail(this.#thread.death ?? new Error('worker thread is dead'))\n\t\t\treturn\n\t\t}\n\t\tthis.#worker.on('message', this.#messageHandler)\n\t\tthis.#worker.on('messageerror', this.#messageErrorHandler)\n\t\tthis.#worker.on('error', this.#errorHandler)\n\t\tthis.#worker.on('exit', this.#exitHandler)\n\t\tif (this.#execution.signal.aborted) {\n\t\t\tthis.#abort()\n\t\t\treturn\n\t\t}\n\t\tthis.#execution.signal.addEventListener('abort', this.#abortHandler, { once: true })\n\t\ttry {\n\t\t\tthis.#worker.postMessage({ id: this.#id, command: 'run', input: this.#input })\n\t\t} catch (error: unknown) {\n\t\t\tthis.#fail(error instanceof Error ? error : new Error(String(error)))\n\t\t}\n\t}\n\n\t#message(value: unknown): void {\n\t\tif (!isRecord(value)) return\n\t\tconst id = attempt(() => value.id)\n\t\tif (!id.success || id.value !== this.#id) return\n\t\tif (!isReply(value, this.#id)) {\n\t\t\tthis.#terminate(new Error('worker reply was malformed'))\n\t\t\treturn\n\t\t}\n\t\tif (value.ok) {\n\t\t\tconst reply = value.value\n\t\t\ttry {\n\t\t\t\tif (this.#result(reply)) this.#succeed(reply)\n\t\t\t\telse this.#fail(new Error('reply did not satisfy result guard'))\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthis.#fail(error)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.#fail(new Error(value.error))\n\t}\n\n\t#messageError(error: Error): void {\n\t\tthis.#terminate(error)\n\t}\n\n\t#error(error: Error): void {\n\t\tthis.#fail(error)\n\t}\n\n\t#exit(): void {\n\t\tthis.#fail(this.#thread.death ?? new Error('worker thread exited'))\n\t}\n\n\t#abort(): void {\n\t\tconst notification: unknown[] = []\n\t\ttry {\n\t\t\tthis.#worker.postMessage({ id: this.#id, command: 'abort' })\n\t\t} catch (cause: unknown) {\n\t\t\tnotification.push(cause)\n\t\t}\n\t\tthis.#terminate(this.#execution.signal.reason, notification)\n\t}\n\n\t#terminate(error: unknown, notification: readonly unknown[] = []): void {\n\t\tif (this.#settled) return\n\t\tthis.#settled = true\n\t\tthis.#detach()\n\t\tif (this.#thread instanceof Thread) this.#thread.evict()\n\t\tlet termination: Promise<number>\n\t\ttry {\n\t\t\ttermination = this.#worker.terminate()\n\t\t} catch (cause: unknown) {\n\t\t\tthis.#reject(new AggregateError([error, ...notification, cause], 'worker termination failed'))\n\t\t\treturn\n\t\t}\n\t\tvoid termination.then(\n\t\t\t() => {\n\t\t\t\tif (notification.length === 0) this.#reject(error)\n\t\t\t\telse {\n\t\t\t\t\tthis.#reject(\n\t\t\t\t\t\tnew AggregateError([error, ...notification], 'worker abort notification failed'),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t\t(cause: unknown) =>\n\t\t\t\tthis.#reject(\n\t\t\t\t\tnew AggregateError([error, ...notification, cause], 'worker termination failed'),\n\t\t\t\t),\n\t\t)\n\t}\n\n\t#succeed(value: TResult): void {\n\t\tif (this.#settled) return\n\t\tthis.#settled = true\n\t\tthis.#detach()\n\t\tthis.#fulfill(value)\n\t}\n\n\t#fail(error: unknown): void {\n\t\tif (this.#settled) return\n\t\tthis.#settled = true\n\t\tthis.#detach()\n\t\tthis.#reject(error)\n\t}\n\n\t#detach(): void {\n\t\tthis.#worker.off('message', this.#messageHandler)\n\t\tthis.#worker.off('messageerror', this.#messageErrorHandler)\n\t\tthis.#worker.off('error', this.#errorHandler)\n\t\tthis.#worker.off('exit', this.#exitHandler)\n\t\tthis.#execution.signal.removeEventListener('abort', this.#abortHandler)\n\t}\n}\n","import type { QueueExecution } from '@orkestrel/queue'\nimport type { Guard } from '@orkestrel/contract'\nimport type { NodeThread } from './types.js'\nimport { Dispatch } from './Dispatch.js'\nimport { Thread } from './Thread.js'\n\n// === The wire protocol (main ↔ thread)\n//\n// The main-side half of the run/abort/reply protocol `serveWorker` answers — spawning a\n// pooled thread, narrowing its replies, and dispatching one job at a time. The envelope\n// types ({@link Reply}, {@link NodeThread}) live in `./types.js` (AGENTS §5); the public\n// bridge across the structured-clone boundary is the `input` / `result` `Guard`s, which\n// narrow the envelopes' opaque `unknown` payloads with no assertion (AGENTS §14).\n\n/**\n * Spawn one worker thread and resolve a live {@link NodeThread} once it comes online.\n *\n * @remarks\n * Constructs the thread with the `script` module and the cloned `workerData`, then\n * resolves on the thread's `online` event (rejecting on an early `error` OR an `exit`\n * that arrives before `online`, so the spawn promise is total — it can never dangle on a\n * thread that died without erroring). The wrapper attaches persistent `error` / `exit`\n * listeners that flip `alive` to `false` AND latch the first terminal event on\n * {@link NodeThread.death}: a crash is observable to an in-flight {@link dispatch} (via\n * its own listeners), to the pool's `validate` (via `alive`), and — crucially — to a\n * dispatch that attaches AFTER the death (via the latch). A `messageerror` is terminal too,\n * so a thread whose inbound payload could not be deserialized is never reused. The latch\n * closes a real race: a thread can become terminal before the readiness promise continuation\n * hands it to `dispatch`, leaving no future death event for that dispatch to observe. Without\n * the latch, that job would wait forever. The pool's `create` hook calls this.\n *\n * @param script - The worker module each thread runs (must call `serveWorker`)\n * @param workerData - Opaque, structured-cloneable data handed to the thread at spawn\n * @returns A promise resolving the online {@link NodeThread}\n */\nexport function spawnThread(script: string | URL, workerData: unknown): Promise<NodeThread> {\n\treturn new Thread(script, workerData).promise\n}\n\n/**\n * Dispatch one job to a leased {@link NodeThread} and await its narrowed reply.\n *\n * @remarks\n * Mints a fresh `id`, posts a `run` envelope, and resolves when the thread replies for\n * that id: a success `value` is narrowed through `result` (a value that fails the guard\n * rejects — the zero-`as` type bridge), a failure rejects with the thread's error string.\n * A thread that ALREADY died rejects synchronously at entry from the latched\n * {@link NodeThread.death} — its death events fired before this dispatch existed and will\n * never fire again, so waiting on the listeners below would dangle forever; the latch makes\n * death total across every event ordering. If the thread `error`s / `exit`s mid-flight it is\n * marked dead and the\n * job rejects. An inbound `messageerror` also evicts and terminates the thread before\n * rejection. On `execution.signal` abort it contains the cooperative `abort` post,\n * evicts the thread, and observes `terminate()` settlement because CPU-bound work cannot\n * honour the signal; the freed pool slot then gets a fresh thread. Every per-job listener\n * (`message` / `messageerror` / `error` / `exit` / `abort`) is removed on settle.\n *\n * @typeParam TResult - The reply type the `result` guard narrows to\n * @param thread - The leased thread to run the job on\n * @param input - The work payload (structured-cloned to the thread)\n * @param execution - The per-attempt handle; its `signal` aborts → terminate + evict\n * @param result - The {@link Guard} narrowing the reply value with no assertion\n * @returns A promise resolving the narrowed `TResult`, or rejecting on error / abort\n */\nexport function dispatch<TResult>(\n\tthread: NodeThread,\n\tinput: unknown,\n\texecution: QueueExecution,\n\tresult: Guard<TResult>,\n): Promise<TResult> {\n\treturn new Dispatch(thread, input, execution, result).promise\n}\n","import type { ServeWorkerOptions } from './types.js'\nimport { parentPort } from 'node:worker_threads'\n\n// The worker-side entry. SELF-CONTAINED by necessity: this module loads as RAW `.ts`\n// inside a spawned thread (Node ≥ 23.6 type-stripping), so it imports ONLY\n// `node:worker_threads` at runtime — no `@src/*`, no `.js`-relative value imports (the\n// only non-node import is the type-only `ServeWorkerOptions`, fully erased at runtime).\n// Its guards are inlined for the same reason. A worker script that needs the cloned\n// `workerData` reads it directly from `node:worker_threads` (it is in a thread already).\n\n// Inlined record guard (do NOT import `isRecord` from `@src/core` — see above). Total:\n// adversarial input returns `false`, never throws (AGENTS §14).\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// Narrow an inbound message to a `run` envelope (a string `id` + a `'run'` command + an\n// `input` payload) — no assertion.\nfunction isRun(value: unknown): value is { readonly id: string; readonly input: unknown } {\n\treturn (\n\t\tisRecord(value) && typeof value.id === 'string' && value.command === 'run' && 'input' in value\n\t)\n}\n\n// Narrow an inbound message to an `abort` envelope (a string `id` + an `'abort'` command).\nfunction isAbort(value: unknown): value is { readonly id: string } {\n\treturn isRecord(value) && typeof value.id === 'string' && value.command === 'abort'\n}\n\n/**\n * Register a worker-thread handler — the worker-side half of {@link createNodeWorker}.\n *\n * @remarks\n * Must be the spawned thread's module entry. It listens on the parent port for the\n * run/abort protocol: a `run` message narrows its `input` through `options.input` (an\n * invalid payload replies with an error envelope, never running the handler), then runs\n * `options.handler(input, { signal })` and replies `{ id, ok: true, value }` on success or\n * `{ id, ok: false, error }` on throw. Input-guard throws use the same failure envelope. If a\n * success value cannot be cloned, the post is retried as a clone-safe failure; if that post also\n * fails, the parent port closes so the main side observes thread exit instead of waiting forever.\n * Each in-flight job has its own `AbortController`,\n * so an `abort` message for that id fires the handler's `signal` (cooperative — the main\n * side ALSO terminates the thread, so a handler that ignores its signal is still stopped).\n * Every inbound message is narrowed with the inlined guards — no `as`. On the main thread\n * (`parentPort === null`) it is a no-op.\n *\n * @typeParam TInput - The work payload (inferred from `options.input`)\n * @typeParam TResult - The value the handler resolves (the reply payload)\n * @param options - The `input` guard and the `handler` (see {@link ServeWorkerOptions})\n *\n * @example\n * ```ts\n * // double.ts — a worker script\n * import { serveWorker } from '@orkestrel/worker/server'\n *\n * serveWorker<number, number>({\n * \tinput: (value): value is number => typeof value === 'number',\n * \thandler: (value) => value * 2,\n * })\n * ```\n */\nexport function serveWorker<TInput, TResult>(options: ServeWorkerOptions<TInput, TResult>): void {\n\tconst port = parentPort\n\tif (port === null) return\n\tconst input = options.input\n\tconst handler = options.handler\n\tconst controllers = new Map<string, AbortController>()\n\tport.on('message', (raw: unknown) => {\n\t\tif (isAbort(raw)) {\n\t\t\tcontrollers.get(raw.id)?.abort()\n\t\t\treturn\n\t\t}\n\t\tif (!isRun(raw)) return\n\t\tconst id = raw.id\n\t\tconst controller = new AbortController()\n\t\tcontrollers.set(id, controller)\n\t\tvoid Promise.resolve()\n\t\t\t.then(() => {\n\t\t\t\tif (!input(raw.input)) {\n\t\t\t\t\tthrow new Error('input did not satisfy input guard')\n\t\t\t\t}\n\t\t\t\tconst value = raw.input\n\t\t\t\treturn handler(value, { signal: controller.signal })\n\t\t\t})\n\t\t\t.then((value) => {\n\t\t\t\tcontrollers.delete(id)\n\t\t\t\tport.postMessage({ id, ok: true, value })\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tcontrollers.delete(id)\n\t\t\t\tlet message = 'worker operation failed'\n\t\t\t\ttry {\n\t\t\t\t\tmessage = error instanceof Error ? error.message : String(error)\n\t\t\t\t} catch {}\n\t\t\t\ttry {\n\t\t\t\t\tport.postMessage({ id, ok: false, error: message })\n\t\t\t\t} catch {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tport.close()\n\t\t\t\t\t} catch {}\n\t\t\t\t}\n\t\t\t})\n\t})\n}\n","import type { WorkerInterface } from '@src/core'\nimport type { Guard } from '@orkestrel/contract'\nimport type { QueueExecution, QueueStoreInterface } from '@orkestrel/queue'\nimport type { NodeThread, NodeWorkerOptions } from './types.js'\nimport { createWorker } from '@src/core'\nimport { attempt } from '@orkestrel/contract'\nimport { dispatch, spawnThread } from './helpers.js'\n\n/**\n * Internal composition entity backing {@link createNodeWorker}.\n *\n * @remarks\n * Supplies bound Pool and Queue operations without nested function assignments. The resulting\n * public entity remains the plain core {@link WorkerInterface}.\n */\nexport class NodeWorker<TInput, TResult> {\n\treadonly #script: string | URL\n\treadonly #input: Guard<TInput>\n\treadonly #result: Guard<TResult>\n\treadonly #workerData: unknown\n\treadonly #concurrency: number | undefined\n\treadonly #retries: number | undefined\n\treadonly #timeout: number | undefined\n\treadonly #store: QueueStoreInterface<TInput> | undefined\n\n\tconstructor(options: NodeWorkerOptions<TInput, TResult>) {\n\t\tthis.#script = options.script\n\t\tthis.#input = options.input\n\t\tthis.#result = options.result\n\t\tthis.#workerData = options.workerData\n\t\tthis.#concurrency = options.concurrency\n\t\tthis.#retries = options.retries\n\t\tthis.#timeout = options.timeout\n\t\tthis.#store = options.store\n\t}\n\n\tbuild(): WorkerInterface<TInput, TResult> {\n\t\treturn createWorker<TInput, NodeThread, TResult>({\n\t\t\tpool: {\n\t\t\t\tcreate: this.#create.bind(this),\n\t\t\t\tdestroy: this.#destroy.bind(this),\n\t\t\t\tvalidate: this.#validate.bind(this),\n\t\t\t\t...(this.#concurrency !== undefined ? { max: this.#concurrency } : {}),\n\t\t\t},\n\t\t\thandler: this.#handle.bind(this),\n\t\t\t...(this.#concurrency !== undefined ? { concurrency: this.#concurrency } : {}),\n\t\t\t...(this.#retries !== undefined ? { retries: this.#retries } : {}),\n\t\t\t...(this.#timeout !== undefined ? { timeout: this.#timeout } : {}),\n\t\t\t...(this.#store !== undefined ? { store: this.#store } : {}),\n\t\t})\n\t}\n\n\t#create(): Promise<NodeThread> {\n\t\treturn spawnThread(this.#script, this.#workerData)\n\t}\n\n\tasync #destroy(thread: NodeThread): Promise<void> {\n\t\tawait thread.worker.terminate()\n\t}\n\n\t#validate(thread: NodeThread): boolean {\n\t\treturn thread.alive && thread.worker.threadId > 0\n\t}\n\n\t#handle(input: TInput, thread: NodeThread, execution: QueueExecution): Promise<TResult> {\n\t\tconst outcome = attempt(() => this.#input(input))\n\t\tif (!outcome.success) return Promise.reject(outcome.error)\n\t\tif (!outcome.value) {\n\t\t\treturn Promise.reject(new Error('input did not satisfy input guard'))\n\t\t}\n\t\treturn dispatch(thread, input, execution, this.#result)\n\t}\n}\n","import type { WorkerInterface } from '@src/core'\nimport type { ContractShape, Infer } from '@orkestrel/contract'\nimport type { QueueStoreInterface } from '@orkestrel/queue'\nimport type { NodeWorkerOptions } from './types.js'\nimport { createJSONDriver } from '@orkestrel/database/server'\nimport { createDatabaseQueueStore } from '@orkestrel/queue'\nimport { NodeWorker } from './NodeWorker.js'\n\n/**\n * Create a persistent JSON-file {@link QueueStoreInterface} — the core\n * `createDatabaseQueueStore` over a server {@link createJSONDriver}.\n *\n * @remarks\n * A queue's durable state is just a database table, so JSON persistence reuses the\n * existing JSON-file driver rather than a bespoke store: the entries are written to\n * (and reloaded from) the file at `path`, surviving a process restart. There is no new\n * class — the store engine ({@link createDatabaseQueueStore}) is shared, and only the\n * driver changes where the bytes live. The `input` shape must be JSON-serializable\n * (the JSON driver round-trips it as JSON). Build a second store over the SAME `path` to\n * resume the outstanding entries a prior store persisted.\n *\n * @typeParam TInput - The contract shape of each entry's `input` payload\n * @param path - The JSON file the entries are loaded from and flushed to\n * @param input - The {@link ContractShape} for the work payload (the `input` column)\n * @returns A JSON-file-backed {@link QueueStoreInterface}, typed by `input`\n *\n * @example\n * ```ts\n * import { stringShape } from '@orkestrel/contract'\n * import { createJSONQueueStore } from '@orkestrel/worker/server'\n *\n * const store = createJSONQueueStore('data/queue.json', stringShape())\n * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })\n * // A later process resumes the outstanding work:\n * const resumed = createJSONQueueStore('data/queue.json', stringShape())\n * const outstanding = await resumed.load()\n * ```\n */\nexport function createJSONQueueStore<TInput extends ContractShape>(\n\tpath: string,\n\tinput: TInput,\n): QueueStoreInterface<Infer<TInput>> {\n\treturn createDatabaseQueueStore(input, createJSONDriver(path))\n}\n\n/**\n * Create a CPU-parallel worker over `node:worker_threads` — a thin specialization of the\n * core `createWorker` whose pooled resource is a worker THREAD.\n *\n * @remarks\n * Composition, not reimplementation: all concurrency, retries, per-attempt timeout,\n * lifecycle, and durability are the core `Worker`'s (a `Queue` ⨉ `Pool`). This factory\n * supplies only the thread pairing — the pool `create`s a thread (via `spawnThread`),\n * `destroy`s it with `terminate()`, and `validate`s it by `alive && threadId > 0` (so an\n * evicted / crashed thread is dropped and replaced) — and an internal handler that\n * narrows the input through `options.input` (fail-fast before the structured-clone\n * boundary) then `dispatch`es the job to the leased thread, narrowing the reply through\n * `options.result`. Both generics INFER from the `input` / `result` guards, so call sites\n * need no explicit type arguments. The boundary is crossed with ZERO `as`: the guards\n * reconstruct `TInput` / `TResult` by validation (AGENTS §14). An `abort` / `timeout`\n * TERMINATES the in-flight thread (CPU-bound work can't honour a signal) and evicts it; a\n * subsequent job spawns a fresh thread. The worker script's module must call\n * `serveWorker`. Returns the plain {@link WorkerInterface} — its methods are the Worker's.\n *\n * @typeParam TInput - The work payload each job carries (inferred from `input`)\n * @typeParam TResult - The value a thread resolves for a job (inferred from `result`)\n * @param options - The `script` plus the `input` / `result` guards and optional\n * `workerData` / `concurrency` / `retries` / `timeout` / `store`\n * (see {@link NodeWorkerOptions})\n * @returns A working {@link WorkerInterface} backed by a thread pool\n *\n * @example\n * ```ts\n * import { createNodeWorker } from '@orkestrel/worker/server'\n *\n * const worker = createNodeWorker({\n * \tscript: new URL('./double.js', import.meta.url),\n * \tinput: (value): value is number => typeof value === 'number',\n * \tresult: (value): value is number => typeof value === 'number',\n * \tconcurrency: 4,\n * })\n *\n * const doubled = await worker.enqueue(21) // 42, computed on a worker thread\n * await worker.destroy() // terminates every thread\n * ```\n */\nexport function createNodeWorker<TInput, TResult>(\n\toptions: NodeWorkerOptions<TInput, TResult>,\n): WorkerInterface<TInput, TResult> {\n\treturn new NodeWorker(options).build()\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAa,SAAb,MAA0C;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,SAAS;CACT;CAEA,YAAY,QAAsB,YAAqB;EACtD,KAAKA,UAAU,IAAI,oBAAA,OAAa,QAAQ,EACvC,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC,EAClD,CAAC;EACD,MAAM,YAAY,QAAQ,cAA0B;EACpD,KAAKC,WAAW,UAAU;EAC1B,KAAKC,WAAW,UAAU;EAC1B,KAAKC,UAAU,UAAU;EACzB,KAAKC,iBAAiB,KAAKK,QAAQ,KAAK,IAAI;EAC5C,KAAKJ,qBAAqB,KAAKK,YAAY,KAAK,IAAI;EACpD,KAAKJ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