@orkestrel/queue 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.
@@ -1,69 +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/helpers.ts
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
+ }
8
72
  /**
9
- * Create the queue failure for an aborted or expired attempt.
73
+ * Determine whether a value is a valid queue retry count.
10
74
  *
11
- * @param expired - Whether the attempt deadline expired
12
- * @returns The queue's documented attempt failure
75
+ * @param value - Value to inspect
76
+ * @returns Whether the value is a nonnegative safe integer
13
77
  *
14
78
  * @example
15
79
  * ```ts
16
- * import { createAttemptError } from '@src/core'
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.
17
104
  *
18
- * createAttemptError(false).message // 'attempt aborted'
19
- * createAttemptError(true).message // 'attempt timed out'
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
20
112
  * ```
21
113
  */
22
- function createAttemptError(expired) {
23
- return /* @__PURE__ */ new Error(expired ? "attempt timed out" : "attempt aborted");
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
+ }
24
123
  }
25
124
  //#endregion
26
125
  //#region src/core/Queue.ts
27
126
  /**
28
- * A concurrent, cooperative job queue.
127
+ * A concurrent, cooperative FIFO job queue with optional outstanding-work persistence.
29
128
  *
30
- * @remarks
31
- * - **Cooperative wake-park loop.** Up to `concurrency` worker loops run; each
32
- * takes the next pending entry, or — when none is ready (empty or paused) —
33
- * PARKS by awaiting a fresh promise whose resolver is held in a wake list.
34
- * `enqueue` / `resume` resolve one parked resolver to wake exactly one worker,
35
- * so idle workers consume no CPU (no busy-poll, no timers, no recursion).
36
- * - **FIFO + bounded concurrency.** Entries run in enqueue order; at most
37
- * `concurrency` are in flight at once (default `1` = strictly ordered). A surplus
38
- * entry waits for a worker to free up.
39
- * - **Per-attempt deadline + cancellation.** Each attempt's `signal` (handed to the
40
- * handler) fires on the per-attempt `Timeout` expiring, a queue-level `abort`, or
41
- * the entry's own `signal`. The handler is RACED against that signal, so an attempt
42
- * that ignores its `signal` still fails on the deadline. Built on the L1 `Abort` /
43
- * `Timeout` primitives (a queue / entry abort CLEARS the deadline, never expires it).
44
- * - **Retries.** A failed attempt (a handler rejection or a per-attempt timeout)
45
- * retries while attempts remain (`retries` + 1 total). A queue-level abort NEVER
46
- * retries — it rejects the entry at once; an entry-`signal` abort likewise.
47
- * - **Lifecycle (§10).** `pause` parks workers; `resume` wakes them; `stop` ends the
48
- * loops permanently and rejects pending (in-flight settle); `abort` fires the queue
49
- * signal (cancelling in-flight attempts) and rejects pending; `clear` drops only
50
- * pending; `destroy` aborts then stops, idempotently.
51
- * - **Durability (optional `store`).** The store mirrors only OUTSTANDING work: an
52
- * entry is `save`d on accept (and re-`save`d as its attempt count climbs) and
53
- * `remove`d the moment it settles (success or terminal failure) or is drained by a
54
- * lifecycle call. Accepting work durably is NOT best-effort — a failed initial `save`
55
- * rejects the enqueue; per-attempt persistence IS best-effort (in-memory state is
56
- * authoritative). A graceful shutdown empties the store; a crash leaves rows that
57
- * `restore()` re-runs at their persisted attempt count (queue-default retries /
58
- * timeout, no per-entry signal). At-least-once — handlers should be idempotent.
59
- * - **Observable (§13).** The owned {@link emitter} ({@link QueueEventMap}) carries the
60
- * lifecycle moments — `enqueue` / `start` / `retry` / `success` / `failure` / `abort` /
61
- * `drain` — for fire-and-forget observers. Every event is emitted directly, strictly AFTER
62
- * the relevant wake / park / settle transition; the emitter isolates a listener throw and
63
- * routes it to its `error` handler (the `error` option), so a buggy observer can NEVER
64
- * reorder, throw into, or corrupt the cooperative wake-park / settle-once engine: `active`
65
- * stays balanced and no parked worker is stranded regardless of what a listener does.
66
- * 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
+ * ```
67
137
  */
