@orkestrel/queue 0.0.4 → 0.0.6

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