@orkestrel/queue 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +59 -0
- package/dist/src/core/index.cjs +581 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +457 -0
- package/dist/src/core/index.d.ts +457 -0
- package/dist/src/core/index.js +575 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
import { createAbort } from "@orkestrel/abort";
|
|
2
|
+
import { Emitter } from "@orkestrel/emitter";
|
|
3
|
+
import { createTimeout } from "@orkestrel/timeout";
|
|
4
|
+
import { integerShape, stringShape } from "@orkestrel/contract";
|
|
5
|
+
import { createDatabase } from "@orkestrel/database";
|
|
6
|
+
//#region src/core/Queue.ts
|
|
7
|
+
/**
|
|
8
|
+
* A concurrent, cooperative job queue.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* - **Cooperative wake-park loop.** Up to `concurrency` worker loops run; each
|
|
12
|
+
* takes the next pending entry, or — when none is ready (empty or paused) —
|
|
13
|
+
* PARKS by awaiting a fresh promise whose resolver is held in a wake list.
|
|
14
|
+
* `enqueue` / `resume` resolve one parked resolver to wake exactly one worker,
|
|
15
|
+
* so idle workers consume no CPU (no busy-poll, no timers, no recursion).
|
|
16
|
+
* - **FIFO + bounded concurrency.** Entries run in enqueue order; at most
|
|
17
|
+
* `concurrency` are in flight at once (default `1` = strictly ordered). A surplus
|
|
18
|
+
* entry waits for a worker to free up.
|
|
19
|
+
* - **Per-attempt deadline + cancellation.** Each attempt's `signal` (handed to the
|
|
20
|
+
* handler) fires on the per-attempt `Timeout` expiring, a queue-level `abort`, or
|
|
21
|
+
* the entry's own `signal`. The handler is RACED against that signal, so an attempt
|
|
22
|
+
* that ignores its `signal` still fails on the deadline. Built on the L1 `Abort` /
|
|
23
|
+
* `Timeout` primitives (a queue / entry abort CLEARS the deadline, never expires it).
|
|
24
|
+
* - **Retries.** A failed attempt (a handler rejection or a per-attempt timeout)
|
|
25
|
+
* retries while attempts remain (`retries` + 1 total). A queue-level abort NEVER
|
|
26
|
+
* retries — it rejects the entry at once; an entry-`signal` abort likewise.
|
|
27
|
+
* - **Lifecycle (§10).** `pause` parks workers; `resume` wakes them; `stop` ends the
|
|
28
|
+
* loops permanently and rejects pending (in-flight settle); `abort` fires the queue
|
|
29
|
+
* signal (cancelling in-flight attempts) and rejects pending; `clear` drops only
|
|
30
|
+
* pending; `destroy` aborts then stops, idempotently.
|
|
31
|
+
* - **Durability (optional `store`).** The store mirrors only OUTSTANDING work: an
|
|
32
|
+
* entry is `save`d on accept (and re-`save`d as its attempt count climbs) and
|
|
33
|
+
* `remove`d the moment it settles (success or terminal failure) or is drained by a
|
|
34
|
+
* lifecycle call. Accepting work durably is NOT best-effort — a failed initial `save`
|
|
35
|
+
* rejects the enqueue; per-attempt persistence IS best-effort (in-memory state is
|
|
36
|
+
* authoritative). A graceful shutdown empties the store; a crash leaves rows that
|
|
37
|
+
* `restore()` re-runs at their persisted attempt count (queue-default retries /
|
|
38
|
+
* timeout, no per-entry signal). At-least-once — handlers should be idempotent.
|
|
39
|
+
* - **Observable (§13).** The owned {@link emitter} ({@link QueueEventMap}) carries the
|
|
40
|
+
* lifecycle moments — `enqueue` / `start` / `retry` / `success` / `failure` / `abort` /
|
|
41
|
+
* `drain` — for fire-and-forget observers. Every event is emitted directly, strictly AFTER
|
|
42
|
+
* the relevant wake / park / settle transition; the emitter isolates a listener throw and
|
|
43
|
+
* routes it to its `error` handler (the `error` option), so a buggy observer can NEVER
|
|
44
|
+
* reorder, throw into, or corrupt the cooperative wake-park / settle-once engine: `active`
|
|
45
|
+
* stays balanced and no parked worker is stranded regardless of what a listener does.
|
|
46
|
+
* Observation is purely a side-channel.
|
|
47
|
+
*/
|
|
48
|
+
var Queue = class {
|
|
49
|
+
#handler;
|
|
50
|
+
#concurrency;
|
|
51
|
+
#retries;
|
|
52
|
+
#timeout;
|
|
53
|
+
#store;
|
|
54
|
+
#abort = createAbort();
|
|
55
|
+
#emitter;
|
|
56
|
+
#pending = [];
|
|
57
|
+
#live = /* @__PURE__ */ new Set();
|
|
58
|
+
#wakes = [];
|
|
59
|
+
#active = 0;
|
|
60
|
+
#running = 0;
|
|
61
|
+
#paused = false;
|
|
62
|
+
#stopped = false;
|
|
63
|
+
#aborted = false;
|
|
64
|
+
#destroyed = false;
|
|
65
|
+
constructor(options) {
|
|
66
|
+
this.#handler = options.handler;
|
|
67
|
+
this.#concurrency = Math.max(1, options.concurrency ?? 1);
|
|
68
|
+
this.#retries = Math.max(0, options.retries ?? 0);
|
|
69
|
+
this.#timeout = Math.max(0, options.timeout ?? 0);
|
|
70
|
+
this.#store = options.store;
|
|
71
|
+
this.#emitter = new Emitter({
|
|
72
|
+
on: options?.on,
|
|
73
|
+
error: options?.error
|
|
74
|
+
});
|
|
75
|
+
this.#spawn();
|
|
76
|
+
}
|
|
77
|
+
get emitter() {
|
|
78
|
+
return this.#emitter;
|
|
79
|
+
}
|
|
80
|
+
get count() {
|
|
81
|
+
return this.#pending.length + this.#active;
|
|
82
|
+
}
|
|
83
|
+
get active() {
|
|
84
|
+
return this.#active;
|
|
85
|
+
}
|
|
86
|
+
get paused() {
|
|
87
|
+
return this.#paused;
|
|
88
|
+
}
|
|
89
|
+
get stopped() {
|
|
90
|
+
return this.#stopped || this.#aborted;
|
|
91
|
+
}
|
|
92
|
+
enqueue(input, options) {
|
|
93
|
+
if (this.#destroyed) return Promise.reject(/* @__PURE__ */ new Error("queue is destroyed"));
|
|
94
|
+
if (this.#aborted) return Promise.reject(/* @__PURE__ */ new Error("queue is aborted"));
|
|
95
|
+
if (this.#stopped) return Promise.reject(/* @__PURE__ */ new Error("queue is stopped"));
|
|
96
|
+
const id = options?.id ?? crypto.randomUUID();
|
|
97
|
+
if (this.#store !== void 0) return this.#persist(this.#store, id, input, options);
|
|
98
|
+
return new Promise((resolve, reject) => {
|
|
99
|
+
this.#live.add(id);
|
|
100
|
+
this.#pending.push({
|
|
101
|
+
id,
|
|
102
|
+
input,
|
|
103
|
+
options,
|
|
104
|
+
attempts: 0,
|
|
105
|
+
resolve,
|
|
106
|
+
reject
|
|
107
|
+
});
|
|
108
|
+
this.#emitter.emit("enqueue", id);
|
|
109
|
+
this.#wake();
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async restore() {
|
|
113
|
+
if (this.#store === void 0 || this.#stopped || this.#aborted || this.#destroyed) return;
|
|
114
|
+
const entries = await this.#store.load();
|
|
115
|
+
if (this.#destroyed || this.#aborted || this.#stopped) return;
|
|
116
|
+
for (const entry of entries) {
|
|
117
|
+
if (this.#live.has(entry.id)) continue;
|
|
118
|
+
new Promise((resolve, reject) => {
|
|
119
|
+
this.#live.add(entry.id);
|
|
120
|
+
this.#pending.push({
|
|
121
|
+
id: entry.id,
|
|
122
|
+
input: entry.input,
|
|
123
|
+
options: void 0,
|
|
124
|
+
attempts: entry.attempts,
|
|
125
|
+
resolve,
|
|
126
|
+
reject
|
|
127
|
+
});
|
|
128
|
+
this.#emitter.emit("enqueue", entry.id);
|
|
129
|
+
this.#wake();
|
|
130
|
+
}).catch(() => {});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
start() {
|
|
134
|
+
if (this.#aborted || this.#destroyed) return;
|
|
135
|
+
this.#stopped = false;
|
|
136
|
+
this.#spawn();
|
|
137
|
+
}
|
|
138
|
+
stop() {
|
|
139
|
+
if (this.#stopped) return;
|
|
140
|
+
this.#stopped = true;
|
|
141
|
+
this.#drain(/* @__PURE__ */ new Error("queue is stopped"));
|
|
142
|
+
this.#wakeAll();
|
|
143
|
+
}
|
|
144
|
+
pause() {
|
|
145
|
+
if (this.#paused || this.stopped || this.#destroyed) return;
|
|
146
|
+
this.#paused = true;
|
|
147
|
+
}
|
|
148
|
+
resume() {
|
|
149
|
+
if (!this.#paused || this.stopped || this.#destroyed) return;
|
|
150
|
+
this.#paused = false;
|
|
151
|
+
this.#wakeAll();
|
|
152
|
+
}
|
|
153
|
+
abort(reason) {
|
|
154
|
+
if (this.#aborted) return;
|
|
155
|
+
this.#aborted = true;
|
|
156
|
+
this.#abort.abort(reason);
|
|
157
|
+
this.#drain(this.#abort.signal.reason);
|
|
158
|
+
this.#wakeAll();
|
|
159
|
+
this.#emitter.emit("abort", this.#abort.signal.reason);
|
|
160
|
+
}
|
|
161
|
+
clear() {
|
|
162
|
+
this.#drain(/* @__PURE__ */ new Error("queue cleared"));
|
|
163
|
+
}
|
|
164
|
+
destroy() {
|
|
165
|
+
if (this.#destroyed) return;
|
|
166
|
+
this.#destroyed = true;
|
|
167
|
+
this.abort();
|
|
168
|
+
this.#stopped = true;
|
|
169
|
+
this.#wakeAll();
|
|
170
|
+
}
|
|
171
|
+
#spawn() {
|
|
172
|
+
if (this.#stopped || this.#aborted || this.#destroyed) return;
|
|
173
|
+
while (this.#running < this.#concurrency) {
|
|
174
|
+
this.#running += 1;
|
|
175
|
+
this.#worker();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async #worker() {
|
|
179
|
+
try {
|
|
180
|
+
while (true) {
|
|
181
|
+
const entry = await this.#next();
|
|
182
|
+
if (entry === void 0) break;
|
|
183
|
+
this.#active += 1;
|
|
184
|
+
try {
|
|
185
|
+
await this.#run(entry);
|
|
186
|
+
} finally {
|
|
187
|
+
this.#active -= 1;
|
|
188
|
+
if (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit("drain");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
} finally {
|
|
192
|
+
this.#running -= 1;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
#next() {
|
|
196
|
+
return new Promise((resolve) => {
|
|
197
|
+
const take = () => {
|
|
198
|
+
if (this.#stopped || this.#aborted || this.#destroyed) {
|
|
199
|
+
resolve(void 0);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (this.#paused || this.#pending.length === 0) {
|
|
203
|
+
this.#wakes.push(take);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
resolve(this.#pending.shift());
|
|
207
|
+
};
|
|
208
|
+
take();
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
#wake() {
|
|
212
|
+
const resolver = this.#wakes.shift();
|
|
213
|
+
if (resolver !== void 0) resolver();
|
|
214
|
+
}
|
|
215
|
+
#wakeAll() {
|
|
216
|
+
const resolvers = this.#wakes.splice(0);
|
|
217
|
+
for (const resolver of resolvers) resolver();
|
|
218
|
+
}
|
|
219
|
+
#drain(error) {
|
|
220
|
+
while (this.#pending.length > 0) {
|
|
221
|
+
const entry = this.#pending.shift();
|
|
222
|
+
if (entry === void 0) continue;
|
|
223
|
+
this.#live.delete(entry.id);
|
|
224
|
+
this.#store?.remove(entry.id).catch(() => {});
|
|
225
|
+
entry.reject(error);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async #persist(store, id, input, options) {
|
|
229
|
+
await store.save({
|
|
230
|
+
id,
|
|
231
|
+
input,
|
|
232
|
+
attempts: 0
|
|
233
|
+
});
|
|
234
|
+
if (this.#destroyed || this.#aborted || this.#stopped) {
|
|
235
|
+
await store.remove(id).catch(() => {});
|
|
236
|
+
throw new Error("queue is stopped");
|
|
237
|
+
}
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
this.#live.add(id);
|
|
240
|
+
this.#pending.push({
|
|
241
|
+
id,
|
|
242
|
+
input,
|
|
243
|
+
options,
|
|
244
|
+
attempts: 0,
|
|
245
|
+
resolve,
|
|
246
|
+
reject
|
|
247
|
+
});
|
|
248
|
+
this.#emitter.emit("enqueue", id);
|
|
249
|
+
this.#wake();
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async #saveAttempt(entry, attempts) {
|
|
253
|
+
try {
|
|
254
|
+
await this.#store?.save({
|
|
255
|
+
id: entry.id,
|
|
256
|
+
input: entry.input,
|
|
257
|
+
attempts
|
|
258
|
+
});
|
|
259
|
+
} catch {}
|
|
260
|
+
}
|
|
261
|
+
async #run(entry) {
|
|
262
|
+
const retries = Math.max(0, entry.options?.retries ?? this.#retries);
|
|
263
|
+
const timeout = Math.max(0, entry.options?.timeout ?? this.#timeout);
|
|
264
|
+
const signal = entry.options?.signal;
|
|
265
|
+
this.#emitter.emit("start", entry.id);
|
|
266
|
+
for (let attempt = entry.attempts;; attempt += 1) {
|
|
267
|
+
if (this.#abort.aborted) return this.#settle(entry, {
|
|
268
|
+
success: false,
|
|
269
|
+
error: this.#abort.signal.reason
|
|
270
|
+
});
|
|
271
|
+
if (signal?.aborted) return this.#settle(entry, {
|
|
272
|
+
success: false,
|
|
273
|
+
error: signal.reason
|
|
274
|
+
});
|
|
275
|
+
if (attempt > entry.attempts) {
|
|
276
|
+
await this.#saveAttempt(entry, attempt);
|
|
277
|
+
this.#emitter.emit("retry", entry.id, attempt);
|
|
278
|
+
}
|
|
279
|
+
const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
|
|
280
|
+
if (outcome.success) return this.#settle(entry, {
|
|
281
|
+
success: true,
|
|
282
|
+
value: outcome.value
|
|
283
|
+
});
|
|
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 < retries) continue;
|
|
293
|
+
return this.#settle(entry, {
|
|
294
|
+
success: false,
|
|
295
|
+
error: outcome.error
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
#settle(entry, outcome) {
|
|
300
|
+
this.#live.delete(entry.id);
|
|
301
|
+
if (this.#store === void 0) {
|
|
302
|
+
this.#commit(entry, outcome);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
return this.#forget(this.#store, entry, outcome);
|
|
306
|
+
}
|
|
307
|
+
#commit(entry, outcome) {
|
|
308
|
+
if (outcome.success) {
|
|
309
|
+
entry.resolve(outcome.value);
|
|
310
|
+
this.#emitter.emit("success", entry.id, outcome.value);
|
|
311
|
+
} else {
|
|
312
|
+
entry.reject(outcome.error);
|
|
313
|
+
this.#emitter.emit("failure", entry.id, outcome.error);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async #forget(store, entry, outcome) {
|
|
317
|
+
try {
|
|
318
|
+
await store.remove(entry.id);
|
|
319
|
+
} catch {}
|
|
320
|
+
this.#commit(entry, outcome);
|
|
321
|
+
}
|
|
322
|
+
async #attempt(id, input, timeout, signal) {
|
|
323
|
+
const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
|
|
324
|
+
let deadline;
|
|
325
|
+
let attemptSignal = cancel;
|
|
326
|
+
if (timeout > 0) {
|
|
327
|
+
deadline = createTimeout({
|
|
328
|
+
ms: timeout,
|
|
329
|
+
signal: cancel
|
|
330
|
+
});
|
|
331
|
+
deadline.start();
|
|
332
|
+
attemptSignal = AbortSignal.any([cancel, deadline.signal]);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
return {
|
|
336
|
+
success: true,
|
|
337
|
+
value: await this.#race(id, input, attemptSignal, deadline)
|
|
338
|
+
};
|
|
339
|
+
} catch (error) {
|
|
340
|
+
return {
|
|
341
|
+
success: false,
|
|
342
|
+
error: error instanceof Error ? error : new Error(String(error), { cause: error })
|
|
343
|
+
};
|
|
344
|
+
} finally {
|
|
345
|
+
deadline?.clear();
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
#race(id, input, signal, deadline) {
|
|
349
|
+
const fault = () => deadline?.expired === true ? /* @__PURE__ */ new Error("attempt timed out") : /* @__PURE__ */ new Error("attempt aborted");
|
|
350
|
+
if (signal.aborted) return Promise.reject(fault());
|
|
351
|
+
return new Promise((resolve, reject) => {
|
|
352
|
+
const onAbort = () => reject(fault());
|
|
353
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
354
|
+
const settle = () => signal.removeEventListener("abort", onAbort);
|
|
355
|
+
Promise.resolve(this.#handler(input, {
|
|
356
|
+
id,
|
|
357
|
+
signal
|
|
358
|
+
})).then((value) => {
|
|
359
|
+
settle();
|
|
360
|
+
resolve(value);
|
|
361
|
+
}, (error) => {
|
|
362
|
+
settle();
|
|
363
|
+
reject(error);
|
|
364
|
+
});
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
//#endregion
|
|
369
|
+
//#region src/core/stores/DatabaseQueueStore.ts
|
|
370
|
+
/**
|
|
371
|
+
* A {@link QueueStoreInterface} backed by one table of the `databases` layer — a
|
|
372
|
+
* queue's durable state IS a table, so persistence reduces to keyed CRUD over a
|
|
373
|
+
* `TableInterface`.
|
|
374
|
+
*
|
|
375
|
+
* @remarks
|
|
376
|
+
* The store is driver-agnostic: it holds a single {@link TableInterface} whose
|
|
377
|
+
* backend (memory, JSON, SQLite) is chosen by whoever builds it (the factories).
|
|
378
|
+
* `save` upserts an entry by its primary key (`set`), `remove` drops one (`remove`),
|
|
379
|
+
* `load` returns every outstanding entry (`records` with no criteria), and `clear`
|
|
380
|
+
* empties the table. Reads are narrowed through the table's contract, so `load`
|
|
381
|
+
* returns typed {@link StoredEntry}`<TInput>[]` with no cast (AGENTS §1) — the table
|
|
382
|
+
* is created over the `{ id; input; attempts }` column map, which `Infer`s to exactly
|
|
383
|
+
* that row. The store holds only OUTSTANDING work (completed entries are `remove`d), so
|
|
384
|
+
* `load` on startup yields precisely the entries to resume.
|
|
385
|
+
*
|
|
386
|
+
* @typeParam TInput - The work input each {@link StoredEntry} carries
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* ```ts
|
|
390
|
+
* import { createMemoryQueueStore, stringShape } from '@src/core'
|
|
391
|
+
*
|
|
392
|
+
* const store = createMemoryQueueStore(stringShape())
|
|
393
|
+
* await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
|
|
394
|
+
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
var DatabaseQueueStore = class {
|
|
398
|
+
#table;
|
|
399
|
+
/**
|
|
400
|
+
* Wrap a table as a queue store.
|
|
401
|
+
*
|
|
402
|
+
* @param table - The {@link TableInterface} holding the outstanding entries — its
|
|
403
|
+
* row is a {@link StoredEntry}`<TInput>` (the `{ id; input; attempts }` shape)
|
|
404
|
+
*/
|
|
405
|
+
constructor(table) {
|
|
406
|
+
this.#table = table;
|
|
407
|
+
}
|
|
408
|
+
/** Upsert an entry by its `id` (a re-`save` of an existing `id` overwrites it). */
|
|
409
|
+
async save(entry) {
|
|
410
|
+
await this.#table.set(entry);
|
|
411
|
+
}
|
|
412
|
+
/** Drop a finished entry by `id`; absent is a no-op (no throw). */
|
|
413
|
+
async remove(id) {
|
|
414
|
+
await this.#table.remove(id);
|
|
415
|
+
}
|
|
416
|
+
/** Every outstanding entry — the work to resume after a restart. */
|
|
417
|
+
load() {
|
|
418
|
+
return this.#table.records();
|
|
419
|
+
}
|
|
420
|
+
/** Empty the store — drop every outstanding entry. */
|
|
421
|
+
async clear() {
|
|
422
|
+
await this.#table.clear();
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
//#endregion
|
|
426
|
+
//#region src/core/stores/MemoryQueueStore.ts
|
|
427
|
+
/**
|
|
428
|
+
* The in-memory {@link QueueStoreInterface} — a process-lifetime `Map` of
|
|
429
|
+
* {@link StoredEntry}s keyed by id, the DEFAULT store
|
|
430
|
+
* {@link import('../factories.js').createMemoryQueueStore} builds.
|
|
431
|
+
*
|
|
432
|
+
* @remarks
|
|
433
|
+
* A plain `Map<string, StoredEntry<TInput>>` (AGENTS §21 — the entry is already pure,
|
|
434
|
+
* self-contained JSON, so no `databases` table / driver codec is needed for the memory
|
|
435
|
+
* tier; this is the zero-plumbing twin of {@link DatabaseQueueStore}, which wraps a
|
|
436
|
+
* `TableInterface` for a driver-pluggable durable backend). The store holds ONLY
|
|
437
|
+
* outstanding work, so `load` yields precisely the entries to resume — though a memory
|
|
438
|
+
* store is gone when the process exits, so `restore()` recovers nothing after a real
|
|
439
|
+
* restart. For durability across restarts, build a {@link DatabaseQueueStore} over a
|
|
440
|
+
* server JSON / SQLite driver (the SAME interface, so the queue / worker never knows).
|
|
441
|
+
*
|
|
442
|
+
* - **`save` upserts an entry under its OWN `id`** (a re-`save` of an existing `id`
|
|
443
|
+
* overwrites it — `Map.set`, never a duplicate).
|
|
444
|
+
* - **`remove` drops a finished entry by `id`**; an absent `id` is a no-op (no throw).
|
|
445
|
+
* - **`load` returns every outstanding entry** as a readonly array (the `Map`'s values
|
|
446
|
+
* in insertion order — the work to resume).
|
|
447
|
+
* - **`clear` empties the store** — drop every outstanding entry.
|
|
448
|
+
*
|
|
449
|
+
* Each primitive is async (it returns a resolved `Promise`) to satisfy the
|
|
450
|
+
* {@link QueueStoreInterface} signatures, wrapping the synchronous `Map` op — so the
|
|
451
|
+
* memory and driver-backed stores are interchangeable behind the one interface. The
|
|
452
|
+
* public surface is EXACTLY `save` / `remove` / `load` / `clear` — no extra members (the
|
|
453
|
+
* §22 method bijection with {@link QueueStoreInterface}).
|
|
454
|
+
*
|
|
455
|
+
* @typeParam TInput - The work input each {@link StoredEntry} carries
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```ts
|
|
459
|
+
* import { createMemoryQueueStore, stringShape } from '@src/core'
|
|
460
|
+
*
|
|
461
|
+
* const store = createMemoryQueueStore(stringShape())
|
|
462
|
+
* await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
|
|
463
|
+
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
464
|
+
* await store.remove('job-1') // a finished entry leaves the store
|
|
465
|
+
* ```
|
|
466
|
+
*/
|
|
467
|
+
var MemoryQueueStore = class {
|
|
468
|
+
#entries = /* @__PURE__ */ new Map();
|
|
469
|
+
/** Upsert an entry under its OWN `id` (a re-`save` of an existing `id` overwrites it). */
|
|
470
|
+
save(entry) {
|
|
471
|
+
this.#entries.set(entry.id, entry);
|
|
472
|
+
return Promise.resolve();
|
|
473
|
+
}
|
|
474
|
+
/** Drop a finished entry by `id`; `Map.delete` of an absent id is already a no-op (no throw). */
|
|
475
|
+
remove(id) {
|
|
476
|
+
this.#entries.delete(id);
|
|
477
|
+
return Promise.resolve();
|
|
478
|
+
}
|
|
479
|
+
/** Every outstanding entry — the work to resume (the `Map`'s values, insertion order). */
|
|
480
|
+
load() {
|
|
481
|
+
return Promise.resolve([...this.#entries.values()]);
|
|
482
|
+
}
|
|
483
|
+
/** Empty the store — drop every outstanding entry. */
|
|
484
|
+
clear() {
|
|
485
|
+
this.#entries.clear();
|
|
486
|
+
return Promise.resolve();
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
//#endregion
|
|
490
|
+
//#region src/core/factories.ts
|
|
491
|
+
/**
|
|
492
|
+
* Create a concurrent, cooperative job queue — a bounded-concurrency engine that
|
|
493
|
+
* runs each enqueued input through a handler, with retries and a per-attempt
|
|
494
|
+
* timeout / abort, all over the L1 `Abort` / `Timeout` primitives.
|
|
495
|
+
*
|
|
496
|
+
* @remarks
|
|
497
|
+
* Worker loops PARK on a wake list when no entry is ready and are woken one-at-a-time
|
|
498
|
+
* by `enqueue` / `resume`, so an idle queue consumes no CPU (no polling). `enqueue`
|
|
499
|
+
* returns a promise that settles when the entry finally completes, fails (after its
|
|
500
|
+
* retries), or is rejected by an abort. A queue-level `abort` never retries; the
|
|
501
|
+
* lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)
|
|
502
|
+
* follows AGENTS §10. The queue is observable (§13): a typed `emitter` surfaces
|
|
503
|
+
* `enqueue` / `start` / `retry` / `success` / `failure` / `abort` / `drain`.
|
|
504
|
+
*
|
|
505
|
+
* @typeParam TInput - The work input each entry carries
|
|
506
|
+
* @typeParam TResult - The value the handler resolves for an entry
|
|
507
|
+
* @param options - The `handler` plus optional `concurrency` (default `1`),
|
|
508
|
+
* `retries` (default `0`), and a default per-attempt `timeout` in milliseconds
|
|
509
|
+
* @returns A working {@link QueueInterface}
|
|
510
|
+
*
|
|
511
|
+
* @example
|
|
512
|
+
* ```ts
|
|
513
|
+
* import { createQueue } from '@src/core'
|
|
514
|
+
*
|
|
515
|
+
* const queue = createQueue<string, number>({
|
|
516
|
+
* handler: async (url, { signal }) => (await fetch(url, { signal })).status,
|
|
517
|
+
* concurrency: 4,
|
|
518
|
+
* retries: 2,
|
|
519
|
+
* timeout: 5_000,
|
|
520
|
+
* })
|
|
521
|
+
*
|
|
522
|
+
* const status = await queue.enqueue('https://example.com')
|
|
523
|
+
* ```
|
|
524
|
+
*/
|
|
525
|
+
function createQueue(options) {
|
|
526
|
+
return new Queue(options);
|
|
527
|
+
}
|
|
528
|
+
function createDatabaseQueueStore(input, driver) {
|
|
529
|
+
return new DatabaseQueueStore(createDatabase({
|
|
530
|
+
driver,
|
|
531
|
+
tables: { entries: {
|
|
532
|
+
id: stringShape(),
|
|
533
|
+
input,
|
|
534
|
+
attempts: integerShape({ min: 0 })
|
|
535
|
+
} }
|
|
536
|
+
}).table("entries"));
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Create an in-memory {@link MemoryQueueStore} — the zero-plumbing DEFAULT queue store
|
|
540
|
+
* over a plain `Map` (the twin of {@link DatabaseQueueStore}).
|
|
541
|
+
*
|
|
542
|
+
* @remarks
|
|
543
|
+
* The convenience for a non-persistent queue store (tests, ephemeral queues): the entries
|
|
544
|
+
* live in a process-lifetime `Map` and are gone when the process exits. UNLIKE
|
|
545
|
+
* {@link createDatabaseQueueStore}, no `databases` table / driver codec is built — a queue
|
|
546
|
+
* entry is already pure JSON, so the memory tier needs no encoding (AGENTS §21). The
|
|
547
|
+
* `input` shape is accepted for SOURCE-COMPATIBILITY with the driver-backed family (every
|
|
548
|
+
* call site passes its payload shape, and the store is still typed by it through `Infer`),
|
|
549
|
+
* but a plain-`Map` store does not validate the payload — durability + contract narrowing
|
|
550
|
+
* are {@link DatabaseQueueStore}'s job. For durability across restarts, build the store
|
|
551
|
+
* over a server JSON / SQLite driver via {@link createDatabaseQueueStore} (or the server
|
|
552
|
+
* `createJSONQueueStore`).
|
|
553
|
+
*
|
|
554
|
+
* @typeParam TInput - The contract shape of each entry's `input` payload
|
|
555
|
+
* @param _input - The {@link ContractShape} for the work payload — types the store (via
|
|
556
|
+
* `Infer`); the plain-`Map` backing does not use it at runtime, so it is `_`-prefixed
|
|
557
|
+
* (AGENTS unused-arg convention) while staying in the signature for source-compatibility
|
|
558
|
+
* with the driver-backed family
|
|
559
|
+
* @returns A memory-backed {@link QueueStoreInterface}, typed by `_input`
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```ts
|
|
563
|
+
* import { createMemoryQueueStore, stringShape } from '@src/core'
|
|
564
|
+
*
|
|
565
|
+
* const store = createMemoryQueueStore(stringShape())
|
|
566
|
+
* await store.save({ id: 'job-1', input: 'task', attempts: 0 })
|
|
567
|
+
* ```
|
|
568
|
+
*/
|
|
569
|
+
function createMemoryQueueStore(_input) {
|
|
570
|
+
return new MemoryQueueStore();
|
|
571
|
+
}
|
|
572
|
+
//#endregion
|
|
573
|
+
export { DatabaseQueueStore, MemoryQueueStore, Queue, createDatabaseQueueStore, createMemoryQueueStore, createQueue };
|
|
574
|
+
|
|
575
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["#handler","#concurrency","#retries","#timeout","#store","#abort","#emitter","#pending","#live","#wakes","#spawn","#active","#paused","#stopped","#aborted","#destroyed","#persist","#wake","#drain","#wakeAll","#running","#worker","#next","#run","#saveAttempt","#settle","#attempt","#commit","#forget","#race","#table","#entries"],"sources":["../../../src/core/Queue.ts","../../../src/core/stores/DatabaseQueueStore.ts","../../../src/core/stores/MemoryQueueStore.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { AbortInterface } from '@orkestrel/abort'\nimport type { Result } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type {\n\tQueueEntry,\n\tQueueEntryOptions,\n\tQueueEventMap,\n\tQueueHandler,\n\tQueueInterface,\n\tQueueOptions,\n\tQueueStoreInterface,\n} from './types.js'\nimport { createAbort } from '@orkestrel/abort'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createTimeout } from '@orkestrel/timeout'\n\n/**\n * A concurrent, cooperative job queue.\n *\n * @remarks\n * - **Cooperative wake-park loop.** Up to `concurrency` worker loops run; each\n * takes the next pending entry, or — when none is ready (empty or paused) —\n * PARKS by awaiting a fresh promise whose resolver is held in a wake list.\n * `enqueue` / `resume` resolve one parked resolver to wake exactly one worker,\n * so idle workers consume no CPU (no busy-poll, no timers, no recursion).\n * - **FIFO + bounded concurrency.** Entries run in enqueue order; at most\n * `concurrency` are in flight at once (default `1` = strictly ordered). A surplus\n * entry waits for a worker to free up.\n * - **Per-attempt deadline + cancellation.** Each attempt's `signal` (handed to the\n * handler) fires on the per-attempt `Timeout` expiring, a queue-level `abort`, or\n * the entry's own `signal`. The handler is RACED against that signal, so an attempt\n * that ignores its `signal` still fails on the deadline. Built on the L1 `Abort` /\n * `Timeout` primitives (a queue / entry abort CLEARS the deadline, never expires it).\n * - **Retries.** A failed attempt (a handler rejection or a per-attempt timeout)\n * retries while attempts remain (`retries` + 1 total). A queue-level abort NEVER\n * retries — it rejects the entry at once; an entry-`signal` abort likewise.\n * - **Lifecycle (§10).** `pause` parks workers; `resume` wakes them; `stop` ends the\n * loops permanently and rejects pending (in-flight settle); `abort` fires the queue\n * signal (cancelling in-flight attempts) and rejects pending; `clear` drops only\n * pending; `destroy` aborts then stops, idempotently.\n * - **Durability (optional `store`).** The store mirrors only OUTSTANDING work: an\n * entry is `save`d on accept (and re-`save`d as its attempt count climbs) and\n * `remove`d the moment it settles (success or terminal failure) or is drained by a\n * lifecycle call. Accepting work durably is NOT best-effort — a failed initial `save`\n * rejects the enqueue; per-attempt persistence IS best-effort (in-memory state is\n * authoritative). A graceful shutdown empties the store; a crash leaves rows that\n * `restore()` re-runs at their persisted attempt count (queue-default retries /\n * timeout, no per-entry signal). At-least-once — handlers should be idempotent.\n * - **Observable (§13).** The owned {@link emitter} ({@link QueueEventMap}) carries the\n * lifecycle moments — `enqueue` / `start` / `retry` / `success` / `failure` / `abort` /\n * `drain` — for fire-and-forget observers. Every event is emitted directly, strictly AFTER\n * the relevant wake / park / settle transition; the emitter isolates a listener throw and\n * routes it to its `error` handler (the `error` option), so a buggy observer can NEVER\n * reorder, throw into, or corrupt the cooperative wake-park / settle-once engine: `active`\n * stays balanced and no parked worker is stranded regardless of what a listener does.\n * Observation is purely a side-channel.\n */\nexport class Queue<TInput, TResult> implements QueueInterface<TInput, TResult> {\n\treadonly #handler: QueueHandler<TInput, TResult>\n\treadonly #concurrency: number\n\treadonly #retries: number\n\treadonly #timeout: number\n\t// Optional durable backing — mirrors outstanding entries so a restart can resume them.\n\treadonly #store: QueueStoreInterface<TInput> | undefined\n\t// The queue-level cancellation — its signal is a parent of every attempt's signal.\n\treadonly #abort: AbortInterface = createAbort()\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// wake-park / settle-once loop.\n\treadonly #emitter: Emitter<QueueEventMap<TResult>>\n\n\treadonly #pending: QueueEntry<TInput, TResult>[] = []\n\t// The ids of LIVE entries — pending or in-flight on THIS queue. An id is added when\n\t// an entry is accepted (enqueue / restore launch) and removed when it settles or is\n\t// drained. `restore` skips any id already here, so it is idempotent + safe on a\n\t// non-idle queue (it re-launches only genuinely-outstanding-but-not-live rows).\n\treadonly #live = new Set<string>()\n\t// Resolvers of parked worker loops, woken one-at-a-time (FIFO).\n\treadonly #wakes: (() => void)[] = []\n\t#active = 0\n\t#running = 0\n\t#paused = false\n\t#stopped = false\n\t#aborted = false\n\t#destroyed = false\n\n\tconstructor(options: QueueOptions<TInput, TResult>) {\n\t\tthis.#handler = options.handler\n\t\tthis.#concurrency = Math.max(1, options.concurrency ?? 1)\n\t\tthis.#retries = Math.max(0, options.retries ?? 0)\n\t\tthis.#timeout = Math.max(0, options.timeout ?? 0)\n\t\tthis.#store = options.store\n\t\tthis.#emitter = new Emitter<QueueEventMap<TResult>>({ on: options?.on, error: options?.error })\n\t\tthis.#spawn()\n\t}\n\n\tget emitter(): EmitterInterface<QueueEventMap<TResult>> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#pending.length + this.#active\n\t}\n\n\tget active(): number {\n\t\treturn this.#active\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#paused\n\t}\n\n\tget stopped(): boolean {\n\t\treturn this.#stopped || this.#aborted\n\t}\n\n\tenqueue(input: TInput, options?: QueueEntryOptions): Promise<TResult> {\n\t\tif (this.#destroyed) return Promise.reject(new Error('queue is destroyed'))\n\t\tif (this.#aborted) return Promise.reject(new Error('queue is aborted'))\n\t\tif (this.#stopped) return Promise.reject(new Error('queue is stopped'))\n\t\tconst id = options?.id ?? crypto.randomUUID()\n\t\t// Durable backing: persist the entry BEFORE it becomes runnable, so accepting\n\t\t// work is durable (a failed initial `save` rejects the enqueue).\n\t\tif (this.#store !== undefined) return this.#persist(this.#store, id, input, options)\n\t\t// No store: keep the fast path 100% synchronous — push and wake within the\n\t\t// executor so `count` reflects the entry the moment `enqueue` returns.\n\t\treturn new Promise<TResult>((resolve, reject) => {\n\t\t\tthis.#live.add(id)\n\t\t\tthis.#pending.push({ id, input, options, attempts: 0, resolve, reject })\n\t\t\t// Observe the accepted entry — AFTER it is live + pending, BEFORE `#wake` (never\n\t\t\t// inside the wake resolver-shift), so a swallowed listener throw can't perturb the\n\t\t\t// worker the wake is about to release.\n\t\t\tthis.#emitter.emit('enqueue', id)\n\t\t\tthis.#wake()\n\t\t})\n\t}\n\n\tasync restore(): Promise<void> {\n\t\tif (this.#store === undefined || this.#stopped || this.#aborted || this.#destroyed) return\n\t\tconst entries = await this.#store.load()\n\t\t// The queue may have been aborted / destroyed during the `load()` await — re-check\n\t\t// the halt flags before launching, so nothing is pushed that would never run + never\n\t\t// settle (mirrors `#persist`'s post-await re-check).\n\t\tif (this.#destroyed || this.#aborted || this.#stopped) return\n\t\tfor (const entry of entries) {\n\t\t\t// Idempotent + safe on a live queue: a row whose id is ALREADY live (pending or\n\t\t\t// in-flight) is skipped, so `restore()` never double-launches an id that is still\n\t\t\t// running — it re-launches only genuinely-outstanding-but-not-live rows.\n\t\t\tif (this.#live.has(entry.id)) continue\n\t\t\t// Resume each at its persisted attempt count. There is no original caller, so\n\t\t\t// swallow a terminal rejection on the result promise (it isn't an unhandled\n\t\t\t// rejection); the row is still removed by `#run`'s settle. Restored entries use\n\t\t\t// the queue-default retries / timeout and carry no per-entry signal.\n\t\t\tconst result = new Promise<TResult>((resolve, reject) => {\n\t\t\t\tthis.#live.add(entry.id)\n\t\t\t\tthis.#pending.push({\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tinput: entry.input,\n\t\t\t\t\toptions: undefined,\n\t\t\t\t\tattempts: entry.attempts,\n\t\t\t\t\tresolve,\n\t\t\t\t\treject,\n\t\t\t\t})\n\t\t\t\t// A restored row is an accepted entry — observe it like a fresh `enqueue`, AFTER\n\t\t\t\t// it is live + pending and BEFORE `#wake`.\n\t\t\t\tthis.#emitter.emit('enqueue', entry.id)\n\t\t\t\tthis.#wake()\n\t\t\t})\n\t\t\tresult.catch(() => {})\n\t\t}\n\t}\n\n\tstart(): void {\n\t\tif (this.#aborted || this.#destroyed) return\n\t\tthis.#stopped = false\n\t\tthis.#spawn()\n\t}\n\n\tstop(): void {\n\t\tif (this.#stopped) return\n\t\tthis.#stopped = true\n\t\tthis.#drain(new Error('queue is stopped'))\n\t\tthis.#wakeAll()\n\t}\n\n\tpause(): void {\n\t\tif (this.#paused || this.stopped || this.#destroyed) return\n\t\tthis.#paused = true\n\t}\n\n\tresume(): void {\n\t\tif (!this.#paused || this.stopped || this.#destroyed) return\n\t\tthis.#paused = false\n\t\tthis.#wakeAll()\n\t}\n\n\tabort(reason?: unknown): void {\n\t\tif (this.#aborted) return\n\t\tthis.#aborted = true\n\t\tthis.#abort.abort(reason)\n\t\tthis.#drain(this.#abort.signal.reason)\n\t\tthis.#wakeAll()\n\t\t// Observe the abort — AFTER the queue signal fired, pending was drained, and the\n\t\t// parked workers were woken, so a swallowed listener throw can't perturb the cancel.\n\t\tthis.#emitter.emit('abort', this.#abort.signal.reason)\n\t}\n\n\tclear(): void {\n\t\tthis.#drain(new Error('queue cleared'))\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.abort()\n\t\tthis.#stopped = true\n\t\tthis.#wakeAll()\n\t}\n\n\t// Spawn worker loops up to `concurrency`, unless the queue is no longer running.\n\t#spawn(): void {\n\t\tif (this.#stopped || this.#aborted || this.#destroyed) return\n\t\twhile (this.#running < this.#concurrency) {\n\t\t\tthis.#running += 1\n\t\t\tvoid this.#worker()\n\t\t}\n\t}\n\n\t// One cooperative worker loop: take the next entry or park; exit when halted.\n\tasync #worker(): Promise<void> {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst entry = await this.#next()\n\t\t\t\tif (entry === undefined) break\n\t\t\t\tthis.#active += 1\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#run(entry)\n\t\t\t\t} finally {\n\t\t\t\t\tthis.#active -= 1\n\t\t\t\t\t// Observe the queue going idle — AFTER the settle balanced `#active` back\n\t\t\t\t\t// down; the entry that just finished was the last in flight and nothing is\n\t\t\t\t\t// pending, so this is the clean drained boundary (the transition fires once,\n\t\t\t\t\t// since exactly one decrement brings `#active` to 0 with an empty backlog).\n\t\t\t\t\tif (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit('drain')\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#running -= 1\n\t\t}\n\t}\n\n\t// The park point: resolve to the next ready entry, or `undefined` once halted.\n\t#next(): Promise<QueueEntry<TInput, TResult> | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst take = (): void => {\n\t\t\t\tif (this.#stopped || this.#aborted || this.#destroyed) {\n\t\t\t\t\tresolve(undefined)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (this.#paused || this.#pending.length === 0) {\n\t\t\t\t\t// Park: hold a resolver that re-checks when a wake fires.\n\t\t\t\t\tthis.#wakes.push(take)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(this.#pending.shift())\n\t\t\t}\n\t\t\ttake()\n\t\t})\n\t}\n\n\t// Wake exactly one parked worker (FIFO) — for a single new entry.\n\t#wake(): void {\n\t\tconst resolver = this.#wakes.shift()\n\t\tif (resolver !== undefined) resolver()\n\t}\n\n\t// Wake every parked worker — for resume / halt, where all must re-check.\n\t#wakeAll(): void {\n\t\tconst resolvers = this.#wakes.splice(0)\n\t\tfor (const resolver of resolvers) resolver()\n\t}\n\n\t// Reject and discard every pending entry (in-flight entries are untouched). The\n\t// in-memory drain stays synchronous; the store catches up via a fire-and-forget\n\t// `remove` per drained entry (its rejection swallowed). In-flight rows are removed\n\t// by their own settle, not wiped here — so a precise `remove`, never `store.clear()`.\n\t#drain(error: unknown): void {\n\t\twhile (this.#pending.length > 0) {\n\t\t\tconst entry = this.#pending.shift()\n\t\t\tif (entry === undefined) continue\n\t\t\tthis.#live.delete(entry.id)\n\t\t\tvoid this.#store?.remove(entry.id).catch(() => {})\n\t\t\tentry.reject(error)\n\t\t}\n\t}\n\n\t// Durably accept an entry: `save` it (at `attempts: 0`) BEFORE it becomes runnable,\n\t// so accepting work is durable. A failed initial `save` PROPAGATES (rejects the\n\t// enqueue). The queue may have died during the `await`, so re-check the halt flags\n\t// afterwards — if so, remove the just-saved row and reject rather than running it.\n\tasync #persist(\n\t\tstore: QueueStoreInterface<TInput>,\n\t\tid: string,\n\t\tinput: TInput,\n\t\toptions: QueueEntryOptions | undefined,\n\t): Promise<TResult> {\n\t\tawait store.save({ id, input, attempts: 0 })\n\t\tif (this.#destroyed || this.#aborted || this.#stopped) {\n\t\t\tawait store.remove(id).catch(() => {})\n\t\t\tthrow new Error('queue is stopped')\n\t\t}\n\t\treturn new Promise<TResult>((resolve, reject) => {\n\t\t\tthis.#live.add(id)\n\t\t\tthis.#pending.push({ id, input, options, attempts: 0, resolve, reject })\n\t\t\t// Observe the durably-accepted entry — AFTER the `save` succeeded + it is live +\n\t\t\t// pending, BEFORE `#wake`.\n\t\t\tthis.#emitter.emit('enqueue', id)\n\t\t\tthis.#wake()\n\t\t})\n\t}\n\n\t// Best-effort persist of the climbing attempt count on a retry — in-memory state is\n\t// authoritative, so a store error is swallowed (the entry keeps running regardless).\n\tasync #saveAttempt(entry: QueueEntry<TInput, TResult>, attempts: number): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#store?.save({ id: entry.id, input: entry.input, attempts })\n\t\t} catch {\n\t\t\t// Per-attempt persistence is best-effort; the in-memory attempt count is the truth.\n\t\t}\n\t}\n\n\t// Run one entry through its attempts, settling the promise `enqueue` returned.\n\t// Resumes at `entry.attempts` (0 for fresh, the persisted count when restored), so\n\t// the retry budget is honoured across a restart. Every terminal exit removes the\n\t// durable row BEFORE settling (`#settle`); a queue / entry abort never retries.\n\tasync #run(entry: QueueEntry<TInput, TResult>): Promise<void> {\n\t\tconst retries = Math.max(0, entry.options?.retries ?? this.#retries)\n\t\tconst timeout = Math.max(0, entry.options?.timeout ?? this.#timeout)\n\t\tconst signal = entry.options?.signal\n\t\t// Observe the attempt beginning — the entry is already dequeued and `#active` was\n\t\t// incremented by `#worker`, so this is strictly after that transition (NOT inside the\n\t\t// park `take`); the per-attempt `#race` below is left emit-free.\n\t\tthis.#emitter.emit('start', entry.id)\n\t\tfor (let attempt = entry.attempts; ; attempt += 1) {\n\t\t\t// A queue / entry abort rejects at once — never retried.\n\t\t\tif (this.#abort.aborted)\n\t\t\t\treturn this.#settle(entry, { success: false, error: this.#abort.signal.reason })\n\t\t\tif (signal?.aborted) return this.#settle(entry, { success: false, error: signal.reason })\n\t\t\t// On a RETRY only, persist the climbing attempt count (best-effort) + observe the\n\t\t\t// retry — AFTER the prior attempt failed, BEFORE re-running (the 1-based attempt no.).\n\t\t\tif (attempt > entry.attempts) {\n\t\t\t\tawait this.#saveAttempt(entry, attempt)\n\t\t\t\tthis.#emitter.emit('retry', entry.id, attempt)\n\t\t\t}\n\t\t\tconst outcome = await this.#attempt(entry.id, entry.input, timeout, signal)\n\t\t\tif (outcome.success) return this.#settle(entry, { success: true, value: outcome.value })\n\t\t\tif (this.#abort.aborted)\n\t\t\t\treturn this.#settle(entry, { success: false, error: this.#abort.signal.reason })\n\t\t\tif (signal?.aborted) return this.#settle(entry, { success: false, error: signal.reason })\n\t\t\tif (attempt < retries) continue\n\t\t\treturn this.#settle(entry, { success: false, error: outcome.error })\n\t\t}\n\t}\n\n\t// Settle one entry from a `#run` exit. WITHOUT a store there is nothing to remove, so\n\t// settle (resolve / reject) SYNCHRONOUSLY and return `void` — no awaited call, no\n\t// thenable to adopt — so the no-store path's microtask timing is byte-for-byte as before\n\t// (`#active` decrements exactly when it always did). WITH a store, return the async\n\t// remove-then-settle so the durable row is gone before the promise settles. A single\n\t// helper keeps the four exit points clean and the `TResult` type at the call site. The\n\t// `outcome` carries what to settle WITH so the terminal `success` / `failure` event fires\n\t// strictly AFTER the resolve / reject (and after the durable `remove` on the store path),\n\t// in the same microtask position the settle has always occupied — observation only.\n\t#settle(entry: QueueEntry<TInput, TResult>, outcome: Result<TResult>): void | Promise<void> {\n\t\t// The entry is no longer live — drop its id so a concurrent `restore` may re-launch\n\t\t// the row should it linger in the store (the single removal point for a settled run,\n\t\t// balancing every accept; the drain path removes the ids it rejects instead).\n\t\tthis.#live.delete(entry.id)\n\t\tif (this.#store === undefined) {\n\t\t\tthis.#commit(entry, outcome)\n\t\t\treturn\n\t\t}\n\t\treturn this.#forget(this.#store, entry, outcome)\n\t}\n\n\t// Resolve / reject the entry, THEN observe the terminal settle. The resolve / reject runs\n\t// FIRST and unchanged (the promise settles exactly as before); the emit is strictly after\n\t// it, so an isolated listener throw can't reorder or re-enter the settle-once latch.\n\t#commit(entry: QueueEntry<TInput, TResult>, outcome: Result<TResult>): void {\n\t\tif (outcome.success) {\n\t\t\tentry.resolve(outcome.value)\n\t\t\tthis.#emitter.emit('success', entry.id, outcome.value)\n\t\t} else {\n\t\t\tentry.reject(outcome.error)\n\t\t\tthis.#emitter.emit('failure', entry.id, outcome.error)\n\t\t}\n\t}\n\n\t// Best-effort remove the durable row (swallowing any store error → at-least-once), THEN\n\t// commit the settle — so a completed entry's promise resolves only after its row is gone\n\t// (a `load()` after `await`ing the entry sees it removed), and the terminal event fires\n\t// after that (`#commit`).\n\tasync #forget(\n\t\tstore: QueueStoreInterface<TInput>,\n\t\tentry: QueueEntry<TInput, TResult>,\n\t\toutcome: Result<TResult>,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait store.remove(entry.id)\n\t\t} catch {\n\t\t\t// Best-effort: the in-memory settle is authoritative; a failed remove leaves a\n\t\t\t// stale row that `restore()` would re-run (at-least-once) — handlers stay idempotent.\n\t\t}\n\t\tthis.#commit(entry, outcome)\n\t}\n\n\t// One attempt: build the combined signal, race the handler against it, settle.\n\tasync #attempt(\n\t\tid: string,\n\t\tinput: TInput,\n\t\ttimeout: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<Result<TResult>> {\n\t\t// Cancellation = the queue abort, plus the entry's own signal when present.\n\t\tconst cancel =\n\t\t\tsignal === undefined ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal])\n\t\t// A deadline that the cancellation CLEARS (never expires); the handler's signal\n\t\t// fires on cancellation OR on the deadline expiring.\n\t\tlet deadline: TimeoutInterface | undefined\n\t\tlet attemptSignal = cancel\n\t\tif (timeout > 0) {\n\t\t\tdeadline = createTimeout({ ms: timeout, signal: cancel })\n\t\t\tdeadline.start()\n\t\t\tattemptSignal = AbortSignal.any([cancel, deadline.signal])\n\t\t}\n\t\ttry {\n\t\t\tconst value = await this.#race(id, input, attemptSignal, deadline)\n\t\t\treturn { success: true, value }\n\t\t} catch (error: unknown) {\n\t\t\t// A non-`Error` handler rejection is wrapped, preserving the original as `cause`.\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error), { cause: error }),\n\t\t\t}\n\t\t} finally {\n\t\t\tdeadline?.clear()\n\t\t}\n\t}\n\n\t// Race the handler against its signal: the deadline expiring or a cancellation\n\t// settles the attempt as a failure even if the handler ignores its `signal`. The\n\t// handler receives the entry's stable `id` (its idempotency key — equal across every\n\t// attempt and a crash-replay) plus the per-attempt `signal`.\n\t#race(\n\t\tid: string,\n\t\tinput: TInput,\n\t\tsignal: AbortSignal,\n\t\tdeadline: TimeoutInterface | undefined,\n\t): Promise<TResult> {\n\t\tconst fault = (): Error =>\n\t\t\tdeadline?.expired === true ? new Error('attempt timed out') : new Error('attempt aborted')\n\t\tif (signal.aborted) return Promise.reject(fault())\n\t\treturn new Promise<TResult>((resolve, reject) => {\n\t\t\tconst onAbort = (): void => reject(fault())\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\tconst settle = (): void => signal.removeEventListener('abort', onAbort)\n\t\t\tPromise.resolve(this.#handler(input, { id, signal })).then(\n\t\t\t\t(value) => {\n\t\t\t\t\tsettle()\n\t\t\t\t\tresolve(value)\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tsettle()\n\t\t\t\t\treject(error)\n\t\t\t\t},\n\t\t\t)\n\t\t})\n\t}\n}\n","import type { TableInterface } from '@orkestrel/database'\nimport type { QueueStoreInterface, StoredEntry } from '../types.js'\n\n/**\n * A {@link QueueStoreInterface} backed by one table of the `databases` layer — a\n * queue's durable state IS a table, so persistence reduces to keyed CRUD over a\n * `TableInterface`.\n *\n * @remarks\n * The store is driver-agnostic: it holds a single {@link TableInterface} whose\n * backend (memory, JSON, SQLite) is chosen by whoever builds it (the factories).\n * `save` upserts an entry by its primary key (`set`), `remove` drops one (`remove`),\n * `load` returns every outstanding entry (`records` with no criteria), and `clear`\n * empties the table. Reads are narrowed through the table's contract, so `load`\n * returns typed {@link StoredEntry}`<TInput>[]` with no cast (AGENTS §1) — the table\n * is created over the `{ id; input; attempts }` column map, which `Infer`s to exactly\n * that row. The store holds only OUTSTANDING work (completed entries are `remove`d), so\n * `load` on startup yields precisely the entries to resume.\n *\n * @typeParam TInput - The work input each {@link StoredEntry} carries\n *\n * @example\n * ```ts\n * import { createMemoryQueueStore, stringShape } from '@src/core'\n *\n * const store = createMemoryQueueStore(stringShape())\n * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })\n * const outstanding = await store.load() // readonly StoredEntry<string>[]\n * ```\n */\nexport class DatabaseQueueStore<TInput> implements QueueStoreInterface<TInput> {\n\treadonly #table: TableInterface<StoredEntry<TInput>>\n\n\t/**\n\t * Wrap a table as a queue store.\n\t *\n\t * @param table - The {@link TableInterface} holding the outstanding entries — its\n\t * row is a {@link StoredEntry}`<TInput>` (the `{ id; input; attempts }` shape)\n\t */\n\tconstructor(table: TableInterface<StoredEntry<TInput>>) {\n\t\tthis.#table = table\n\t}\n\n\t/** Upsert an entry by its `id` (a re-`save` of an existing `id` overwrites it). */\n\tasync save(entry: StoredEntry<TInput>): Promise<void> {\n\t\tawait this.#table.set(entry)\n\t}\n\n\t/** Drop a finished entry by `id`; absent is a no-op (no throw). */\n\tasync remove(id: string): Promise<void> {\n\t\tawait this.#table.remove(id)\n\t}\n\n\t/** Every outstanding entry — the work to resume after a restart. */\n\tload(): Promise<readonly StoredEntry<TInput>[]> {\n\t\treturn this.#table.records()\n\t}\n\n\t/** Empty the store — drop every outstanding entry. */\n\tasync clear(): Promise<void> {\n\t\tawait this.#table.clear()\n\t}\n}\n","import type { QueueStoreInterface, StoredEntry } from '../types.js'\n\n/**\n * The in-memory {@link QueueStoreInterface} — a process-lifetime `Map` of\n * {@link StoredEntry}s keyed by id, the DEFAULT store\n * {@link import('../factories.js').createMemoryQueueStore} builds.\n *\n * @remarks\n * A plain `Map<string, StoredEntry<TInput>>` (AGENTS §21 — the entry is already pure,\n * self-contained JSON, so no `databases` table / driver codec is needed for the memory\n * tier; this is the zero-plumbing twin of {@link DatabaseQueueStore}, which wraps a\n * `TableInterface` for a driver-pluggable durable backend). The store holds ONLY\n * outstanding work, so `load` yields precisely the entries to resume — though a memory\n * store is gone when the process exits, so `restore()` recovers nothing after a real\n * restart. For durability across restarts, build a {@link DatabaseQueueStore} over a\n * server JSON / SQLite driver (the SAME interface, so the queue / worker never knows).\n *\n * - **`save` upserts an entry under its OWN `id`** (a re-`save` of an existing `id`\n * overwrites it — `Map.set`, never a duplicate).\n * - **`remove` drops a finished entry by `id`**; an absent `id` is a no-op (no throw).\n * - **`load` returns every outstanding entry** as a readonly array (the `Map`'s values\n * in insertion order — the work to resume).\n * - **`clear` empties the store** — drop every outstanding entry.\n *\n * Each primitive is async (it returns a resolved `Promise`) to satisfy the\n * {@link QueueStoreInterface} signatures, wrapping the synchronous `Map` op — so the\n * memory and driver-backed stores are interchangeable behind the one interface. The\n * public surface is EXACTLY `save` / `remove` / `load` / `clear` — no extra members (the\n * §22 method bijection with {@link QueueStoreInterface}).\n *\n * @typeParam TInput - The work input each {@link StoredEntry} carries\n *\n * @example\n * ```ts\n * import { createMemoryQueueStore, stringShape } from '@src/core'\n *\n * const store = createMemoryQueueStore(stringShape())\n * await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })\n * const outstanding = await store.load() // readonly StoredEntry<string>[]\n * await store.remove('job-1') // a finished entry leaves the store\n * ```\n */\nexport class MemoryQueueStore<TInput> implements QueueStoreInterface<TInput> {\n\treadonly #entries = new Map<string, StoredEntry<TInput>>()\n\n\t/** Upsert an entry under its OWN `id` (a re-`save` of an existing `id` overwrites it). */\n\tsave(entry: StoredEntry<TInput>): Promise<void> {\n\t\tthis.#entries.set(entry.id, entry)\n\t\treturn Promise.resolve()\n\t}\n\n\t/** Drop a finished entry by `id`; `Map.delete` of an absent id is already a no-op (no throw). */\n\tremove(id: string): Promise<void> {\n\t\tthis.#entries.delete(id)\n\t\treturn Promise.resolve()\n\t}\n\n\t/** Every outstanding entry — the work to resume (the `Map`'s values, insertion order). */\n\tload(): Promise<readonly StoredEntry<TInput>[]> {\n\t\treturn Promise.resolve([...this.#entries.values()])\n\t}\n\n\t/** Empty the store — drop every outstanding entry. */\n\tclear(): Promise<void> {\n\t\tthis.#entries.clear()\n\t\treturn Promise.resolve()\n\t}\n}\n","import type { ContractShape, Infer } from '@orkestrel/contract'\nimport type { DriverInterface, TableInterface } from '@orkestrel/database'\nimport type { QueueInterface, QueueOptions, QueueStoreInterface, StoredEntry } from './types.js'\nimport { integerShape, stringShape } from '@orkestrel/contract'\nimport { createDatabase } from '@orkestrel/database'\nimport { Queue } from './Queue.js'\nimport { DatabaseQueueStore } from './stores/DatabaseQueueStore.js'\nimport { MemoryQueueStore } from './stores/MemoryQueueStore.js'\n\n/**\n * Create a concurrent, cooperative job queue — a bounded-concurrency engine that\n * runs each enqueued input through a handler, with retries and a per-attempt\n * timeout / abort, all over the L1 `Abort` / `Timeout` primitives.\n *\n * @remarks\n * Worker loops PARK on a wake list when no entry is ready and are woken one-at-a-time\n * by `enqueue` / `resume`, so an idle queue consumes no CPU (no polling). `enqueue`\n * returns a promise that settles when the entry finally completes, fails (after its\n * retries), or is rejected by an abort. A queue-level `abort` never retries; the\n * lifecycle (`start` / `stop` / `pause` / `resume` / `abort` / `clear` / `destroy`)\n * follows AGENTS §10. The queue is observable (§13): a typed `emitter` surfaces\n * `enqueue` / `start` / `retry` / `success` / `failure` / `abort` / `drain`.\n *\n * @typeParam TInput - The work input each entry carries\n * @typeParam TResult - The value the handler resolves for an entry\n * @param options - The `handler` plus optional `concurrency` (default `1`),\n * `retries` (default `0`), and a default per-attempt `timeout` in milliseconds\n * @returns A working {@link QueueInterface}\n *\n * @example\n * ```ts\n * import { createQueue } from '@src/core'\n *\n * const queue = createQueue<string, number>({\n * \thandler: async (url, { signal }) => (await fetch(url, { signal })).status,\n * \tconcurrency: 4,\n * \tretries: 2,\n * \ttimeout: 5_000,\n * })\n *\n * const status = await queue.enqueue('https://example.com')\n * ```\n */\nexport function createQueue<TInput, TResult>(\n\toptions: QueueOptions<TInput, TResult>,\n): QueueInterface<TInput, TResult> {\n\treturn new Queue(options)\n}\n\n/**\n * Create a {@link DatabaseQueueStore} over any {@link DriverInterface} — the durable,\n * driver-pluggable backing for a queue's outstanding entries.\n *\n * @remarks\n * Builds a one-table database (`entries`, keyed by `id`) over the supplied driver, with\n * the fixed `{ id; input; attempts }` column map — `input` is the caller's own shape,\n * so the stored entry's payload is validated and typed by it. Reads narrow through that\n * contract, so the store's `load` returns typed `StoredEntry<Infer<TInput>>[]` with no\n * cast. Pass `createMemoryDriver()` for an ephemeral store, a server `createJSONDriver` /\n * `createSQLiteDriver` for a persistent one — the durability is the driver's job, the\n * store engine is shared. The `input` shape must be JSON-serializable to survive a JSON\n * or SQLite driver.\n *\n * @typeParam TInput - The contract shape of each entry's `input` payload\n * @param input - The {@link ContractShape} for the work payload (used directly as the\n * `input` column)\n * @param driver - The storage backend the entries persist to\n * @returns A {@link QueueStoreInterface} over the driver, typed by `input`\n *\n * @example\n * ```ts\n * import { createDatabaseQueueStore, createMemoryDriver, objectShape, stringShape } from '@src/core'\n *\n * const store = createDatabaseQueueStore(\n * \tobjectShape({ url: stringShape(), label: stringShape() }),\n * \tcreateMemoryDriver(),\n * )\n * await store.save({ id: 'job-1', input: { url: 'https://example.com', label: 'home' }, attempts: 0 })\n * ```\n */\nexport function createDatabaseQueueStore<TInput extends ContractShape>(\n\tinput: TInput,\n\tdriver: DriverInterface,\n): QueueStoreInterface<Infer<TInput>>\n// The public signature above types the store by `Infer<TInput>`. The implementation\n// runs on the BROAD `ContractShape`, so the `entries` row is built and the table read\n// once — not re-instantiated per concrete `TInput`. (A generic `TInput` member can't be\n// reduced by the contract's object inference, which would also trip TS's\n// instantiation-depth guard; the broad body sidesteps both, and every call site still\n// sees the precise `Infer<TInput>` from the overload.) No cast: the contract-narrowed\n// row satisfies `StoredEntry<unknown>` structurally.\nexport function createDatabaseQueueStore(\n\tinput: ContractShape,\n\tdriver: DriverInterface,\n): QueueStoreInterface<unknown> {\n\tconst columns = { id: stringShape(), input, attempts: integerShape({ min: 0 }) }\n\tconst database = createDatabase({ driver, tables: { entries: columns } })\n\tconst table: TableInterface<StoredEntry<unknown>> = database.table('entries')\n\treturn new DatabaseQueueStore(table)\n}\n\n/**\n * Create an in-memory {@link MemoryQueueStore} — the zero-plumbing DEFAULT queue store\n * over a plain `Map` (the twin of {@link DatabaseQueueStore}).\n *\n * @remarks\n * The convenience for a non-persistent queue store (tests, ephemeral queues): the entries\n * live in a process-lifetime `Map` and are gone when the process exits. UNLIKE\n * {@link createDatabaseQueueStore}, no `databases` table / driver codec is built — a queue\n * entry is already pure JSON, so the memory tier needs no encoding (AGENTS §21). The\n * `input` shape is accepted for SOURCE-COMPATIBILITY with the driver-backed family (every\n * call site passes its payload shape, and the store is still typed by it through `Infer`),\n * but a plain-`Map` store does not validate the payload — durability + contract narrowing\n * are {@link DatabaseQueueStore}'s job. For durability across restarts, build the store\n * over a server JSON / SQLite driver via {@link createDatabaseQueueStore} (or the server\n * `createJSONQueueStore`).\n *\n * @typeParam TInput - The contract shape of each entry's `input` payload\n * @param _input - The {@link ContractShape} for the work payload — types the store (via\n * `Infer`); the plain-`Map` backing does not use it at runtime, so it is `_`-prefixed\n * (AGENTS unused-arg convention) while staying in the signature for source-compatibility\n * with the driver-backed family\n * @returns A memory-backed {@link QueueStoreInterface}, typed by `_input`\n *\n * @example\n * ```ts\n * import { createMemoryQueueStore, stringShape } from '@src/core'\n *\n * const store = createMemoryQueueStore(stringShape())\n * await store.save({ id: 'job-1', input: 'task', attempts: 0 })\n * ```\n */\nexport function createM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