68
138
  var Queue = class {
69
139
  #handler;
@@ -73,35 +143,73 @@ var Queue = class {
73
143
  #store;
74
144
  #abort = (0, _orkestrel_abort.createAbort)();
75
145
  #emitter;
146
+ #entries = /* @__PURE__ */ new Map();
147
+ #live = /* @__PURE__ */ new Map();
76
148
  #pending = [];
77
- #live = /* @__PURE__ */ new Set();
149
+ #claims = /* @__PURE__ */ new Set();
78
150
  #wakes = [];
79
- #active = 0;
80
- #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;
81
160
  #paused = false;
82
161
  #stopped = false;
83
162
  #aborted = false;
84
163
  #destroyed = false;
164
+ #drained = true;
165
+ /**
166
+ * Create a queue.
167
+ *
168
+ * @param options - Handler, validated execution limits, persistence, and observation hooks
169
+ */
85
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
+ });
86
195
  this.#handler = options.handler;
87
- this.#concurrency = Math.max(1, options.concurrency ?? 1);
88
- this.#retries = Math.max(0, options.retries ?? 0);
89
- this.#timeout = Math.max(0, options.timeout ?? 0);
196
+ this.#concurrency = concurrency;
197
+ this.#retries = retries;
198
+ this.#timeout = timeout;
90
199
  this.#store = options.store;
91
200
  this.#emitter = new _orkestrel_emitter.Emitter({
92
- ...options.on !== void 0 ? { on: options.on } : {},
93
- ...options.error !== void 0 ? { error: options.error } : {}
201
+ ...options.on === void 0 ? {} : { on: options.on },
202
+ ...options.error === void 0 ? {} : { error: options.error }
94
203
  });
95
- this.#spawn();
96
204
  }
97
205
  get emitter() {
98
206
  return this.#emitter;
99
207
  }
100
208
  get count() {
101
- return this.#pending.length + this.#active;
209
+ return this.#live.size;
102
210
  }
103
211
  get active() {
104
- return this.#active;
212
+ return this.#claims.size;
105
213
  }
