@orkestrel/queue 0.0.11 → 0.0.13

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,11 +1,12 @@
1
- import { cloneJSONValue, createContract, integerShape, isFiniteNumber, isInteger, isString, preview, stringShape } from "@orkestrel/contract";
1
+ import { cloneJSONValue, createContract, integerShape, isFiniteNumber, isInteger, isRecord, isString, preview, stringShape } from "@orkestrel/contract";
2
+ import { MAX_TIMEOUT_MS, createTimeout } from "@orkestrel/timeout";
2
3
  import { createAbort } from "@orkestrel/abort";
3
4
  import { Emitter } from "@orkestrel/emitter";
4
- import { createTimeout } from "@orkestrel/timeout";
5
5
  import { createDatabase } from "@orkestrel/database";
6
6
  //#region src/core/errors.ts
7
7
  /**
8
- * Error carrying a machine-readable queue category and optional context.
8
+ * Represents a queue failure carrying a lowercase machine-readable `code`, optional
9
+ * structured context, and an optional cause.
9
10
  *
10
11
  * @example
11
12
  * ```ts
@@ -17,7 +18,7 @@ var QueueError = class extends Error {
17
18
  code;
18
19
  context;
19
20
  /**
20
- * Create a queue error.
21
+ * Creates a queue error.
21
22
  *
22
23
  * @param message - Human-readable failure description
23
24
  * @param options - Machine-readable category, optional context, and optional cause
@@ -30,10 +31,12 @@ var QueueError = class extends Error {
30
31
  }
31
32
  };
32
33
  /**
33
- * Determine whether an unknown value is a {@link QueueError}.
34
+ * Determines whether an unknown value is a {@link QueueError}, staying total for a hostile
35
+ * value.
34
36
  *
35
37
  * @param value - The value to inspect
36
- * @returns `true` only for a `QueueError`; hostile values return `false`
38
+ * @returns True if the value is a real `QueueError` instance; false otherwise, including for
39
+ * a hostile value
37
40
  *
38
41
  * @example
39
42
  * ```ts
@@ -54,10 +57,10 @@ function isQueueError(value) {
54
57
  //#endregion
55
58
  //#region src/core/validators.ts
56
59
  /**
57
- * Determine whether a value is a valid queue concurrency.
60
+ * Determines whether a value is a valid queue concurrency — a positive safe integer.
58
61
  *
59
62
  * @param value - Value to inspect
60
- * @returns Whether the value is a positive safe integer
63
+ * @returns True if the value is a positive safe integer; false otherwise
61
64
  *
62
65
  * @example
63
66
  * ```ts
@@ -69,10 +72,10 @@ function isQueueConcurrency(value) {
69
72
  return isInteger(value) && Number.isSafeInteger(value) && value > 0;
70
73
  }
71
74
  /**
72
- * Determine whether a value is a valid queue retry count.
75
+ * Determines whether a value is a valid queue retry count — a nonnegative safe integer.
73
76
  *
74
77
  * @param value - Value to inspect
75
- * @returns Whether the value is a nonnegative safe integer
78
+ * @returns True if the value is a nonnegative safe integer; false otherwise
76
79
  *
77
80
  * @example
78
81
  * ```ts
@@ -84,10 +87,12 @@ function isQueueRetries(value) {
84
87
  return isInteger(value) && Number.isSafeInteger(value) && value >= 0;
85
88
  }
86
89
  /**
87
- * Determine whether a value is a valid queue timeout.
90
+ * Determines whether a value is a valid queue timeout — an integer count of milliseconds
91
+ * inside the native timer range.
88
92
  *
89
93
  * @param value - Value to inspect
90
- * @returns Whether the value is an integer within the native timer range, inclusive
94
+ * @returns True if the value is an integer within the native timer range,
95
+ * inclusive; false otherwise
91
96
  *
92
97
  * @example
93
98
  * ```ts
@@ -96,13 +101,14 @@ function isQueueRetries(value) {
96
101
  * ```
97
102
  */
