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