106
214
  get paused() {
107
215
  return this.#paused;
@@ -109,122 +217,348 @@ var Queue = class {
109
217
  get stopped() {
110
218
  return this.#stopped || this.#aborted;
111
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
+ */
112
228
  enqueue(input, options) {
113
- if (this.#destroyed) return Promise.reject(/* @__PURE__ */ new Error("queue is destroyed"));
114
- if (this.#aborted) return Promise.reject(/* @__PURE__ */ new Error("queue is aborted"));
115
- if (this.#stopped) return Promise.reject(/* @__PURE__ */ new Error("queue is stopped"));
116
- const id = options?.id ?? crypto.randomUUID();
117
- if (this.#store !== void 0) return this.#persist(this.#store, id, input, options);
118
- return new Promise((resolve, reject) => {
119
- this.#live.add(id);
120
- this.#pending.push({
121
- id,
122
- input,
123
- options,
124
- attempts: 0,
125
- resolve,
126
- 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" }
127
237
  });
128
- this.#emitter.emit("enqueue", id);
129
- 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
+ }
130
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 }
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;
131
315
  }
316
+ /** Load and accept every outstanding stored entry from the current lifecycle generation. */
132
317
  async restore() {
133
- if (this.#store === void 0 || this.#stopped || this.#aborted || this.#destroyed) return;
134
- const entries = await this.#store.load();
135
- if (this.#destroyed || this.#aborted || this.#stopped) return;
136
- for (const entry of entries) {
137
- if (this.#live.has(entry.id)) continue;
138
- new Promise((resolve, reject) => {
139
- this.#live.add(entry.id);
140
- this.#pending.push({
141
- id: entry.id,
142
- input: entry.input,
143
- options: void 0,
144
- attempts: entry.attempts,
145
- resolve,
146
- 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" }
147
331
  });
148
- this.#emitter.emit("enqueue", entry.id);
149
- this.#wake();
150
- }).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(() => {});
151
353
  }
152
354
  }
355
+ /** Begin or restart worker execution unless the queue is terminal. */
153
356
  start() {
154
357
  if (this.#aborted || this.#destroyed) return;
155
358
  this.#stopped = false;
359
+ this.#stopPromise = void 0;
156
360
  this.#spawn();
157
361
  }
362
+ /** Reject non-active work and await current-loop and durable cleanup quiescence. */
158
363
  stop() {
159
- 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;
160
369
  this.#stopped = true;
161
- 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
+ ];
162
379
  this.#wakeAll();
380
+ this.#settleBarrier(barrier, tasks, "queue stop cleanup failed");
381
+ return barrier.promise;
163
382
  }
383
+ /** Suspend new execution while leaving active entries untouched. */
164
384
  pause() {
165
385
  if (this.#paused || this.stopped || this.#destroyed) return;
166
386
  this.#paused = true;
167
387
  }
388
+ /** Continue execution after a pause. */
168
389
  resume() {
169
390
  if (!this.#paused || this.stopped || this.#destroyed) return;
170
391
  this.#paused = false;
171
392
  this.#wakeAll();
172
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
+ */
173
400
  abort(reason) {
174
- if (this.#aborted) return;
401
+ if (this.#abortPromise !== void 0) return this.#abortPromise;
402
+ const barrier = Promise.withResolvers();
403
+ this.#abortPromise = barrier.promise;
175
404
  this.#aborted = true;
176
- this.#abort.abort(reason);
177
- 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
+ ];
178
420
  this.#wakeAll();
179
- 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;
180
424
  }
425
+ /** Reject non-active work and await its durable cleanup. */
181
426
  clear() {
182
- 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");
183
436
  }
437
+ /** Tear down once, destroying the emitter only after cleanup finishes. */
184
438
  destroy() {
185
- if (this.#destroyed) return;
439
+ if (this.#destroyPromise !== void 0) return this.#destroyPromise;
440
+ const barrier = Promise.withResolvers();
441
+ this.#destroyPromise = barrier.promise;
186
442
  this.#destroyed = true;
187
- this.abort();
188
- this.#stopped = true;
189
- 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();
190
513
  }
191
514
  #spawn() {
192
515
  if (this.#stopped || this.#aborted || this.#destroyed) return;
193
- while (this.#running < this.#concurrency) {
194
- this.#running += 1;
195
- 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(() => {});
196
525
  }
197
526
  }
198
- async #worker() {
199
- try {
200
- while (true) {
201
- const entry = await this.#next();
202
- if (entry === void 0) break;
203
- this.#active += 1;
204
- try {
205
- await this.#run(entry);
206
- } finally {
207
- this.#active -= 1;
208
- if (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit("drain");
209
- }
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;
210
536
  }
211
- } finally {
212
- this.#running -= 1;
213
537
  }
214
538
  }
215
- #next() {
216
- return new Promise((resolve) => this.#take(resolve));
539
+ #next(generation) {
540
+ return new Promise((resolve) => this.#take(generation, resolve));
217
541
  }
218
- #take(resolve) {
219
- if (this.#stopped || this.#aborted || this.#destroyed) {
542
+ #take(generation, resolve) {
543
+ if (generation !== this.#generation || this.#stopped || this.#aborted || this.#destroyed) {
220
544
  resolve(void 0);
221
545
  return;
222
546
  }
223
547
  if (this.#paused || this.#pending.length === 0) {
224
- this.#wakes.push(() => this.#take(resolve));
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);
225
558
  return;
226
559
  }
227
- resolve(this.#pending.shift());
560
+ this.#claims.add(token);
561
+ resolve(token);
228
562
  }
229
563
  #wake() {
230
564
  const resolver = this.#wakes.shift();
@@ -235,107 +569,186 @@ var Queue = class {
235
569
  for (const resolver of resolvers) resolver();
236
570
  }
237
571
  #drain(error) {
238
- while (this.#pending.length > 0) {
239
- const entry = this.#pending.shift();
240
- if (entry === void 0) continue;
241
- this.#live.delete(entry.id);
242
- this.#store?.remove(entry.id).catch(() => {});
243
- 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));
244
584
  }
585
+ return cleanup;
245
586
  }
246
- async #persist(store, id, input, options) {
247
- await store.save({
248
- id,
249
- input,
250
- attempts: 0
251
- });
252
- if (this.#destroyed || this.#aborted || this.#stopped) {
253
- await store.remove(id).catch(() => {});
254
- 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();
255
597
  }
256
- return new Promise((resolve, reject) => {
257
- this.#live.add(id);
258
- this.#pending.push({
259
- id,
260
- input,
261
- options,
262
- attempts: 0,
263
- resolve,
264
- 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
265
671
  });
266
- this.#emitter.emit("enqueue", id);
267
- 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
+ })
268
682
  });
683
+ return true;
269
684
  }
270
- 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;
271
688
  try {
272
- await this.#store?.save({
689
+ await this.#store.save({
273
690
  id: entry.id,
274
691
  input: entry.input,
275
692
  attempts
276
693
  });
277
694
  } catch {}
278
695
  }
279
- async #run(entry) {
280
- const retries = Math.max(0, entry.options?.retries ?? this.#retries);
281
- const timeout = Math.max(0, entry.options?.timeout ?? this.#timeout);
282
- const signal = entry.options?.signal;
283
- this.#emitter.emit("start", entry.id);
284
- for (let attempt = entry.attempts;; attempt += 1) {
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 > entry.attempts) {
294
- await this.#saveAttempt(entry, attempt);
295
- this.#emitter.emit("retry", entry.id, attempt);
296
- }
297
- const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
298
- if (outcome.success) return this.#settle(entry, {
299
- success: true,
300
- value: outcome.value
301
- });
302
- if (this.#abort.aborted) return this.#settle(entry, {
303
- success: false,
304
- error: this.#abort.signal.reason
305
- });
306
- 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, {
307
702
  success: false,
308
- error: signal.reason
703
+ error: cleanup
309
704
  });
