@orkestrel/queue 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,50 +1,139 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_contract = require("@orkestrel/contract");
2
3
  let _orkestrel_abort = require("@orkestrel/abort");
3
4
  let _orkestrel_emitter = require("@orkestrel/emitter");
4
5
  let _orkestrel_timeout = require("@orkestrel/timeout");
5
- let _orkestrel_contract = require("@orkestrel/contract");
6
6
  let _orkestrel_database = require("@orkestrel/database");
7
+ //#region src/core/errors.ts
8
+ /**
9
+ * Error carrying a machine-readable queue category and optional context.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * new QueueError('duplicate id', { code: 'duplicate', context: { id: 'job-1' } })
14
+ * ```
15
+ */
16
+ var QueueError = class extends Error {
17
+ name = "QueueError";
18
+ code;
19
+ context;
20
+ /**
21
+ * Create a queue error.
22
+ *
23
+ * @param message - Human-readable failure description
24
+ * @param options - Machine-readable category, optional context, and optional cause
25
+ */
26
+ constructor(message, options) {
27
+ const cause = options.cause;
28
+ super(message, cause === void 0 ? void 0 : { cause });
29
+ this.code = options.code;
30
+ this.context = options.context === void 0 ? void 0 : Object.freeze({ ...options.context });
31
+ }
32
+ };
33
+ /**
34
+ * Determine whether an unknown value is a {@link QueueError}.
35
+ *
36
+ * @param value - The value to inspect
37
+ * @returns `true` only for a `QueueError`; hostile values return `false`
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * try {
42
+ * await queue.clear()
43
+ * } catch (error) {
44
+ * if (isQueueError(error) && error.code === 'cleanup') report(error.context)
45
+ * }
46
+ * ```
47
+ */
48
+ function isQueueError(value) {
49
+ try {
50
+ return value instanceof QueueError;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+ //#endregion
56
+ //#region src/core/validators.ts
57
+ /**
58
+ * Determine whether a value is a valid queue concurrency.
59
+ *
60
+ * @param value - Value to inspect
61
+ * @returns Whether the value is a positive safe integer
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * isQueueConcurrency(4) // true
66
+ * isQueueConcurrency(0) // false
67
+ * ```
68
+ */
69
+ function isQueueConcurrency(value) {
70
+ return (0, _orkestrel_contract.isInteger)(value) && Number.isSafeInteger(value) && value > 0;
71
+ }
72
+ /**
73
+ * Determine whether a value is a valid queue retry count.
74
+ *
75
+ * @param value - Value to inspect
76
+ * @returns Whether the value is a nonnegative safe integer
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * isQueueRetries(2) // true
81
+ * isQueueRetries(-1) // false
82
+ * ```
83
+ */
84
+ function isQueueRetries(value) {
85
+ return (0, _orkestrel_contract.isInteger)(value) && Number.isSafeInteger(value) && value >= 0;
86
+ }
87
+ /**
88
+ * Determine whether a value is a valid queue timeout.
89
+ *
90
+ * @param value - Value to inspect
91
+ * @returns Whether the value is within the native timer range, inclusive
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * isQueueTimeout(500) // true
96
+ * isQueueTimeout(2_147_483_648) // false
97
+ * ```
98
+ */
99
+ function isQueueTimeout(value) {
100
+ return (0, _orkestrel_contract.isFiniteNumber)(value) && value >= 0 && value <= 2147483647;
101
+ }
102
+ /**
103
+ * Determine whether a value is a native abort signal usable by the queue.
104
+ *
105
+ * @param value - Value to inspect
106
+ * @returns Whether the value carries the native `AbortSignal` internal slot
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * isQueueSignal(new AbortController().signal) // true
111
+ * isQueueSignal({}) // false
112
+ * ```
113
+ */
114
+ function isQueueSignal(value) {
115
+ try {
116
+ const getter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")?.get;
117
+ if (getter === void 0) return false;
118
+ Reflect.apply(getter, value, []);
119
+ return true;
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+ //#endregion
7
125
  //#region src/core/Queue.ts
8
126
  /**
9
- * A concurrent, cooperative job queue.
127
+ * A concurrent, cooperative FIFO job queue with optional outstanding-work persistence.
10
128
  *
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.
129
+ * @typeParam TInput - The work input each entry carries
130
+ * @typeParam TResult - The value each entry resolves
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * const queue = new Queue<number, number>({ handler: (input) => input * 2 })
135
+ * const result = await queue.enqueue(21)
136
+ * ```
48
137
  */
49
138
  var Queue = class {
50
139
  #handler;
@@ -54,35 +143,73 @@ var Queue = class {
54
143
  #store;
55
144
  #abort = (0, _orkestrel_abort.createAbort)();
56
145
  #emitter;
146
+ #entries = /* @__PURE__ */ new Map();
147
+ #live = /* @__PURE__ */ new Map();
57
148
  #pending = [];
58
- #live = /* @__PURE__ */ new Set();
149
+ #claims = /* @__PURE__ */ new Set();
59
150
  #wakes = [];
60
- #active = 0;
61
- #running = 0;
151
+ #workers = /* @__PURE__ */ new Set();
152
+ #admissions = /* @__PURE__ */ new Map();
153
+ #orphans = /* @__PURE__ */ new Set();
154
+ #cleanups = /* @__PURE__ */ new Map();
155
+ #admission = Promise.resolve();
156
+ #stopPromise;
157
+ #abortPromise;
158
+ #destroyPromise;
159
+ #generation = 0;
62
160
  #paused = false;
63
161
  #stopped = false;
64
162
  #aborted = false;
65
163
  #destroyed = false;
164
+ #drained = true;
165
+ /**
166
+ * Create a queue.
167
+ *
168
+ * @param options - Handler, validated execution limits, persistence, and observation hooks
169
+ */
66
170
  constructor(options) {
171
+ const concurrency = options.concurrency ?? 1;
172
+ const retries = options.retries ?? 0;
173
+ const timeout = options.timeout ?? 0;
174
+ if (!isQueueConcurrency(concurrency)) throw new QueueError("queue concurrency must be a positive safe integer", {
175
+ code: "invalid",
176
+ context: {
177
+ option: "concurrency",
178
+ value: concurrency
179
+ }
180
+ });
181
+ if (!isQueueRetries(retries)) throw new QueueError("queue retries must be a nonnegative safe integer", {
182
+ code: "invalid",
183
+ context: {
184
+ option: "retries",
185
+ value: retries
186
+ }
187
+ });
188
+ if (!isQueueTimeout(timeout)) throw new QueueError("queue timeout must be within the native timer range", {
189
+ code: "invalid",
190
+ context: {
191
+ option: "timeout",
192
+ value: timeout
193
+ }
194
+ });
67
195
  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);
196
+ this.#concurrency = concurrency;
197
+ this.#retries = retries;
198
+ this.#timeout = timeout;
71
199
  this.#store = options.store;
72
200
  this.#emitter = new _orkestrel_emitter.Emitter({
73
- on: options?.on,
74
- error: options?.error
201
+ ...options.on === void 0 ? {} : { on: options.on },
202
+ ...options.error === void 0 ? {} : { error: options.error }
75
203
  });
76
- this.#spawn();
77
204
  }
78
205
  get emitter() {
79
206
  return this.#emitter;
80
207
  }
81
208
  get count() {
82
- return this.#pending.length + this.#active;
209
+ return this.#live.size;
83
210
  }
84
211
  get active() {
85
- return this.#active;
212
+ return this.#claims.size;
86
213
  }
87
214
  get paused() {
88
215
  return this.#paused;
@@ -90,124 +217,348 @@ var Queue = class {
90
217
  get stopped() {
91
218
  return this.#stopped || this.#aborted;
92
219
  }
220
+ /**
221
+ * Reserve and submit one FIFO entry.
222
+ *
223
+ * @param input - Handler input
224
+ * @param options - Optional id, retry/timeout overrides, and entry abort signal
225
+ * @returns The entry's settle-once execution promise
226
+ * @throws {QueueError} Synchronously when an option is inaccessible or invalid
227
+ */
93
228
  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
229
+ let supplied;
230
+ try {
231
+ supplied = options?.id;
232
+ } catch (error) {
233
+ throw new QueueError("queue entry id could not be read", {
234
+ code: "invalid",
235
+ cause: error,
236
+ context: { option: "id" }
108
237
  });
109
- this.#emitter.emit("enqueue", id);
110
- this.#wake();
238
+ }
239
+ if (supplied !== void 0 && !(0, _orkestrel_contract.isString)(supplied)) throw new QueueError("queue entry id must be a string", {
240
+ code: "invalid",
241
+ context: {
242
+ option: "id",
243
+ value: supplied
244
+ }
245
+ });
246
+ let retries;
247
+ try {
248
+ retries = options?.retries;
249
+ } catch (error) {
250
+ throw new QueueError("queue retries could not be read", {
251
+ code: "invalid",
252
+ cause: error,
253
+ context: { option: "retries" }
254
+ });
255
+ }
256
+ if (retries !== void 0 && !isQueueRetries(retries)) throw new QueueError("queue retries must be a nonnegative safe integer", {
257
+ code: "invalid",
258
+ context: {
259
+ option: "retries",
260
+ value: retries
261
+ }
262
+ });
263
+ let timeout;
264
+ try {
265
+ timeout = options?.timeout;
266
+ } catch (error) {
267
+ throw new QueueError("queue timeout could not be read", {
268
+ code: "invalid",
269
+ cause: error,
270
+ context: { option: "timeout" }
271
+ });
272
+ }
273
+ if (timeout !== void 0 && !isQueueTimeout(timeout)) throw new QueueError("queue timeout must be within the native timer range", {
274
+ code: "invalid",
275
+ context: {
276
+ option: "timeout",
277
+ value: timeout
278
+ }
279
+ });
280
+ let signal;
281
+ try {
282
+ signal = options?.signal;
283
+ } catch (error) {
284
+ throw new QueueError("queue signal could not be read", {
285
+ code: "invalid",
286
+ cause: error,
287
+ context: { option: "signal" }
288
+ });
289
+ }
290
+ if (signal !== void 0 && !isQueueSignal(signal)) throw new QueueError("queue signal must be an AbortSignal", {
291
+ code: "invalid",
292
+ context: {
293
+ option: "signal",
294
+ value: signal
295
+ }
296
+ });
297
+ const normalized = options === void 0 ? void 0 : Object.freeze({
298
+ ...supplied === void 0 ? {} : { id: supplied },
299
+ ...retries === void 0 ? {} : { retries },
300
+ ...timeout === void 0 ? {} : { timeout },
301
+ ...signal === void 0 ? {} : { signal }
111
302
  });
303
+ if (this.#destroyed) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
304
+ if (this.#aborted) return Promise.reject(new QueueError("queue is aborted", { code: "aborted" }));
305
+ if (this.#stopped) return Promise.reject(new QueueError("queue is stopped", { code: "stopped" }));
306
+ const id = supplied ?? crypto.randomUUID();
307
+ if (this.#live.has(id)) return Promise.reject(new QueueError("queue entry id is already live", {
308
+ code: "duplicate",
309
+ context: { id }
310
+ }));
311
+ const token = this.#reserve(id, input, normalized, 0);
312
+ if (this.#store === void 0) this.#accept(token);
313
+ else this.#schedule(token);
314
+ return token.promise;
112
315
  }
316
+ /** Load and accept every outstanding stored entry from the current lifecycle generation. */
113
317
  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
318
+ if (this.#store === void 0 || this.stopped || this.#destroyed) return;
319
+ const generation = this.#generation;
320
+ let entries;
321
+ try {
322
+ const loaded = await this.#store.load();
323
+ const snapshots = [];
324
+ for (const stored of loaded) {
325
+ const id = stored.id;
326
+ const input = stored.input;
327
+ const attempts = stored.attempts;
328
+ if (!(0, _orkestrel_contract.isString)(id) || !isQueueRetries(attempts)) throw new QueueError("queue store returned an invalid entry", {
329
+ code: "store",
330
+ context: { operation: "load" }
128
331
  });
129
- this.#emitter.emit("enqueue", entry.id);
130
- this.#wake();
131
- }).catch(() => {});
332
+ snapshots.push(Object.freeze({
333
+ id,
334
+ input,
335
+ attempts
336
+ }));
337
+ }
338
+ entries = snapshots;
339
+ } catch (error) {
340
+ throw new QueueError("queue store load failed", {
341
+ code: "store",
342
+ cause: error,
343
+ context: { operation: "load" }
344
+ });
345
+ }
346
+ if (generation !== this.#generation || this.stopped || this.#destroyed) return;
347
+ for (const stored of entries) {
348
+ if (generation !== this.#generation || this.stopped || this.#destroyed) return;
349
+ if (this.#live.has(stored.id)) continue;
350
+ const token = this.#reserve(stored.id, stored.input, void 0, stored.attempts);
351
+ this.#accept(token);
352
+ token.promise.catch(() => {});
132
353
  }
133
354
  }
355
+ /** Begin or restart worker execution unless the queue is terminal. */
134
356
  start() {
135
357
  if (this.#aborted || this.#destroyed) return;
136
358
  this.#stopped = false;
359
+ this.#stopPromise = void 0;
137
360
  this.#spawn();
138
361
  }
362
+ /** Reject non-active work and await current-loop and durable cleanup quiescence. */
139
363
  stop() {
140
- if (this.#stopped) return;
364
+ if (this.#destroyPromise !== void 0) return this.#destroyPromise;
365
+ if (this.#abortPromise !== void 0) return this.#abortPromise;
366
+ if (this.#stopped && this.#stopPromise !== void 0) return this.#stopPromise;
367
+ const barrier = Promise.withResolvers();
368
+ this.#stopPromise = barrier.promise;
141
369
  this.#stopped = true;
142
- this.#drain(/* @__PURE__ */ new Error("queue is stopped"));
370
+ this.#generation += 1;
371
+ const existing = [...this.#cleanups.values()];
372
+ const cleanup = [...this.#drain(new QueueError("queue is stopped", { code: "stopped" })), ...this.#cleanOrphans(true)];
373
+ const tasks = [
374
+ ...this.#workers,
375
+ ...this.#admissions.values(),
376
+ ...existing,
377
+ ...cleanup
378
+ ];
143
379
  this.#wakeAll();
380
+ this.#settleBarrier(barrier, tasks, "queue stop cleanup failed");
381
+ return barrier.promise;
144
382
  }
383
+ /** Suspend new execution while leaving active entries untouched. */
145
384
  pause() {
146
385
  if (this.#paused || this.stopped || this.#destroyed) return;
147
386
  this.#paused = true;
148
387
  }
388
+ /** Continue execution after a pause. */
149
389
  resume() {
150
390
  if (!this.#paused || this.stopped || this.#destroyed) return;
151
391
  this.#paused = false;
152
392
  this.#wakeAll();
153
393
  }
394
+ /**
395
+ * Cancel the queue and await owned cleanup.
396
+ *
397
+ * @param reason - Optional cause carried by the coded abort error
398
+ * @returns The stable abort barrier
399
+ */
154
400
  abort(reason) {
155
- if (this.#aborted) return;
401
+ if (this.#abortPromise !== void 0) return this.#abortPromise;
402
+ const barrier = Promise.withResolvers();
403
+ this.#abortPromise = barrier.promise;
156
404
  this.#aborted = true;
157
- this.#abort.abort(reason);
158
- this.#drain(this.#abort.signal.reason);
405
+ this.#stopped = true;
406
+ this.#generation += 1;
407
+ const error = new QueueError(reason instanceof Error ? reason.message : "queue is aborted", {
408
+ code: "aborted",
409
+ ...reason === void 0 ? {} : { cause: reason }
410
+ });
411
+ this.#abort.abort(error);
412
+ const existing = [...this.#cleanups.values()];
413
+ const cleanup = [...this.#drain(error), ...this.#cleanOrphans(true)];
414
+ const tasks = [
415
+ ...this.#workers,
416
+ ...this.#admissions.values(),
417
+ ...existing,
418
+ ...cleanup
419
+ ];
159
420
  this.#wakeAll();
160
- this.#emitter.emit("abort", this.#abort.signal.reason);
421
+ this.#emitter.emit("abort", error);
422
+ this.#settleBarrier(barrier, tasks, "queue abort cleanup failed");
423
+ return barrier.promise;
161
424
  }
425
+ /** Reject non-active work and await its durable cleanup. */
162
426
  clear() {
163
- this.#drain(/* @__PURE__ */ new Error("queue cleared"));
427
+ if (this.#destroyed) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
428
+ const existing = [];
429
+ for (const [token, cleanup] of this.#cleanups) if (!this.#claims.has(token)) existing.push(cleanup);
430
+ const cleanup = [...this.#drain(new QueueError("queue is cleared", { code: "cleared" })), ...this.#cleanOrphans(false)];
431
+ return this.#finish([
432
+ ...this.#admissions.values(),
433
+ ...existing,
434
+ ...cleanup
435
+ ], "queue clear cleanup failed");
164
436
  }
437
+ /** Tear down once, destroying the emitter only after cleanup finishes. */
165
438
  destroy() {
166
- if (this.#destroyed) return;
439
+ if (this.#destroyPromise !== void 0) return this.#destroyPromise;
440
+ const barrier = Promise.withResolvers();
441
+ this.#destroyPromise = barrier.promise;
167
442
  this.#destroyed = true;
168
- this.abort();
169
- this.#stopped = true;
170
- this.#wakeAll();
443
+ const aborting = this.abort(new QueueError("queue is destroyed", { code: "destroyed" }));
444
+ this.#settleDestroy(barrier, aborting);
445
+ return barrier.promise;
446
+ }
447
+ #reserve(id, input, options, attempts) {
448
+ const token = Promise.withResolvers();
449
+ this.#entries.set(token, {
450
+ id,
451
+ input,
452
+ options,
453
+ attempts,
454
+ settled: false
455
+ });
456
+ this.#live.set(id, token);
457
+ this.#drained = false;
458
+ return token;
459
+ }
460
+ #schedule(token) {
461
+ const task = this.#admission.then(() => this.#admit(token));
462
+ this.#admissions.set(token, task);
463
+ this.#admission = task.catch(() => {});
464
+ task.finally(() => this.#admissions.delete(token)).catch(() => {});
465
+ }
466
+ async #admit(token) {
467
+ const entry = this.#entries.get(token);
468
+ if (entry === void 0 || this.#store === void 0) return;
469
+ try {
470
+ await this.#store.save({
471
+ id: entry.id,
472
+ input: entry.input,
473
+ attempts: entry.attempts
474
+ });
475
+ } catch (error) {
476
+ try {
477
+ await this.#cleanup(token);
478
+ } catch (cleanup) {
479
+ this.#settleToken(token, {
480
+ success: false,
481
+ error: cleanup
482
+ });
483
+ this.#emitDrain();
484
+ throw cleanup;
485
+ }
486
+ this.#settleToken(token, {
487
+ success: false,
488
+ error: new QueueError(error instanceof Error ? error.message : "queue admission save failed", {
489
+ code: "store",
490
+ cause: error,
491
+ context: {
492
+ id: entry.id,
493
+ operation: "save"
494
+ }
495
+ })
496
+ });
497
+ this.#emitDrain();
498
+ return;
499
+ }
500
+ if (entry.settled || this.#aborted || this.#destroyed || this.#stopped) {
501
+ await this.#discard(token);
502
+ return;
503
+ }
504
+ this.#accept(token);
505
+ }
506
+ #accept(token) {
507
+ const entry = this.#entries.get(token);
508
+ if (entry === void 0) return;
509
+ this.#pending.push(token);
510
+ this.#emitter.emit("enqueue", entry.id);
511
+ this.#spawn();
512
+ this.#wake();
171
513
  }
172
514
  #spawn() {
173
515
  if (this.#stopped || this.#aborted || this.#destroyed) return;
174
- while (this.#running < this.#concurrency) {
175
- this.#running += 1;
176
- this.#worker();
516
+ const demand = Math.min(this.#concurrency, this.#claims.size + this.#pending.length);
517
+ while (this.#workers.size < demand) {
518
+ const generation = this.#generation;
519
+ const worker = this.#worker(generation);
520
+ this.#workers.add(worker);
521
+ worker.finally(() => {
522
+ this.#workers.delete(worker);
523
+ this.#spawn();
524
+ }).catch(() => {});
177
525
  }
178
526
  }
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
- }
527
+ async #worker(generation) {
528
+ while (generation === this.#generation) {
529
+ const token = await this.#next(generation);
530
+ if (token === void 0) return;
531
+ try {
532
+ await this.#run(token);
533
+ } catch (error) {
534
+ await this.#fail(token, error);
535
+ throw error;
191
536
  }
192
- } finally {
193
- this.#running -= 1;
194
537
  }
195
538
  }
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
- });
539
+ #next(generation) {
540
+ return new Promise((resolve) => this.#take(generation, resolve));
541
+ }
542
+ #take(generation, resolve) {
543
+ if (generation !== this.#generation || this.#stopped || this.#aborted || this.#destroyed) {
544
+ resolve(void 0);
545
+ return;
546
+ }
547
+ if (this.#paused || this.#pending.length === 0) {
548
+ this.#wakes.push(() => this.#take(generation, resolve));
549
+ return;
550
+ }
551
+ const token = this.#pending.shift();
552
+ if (token === void 0) {
553
+ this.#wakes.push(() => this.#take(generation, resolve));
554
+ return;
555
+ }
556
+ if (this.#entries.get(token) === void 0) {
557
+ this.#take(generation, resolve);
558
+ return;
559
+ }
560
+ this.#claims.add(token);
561
+ resolve(token);
211
562
  }
212
563
  #wake() {
213
564
  const resolver = this.#wakes.shift();
@@ -218,107 +569,186 @@ var Queue = class {
218
569
  for (const resolver of resolvers) resolver();
219
570
  }
220
571
  #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);
572
+ for (const token of this.#admissions.keys()) this.#settleToken(token, {
573
+ success: false,
574
+ error
575
+ });
576
+ const tokens = this.#pending.splice(0);
577
+ const cleanup = [];
578
+ for (const token of tokens) {
579
+ this.#settleToken(token, {
580
+ success: false,
581
+ error
582
+ });
583
+ cleanup.push(this.#discard(token));
227
584
  }
585
+ return cleanup;
228
586
  }
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");
587
+ #cleanOrphans(claimed) {
588
+ const cleanup = [];
589
+ for (const token of this.#orphans) if (claimed || !this.#claims.has(token)) cleanup.push(this.#discard(token));
590
+ return cleanup;
591
+ }
592
+ async #discard(token) {
593
+ try {
594
+ await this.#cleanup(token);
595
+ } finally {
596
+ this.#emitDrain();
238
597
  }
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
598
+ }
599
+ #cleanup(token) {
600
+ const current = this.#cleanups.get(token);
601
+ if (current !== void 0) return current;
602
+ const barrier = Promise.withResolvers();
603
+ this.#cleanups.set(token, barrier.promise);
604
+ this.#clean(token, barrier);
605
+ return barrier.promise;
606
+ }
607
+ async #clean(token, barrier) {
608
+ const entry = this.#entries.get(token);
609
+ if (entry === void 0) {
610
+ barrier.resolve();
611
+ this.#cleanups.delete(token);
612
+ return;
613
+ }
614
+ try {
615
+ if (this.#store !== void 0) await this.#store.remove(entry.id);
616
+ this.#release(token);
617
+ barrier.resolve();
618
+ } catch (error) {
619
+ if (this.#live.get(entry.id) === token) this.#orphans.add(token);
620
+ barrier.reject(new QueueError("queue entry cleanup failed", {
621
+ code: "cleanup",
622
+ cause: error,
623
+ context: {
624
+ id: entry.id,
625
+ operation: "remove"
626
+ }
627
+ }));
628
+ } finally {
629
+ if (this.#cleanups.get(token) === barrier.promise) this.#cleanups.delete(token);
630
+ }
631
+ }
632
+ #release(token) {
633
+ const entry = this.#entries.get(token);
634
+ if (entry === void 0 || this.#live.get(entry.id) !== token) return;
635
+ this.#live.delete(entry.id);
636
+ this.#orphans.delete(token);
637
+ if (entry.settled) this.#entries.delete(token);
638
+ }
639
+ async #run(token) {
640
+ const entry = this.#entries.get(token);
641
+ if (entry === void 0) return;
642
+ const retries = entry.options?.retries ?? this.#retries;
643
+ const timeout = entry.options?.timeout ?? this.#timeout;
644
+ const signal = entry.options?.signal;
645
+ let completed = entry.attempts;
646
+ this.#emitter.emit("start", entry.id);
647
+ while (true) {
648
+ if (await this.#interrupt(token, signal)) return;
649
+ const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
650
+ completed += 1;
651
+ if (outcome.success) {
652
+ await this.#settle(token, outcome);
653
+ return;
654
+ }
655
+ if (await this.#interrupt(token, signal)) return;
656
+ if (completed > retries) {
657
+ await this.#settle(token, outcome);
658
+ return;
659
+ }
660
+ await this.#saveAttempt(token, completed);
661
+ this.#emitter.emit("retry", entry.id, completed);
662
+ }
663
+ }
664
+ async #interrupt(token, signal) {
665
+ const entry = this.#entries.get(token);
666
+ if (entry === void 0) return true;
667
+ if (this.#abort.aborted) {
668
+ await this.#settle(token, {
669
+ success: false,
670
+ error: this.#abort.signal.reason
248
671
  });
249
- this.#emitter.emit("enqueue", id);
250
- this.#wake();
672
+ return true;
673
+ }
674
+ if (!signal?.aborted) return false;
675
+ await this.#settle(token, {
676
+ success: false,
677
+ error: new QueueError(signal.reason instanceof Error ? signal.reason.message : "queue entry is aborted", {
678
+ code: "aborted",
679
+ cause: signal.reason,
680
+ context: { id: entry.id }
681
+ })
251
682
  });
683
+ return true;
252
684
  }
253
- async #saveAttempt(entry, attempts) {
685
+ async #saveAttempt(token, attempts) {
686
+ const entry = this.#entries.get(token);
687
+ if (this.#store === void 0 || entry === void 0) return;
254
688
  try {
255
- await this.#store?.save({
689
+ await this.#store.save({
256
690
  id: entry.id,
257
691
  input: entry.input,
258
692
  attempts
259
693
  });
260
694
  } catch {}
261
695
  }
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, {
696
+ async #fail(token, error) {
697
+ if (!this.#claims.has(token)) return;
698
+ try {
699
+ await this.#cleanup(token);
700
+ } catch (cleanup) {
701
+ this.#finishEntry(token, {
290
702
  success: false,
291
- error: signal.reason
703
+ error: cleanup
292
704
  });
293
- if (attempt < retries) continue;
294
- return this.#settle(entry, {
705
+ throw cleanup;
706
+ }
707
+ this.#finishEntry(token, {
708
+ success: false,
709
+ error
710
+ });
711
+ }
712
+ async #settle(token, outcome) {
713
+ try {
714
+ await this.#cleanup(token);
715
+ } catch (error) {
716
+ this.#finishEntry(token, {
295
717
  success: false,
296
- error: outcome.error
718
+ error
297
719
  });
