@orkestrel/queue 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orkestrel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @orkestrel/queue
2
+
3
+ A concurrent, cooperative typed **FIFO job queue**: `Queue` runs enqueued
4
+ inputs through a handler under bounded concurrency, with retries and a
5
+ per-attempt timeout / abort — each `enqueue` returns a promise that settles
6
+ with the job's result. Idle worker loops **park** on a wake list instead of
7
+ busy-polling, so an idle queue burns zero CPU; `enqueue` / `resume` wake
8
+ exactly one (or all) parked loops. Cancellation is built on the L1 abort +
9
+ timeout primitives, so an attempt that ignores its `signal` still fails when
10
+ the per-attempt deadline runs out. Durability is opt-in and outstanding-only —
11
+ pass a `store` and a `restore()` after a restart re-runs precisely the
12
+ unfinished work; `DatabaseQueueStore` persists over any driver, and
13
+ `MemoryQueueStore` is the zero-plumbing in-process default. The queue is
14
+ observable (a typed `emitter` surfaces `enqueue` / `start` / `retry` /
15
+ `success` / `failure` / `abort` / `drain`) and deliberately de-bloated — no
16
+ scheduler, no priorities. Environment-agnostic — no I/O, no browser or server
17
+ assumptions. Part of the `@orkestrel` line.
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ npm install @orkestrel/queue
23
+ ```
24
+
25
+ ## Requirements
26
+
27
+ - Node.js >= 24
28
+ - ESM-only (no CommonJS build)
29
+
30
+ ## Usage
31
+
32
+ ```ts
33
+ import { createQueue } from '@orkestrel/queue'
34
+
35
+ const queue = createQueue<string, number>({
36
+ handler: async (url, { signal }) => (await fetch(url, { signal })).status,
37
+ concurrency: 4, // up to four in flight at once (default 1 = ordered)
38
+ retries: 2, // two extra attempts on failure
39
+ timeout: 5_000, // each attempt is bounded to 5s
40
+ })
41
+
42
+ const status = await queue.enqueue('https://example.com')
43
+ ```
44
+
45
+ ## Guide
46
+
47
+ For the full surface — the `Queue` engine, options, the durable
48
+ `QueueStoreInterface` (`MemoryQueueStore` / `DatabaseQueueStore`), the
49
+ observable `emitter`, and usage patterns — see
50
+ [`guides/src/queue.md`](guides/src/queue.md).
51
+
52
+ ## Package
53
+
54
+ Published as a single typed entry point per the `exports` field in
55
+ `package.json`.
56
+
57
+ ## License
58
+
59
+ MIT © [Orkestrel](https://github.com/orkestrel) — see [LICENSE](./LICENSE).
@@ -0,0 +1,581 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_abort = require("@orkestrel/abort");
3
+ let _orkestrel_emitter = require("@orkestrel/emitter");
4
+ let _orkestrel_timeout = require("@orkestrel/timeout");
5
+ let _orkestrel_contract = require("@orkestrel/contract");
6
+ let _orkestrel_database = require("@orkestrel/database");
7
+ //#region src/core/Queue.ts
8
+ /**
9
+ * A concurrent, cooperative job queue.
10
+ *
11
+ * @remarks
12
+ * - **Cooperative wake-park loop.** Up to `concurrency` worker loops run; each
13
+ * takes the next pending entry, or — when none is ready (empty or paused) —
14
+ * PARKS by awaiting a fresh promise whose resolver is held in a wake list.
15
+ * `enqueue` / `resume` resolve one parked resolver to wake exactly one worker,
16
+ * so idle workers consume no CPU (no busy-poll, no timers, no recursion).
17
+ * - **FIFO + bounded concurrency.** Entries run in enqueue order; at most
18
+ * `concurrency` are in flight at once (default `1` = strictly ordered). A surplus
19
+ * entry waits for a worker to free up.
20
+ * - **Per-attempt deadline + cancellation.** Each attempt's `signal` (handed to the
21
+ * handler) fires on the per-attempt `Timeout` expiring, a queue-level `abort`, or
22
+ * the entry's own `signal`. The handler is RACED against that signal, so an attempt
23
+ * that ignores its `signal` still fails on the deadline. Built on the L1 `Abort` /
24
+ * `Timeout` primitives (a queue / entry abort CLEARS the deadline, never expires it).
25
+ * - **Retries.** A failed attempt (a handler rejection or a per-attempt timeout)
26
+ * retries while attempts remain (`retries` + 1 total). A queue-level abort NEVER
27
+ * retries — it rejects the entry at once; an entry-`signal` abort likewise.
28
+ * - **Lifecycle (§10).** `pause` parks workers; `resume` wakes them; `stop` ends the
29
+ * loops permanently and rejects pending (in-flight settle); `abort` fires the queue
30
+ * signal (cancelling in-flight attempts) and rejects pending; `clear` drops only
31
+ * pending; `destroy` aborts then stops, idempotently.
32
+ * - **Durability (optional `store`).** The store mirrors only OUTSTANDING work: an
33
+ * entry is `save`d on accept (and re-`save`d as its attempt count climbs) and
34
+ * `remove`d the moment it settles (success or terminal failure) or is drained by a
35
+ * lifecycle call. Accepting work durably is NOT best-effort — a failed initial `save`
36
+ * rejects the enqueue; per-attempt persistence IS best-effort (in-memory state is
37
+ * authoritative). A graceful shutdown empties the store; a crash leaves rows that
38
+ * `restore()` re-runs at their persisted attempt count (queue-default retries /
39
+ * timeout, no per-entry signal). At-least-once — handlers should be idempotent.
40
+ * - **Observable (§13).** The owned {@link emitter} ({@link QueueEventMap}) carries the
41
+ * lifecycle moments — `enqueue` / `start` / `retry` / `success` / `failure` / `abort` /
42
+ * `drain` — for fire-and-forget observers. Every event is emitted directly, strictly AFTER
43
+ * the relevant wake / park / settle transition; the emitter isolates a listener throw and
44
+ * routes it to its `error` handler (the `error` option), so a buggy observer can NEVER
45
+ * reorder, throw into, or corrupt the cooperative wake-park / settle-once engine: `active`
46
+ * stays balanced and no parked worker is stranded regardless of what a listener does.
47
+ * Observation is purely a side-channel.
48
+ */
49
+ var Queue = class {
50
+ #handler;
51
+ #concurrency;
52
+ #retries;
53
+ #timeout;
54
+ #store;
55
+ #abort = (0, _orkestrel_abort.createAbort)();
56
+ #emitter;
57
+ #pending = [];
58
+ #live = /* @__PURE__ */ new Set();
59
+ #wakes = [];
60
+ #active = 0;
61
+ #running = 0;
62
+ #paused = false;
63
+ #stopped = false;
64
+ #aborted = false;
65
+ #destroyed = false;
66
+ constructor(options) {
67
+ this.#handler = options.handler;
68
+ this.#concurrency = Math.max(1, options.concurrency ?? 1);
69
+ this.#retries = Math.max(0, options.retries ?? 0);
70
+ this.#timeout = Math.max(0, options.timeout ?? 0);
71
+ this.#store = options.store;
72
+ this.#emitter = new _orkestrel_emitter.Emitter({
73
+ on: options?.on,
74
+ error: options?.error
75
+ });
76
+ this.#spawn();
77
+ }
78
+ get emitter() {
79
+ return this.#emitter;
80
+ }
81
+ get count() {
82
+ return this.#pending.length + this.#active;
83
+ }
84
+ get active() {
85
+ return this.#active;
86
+ }
87
+ get paused() {
88
+ return this.#paused;
89
+ }
90
+ get stopped() {
91
+ return this.#stopped || this.#aborted;
92
+ }
93
+ enqueue(input, options) {
94
+ if (this.#destroyed) return Promise.reject(/* @__PURE__ */ new Error("queue is destroyed"));
95
+ if (this.#aborted) return Promise.reject(/* @__PURE__ */ new Error("queue is aborted"));
96
+ if (this.#stopped) return Promise.reject(/* @__PURE__ */ new Error("queue is stopped"));
97
+ const id = options?.id ?? crypto.randomUUID();
98
+ if (this.#store !== void 0) return this.#persist(this.#store, id, input, options);
99
+ return new Promise((resolve, reject) => {
100
+ this.#live.add(id);
101
+ this.#pending.push({
102
+ id,
103
+ input,
104
+ options,
105
+ attempts: 0,
106
+ resolve,
107
+ reject
108
+ });
109
+ this.#emitter.emit("enqueue", id);
110
+ this.#wake();
111
+ });
112
+ }
113
+ async restore() {
114
+ if (this.#store === void 0 || this.#stopped || this.#aborted || this.#destroyed) return;
115
+ const entries = await this.#store.load();
116
+ if (this.#destroyed || this.#aborted || this.#stopped) return;
117
+ for (const entry of entries) {
118
+ if (this.#live.has(entry.id)) continue;
119
+ new Promise((resolve, reject) => {
120
+ this.#live.add(entry.id);
121
+ this.#pending.push({
122
+ id: entry.id,
123
+ input: entry.input,
124
+ options: void 0,
125
+ attempts: entry.attempts,
126
+ resolve,
127
+ reject
128
+ });
129
+ this.#emitter.emit("enqueue", entry.id);
130
+ this.#wake();
131
+ }).catch(() => {});
132
+ }
133
+ }
134
+ start() {
135
+ if (this.#aborted || this.#destroyed) return;
136
+ this.#stopped = false;
137
+ this.#spawn();
138
+ }
139
+ stop() {
140
+ if (this.#stopped) return;
141
+ this.#stopped = true;
142
+ this.#drain(/* @__PURE__ */ new Error("queue is stopped"));
143
+ this.#wakeAll();
144
+ }
145
+ pause() {
146
+ if (this.#paused || this.stopped || this.#destroyed) return;
147
+ this.#paused = true;
148
+ }
149
+ resume() {
150
+ if (!this.#paused || this.stopped || this.#destroyed) return;
151
+ this.#paused = false;
152
+ this.#wakeAll();
153
+ }
154
+ abort(reason) {
155
+ if (this.#aborted) return;
156
+ this.#aborted = true;
157
+ this.#abort.abort(reason);
158
+ this.#drain(this.#abort.signal.reason);
159
+ this.#wakeAll();
160
+ this.#emitter.emit("abort", this.#abort.signal.reason);
161
+ }
162
+ clear() {
163
+ this.#drain(/* @__PURE__ */ new Error("queue cleared"));
164
+ }
165
+ destroy() {
166
+ if (this.#destroyed) return;
167
+ this.#destroyed = true;
168
+ this.abort();
169
+ this.#stopped = true;
170
+ this.#wakeAll();
171
+ }
172
+ #spawn() {
173
+ if (this.#stopped || this.#aborted || this.#destroyed) return;
174
+ while (this.#running < this.#concurrency) {
175
+ this.#running += 1;
176
+ this.#worker();
177
+ }
178
+ }
179
+ async #worker() {
180
+ try {
181
+ while (true) {
182
+ const entry = await this.#next();
183
+ if (entry === void 0) break;
184
+ this.#active += 1;
185
+ try {
186
+ await this.#run(entry);
187
+ } finally {
188
+ this.#active -= 1;
189
+ if (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit("drain");
190
+ }
191
+ }
192
+ } finally {
193
+ this.#running -= 1;
194
+ }
195
+ }
196
+ #next() {
197
+ return new Promise((resolve) => {
198
+ const take = () => {
199
+ if (this.#stopped || this.#aborted || this.#destroyed) {
200
+ resolve(void 0);
201
+ return;
202
+ }
203
+ if (this.#paused || this.#pending.length === 0) {
204
+ this.#wakes.push(take);
205
+ return;
206
+ }
207
+ resolve(this.#pending.shift());
208
+ };
209
+ take();
210
+ });
211
+ }
212
+ #wake() {
213
+ const resolver = this.#wakes.shift();
214
+ if (resolver !== void 0) resolver();
215
+ }
216
+ #wakeAll() {
217
+ const resolvers = this.#wakes.splice(0);
218
+ for (const resolver of resolvers) resolver();
219
+ }
220
+ #drain(error) {
221
+ while (this.#pending.length > 0) {
222
+ const entry = this.#pending.shift();
223
+ if (entry === void 0) continue;
224
+ this.#live.delete(entry.id);
225
+ this.#store?.remove(entry.id).catch(() => {});
226
+ entry.reject(error);
227
+ }
228
+ }
229
+ async #persist(store, id, input, options) {
230
+ await store.save({
231
+ id,
232
+ input,
233
+ attempts: 0
234
+ });
235
+ if (this.#destroyed || this.#aborted || this.#stopped) {
236
+ await store.remove(id).catch(() => {});
237
+ throw new Error("queue is stopped");
238
+ }
239
+ return new Promise((resolve, reject) => {
240
+ this.#live.add(id);
241
+ this.#pending.push({
242
+ id,
243
+ input,
244
+ options,
245
+ attempts: 0,
246
+ resolve,
247
+ reject
248
+ });
249
+ this.#emitter.emit("enqueue", id);
250
+ this.#wake();
251
+ });
252
+ }
253
+ async #saveAttempt(entry, attempts) {
254
+ try {
255
+ await this.#store?.save({
256
+ id: entry.id,
257
+ input: entry.input,
258
+ attempts
259
+ });
260
+ } catch {}
261
+ }
262
+ async #run(entry) {
263
+ const retries = Math.max(0, entry.options?.retries ?? this.#retries);
264
+ const timeout = Math.max(0, entry.options?.timeout ?? this.#timeout);
265
+ const signal = entry.options?.signal;
266
+ this.#emitter.emit("start", entry.id);
267
+ for (let attempt = entry.attempts;; attempt += 1) {
268
+ if (this.#abort.aborted) return this.#settle(entry, {
269
+ success: false,
270
+ error: this.#abort.signal.reason
271
+ });
272
+ if (signal?.aborted) return this.#settle(entry, {
273
+ success: false,
274
+ error: signal.reason
275
+ });
276
+ if (attempt > entry.attempts) {
277
+ await this.#saveAttempt(entry, attempt);
278
+ this.#emitter.emit("retry", entry.id, attempt);
279
+ }
280
+ const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
281
+ if (outcome.success) return this.#settle(entry, {
282
+ success: true,
283
+ value: outcome.value
284
+ });
285
+ if (this.#abort.aborted) return this.#settle(entry, {
286
+ success: false,
287
+ error: this.#abort.signal.reason
288
+ });
289
+ if (signal?.aborted) return this.#settle(entry, {
290
+ success: false,
291
+ error: signal.reason
292
+ });
293
+ if (attempt < retries) continue;
294
+ return this.#settle(entry, {
295
+ success: false,
296
+ error: outcome.error
297
+ });
298
+ }
299
+ }
300
+ #settle(entry, outcome) {
301
+ this.#live.delete(entry.id);
302
+ if (this.#store === void 0) {
303
+ this.#commit(entry, outcome);
304
+ return;
305
+ }
306
+ return this.#forget(this.#store, entry, outcome);
307
+ }
308
+ #commit(entry, outcome) {
309
+ if (outcome.success) {
310
+ entry.resolve(outcome.value);
311
+ this.#emitter.emit("success", entry.id, outcome.value);
312
+ } else {
313
+ entry.reject(outcome.error);
314
+ this.#emitter.emit("failure", entry.id, outcome.error);
315
+ }
316
+ }
317
+ async #forget(store, entry, outcome) {
318
+ try {
319
+ await store.remove(entry.id);
320
+ } catch {}
321
+ this.#commit(entry, outcome);
322
+ }
323
+ async #attempt(id, input, timeout, signal) {
324
+ const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
325
+ let deadline;
326
+ let attemptSignal = cancel;
327
+ if (timeout > 0) {
328
+ deadline = (0, _orkestrel_timeout.createTimeout)({
329
+ ms: timeout,
330
+ signal: cancel
331
+ });
332
+ deadline.start();
333
+ attemptSignal = AbortSignal.any([cancel, deadline.signal]);
334
+ }
335
+ try {
336
+ return {
337
+ success: true,
338
+ value: await this.#race(id, input, attemptSignal, deadline)
339
+ };
340
+ } catch (error) {
341
+ return {
342
+ success: false,
343
+ error: error instanceof Error ? error : new Error(String(error), { cause: error })
344
+ };
345
+ } finally {
346
+ deadline?.clear();
347
+ }
348
+ }
349
+ #race(id, input, signal, deadline) {
350
+ const fault = () => deadline?.expired === true ? /* @__PURE__ */ new Error("attempt timed out") : /* @__PURE__ */ new Error("attempt aborted");
351
+ if (signal.aborted) return Promise.reject(fault());
352
+ return new Promise((resolve, reject) => {
353
+ const onAbort = () => reject(fault());
354
+ signal.addEventListener("abort", onAbort, { once: true });
355
+ const settle = () => signal.removeEventListener("abort", onAbort);
356
+ Promise.resolve(this.#handler(input, {
357
+ id,
358
+ signal
359
+ })).then((value) => {
360
+ settle();
361
+ resolve(value);
362
+ }, (error) => {
363
+ settle();
364
+ reject(error);
365
+ });
366
+ });
367
+ }
368
+ };
369
+ //#endregion
370
+ //#region src/core/stores/DatabaseQueueStore.ts
371
+ /**
372
+ * A {@link QueueStoreInterface} backed by one table of the `databases` layer — a
373
+ * queue's durable state IS a table, so persistence reduces to keyed CRUD over a
374
+ * `TableInterface`.
375
+ *
376
+ * @remarks
377
+ * The store is driver-agnostic: it holds a single {@link TableInterface} whose
378
+ * backend (memory, JSON, SQLite) is chosen by whoever builds it (the factories).
379
+ * `save` upserts an entry by its primary key (`set`), `remove` drops one (`remove`),
380
+ * `load` returns every outstanding entry (`records` with no criteria), and `clear`
381
+ * empties the table. Reads are narrowed through the table's contract, so `load`
382
+ * returns typed {@link StoredEntry}`<TInput>[]` with no cast (AGENTS §1) — the table
383
+ * is created over the `{ id; input; attempts }` column map, which `Infer`s to exactly
384
+ * that row. The store holds only OUTSTANDING work (completed entries are `remove`d), so
385
+ * `load` on startup yields precisely the entries to resume.
386
+ *
387
+ * @typeParam TInput - The work input each {@link StoredEntry} carries
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * import { createMemoryQueueStore, stringShape } from '@src/core'
392
+ *
393
+ * const store = createMemoryQueueStore(stringShape())
394
+ * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
395
+ * const outstanding = await store.load() // readonly StoredEntry<string>[]
396
+ * ```
397
+ */
398
+ var DatabaseQueueStore = class {
399
+ #table;
400
+ /**
401
+ * Wrap a table as a queue store.
402
+ *
403
+ * @param table - The {@link TableInterface} holding the outstanding entries — its
404
+ * row is a {@link StoredEntry}`<TInput>` (the `{ id; input; attempts }` shape)
405
+ */
406
+ constructor(table) {
407
+ this.#table = table;
408
+ }
409
+ /** Upsert an entry by its `id` (a re-`save` of an existing `id` overwrites it). */
410
+ async save(entry) {
411
+ await this.#table.set(entry);
412
+ }
413
+ /** Drop a finished entry by `id`; absent is a no-op (no throw). */
414
+ async remove(id) {
415
+ await this.#table.remove(id);
416
+ }
417
+ /** Every outstanding entry — the work to resume after a restart. */
418
+ load() {
419
+ return this.#table.records();
420
+ }
421
+ /** Empty the store — drop every outstanding entry. */
422
+ async clear() {
423
+ await this.#table.clear();
424
+ }
425
+ };
426
+ //#endregion
427
+ //#region src/core/stores/MemoryQueueStore.ts
428
+ /**
429
+ * The in-memory {@link QueueStoreInterface} — a process-lifetime `Map` of
430
+ * {@link StoredEntry}s keyed by id, the DEFAULT store
431
+ * {@link import('../factories.js').createMemoryQueueStore} builds.
432
+ *
433
+ * @remarks
434
+ * A plain `Map<string, StoredEntry<TInput>>` (AGENTS §21 — the entry is already pure,
435
+ * self-contained JSON, so no `databases` table / driver codec is needed for the memory
436
+ * tier; this is the zero-plumbing twin of {@link DatabaseQueueStore}, which wraps a
437
+ * `TableInterface` for a driver-pluggable durable backend). The store holds ONLY
438
+ * outstanding work, so `load` yields precisely the entries to resume — though a memory
439
+ * store is gone when the process exits, so `restore()` recovers nothing after a real
440
+ * restart. For durability across restarts, build a {@link DatabaseQueueStore} over a
441
+ * server JSON / SQLite driver (the SAME interface, so the queue / worker never knows).
442
+ *
443
+ * - **`save` upserts an entry under its OWN `id`** (a re-`save` of an existing `id`
444
+ * overwrites it — `Map.set`, never a duplicate).
445
+ * - **`remove` drops a finished entry by `id`**; an absent `id` is a no-op (no throw).
446
+ * - **`load` returns every outstanding entry** as a readonly array (the `Map`'s values
447
+ * in insertion order — the work to resume).
448
+ * - **`clear` empties the store** — drop every outstanding entry.
449
+ *
450
+ * Each primitive is async (it returns a resolved `Promise`) to satisfy the
451
+ * {@link QueueStoreInterface} signatures, wrapping the synchronous `Map` op — so the
452
+ * memory and driver-backed stores are interchangeable behind the one interface. The
453
+ * public surface is EXACTLY `save` / `remove` / `load` / `clear` — no extra members (the
454
+ * §22 method bijection with {@link QueueStoreInterface}).
455
+ *
456
+ * @typeParam TInput - The work input each {@link StoredEntry} carries
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * import { createMemoryQueueStore, stringShape } from '@src/core'
461
+ *
462
+ * const store = createMemoryQueueStore(stringShape())
463
+ * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
464
+ * const outstanding = await store.load() // readonly StoredEntry<string>[]
465
+ * await store.remove('job-1') // a finished entry leaves the store
466
+ * ```
467
+ */
468
+ var MemoryQueueStore = class {
469
+ #entries = /* @__PURE__ */ new Map();
470
+ /** Upsert an entry under its OWN `id` (a re-`save` of an existing `id` overwrites it). */
471
+ save(entry) {
472
+ this.#entries.set(entry.id, entry);
473
+ return Promise.resolve();
474
+ }
475
+ /** Drop a finished entry by `id`; `Map.delete` of an absent id is already a no-op (no throw). */
476
+ remove(id) {
477
+ this.#entries.delete(id);
478
+ return Promise.resolve();
479
+ }
480
+ /** Every outstanding entry — the work to resume (the `Map`'s values, insertion order). */
481
+ load() {
482
+ return Promise.resolve([...this.#entries.values()]);
483
+ }
484
+ /** Empty the store — drop every outstanding entry. */
485
+ clear() {
486
+ this.#entries.clear();
487
+ return Promise.resolve();
488
+ }
489
+ };
490
+ //#endregion
491
+ //#region src/core/factories.ts
492
+ /**
493
+ * Create a concurrent, cooperative job queue — a bounded-concurrency engine that
494
+ * runs each enqueued input through a handler, with retries and a per-attempt
495
+ * timeout / abort, all over the L1 `Abort` / `Timeout` primitives.
496
+ *
497
+ * @remarks
498
+ * Worker loops PARK on a wake list when no entry is ready and are woken one-at-a-time
499
+ * by `enqueue` / `resume`, so an idle queue consumes no CPU (no polling). `enqueue`
500
+ * returns a promise that settles when the entry finally completes, fails (after its
501
+ * retries), or is rejected by an abort. A queue-level `abort` never retries; the
502
+ * lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)
503
+ * follows AGENTS §10. The queue is observable (§13): a typed `emitter` surfaces
504
+ * `enqueue` / `start` / `retry` / `success` / `failure` / `abort` / `drain`.
505
+ *
506
+ * @typeParam TInput - The work input each entry carries
507
+ * @typeParam TResult - The value the handler resolves for an entry
508
+ * @param options - The `handler` plus optional `concurrency` (default `1`),
509
+ * `retries` (default `0`), and a default per-attempt `timeout` in milliseconds
510
+ * @returns A working {@link QueueInterface}
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * import { createQueue } from '@src/core'
515
+ *
516
+ * const queue = createQueue<string, number>({
517
+ * handler: async (url, { signal }) => (await fetch(url, { signal })).status,
518
+ * concurrency: 4,
519
+ * retries: 2,
520
+ * timeout: 5_000,
521
+ * })
522
+ *
523
+ * const status = await queue.enqueue('https://example.com')
524
+ * ```
525
+ */
526
+ function createQueue(options) {
527
+ return new Queue(options);
528
+ }
529
+ function createDatabaseQueueStore(input, driver) {
530
+ return new DatabaseQueueStore((0, _orkestrel_database.createDatabase)({
531
+ driver,
532
+ tables: { entries: {
533
+ id: (0, _orkestrel_contract.stringShape)(),
534
+ input,
535
+ attempts: (0, _orkestrel_contract.integerShape)({ min: 0 })
536
+ } }
537
+ }).table("entries"));
538
+ }
539
+ /**
540
+ * Create an in-memory {@link MemoryQueueStore} — the zero-plumbing DEFAULT queue store
541
+ * over a plain `Map` (the twin of {@link DatabaseQueueStore}).
542
+ *
543
+ * @remarks
544
+ * The convenience for a non-persistent queue store (tests, ephemeral queues): the entries
545
+ * live in a process-lifetime `Map` and are gone when the process exits. UNLIKE
546
+ * {@link createDatabaseQueueStore}, no `databases` table / driver codec is built — a queue
547
+ * entry is already pure JSON, so the memory tier needs no encoding (AGENTS §21). The
548
+ * `input` shape is accepted for SOURCE-COMPATIBILITY with the driver-backed family (every
549
+ * call site passes its payload shape, and the store is still typed by it through `Infer`),
550
+ * but a plain-`Map` store does not validate the payload — durability + contract narrowing
551
+ * are {@link DatabaseQueueStore}'s job. For durability across restarts, build the store
552
+ * over a server JSON / SQLite driver via {@link createDatabaseQueueStore} (or the server
553
+ * `createJSONQueueStore`).
554
+ *
555
+ * @typeParam TInput - The contract shape of each entry's `input` payload
556
+ * @param _input - The {@link ContractShape} for the work payload — types the store (via
557
+ * `Infer`); the plain-`Map` backing does not use it at runtime, so it is `_`-prefixed
558
+ * (AGENTS unused-arg convention) while staying in the signature for source-compatibility
559
+ * with the driver-backed family
560
+ * @returns A memory-backed {@link QueueStoreInterface}, typed by `_input`
561
+ *
562
+ * @example
563
+ * ```ts
564
+ * import { createMemoryQueueStore, stringShape } from '@src/core'
565
+ *
566
+ * const store = createMemoryQueueStore(stringShape())
567
+ * await store.save({ id: 'job-1', input: 'task', attempts: 0 })
568
+ * ```
569
+ */
570
+ function createMemoryQueueStore(_input) {
571
+ return new MemoryQueueStore();
572
+ }
573
+ //#endregion
574
+ exports.DatabaseQueueStore = DatabaseQueueStore;
575
+ exports.MemoryQueueStore = MemoryQueueStore;
576
+ exports.Queue = Queue;
577
+ exports.createDatabaseQueueStore = createDatabaseQueueStore;
578
+ exports.createMemoryQueueStore = createMemoryQueueStore;
579
+ exports.createQueue = createQueue;
580
+
581
+ //# sourceMappingURL=index.cjs.map