98
103
  function isQueueTimeout(value) {
99
- return isFiniteNumber(value) && isInteger(value) && value >= 0 && value <= 2147483647;
104
+ return isFiniteNumber(value) && isInteger(value) && value >= 0 && value <= MAX_TIMEOUT_MS;
100
105
  }
101
106
  /**
102
- * Determine whether a value is a native abort signal usable by the queue.
107
+ * Determines whether a value is a native abort signal usable by the queue, testing the
108
+ * native brand rather than the shape.
103
109
  *
104
110
  * @param value - Value to inspect
105
- * @returns Whether the value carries the native `AbortSignal` internal slot
111
+ * @returns True if the value carries the native `AbortSignal` internal slot; false otherwise
106
112
  *
107
113
  * @example
108
114
  * ```ts
@@ -120,10 +126,97 @@ function isQueueSignal(value) {
120
126
  return false;
121
127
  }
122
128
  }
129
+ /**
130
+ * Determines whether a value is a valid stored queue entry — a record holding a string
131
+ * `id`, an `input`, and a nonnegative safe-integer `attempts`.
132
+ *
133
+ * @remarks
134
+ * The single test for what a {@link StoredEntry} is, shared by the queue's `restore`
135
+ * boundary and the memory store's `save` boundary. `input` carries the caller's own
136
+ * payload type, so only its presence is checked.
137
+ *
138
+ * @param value - Value to inspect
139
+ * @returns True if the value is a record holding a string `id`, an `input` member, and a
140
+ * nonnegative safe-integer `attempts`; false otherwise
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * isStoredEntry({ id: 'job-1', input: 'task', attempts: 0 }) // true
145
+ * isStoredEntry({ id: 'job-1', input: 'task', attempts: -1 }) // false
146
+ * ```
147
+ */
148
+ function isStoredEntry(value) {
149
+ try {
150
+ if (!isRecord(value)) return false;
151
+ return isString(value.id) && "input" in value && isQueueRetries(value.attempts);
152
+ } catch {
153
+ return false;
154
+ }
155
+ }
156
+ //#endregion
157
+ //#region src/core/helpers.ts
158
+ /**
159
+ * Reads one named option from a caller-supplied entry options object exactly once,
160
+ * containing a throwing getter as a coded failure.
161
+ *
162
+ * @remarks
163
+ * An absent options object reads nothing and yields `undefined`.
164
+ *
165
+ * @param options - The caller's own entry options, or `undefined`
166
+ * @param option - The option key to read
167
+ * @param message - The failure description the thrown error carries
168
+ * @returns The value the property held, or `undefined` when no options object was supplied
169
+ * @throws {QueueError} Thrown when reading the property throws, coded `invalid` with the
170
+ * option in its context.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * readOption({ retries: 2 }, 'retries', 'queue retries could not be read') // 2
175
+ * ```
176
+ */
177
+ function readOption(options, option, message) {
178
+ try {
179
+ return options?.[option];
180
+ } catch (error) {
181
+ throw new QueueError(message, {
182
+ code: "invalid",
183
+ cause: error,
184
+ context: { option }
185
+ });
186
+ }
187
+ }
188
+ /**
189
+ * Validates one already-read queue option against its guard, and throws the coded invalid
190
+ * failure carrying the option and the refused value when the guard refuses it.
191
+ *
192
+ * @param value - The option value to check
193
+ * @param guard - The total guard the value must satisfy
194
+ * @param option - The option key the failure context reports
195
+ * @param message - The failure description the thrown error carries
196
+ * @returns The same value, narrowed by the guard
197
+ * @throws {QueueError} Thrown when the guard refuses the value, coded `invalid` with the
198
+ * option and the refused value in its context.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * validateOption(4, isQueueConcurrency, 'concurrency', 'queue concurrency must be positive') // 4
203
+ * ```
204
+ */
205
+ function validateOption(value, guard, option, message) {
206
+ if (guard(value)) return value;
207
+ throw new QueueError(message, {
208
+ code: "invalid",
209
+ context: {
210
+ option,
211
+ value
212
+ }
213
+ });
214
+ }
123
215
  //#endregion