720
+ throw error;
298
721
  }
722
+ this.#finishEntry(token, outcome);
299
723
  }
300
- #settle(entry, outcome) {
301
- this.#live.delete(entry.id);
302
- if (this.#store === void 0) {
303
- this.#commit(entry, outcome);
724
+ #finishEntry(token, outcome) {
725
+ if (!this.#claims.delete(token)) return;
726
+ const entry = this.#entries.get(token);
727
+ const drain = this.#latchDrain();
728
+ if (entry === void 0 || !this.#settleToken(token, outcome)) {
729
+ if (drain) this.#emitter.emit("drain");
304
730
  return;
305
731
  }
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
- }
732
+ if (outcome.success) this.#emitter.emit("success", entry.id, outcome.value);
733
+ else this.#emitter.emit("failure", entry.id, outcome.error);
734
+ if (drain) this.#emitter.emit("drain");
316
735
  }
317
- async #forget(store, entry, outcome) {
318
- try {
319
- await store.remove(entry.id);
320
- } catch {}
321
- this.#commit(entry, outcome);
736
+ #settleToken(token, outcome) {
737
+ const entry = this.#entries.get(token);
738
+ if (entry === void 0 || entry.settled) return false;
739
+ entry.settled = true;
740
+ if (outcome.success) token.resolve(outcome.value);
741
+ else token.reject(outcome.error);
742
+ if (this.#live.get(entry.id) !== token) this.#entries.delete(token);
743
+ return true;
744
+ }
745
+ #latchDrain() {
746
+ if (this.#drained || this.#claims.size !== 0 || this.#live.size !== 0) return false;
747
+ this.#drained = true;
748
+ return true;
749
+ }
750
+ #emitDrain() {
751
+ if (this.#latchDrain()) this.#emitter.emit("drain");
322
752
  }