310
- if (attempt < retries) continue;
311
- 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, {
312
717
  success: false,
313
- error: outcome.error
718
+ error
314
719
  });
720
+ throw error;
315
721
  }
722
+ this.#finishEntry(token, outcome);
316
723
  }
317
- #settle(entry, outcome) {
318
- this.#live.delete(entry.id);
319
- if (this.#store === void 0) {
320
- 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");
321
730
  return;
322
731
  }
323
- return this.#forget(this.#store, entry, outcome);
324
- }
325
- #commit(entry, outcome) {
326
- if (outcome.success) {
327
- entry.resolve(outcome.value);
328
- this.#emitter.emit("success", entry.id, outcome.value);
329
- } else {
330
- entry.reject(outcome.error);
331
- this.#emitter.emit("failure", entry.id, outcome.error);
332
- }
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");
333
735
  }
334
- async #forget(store, entry, outcome) {
335
- try {
336
- await store.remove(entry.id);
337
- } catch {}
338
- 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");
339
752
  }
340
753
  async #attempt(id, input, timeout, signal) {
341
754
  const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
@@ -357,17 +770,25 @@ var Queue = class {
357
770
  } catch (error) {
358
771
  return {
359
772
  success: false,
360
- 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 })
361
774
  };
362
775
  } finally {
363
776
  deadline?.clear();
364
777
  }
365
778
  }
366
779
  #race(id, input, signal, deadline) {
367
- if (signal.aborted) return Promise.reject(createAttemptError(deadline?.expired === true));
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
+ }));
368
785
  const cleanup = new AbortController();
369
786
  return new Promise((resolve, reject) => {
370
- signal.addEventListener("abort", () => reject(createAttemptError(deadline?.expired === true)), {
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
+ })), {
371
792
  once: true,
372
793
  signal: cleanup.signal
373
794
  });
@@ -388,6 +809,53 @@ var Queue = class {
388
809
  }
389
810
  });
390
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" }
823
+ });
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
+ }
391
859
  };
392
860
  //#endregion
393
861
  //#region src/core/stores/DatabaseQueueStore.ts