124
216
  //#region src/core/Queue.ts
125
217
  /**
126
- * A concurrent, cooperative FIFO job queue with optional outstanding-work persistence.
218
+ * Represents a concurrent, cooperative FIFO job queue — a wake-park worker loop with
219
+ * retries, a per-attempt timeout, abort, and optional outstanding-work persistence.
127
220
  *
128
221
  * @typeParam TInput - The work input each entry carries
129
222
  * @typeParam TResult - The value each entry resolves
@@ -158,42 +251,19 @@ var Queue = class {
158
251
  #generation = 0;
159
252
  #paused = false;
160
253
  #stopped = false;
161
- #aborted = false;
162
- #destroyed = false;
163
254
  #drained = true;
164
255
  /**
165
- * Create a queue.
256
+ * Creates a queue.
166
257
  *
167
258
  * @param options - Handler, validated execution limits, persistence, and observation hooks
168
259
  */
169
260
  constructor(options) {
170
261
  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
- });
262
+ const concurrency = validateOption(configuredConcurrency === void 0 ? 1 : configuredConcurrency, isQueueConcurrency, "concurrency", "queue concurrency must be a positive safe integer");
179
263
  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
- });
264
+ const retries = validateOption(configuredRetries === void 0 ? 0 : configuredRetries, isQueueRetries, "retries", "queue retries must be a nonnegative safe integer");
188
265
  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
- });
266
+ const timeout = validateOption(configuredTimeout === void 0 ? 0 : configuredTimeout, isQueueTimeout, "timeout", "queue timeout must be within the native timer range");
197
267
  const on = options.on;
198
268
  const error = options.error;
199
269
  this.#handler = options.handler;
@@ -219,93 +289,33 @@ var Queue = class {
219
289
  return this.#paused;
220
290
  }
221
291
  get stopped() {
222
- return this.#stopped || this.#aborted;
292
+ return this.#stopped || this.#abortPromise !== void 0;
223
293
  }
224
294
  /**
225
- * Reserve and submit one FIFO entry.
295
+ * Reserves and submits one FIFO entry.
226
296
  *
227
297
  * @param input - Handler input
228
298
  * @param options - Optional id, retry/timeout overrides, and entry abort signal
229
299
  * @returns The entry's settle-once execution promise
230
- * @throws {QueueError} Synchronously when an option is inaccessible or invalid
300
+ * @throws {QueueError} Thrown synchronously when an option is inaccessible or invalid.
231
301
  */