323
753
  async #attempt(id, input, timeout, signal) {
324
754
  const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
@@ -340,31 +770,92 @@ var Queue = class {
340
770
  } catch (error) {
341
771
  return {
342
772
  success: false,
343
- error: error instanceof Error ? error : new Error(String(error), { cause: error })
773
+ error: error instanceof Error ? error : new Error((0, _orkestrel_contract.preview)(error), { cause: error })
344
774
  };
345
775
  } finally {
346
776
  deadline?.clear();
347
777
  }
348
778
  }
349
779
  #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());
780
+ if (signal.aborted) return Promise.reject(new QueueError(deadline?.expired === true ? "queue attempt timed out" : "queue attempt aborted", {
781
+ code: deadline?.expired === true ? "timeout" : "aborted",
782
+ cause: signal.reason,
783
+ context: { id }
784
+ }));
785
+ const cleanup = new AbortController();
352
786
  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);
787
+ signal.addEventListener("abort", () => reject(new QueueError(deadline?.expired === true ? "queue attempt timed out" : "queue attempt aborted", {
788
+ code: deadline?.expired === true ? "timeout" : "aborted",
789
+ cause: signal.reason,
790
+ context: { id }
791
+ })), {
792
+ once: true,
793
+ signal: cleanup.signal
365
794
  });