@@ -411,9 +879,11 @@ var Queue = class {
411
879
  *
412
880
  * @example
413
881
  * ```ts
414
- * import { createMemoryQueueStore, stringShape } from '@src/core'
882
+ * import { stringShape } from '@orkestrel/contract'
883
+ * import { createMemoryDriver } from '@orkestrel/database'
884
+ * import { createDatabaseQueueStore } from '@orkestrel/queue'
415
885
  *
416
- * const store = createMemoryQueueStore(stringShape())
886
+ * const store = createDatabaseQueueStore(stringShape(), createMemoryDriver())
417
887
  * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
418
888
  * const outstanding = await store.load() // readonly StoredEntry<string>[]
419
889
  * ```
@@ -449,66 +919,94 @@ var DatabaseQueueStore = class {
449
919
  //#endregion
450
920
  //#region src/core/stores/MemoryQueueStore.ts
451
921
  /**
452
- * The in-memory {@link QueueStoreInterface} — a process-lifetime `Map` of
453
- * {@link StoredEntry}s keyed by id, the DEFAULT store
454
- * {@link import('../factories.js').createMemoryQueueStore} builds.
922
+ * An in-memory store owning validated, immutable JSON snapshots of outstanding entries.
455
923
  *
456
- * @remarks
457
- * A plain `Map<string, StoredEntry<TInput>>` (AGENTS §21 — the entry is already pure,
458
- * self-contained JSON, so no `databases` table / driver codec is needed for the memory
459
- * tier; this is the zero-plumbing twin of {@link DatabaseQueueStore}, which wraps a
460
- * `TableInterface` for a driver-pluggable durable backend). The store holds ONLY
461
- * outstanding work, so `load` yields precisely the entries to resume — though a memory
462
- * store is gone when the process exits, so `restore()` recovers nothing after a real
463
- * restart. For durability across restarts, build a {@link DatabaseQueueStore} over a
464
- * server JSON / SQLite driver (the SAME interface, so the queue / worker never knows).
465
- *
466
- * - **`save` upserts an entry under its OWN `id`** (a re-`save` of an existing `id`
467
- * overwrites it — `Map.set`, never a duplicate).
468
- * - **`remove` drops a finished entry by `id`**; an absent `id` is a no-op (no throw).
469
- * - **`load` returns every outstanding entry** as a readonly array (the `Map`'s values
470
- * in insertion order — the work to resume).
471
- * - **`clear` empties the store** — drop every outstanding entry.
472
- *
473
- * Each primitive is async (it returns a resolved `Promise`) to satisfy the
474
- * {@link QueueStoreInterface} signatures, wrapping the synchronous `Map` op — so the
475
- * memory and driver-backed stores are interchangeable behind the one interface. The
476
- * public surface is EXACTLY `save` / `remove` / `load` / `clear` — no extra members (the
477
- * §22 method bijection with {@link QueueStoreInterface}).
478
- *
479
- * @typeParam TInput - The work input each {@link StoredEntry} carries
924
+ * @typeParam TInput - The contract shape for each stored input
480
925
  *
481
926
  * @example
482
927
  * ```ts
483
- * import { createMemoryQueueStore, stringShape } from '@src/core'
928
+ * import { stringShape } from '@orkestrel/contract'
929
+ * import { MemoryQueueStore } from '@orkestrel/queue'
484
930
  *
485
- * const store = createMemoryQueueStore(stringShape())
486
- * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
487
- * const outstanding = await store.load() // readonly StoredEntry<string>[]
488
- * 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 })
489
933
  * ```
490
934
  */
491
935
  var MemoryQueueStore = class {
936
+ #contract;
492
937
  #entries = /* @__PURE__ */ new Map();
493
- /** 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. */
494
947
  save(entry) {
495
- this.#entries.set(entry.id, entry);
496
- 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
+ }
497
965
  }
498
- /** 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. */
499
967
  remove(id) {
500
968
  this.#entries.delete(id);
501
969
  return Promise.resolve();
502
970
  }
503
- /** Every outstanding entry — the work to resume (the `Map`'s values, insertion order). */
971
+ /** Return fresh immutable snapshots of every outstanding entry. */
504
972
  load() {
505
- 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
+ }
506
989
  }
507
- /** Empty the store — drop every outstanding entry. */
990
+ /** Remove every outstanding entry. */
508
991
  clear() {
509
992
  this.#entries.clear();
510
993
  return Promise.resolve();
511
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
+ }
512
1010
  };
513
1011
  //#endregion
514
1012
  //#region src/core/factories.ts