232
302
  enqueue(input, options) {
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" }
258
- });
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
- }
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
- });
303
+ const rawId = readOption(options, "id", "queue entry id could not be read");
304
+ const supplied = rawId === void 0 ? void 0 : validateOption(rawId, isString, "id", "queue entry id must be a string");
305
+ const rawRetries = readOption(options, "retries", "queue retries could not be read");
306
+ const retries = rawRetries === void 0 ? void 0 : validateOption(rawRetries, isQueueRetries, "retries", "queue retries must be a nonnegative safe integer");
307
+ const rawTimeout = readOption(options, "timeout", "queue timeout could not be read");
308
+ const timeout = rawTimeout === void 0 ? void 0 : validateOption(rawTimeout, isQueueTimeout, "timeout", "queue timeout must be within the native timer range");
309
+ const rawSignal = readOption(options, "signal", "queue signal could not be read");
310
+ const signal = rawSignal === void 0 ? void 0 : validateOption(rawSignal, isQueueSignal, "signal", "queue signal must be an AbortSignal");
301
311
  const normalized = options === void 0 ? void 0 : Object.freeze({
302
312
  ...supplied === void 0 ? {} : { id: supplied },
303
313
  ...retries === void 0 ? {} : { retries },
304
314
  ...timeout === void 0 ? {} : { timeout },
305
315
  ...signal === void 0 ? {} : { signal }
306
316
  });
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" }));
317
+ if (this.#destroyPromise !== void 0) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
318
+ if (this.#abortPromise !== void 0) return Promise.reject(new QueueError("queue is aborted", { code: "aborted" }));
309
319
  if (this.#stopped) return Promise.reject(new QueueError("queue is stopped", { code: "stopped" }));
310
320
  const id = supplied ?? crypto.randomUUID();
311
321
  if (this.#live.has(id)) return Promise.reject(new QueueError("queue entry id is already live", {
@@ -317,27 +327,30 @@ var Queue = class {
317
327
  else this.#schedule(token);
318
328
  return token.promise;
319
329
  }
320
- /** Load and accept every outstanding stored entry from the current lifecycle generation. */
330
+ /**
331
+ * Loads and accepts every outstanding stored entry from the current lifecycle generation.
332
+ *
333
+ * @returns A promise that settles after every loaded entry is reserved and accepted
334
+ * @throws {QueueError} Thrown when the store's load fails or returns a malformed entry.
335
+ */
321
336
  async restore() {
322
- if (this.#store === void 0 || this.stopped || this.#destroyed) return;
337
+ if (this.#store === void 0 || this.stopped || this.#destroyPromise !== void 0) return;
323
338
  const generation = this.#generation;
324
339
  const entries = [];
325
340
  let malformed = false;
326
341
  try {
327
342
  const loaded = await this.#store.load();
328
343
  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)) {
344
+ const candidate = {
345
+ id: stored.id,
346
+ input: stored.input,
347
+ attempts: stored.attempts
348
+ };
349
+ if (!isStoredEntry(candidate)) {
333
350
  malformed = true;
334
351
  break;
335
352
  }
336
- entries.push(Object.freeze({
337
- id,
338
- input,
339
- attempts
340
- }));
353
+ entries.push(Object.freeze(candidate));
341
354
  }
342
355
  } catch (error) {
343
356
  throw new QueueError("queue store load failed", {
@@ -350,23 +363,27 @@ var Queue = class {
350
363
  code: "store",
351
364
  context: { operation: "load" }
352
365
  });
353
- if (generation !== this.#generation || this.stopped || this.#destroyed) return;
366
+ if (generation !== this.#generation || this.stopped || this.#destroyPromise !== void 0) return;
354
367
  for (const stored of entries) {
355
- if (generation !== this.#generation || this.stopped || this.#destroyed) return;
368
+ if (generation !== this.#generation || this.stopped || this.#destroyPromise !== void 0) return;
356
369
  if (this.#live.has(stored.id)) continue;
357
370
  const token = this.#reserve(stored.id, stored.input, void 0, stored.attempts);
358
371
  this.#accept(token);
359
372
  token.promise.catch(() => {});
360
373
  }
361
374
  }
362
- /** Begin or restart worker execution unless the queue is terminal. */
375
+ /** Begins or restarts worker execution unless the queue is terminal. */
363
376
  start() {
364
- if (this.#aborted || this.#destroyed) return;
377
+ if (this.#abortPromise !== void 0 || this.#destroyPromise !== void 0) return;
365
378
  this.#stopped = false;
366
379
  this.#stopPromise = void 0;
367
380
  this.#spawn();
368
381
  }
369
- /** Reject non-active work and await current-loop and durable cleanup quiescence. */
382
+ /**
383
+ * Rejects non-active work and awaits current-loop and durable cleanup quiescence.
384
+ *
385
+ * @returns The stable stop barrier
386
+ */
370
387
  stop() {
371
388
  if (this.#destroyPromise !== void 0) return this.#destroyPromise;
372
389
  if (this.#abortPromise !== void 0) return this.#abortPromise;
@@ -387,19 +404,19 @@ var Queue = class {
387
404
  this.#settleBarrier(barrier, tasks, "queue stop cleanup failed");
388
405
  return barrier.promise;
389
406
  }
390
- /** Suspend new execution while leaving active entries untouched. */
407
+ /** Suspends new execution while leaving active entries untouched. */
391
408
  pause() {
392
- if (this.#paused || this.stopped || this.#destroyed) return;
409
+ if (this.#paused || this.stopped || this.#destroyPromise !== void 0) return;
393
410
  this.#paused = true;
394
411
  }
395
- /** Continue execution after a pause. */
412
+ /** Continues execution after a pause. */
396
413
  resume() {
397
- if (!this.#paused || this.stopped || this.#destroyed) return;
414
+ if (!this.#paused || this.stopped || this.#destroyPromise !== void 0) return;
398
415
  this.#paused = false;
399
416
  this.#wakeAll();
400
417
  }
401
418
  /**
402
- * Cancel the queue and await owned cleanup.
419
+ * Cancels the queue and awaits owned cleanup.
403
420
  *
404
421
  * @param reason - Optional cause carried by the coded abort error
405
422
  * @returns The stable abort barrier
@@ -408,7 +425,6 @@ var Queue = class {
408
425
  if (this.#abortPromise !== void 0) return this.#abortPromise;
409
426
  const barrier = Promise.withResolvers();
410
427
  this.#abortPromise = barrier.promise;
411
- this.#aborted = true;
412
428
  this.#stopped = true;
413
429
  this.#generation += 1;
414
430
  const error = new QueueError(reason instanceof Error ? reason.message : "queue is aborted", {
@@ -429,9 +445,13 @@ var Queue = class {
429
445
  this.#settleBarrier(barrier, tasks, "queue abort cleanup failed");
430
446
  return barrier.promise;
431
447
  }
432
- /** Reject non-active work and await its durable cleanup. */
448
+ /**
449
+ * Rejects non-active work and awaits its durable cleanup.
450
+ *
451
+ * @returns A promise that settles after every affected removal completes
452
+ */
433
453
  clear() {
434
- if (this.#destroyed) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
454
+ if (this.#destroyPromise !== void 0) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
435
455
  const existing = [];
436
456
  for (const [token, cleanup] of this.#cleanups) if (!this.#claims.has(token)) existing.push(cleanup);
437
457
  const cleanup = [...this.#drain(new QueueError("queue is cleared", { code: "cleared" })), ...this.#cleanOrphans(false)];
@@ -441,12 +461,15 @@ var Queue = class {
441
461
  ...cleanup
442
462
  ], "queue clear cleanup failed");
443
463
  }
444
- /** Tear down once, destroying the emitter only after cleanup finishes. */
464
+ /**
465
+ * Tears down once, destroying the emitter only after cleanup finishes.
466
+ *
467
+ * @returns The stable destroy barrier
468
+ */
445
469
  destroy() {
446
470
  if (this.#destroyPromise !== void 0) return this.#destroyPromise;
447
471
  const barrier = Promise.withResolvers();
448
472
  this.#destroyPromise = barrier.promise;
449
- this.#destroyed = true;
450
473
  const aborting = this.abort(new QueueError("queue is destroyed", { code: "destroyed" }));
451
474
  this.#settleDestroy(barrier, aborting);
452
475
  return barrier.promise;
@@ -504,7 +527,7 @@ var Queue = class {
504
527
  this.#emitDrain();
505
528
  return;
506
529
  }
507
- if (entry.settled || this.#aborted || this.#destroyed || this.#stopped) {
530
+ if (entry.settled || this.#abortPromise !== void 0 || this.#destroyPromise !== void 0 || this.#stopped) {
508
531
  await this.#discard(token);
509
532
  return;
510
533
  }
@@ -519,7 +542,7 @@ var Queue = class {
519
542
  this.#wake();
520
543
  }
521
544
  #spawn() {
522
- if (this.#stopped || this.#aborted || this.#destroyed) return;
545
+ if (this.#stopped || this.#abortPromise !== void 0 || this.#destroyPromise !== void 0) return;
523
546
  const demand = Math.min(this.#concurrency, this.#claims.size + this.#pending.length);
524
547
  while (this.#workers.size < demand) {
525
548
  const generation = this.#generation;
@@ -547,7 +570,7 @@ var Queue = class {
547
570
  return new Promise((resolve) => this.#take(generation, resolve));
548
571
  }
549
572
  #take(generation, resolve) {
550
- if (generation !== this.#generation || this.#stopped || this.#aborted || this.#destroyed) {
573
+ if (generation !== this.#generation || this.#stopped || this.#abortPromise !== void 0 || this.#destroyPromise !== void 0) {
551
574
  resolve(void 0);
552
575
  return;
553
576
  }
@@ -867,9 +890,9 @@ var Queue = class {
867
890
  //#endregion
868
891
  //#region src/core/stores/DatabaseQueueStore.ts
869
892
  /**
870
- * A {@link QueueStoreInterface} backed by one table of the `databases` layer — a
871
- * queue's durable state IS a table, so persistence reduces to keyed CRUD over a
872
- * `TableInterface`.
893
+ * Represents the opt-in durable store for a queue's outstanding entries, backed by one table
894
+ * of the `@orkestrel/database` layer — a queue's durable state is a table, so persistence
895
+ * reduces to keyed CRUD over a `TableInterface`.
873
896
  *
874
897
  * @remarks
875
898
  * The store is driver-agnostic: it holds a single {@link TableInterface} whose
@@ -877,9 +900,9 @@ var Queue = class {
877
900
  * `save` upserts an entry by its primary key (`set`), `remove` drops one (`remove`),
878
901
  * `load` returns every outstanding entry (`records` with no criteria), and `clear`
879
902
  * empties the table. Reads are narrowed through the table's contract, so `load`
880
- * returns typed {@link StoredEntry}`<TInput>[]` with no cast (AGENTS §1) — the table
903
+ * returns typed {@link StoredEntry}`<TInput>[]` with no cast — the table
881
904
  * is created over the `{ id; input; attempts }` column map, which `Infer`s to exactly
882
- * that row. The store holds only OUTSTANDING work (completed entries are `remove`d), so
905
+ * that row. The store holds only outstanding work (completed entries are `remove`d), so
883
906
  * `load` on startup yields precisely the entries to resume.
884
907
  *
885
908
  * @typeParam TInput - The work input each {@link StoredEntry} carries
@@ -898,7 +921,7 @@ var Queue = class {
898
921
  var DatabaseQueueStore = class {
899
922
  #table;
900
923
  /**
901
- * Wrap a table as a queue store.
924
+ * Wraps a table as a queue store.
902
925
  *
903
926
  * @param table - The {@link TableInterface} holding the outstanding entries — its
904
927
  * row is a {@link StoredEntry}`<TInput>` (the `{ id; input; attempts }` shape)
@@ -906,19 +929,19 @@ var DatabaseQueueStore = class {
906
929
  constructor(table) {
907
930
  this.#table = table;
908
931
  }
909
- /** Upsert an entry by its `id` (a re-`save` of an existing `id` overwrites it). */
932
+ /** Upserts an entry by its `id` (a re-`save` of an existing `id` overwrites it). */
910
933
  async save(entry) {
911
934
  await this.#table.set(entry);
912
935
  }
913
- /** Drop a finished entry by `id`; absent is a no-op (no throw). */
936
+ /** Drops a finished entry by `id`; absent is a no-op (no throw). */
914
937
  async remove(id) {
915
938
  await this.#table.remove(id);
916
939
  }
917
- /** Every outstanding entry — the work to resume after a restart. */
940
+ /** Returns every outstanding entry — the work to resume after a restart. */
918
941
  load() {
919
942
  return this.#table.records();
920
943
  }
921
- /** Empty the store — drop every outstanding entry. */
944
+ /** Empties the store — drops every outstanding entry. */
922
945
  async clear() {
923
946
  await this.#table.clear();
924
947
  }
@@ -926,7 +949,8 @@ var DatabaseQueueStore = class {
926
949
  //#endregion
927
950
  //#region src/core/stores/MemoryQueueStore.ts
928
951
  /**
929
- * An in-memory store owning validated, immutable JSON snapshots of outstanding entries.
952
+ * Represents an in-memory store of a queue's outstanding entries — a process-lifetime `Map`
953
+ * owning validated, immutable JSON snapshots.
930
954
  *
931
955
  * @typeParam TInput - The contract shape for each stored input
932
956
  *
@@ -943,23 +967,26 @@ var MemoryQueueStore = class {
943
967
  #contract;
944
968
  #entries = /* @__PURE__ */ new Map();
945
969
  /**
946
- * Create an in-memory queue store.
970
+ * Creates an in-memory queue store.
947
971
  *
948
972
  * @param input - Runtime contract for each stored input
949
973
  */
950
974
  constructor(input) {
951
975
  this.#contract = createContract(input);
952
976
  }
953
- /** Upsert a validated, owned snapshot under the entry's id. */
977
+ /** Upserts a validated, owned snapshot under the entry's id. */
954
978
  save(entry) {
955
979
  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", {
980
+ const candidate = {
981
+ id: entry.id,
982
+ input: entry.input,
983
+ attempts: entry.attempts
984
+ };
985
+ if (!isStoredEntry(candidate)) throw new QueueError("queue store entry is invalid", {
960
986
  code: "store",
961
987
  context: { operation: "save" }
962
988
  });
989
+ const { id, input, attempts } = candidate;
963
990
  this.#entries.set(id, this.#snapshot(id, input, attempts, "save"));
964
991
  return Promise.resolve();
965
992
  } catch (error) {
@@ -970,12 +997,12 @@ var MemoryQueueStore = class {
970
997
  }));
971
998
  }
972
999
  }
973
- /** Remove an entry; an absent id is a no-op. */
1000
+ /** Removes an entry; an absent id is a no-op. */
974
1001
  remove(id) {
975
1002
  this.#entries.delete(id);
976
1003
  return Promise.resolve();
977
1004
  }
978
- /** Return fresh immutable snapshots of every outstanding entry. */
1005
+ /** Returns fresh immutable snapshots of every outstanding entry. */
979
1006
  load() {
980
1007
  try {
981
1008
  const snapshots = [];
@@ -994,7 +1021,7 @@ var MemoryQueueStore = class {
994
1021
  }));
995
1022
  }
996
1023
  }
997
- /** Remove every outstanding entry. */
1024
+ /** Removes every outstanding entry. */
998
1025
  clear() {
999
1026
  this.#entries.clear();
1000
1027
  return Promise.resolve();
@@ -1018,37 +1045,44 @@ var MemoryQueueStore = class {
1018
1045
  //#endregion
1019
1046
  //#region src/core/factories.ts
1020
1047
  /**
1021
- * Create a concurrent, cooperative job queue — a bounded-concurrency engine that
1048
+ * Creates a concurrent, cooperative job queue — a bounded-concurrency engine that
1022
1049
  * runs each enqueued input through a handler, with retries and a per-attempt
1023
1050
  * timeout / abort, all over the L1 `Abort` / `Timeout` primitives.
1024
1051
  *
1025
1052
  * @remarks
1026
- * Worker loops PARK on a wake list when no entry is ready and are woken one-at-a-time
1053
+ * Worker loops park on a wake list when no entry is ready and are woken one-at-a-time
1027
1054
  * by `enqueue` / `resume`, so an idle queue consumes no CPU (no polling). `enqueue`
1028
1055
  * returns a promise that settles when the entry finally completes, fails (after its
1029
1056
  * retries), or is rejected by an abort. A queue-level `abort` never retries; the
1030
1057
  * lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)
1031
- * follows AGENTS §10. The queue is observable (§13): a typed `emitter` surfaces
1058
+ * follows the fixed lifecycle vocabulary. The queue is observable: a typed `emitter` surfaces
1032
1059
  * `enqueue` / `start` / `retry` / `success` / `failure` / `abort` / `drain`.
1033
1060
  *
1034
1061
  * @typeParam TInput - The work input each entry carries
1035
1062
  * @typeParam TResult - The value the handler resolves for an entry
1036
- * @param options - The `handler` plus optional `concurrency` (default `1`),
1037
- * `retries` (default `0`), and a default per-attempt `timeout` in milliseconds
1063
+ * @param options - The `handler` plus optional `concurrency`, `retries`, and a default
1064
+ * per-attempt `timeout` in milliseconds. Default: `concurrency` `1`, `retries` `0`,
1065
+ * `timeout` `0`.
1038
1066
  * @returns A working {@link QueueInterface}
1039
1067
  *
1040
- * @example
1068
+ * @example Create a queue
1041
1069
  * ```ts
1042
1070
  * import { createQueue } from '@orkestrel/queue'
1043
1071
  *
1044
- * const queue = createQueue<string, number>({
1072
+ * // Ordered (concurrency defaults to 1): each entry runs to completion before the next.
1073
+ * const queue = createQueue<Job, Output>({ handler: (job) => run(job) })
1074
+ *
1075
+ * const output = await queue.enqueue(job)
1076
+ *
1077
+ * // Bounded, retried, and time-boxed: four in flight, two extra attempts, 5s per attempt.
1078
+ * const fetches = createQueue<string, number>({
1045
1079
  * handler: async (url, { signal }) => (await fetch(url, { signal })).status,
1046
1080
  * concurrency: 4,
1047
1081
  * retries: 2,
1048
1082
  * timeout: 5_000,
1049
1083
  * })
1050
1084
  *
1051
- * const status = await queue.enqueue('https://example.com')
1085
+ * const status = await fetches.enqueue('https://example.com')
1052
1086
  * ```
1053
1087
  */
1054
1088
  function createQueue(options) {
@@ -1069,8 +1103,9 @@ function createDatabaseQueueStore(input, driver) {
1069
1103
  }).table("entries"));
1070
1104
  }
1071
1105
  /**
1072
- * Create an in-memory {@link MemoryQueueStore} — the zero-plumbing DEFAULT queue store
1073
- * over a plain `Map` (the twin of {@link DatabaseQueueStore}).
1106
+ * Creates an in-memory {@link MemoryQueueStore} over a plain `Map` — the zero-plumbing
1107
+ * {@link QueueStoreInterface} a queue takes when its outstanding entries need not outlive
1108
+ * the process, and the twin of {@link DatabaseQueueStore}.
1074
1109
  *
1075
1110
  * @remarks
1076
1111
  * The entries live in a process-lifetime `Map` and are gone when the process exits. The
@@ -1097,6 +1132,6 @@ function createMemoryQueueStore(input) {
1097
1132
  return new MemoryQueueStore(input);
1098
1133
  }
1099
1134
  //#endregion
1100
- export { DatabaseQueueStore, MemoryQueueStore, Queue, QueueError, createDatabaseQueueStore, createMemoryQueueStore, createQueue, isQueueConcurrency, isQueueError, isQueueRetries, isQueueSignal, isQueueTimeout };
1135
+ export { DatabaseQueueStore, MemoryQueueStore, Queue, QueueError, createDatabaseQueueStore, createMemoryQueueStore, createQueue, isQueueConcurrency, isQueueError, isQueueRetries, isQueueSignal, isQueueTimeout, isStoredEntry, readOption, validateOption };
1101
1136
 
1102
1137
  //# sourceMappingURL=index.js.map