795
+ try {
796
+ Promise.resolve(this.#handler(input, {
797
+ id,
798
+ signal
799
+ })).then((value) => {
800
+ cleanup.abort();
801
+ resolve(value);
802
+ }, (error) => {
803
+ cleanup.abort();
804
+ reject(error);
805
+ });
806
+ } catch (error) {
807
+ cleanup.abort();
808
+ reject(error);
809
+ }
810
+ });
811
+ }
812
+ async #finish(tasks, message) {
813
+ const results = await Promise.allSettled(tasks);
814
+ const errors = [];
815
+ for (const result of results) if (result.status === "rejected" && !errors.includes(result.reason)) errors.push(result.reason);
816
+ if (errors.length === 0) return;
817
+ const error = errors[0];
818
+ if (errors.length === 1 && isQueueError(error)) throw error;
819
+ throw new QueueError(message, {
820
+ code: "cleanup",
821
+ cause: new AggregateError(errors, message),
822
+ context: { operation: "remove" }
366
823
  });
367
824
  }
825
+ async #settleBarrier(barrier, tasks, message) {
826
+ try {
827
+ await this.#finish(tasks, message);
828
+ barrier.resolve();
829
+ } catch (error) {
830
+ barrier.reject(error);
831
+ }
832
+ }
833
+ async #settleDestroy(barrier, aborting) {
834
+ let failure;
835
+ try {
836
+ await aborting;
837
+ } catch (error) {
838
+ failure = error;
839
+ }
840
+ try {
841
+ await this.#finish([
842
+ ...this.#workers,
843
+ ...this.#admissions.values(),
844
+ ...this.#cleanups.values(),
845
+ ...this.#cleanOrphans(true)
846
+ ], "queue destroy cleanup failed");
847
+ } catch (error) {
848
+ failure = failure === void 0 ? error : new QueueError("queue destroy cleanup failed", {
849
+ code: "cleanup",
850
+ cause: new AggregateError([failure, error], "queue destroy cleanup failed"),
851
+ context: { operation: "remove" }
852
+ });
853
+ } finally {
854
+ this.#emitter.destroy();
855
+ }
856
+ if (failure === void 0) barrier.resolve();
857
+ else barrier.reject(failure);
858
+ }
368
859
  };