@@ -534,7 +1032,7 @@ var MemoryQueueStore = class {
534
1032
  *
535
1033
  * @example
536
1034
  * ```ts
537
- * import { createQueue } from '@src/core'
1035
+ * import { createQueue } from '@orkestrel/queue'
538
1036
  *
539
1037
  * const queue = createQueue<string, number>({
540
1038
  * handler: async (url, { signal }) => (await fetch(url, { signal })).status,
@@ -550,13 +1048,17 @@ function createQueue(options) {
550
1048
  return new Queue(options);
551
1049
  }
552
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
+ };
553
1059
  return new DatabaseQueueStore((0, _orkestrel_database.createDatabase)({
554
1060
  driver,
555
- tables: { entries: {
556
- id: (0, _orkestrel_contract.stringShape)(),
557
- input,
558
- attempts: (0, _orkestrel_contract.integerShape)({ min: 0 })
559
- } }
1061
+ tables: { entries: columns }
560
1062
  }).table("entries"));
561
1063
  }
562
1064
  /**
@@ -564,42 +1066,41 @@ function createDatabaseQueueStore(input, driver) {
564
1066
  * over a plain `Map` (the twin of {@link DatabaseQueueStore}).
565
1067
  *
566
1068
  * @remarks
567
- * The convenience for a non-persistent queue store (tests, ephemeral queues): the entries
568
- * live in a process-lifetime `Map` and are gone when the process exits. UNLIKE
569
- * {@link createDatabaseQueueStore}, no `databases` table / driver codec is built — a queue
570
- * entry is already pure JSON, so the memory tier needs no encoding (AGENTS §21). The
571
- * `input` shape is accepted for SOURCE-COMPATIBILITY with the driver-backed family (every
572
- * call site passes its payload shape, and the store is still typed by it through `Infer`),
573
- * but a plain-`Map` store does not validate the payload — durability + contract narrowing
574
- * are {@link DatabaseQueueStore}'s job. For durability across restarts, build the store
575
- * over a server JSON / SQLite driver via {@link createDatabaseQueueStore} (or the server
576
- * `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}.
577
1075
  *
578
1076
  * @typeParam TInput - The contract shape of each entry's `input` payload
579
- * @param _input - The {@link ContractShape} for the work payload — types the store (via
580
- * `Infer`); the plain-`Map` backing does not use it at runtime, so it is `_`-prefixed
581
- * (AGENTS unused-arg convention) while staying in the signature for source-compatibility
582
- * with the driver-backed family
583
- * @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`
584
1079
  *
585
1080
  * @example
586
1081
  * ```ts
587
- * import { createMemoryQueueStore, stringShape } from '@src/core'
1082
+ * import { stringShape } from '@orkestrel/contract'
1083
+ * import { createMemoryQueueStore } from '@orkestrel/queue'
588
1084
  *
589
1085
  * const store = createMemoryQueueStore(stringShape())
590
1086
  * await store.save({ id: 'job-1', input: 'task', attempts: 0 })
591
1087
  * ```
592
1088
  */
593
- function createMemoryQueueStore(_input) {
594
- return new MemoryQueueStore();
1089
+ function createMemoryQueueStore(input) {
1090
+ return new MemoryQueueStore(input);
595
1091
  }
596
1092
  //#endregion
597
1093
  exports.DatabaseQueueStore = DatabaseQueueStore;
598
1094
  exports.MemoryQueueStore = MemoryQueueStore;
599
1095
  exports.Queue = Queue;
600
- exports.createAttemptError = createAttemptError;
1096
+ exports.QueueError = QueueError;
601
1097
  exports.createDatabaseQueueStore = createDatabaseQueueStore;
602
1098
  exports.createMemoryQueueStore = createMemoryQueueStore;
603
1099
  exports.createQueue = createQueue;
1100
+ exports.isQueueConcurrency = isQueueConcurrency;
1101
+ exports.isQueueError = isQueueError;
1102
+ exports.isQueueRetries = isQueueRetries;
1103
+ exports.isQueueSignal = isQueueSignal;
1104
+ exports.isQueueTimeout = isQueueTimeout;
604
1105
 
605
1106
  //# sourceMappingURL=index.cjs.map