369
860
  //#endregion
370
861
  //#region src/core/stores/DatabaseQueueStore.ts
@@ -388,9 +879,11 @@ var Queue = class {
388
879
  *
389
880
  * @example
390
881
  * ```ts
391
- * import { createMemoryQueueStore, stringShape } from '@src/core'
882
+ * import { stringShape } from '@orkestrel/contract'
883
+ * import { createMemoryDriver } from '@orkestrel/database'
884
+ * import { createDatabaseQueueStore } from '@orkestrel/queue'
392
885
  *
393
- * const store = createMemoryQueueStore(stringShape())
886
+ * const store = createDatabaseQueueStore(stringShape(), createMemoryDriver())
394
887
  * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
395
888
  * const outstanding = await store.load() // readonly StoredEntry<string>[]
396
889
  * ```
@@ -426,66 +919,94 @@ var DatabaseQueueStore = class {
426
919
  //#endregion
427
920
  //#region src/core/stores/MemoryQueueStore.ts
428
921
  /**
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).
922
+ * An in-memory store owning validated, immutable JSON snapshots of outstanding entries.
442
923
  *
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
924
+ * @typeParam TInput - The contract shape for each stored input
457
925
  *
458
926
  * @example
459
927
  * ```ts
460
- * import { createMemoryQueueStore, stringShape } from '@src/core'
928
+ * import { stringShape } from '@orkestrel/contract'
929
+ * import { MemoryQueueStore } from '@orkestrel/queue'
461
930
  *
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
931
+ * const store = new MemoryQueueStore(stringShape())
932
+ * await store.save({ id: 'job-1', input: 'task', attempts: 0 })
466
933
  * ```
467
934
  */
468
935
  var MemoryQueueStore = class {
936
+ #contract;
469
937
  #entries = /* @__PURE__ */ new Map();
470
- /** Upsert an entry under its OWN `id` (a re-`save` of an existing `id` overwrites it). */
938
+ /**
939
+ * Create an in-memory queue store.
940
+ *
941
+ * @param input - Runtime contract for each stored input
942
+ */
943
+ constructor(input) {
944
+ this.#contract = (0, _orkestrel_contract.createContract)(input);
945
+ }
946
+ /** Upsert a validated, owned snapshot under the entry's id. */
471
947
  save(entry) {
472
- this.#entries.set(entry.id, entry);
473
- return Promise.resolve();
948
+ try {
949
+ const id = entry.id;
950
+ const input = entry.input;
951
+ const attempts = entry.attempts;
952
+ if (!(0, _orkestrel_contract.isString)(id) || !isQueueRetries(attempts)) throw new QueueError("queue store entry is invalid", {
953
+ code: "store",
954
+ context: { operation: "save" }
955
+ });
956
+ this.#entries.set(id, this.#snapshot(id, input, attempts, "save"));
957
+ return Promise.resolve();
958
+ } catch (error) {
959
+ return Promise.reject(new QueueError("queue store save failed", {
960
+ code: "store",
961
+ cause: error,
962
+ context: { operation: "save" }
963
+ }));
964
+ }
474
965
  }
475
- /** Drop a finished entry by `id`; `Map.delete` of an absent id is already a no-op (no throw). */
966
+ /** Remove an entry; an absent id is a no-op. */
476
967
  remove(id) {
477
968
  this.#entries.delete(id);
478
969
  return Promise.resolve();
479
970
  }
480
- /** Every outstanding entry — the work to resume (the `Map`'s values, insertion order). */
971
+ /** Return fresh immutable snapshots of every outstanding entry. */
481
972
  load() {
482
- return Promise.resolve([...this.#entries.values()]);
973
+ try {
974
+ const snapshots = [];
975
+ for (const entry of this.#entries.values()) {
976
+ const id = entry.id;
977
+ const input = entry.input;
978
+ const attempts = entry.attempts;
979
+ snapshots.push(this.#snapshot(id, input, attempts, "load"));
980
+ }
981
+ return Promise.resolve(snapshots);
982
+ } catch (error) {
983
+ return Promise.reject(new QueueError("queue store load failed", {
984
+ code: "store",
985
+ cause: error,
986
+ context: { operation: "load" }
987
+ }));
988
+ }
483
989
  }
484
- /** Empty the store — drop every outstanding entry. */
990
+ /** Remove every outstanding entry. */
485
991
  clear() {
486
992
  this.#entries.clear();
487
993
  return Promise.resolve();
488
994
  }
995
+ #snapshot(id, input, attempts, operation) {
996
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)(input);
997
+ if (!this.#contract.is(snapshot)) throw new QueueError("queue store input does not satisfy its contract", {
998
+ code: "store",
999
+ context: {
1000
+ id,
1001
+ operation
1002
+ }
1003
+ });
1004
+ return Object.freeze({
1005
+ id,
1006
+ input: snapshot,
1007
+ attempts
1008
+ });
1009
+ }
489
1010
  };
490
1011
  //#endregion
491
1012
  //#region src/core/factories.ts
@@ -511,7 +1032,7 @@ var MemoryQueueStore = class {
511
1032
  *
512
1033
  * @example
513
1034
  * ```ts
514
- * import { createQueue } from '@src/core'
1035
+ * import { createQueue } from '@orkestrel/queue'
515
1036
  *
516
1037
  * const queue = createQueue<string, number>({
517
1038
  * handler: async (url, { signal }) => (await fetch(url, { signal })).status,
@@ -527,13 +1048,17 @@ function createQueue(options) {
527
1048
  return new Queue(options);
528
1049
  }
529
1050
  function createDatabaseQueueStore(input, driver) {
1051
+ const columns = {
1052
+ id: (0, _orkestrel_contract.stringShape)(),
1053
+ input,
1054
+ attempts: (0, _orkestrel_contract.integerShape)({
1055
+ min: 0,
1056
+ max: Number.MAX_SAFE_INTEGER
1057
+ })
1058
+ };
530
1059
  return new DatabaseQueueStore((0, _orkestrel_database.createDatabase)({
531
1060
  driver,
532
- tables: { entries: {
533
- id: (0, _orkestrel_contract.stringShape)(),
534
- input,
535
- attempts: (0, _orkestrel_contract.integerShape)({ min: 0 })
536
- } }
1061
+ tables: { entries: columns }
537
1062
  }).table("entries"));
538
1063
  }
539
1064
  /**
@@ -541,41 +1066,41 @@ function createDatabaseQueueStore(input, driver) {
541
1066
  * over a plain `Map` (the twin of {@link DatabaseQueueStore}).
542
1067
  *
543
1068
  * @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`).
1069
+ * The entries live in a process-lifetime `Map` and are gone when the process exits. The
1070
+ * supplied shape is compiled and enforced for every save. Exact JSON inputs are cloned
1071
+ * into deeply frozen owned snapshots, and each load returns fresh snapshots, so neither
1072
+ * caller mutation nor a returned object can alias stored state. For durability across
1073
+ * restarts, build the store over a persistent driver with
1074
+ * {@link createDatabaseQueueStore}.
554
1075
  *
555
1076
  * @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`
1077
+ * @param input - The runtime {@link ContractShape} for the work payload
1078
+ * @returns A validated memory-backed {@link QueueStoreInterface}, typed by `input`
561
1079
  *
562
1080
  * @example
563
1081
  * ```ts
564
- * import { createMemoryQueueStore, stringShape } from '@src/core'
1082
+ * import { stringShape } from '@orkestrel/contract'
1083
+ * import { createMemoryQueueStore } from '@orkestrel/queue'
565
1084
  *
566
1085
  * const store = createMemoryQueueStore(stringShape())
567
1086
  * await store.save({ id: 'job-1', input: 'task', attempts: 0 })
568
1087
  * ```
569
1088
  */
570
- function createMemoryQueueStore(_input) {
571
- return new MemoryQueueStore();
1089
+ function createMemoryQueueStore(input) {
1090
+ return new MemoryQueueStore(input);
572
1091
  }
573
1092
  //#endregion
574
1093
  exports.DatabaseQueueStore = DatabaseQueueStore;
575
1094
  exports.MemoryQueueStore = MemoryQueueStore;
576
1095
  exports.Queue = Queue;
1096
+ exports.QueueError = QueueError;
577
1097
  exports.createDatabaseQueueStore = createDatabaseQueueStore;
578
1098
  exports.createMemoryQueueStore = createMemoryQueueStore;
579
1099
  exports.createQueue = createQueue;
1100
+ exports.isQueueConcurrency = isQueueConcurrency;
1101
+ exports.isQueueError = isQueueError;
1102
+ exports.isQueueRetries = isQueueRetries;
1103
+ exports.isQueueSignal = isQueueSignal;
1104
+ exports.isQueueTimeout = isQueueTimeout;
580
1105
 
581
1106
  //# sourceMappingURL=index.cjs.map