@orkestrel/queue 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/core/index.cjs +810 -285
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +277 -133
- package/dist/src/core/index.d.ts +277 -133
- package/dist/src/core/index.js +805 -286
- package/dist/src/core/index.js.map +1 -1
- package/package.json +22 -19
package/dist/src/core/index.js
CHANGED
|
@@ -1,49 +1,138 @@
|
|
|
1
|
+
import { cloneJSONValue, createContract, integerShape, isFiniteNumber, isInteger, isString, preview, stringShape } from "@orkestrel/contract";
|
|
1
2
|
import { createAbort } from "@orkestrel/abort";
|
|
2
3
|
import { Emitter } from "@orkestrel/emitter";
|
|
3
4
|
import { createTimeout } from "@orkestrel/timeout";
|
|
4
|
-
import { integerShape, stringShape } from "@orkestrel/contract";
|
|
5
5
|
import { createDatabase } from "@orkestrel/database";
|
|
6
|
+
//#region src/core/errors.ts
|
|
7
|
+
/**
|
|
8
|
+
* Error carrying a machine-readable queue category and optional context.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* new QueueError('duplicate id', { code: 'duplicate', context: { id: 'job-1' } })
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
var QueueError = class extends Error {
|
|
16
|
+
name = "QueueError";
|
|
17
|
+
code;
|
|
18
|
+
context;
|
|
19
|
+
/**
|
|
20
|
+
* Create a queue error.
|
|
21
|
+
*
|
|
22
|
+
* @param message - Human-readable failure description
|
|
23
|
+
* @param options - Machine-readable category, optional context, and optional cause
|
|
24
|
+
*/
|
|
25
|
+
constructor(message, options) {
|
|
26
|
+
const cause = options.cause;
|
|
27
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
28
|
+
this.code = options.code;
|
|
29
|
+
this.context = options.context === void 0 ? void 0 : Object.freeze({ ...options.context });
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Determine whether an unknown value is a {@link QueueError}.
|
|
34
|
+
*
|
|
35
|
+
* @param value - The value to inspect
|
|
36
|
+
* @returns `true` only for a `QueueError`; hostile values return `false`
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* try {
|
|
41
|
+
* await queue.clear()
|
|
42
|
+
* } catch (error) {
|
|
43
|
+
* if (isQueueError(error) && error.code === 'cleanup') report(error.context)
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
function isQueueError(value) {
|
|
48
|
+
try {
|
|
49
|
+
return value instanceof QueueError;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/core/validators.ts
|
|
56
|
+
/**
|
|
57
|
+
* Determine whether a value is a valid queue concurrency.
|
|
58
|
+
*
|
|
59
|
+
* @param value - Value to inspect
|
|
60
|
+
* @returns Whether the value is a positive safe integer
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* isQueueConcurrency(4) // true
|
|
65
|
+
* isQueueConcurrency(0) // false
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
function isQueueConcurrency(value) {
|
|
69
|
+
return isInteger(value) && Number.isSafeInteger(value) && value > 0;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Determine whether a value is a valid queue retry count.
|
|
73
|
+
*
|
|
74
|
+
* @param value - Value to inspect
|
|
75
|
+
* @returns Whether the value is a nonnegative safe integer
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* isQueueRetries(2) // true
|
|
80
|
+
* isQueueRetries(-1) // false
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
function isQueueRetries(value) {
|
|
84
|
+
return isInteger(value) && Number.isSafeInteger(value) && value >= 0;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Determine whether a value is a valid queue timeout.
|
|
88
|
+
*
|
|
89
|
+
* @param value - Value to inspect
|
|
90
|
+
* @returns Whether the value is within the native timer range, inclusive
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* isQueueTimeout(500) // true
|
|
95
|
+
* isQueueTimeout(2_147_483_648) // false
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
function isQueueTimeout(value) {
|
|
99
|
+
return isFiniteNumber(value) && value >= 0 && value <= 2147483647;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Determine whether a value is a native abort signal usable by the queue.
|
|
103
|
+
*
|
|
104
|
+
* @param value - Value to inspect
|
|
105
|
+
* @returns Whether the value carries the native `AbortSignal` internal slot
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```ts
|
|
109
|
+
* isQueueSignal(new AbortController().signal) // true
|
|
110
|
+
* isQueueSignal({}) // false
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
function isQueueSignal(value) {
|
|
114
|
+
try {
|
|
115
|
+
const getter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")?.get;
|
|
116
|
+
if (getter === void 0) return false;
|
|
117
|
+
Reflect.apply(getter, value, []);
|
|
118
|
+
return true;
|
|
119
|
+
} catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
6
124
|
//#region src/core/Queue.ts
|
|
7
125
|
/**
|
|
8
|
-
* A concurrent, cooperative job queue.
|
|
126
|
+
* A concurrent, cooperative FIFO job queue with optional outstanding-work persistence.
|
|
9
127
|
*
|
|
10
|
-
* @
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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.
|
|
128
|
+
* @typeParam TInput - The work input each entry carries
|
|
129
|
+
* @typeParam TResult - The value each entry resolves
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* const queue = new Queue<number, number>({ handler: (input) => input * 2 })
|
|
134
|
+
* const result = await queue.enqueue(21)
|
|
135
|
+
* ```
|
|
47
136
|
*/
|
|
48
137
|
var Queue = class {
|
|
49
138
|
#handler;
|
|
@@ -53,35 +142,73 @@ var Queue = class {
|
|
|
53
142
|
#store;
|
|
54
143
|
#abort = createAbort();
|
|
55
144
|
#emitter;
|
|
145
|
+
#entries = /* @__PURE__ */ new Map();
|
|
146
|
+
#live = /* @__PURE__ */ new Map();
|
|
56
147
|
#pending = [];
|
|
57
|
-
#
|
|
148
|
+
#claims = /* @__PURE__ */ new Set();
|
|
58
149
|
#wakes = [];
|
|
59
|
-
#
|
|
60
|
-
#
|
|
150
|
+
#workers = /* @__PURE__ */ new Set();
|
|
151
|
+
#admissions = /* @__PURE__ */ new Map();
|
|
152
|
+
#orphans = /* @__PURE__ */ new Set();
|
|
153
|
+
#cleanups = /* @__PURE__ */ new Map();
|
|
154
|
+
#admission = Promise.resolve();
|
|
155
|
+
#stopPromise;
|
|
156
|
+
#abortPromise;
|
|
157
|
+
#destroyPromise;
|
|
158
|
+
#generation = 0;
|
|
61
159
|
#paused = false;
|
|
62
160
|
#stopped = false;
|
|
63
161
|
#aborted = false;
|
|
64
162
|
#destroyed = false;
|
|
163
|
+
#drained = true;
|
|
164
|
+
/**
|
|
165
|
+
* Create a queue.
|
|
166
|
+
*
|
|
167
|
+
* @param options - Handler, validated execution limits, persistence, and observation hooks
|
|
168
|
+
*/
|
|
65
169
|
constructor(options) {
|
|
170
|
+
const concurrency = options.concurrency ?? 1;
|
|
171
|
+
const retries = options.retries ?? 0;
|
|
172
|
+
const timeout = options.timeout ?? 0;
|
|
173
|
+
if (!isQueueConcurrency(concurrency)) throw new QueueError("queue concurrency must be a positive safe integer", {
|
|
174
|
+
code: "invalid",
|
|
175
|
+
context: {
|
|
176
|
+
option: "concurrency",
|
|
177
|
+
value: concurrency
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
if (!isQueueRetries(retries)) throw new QueueError("queue retries must be a nonnegative safe integer", {
|
|
181
|
+
code: "invalid",
|
|
182
|
+
context: {
|
|
183
|
+
option: "retries",
|
|
184
|
+
value: retries
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
if (!isQueueTimeout(timeout)) throw new QueueError("queue timeout must be within the native timer range", {
|
|
188
|
+
code: "invalid",
|
|
189
|
+
context: {
|
|
190
|
+
option: "timeout",
|
|
191
|
+
value: timeout
|
|
192
|
+
}
|
|
193
|
+
});
|
|
66
194
|
this.#handler = options.handler;
|
|
67
|
-
this.#concurrency =
|
|
68
|
-
this.#retries =
|
|
69
|
-
this.#timeout =
|
|
195
|
+
this.#concurrency = concurrency;
|
|
196
|
+
this.#retries = retries;
|
|
197
|
+
this.#timeout = timeout;
|
|
70
198
|
this.#store = options.store;
|
|
71
199
|
this.#emitter = new Emitter({
|
|
72
|
-
on: options
|
|
73
|
-
error: options
|
|
200
|
+
...options.on === void 0 ? {} : { on: options.on },
|
|
201
|
+
...options.error === void 0 ? {} : { error: options.error }
|
|
74
202
|
});
|
|
75
|
-
this.#spawn();
|
|
76
203
|
}
|
|
77
204
|
get emitter() {
|
|
78
205
|
return this.#emitter;
|
|
79
206
|
}
|
|
80
207
|
get count() {
|
|
81
|
-
return this.#
|
|
208
|
+
return this.#live.size;
|
|
82
209
|
}
|
|
83
210
|
get active() {
|
|
84
|
-
return this.#
|
|
211
|
+
return this.#claims.size;
|
|
85
212
|
}
|
|
86
213
|
get paused() {
|
|
87
214
|
return this.#paused;
|
|
@@ -89,124 +216,348 @@ var Queue = class {
|
|
|
89
216
|
get stopped() {
|
|
90
217
|
return this.#stopped || this.#aborted;
|
|
91
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Reserve and submit one FIFO entry.
|
|
221
|
+
*
|
|
222
|
+
* @param input - Handler input
|
|
223
|
+
* @param options - Optional id, retry/timeout overrides, and entry abort signal
|
|
224
|
+
* @returns The entry's settle-once execution promise
|
|
225
|
+
* @throws {QueueError} Synchronously when an option is inaccessible or invalid
|
|
226
|
+
*/
|
|
92
227
|
enqueue(input, options) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
id,
|
|
102
|
-
input,
|
|
103
|
-
options,
|
|
104
|
-
attempts: 0,
|
|
105
|
-
resolve,
|
|
106
|
-
reject
|
|
228
|
+
let supplied;
|
|
229
|
+
try {
|
|
230
|
+
supplied = options?.id;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
throw new QueueError("queue entry id could not be read", {
|
|
233
|
+
code: "invalid",
|
|
234
|
+
cause: error,
|
|
235
|
+
context: { option: "id" }
|
|
107
236
|
});
|
|
108
|
-
|
|
109
|
-
|
|
237
|
+
}
|
|
238
|
+
if (supplied !== void 0 && !isString(supplied)) throw new QueueError("queue entry id must be a string", {
|
|
239
|
+
code: "invalid",
|
|
240
|
+
context: {
|
|
241
|
+
option: "id",
|
|
242
|
+
value: supplied
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
let retries;
|
|
246
|
+
try {
|
|
247
|
+
retries = options?.retries;
|
|
248
|
+
} catch (error) {
|
|
249
|
+
throw new QueueError("queue retries could not be read", {
|
|
250
|
+
code: "invalid",
|
|
251
|
+
cause: error,
|
|
252
|
+
context: { option: "retries" }
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
if (retries !== void 0 && !isQueueRetries(retries)) throw new QueueError("queue retries must be a nonnegative safe integer", {
|
|
256
|
+
code: "invalid",
|
|
257
|
+
context: {
|
|
258
|
+
option: "retries",
|
|
259
|
+
value: retries
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
let timeout;
|
|
263
|
+
try {
|
|
264
|
+
timeout = options?.timeout;
|
|
265
|
+
} catch (error) {
|
|
266
|
+
throw new QueueError("queue timeout could not be read", {
|
|
267
|
+
code: "invalid",
|
|
268
|
+
cause: error,
|
|
269
|
+
context: { option: "timeout" }
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
if (timeout !== void 0 && !isQueueTimeout(timeout)) throw new QueueError("queue timeout must be within the native timer range", {
|
|
273
|
+
code: "invalid",
|
|
274
|
+
context: {
|
|
275
|
+
option: "timeout",
|
|
276
|
+
value: timeout
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
let signal;
|
|
280
|
+
try {
|
|
281
|
+
signal = options?.signal;
|
|
282
|
+
} catch (error) {
|
|
283
|
+
throw new QueueError("queue signal could not be read", {
|
|
284
|
+
code: "invalid",
|
|
285
|
+
cause: error,
|
|
286
|
+
context: { option: "signal" }
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
if (signal !== void 0 && !isQueueSignal(signal)) throw new QueueError("queue signal must be an AbortSignal", {
|
|
290
|
+
code: "invalid",
|
|
291
|
+
context: {
|
|
292
|
+
option: "signal",
|
|
293
|
+
value: signal
|
|
294
|
+
}
|
|
110
295
|
});
|
|
296
|
+
const normalized = options === void 0 ? void 0 : Object.freeze({
|
|
297
|
+
...supplied === void 0 ? {} : { id: supplied },
|
|
298
|
+
...retries === void 0 ? {} : { retries },
|
|
299
|
+
...timeout === void 0 ? {} : { timeout },
|
|
300
|
+
...signal === void 0 ? {} : { signal }
|
|
301
|
+
});
|
|
302
|
+
if (this.#destroyed) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
|
|
303
|
+
if (this.#aborted) return Promise.reject(new QueueError("queue is aborted", { code: "aborted" }));
|
|
304
|
+
if (this.#stopped) return Promise.reject(new QueueError("queue is stopped", { code: "stopped" }));
|
|
305
|
+
const id = supplied ?? crypto.randomUUID();
|
|
306
|
+
if (this.#live.has(id)) return Promise.reject(new QueueError("queue entry id is already live", {
|
|
307
|
+
code: "duplicate",
|
|
308
|
+
context: { id }
|
|
309
|
+
}));
|
|
310
|
+
const token = this.#reserve(id, input, normalized, 0);
|
|
311
|
+
if (this.#store === void 0) this.#accept(token);
|
|
312
|
+
else this.#schedule(token);
|
|
313
|
+
return token.promise;
|
|
111
314
|
}
|
|
315
|
+
/** Load and accept every outstanding stored entry from the current lifecycle generation. */
|
|
112
316
|
async restore() {
|
|
113
|
-
if (this.#store === void 0 || this
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
reject
|
|
317
|
+
if (this.#store === void 0 || this.stopped || this.#destroyed) return;
|
|
318
|
+
const generation = this.#generation;
|
|
319
|
+
let entries;
|
|
320
|
+
try {
|
|
321
|
+
const loaded = await this.#store.load();
|
|
322
|
+
const snapshots = [];
|
|
323
|
+
for (const stored of loaded) {
|
|
324
|
+
const id = stored.id;
|
|
325
|
+
const input = stored.input;
|
|
326
|
+
const attempts = stored.attempts;
|
|
327
|
+
if (!isString(id) || !isQueueRetries(attempts)) throw new QueueError("queue store returned an invalid entry", {
|
|
328
|
+
code: "store",
|
|
329
|
+
context: { operation: "load" }
|
|
127
330
|
});
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
331
|
+
snapshots.push(Object.freeze({
|
|
332
|
+
id,
|
|
333
|
+
input,
|
|
334
|
+
attempts
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
entries = snapshots;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
throw new QueueError("queue store load failed", {
|
|
340
|
+
code: "store",
|
|
341
|
+
cause: error,
|
|
342
|
+
context: { operation: "load" }
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
if (generation !== this.#generation || this.stopped || this.#destroyed) return;
|
|
346
|
+
for (const stored of entries) {
|
|
347
|
+
if (generation !== this.#generation || this.stopped || this.#destroyed) return;
|
|
348
|
+
if (this.#live.has(stored.id)) continue;
|
|
349
|
+
const token = this.#reserve(stored.id, stored.input, void 0, stored.attempts);
|
|
350
|
+
this.#accept(token);
|
|
351
|
+
token.promise.catch(() => {});
|
|
131
352
|
}
|
|
132
353
|
}
|
|
354
|
+
/** Begin or restart worker execution unless the queue is terminal. */
|
|
133
355
|
start() {
|
|
134
356
|
if (this.#aborted || this.#destroyed) return;
|
|
135
357
|
this.#stopped = false;
|
|
358
|
+
this.#stopPromise = void 0;
|
|
136
359
|
this.#spawn();
|
|
137
360
|
}
|
|
361
|
+
/** Reject non-active work and await current-loop and durable cleanup quiescence. */
|
|
138
362
|
stop() {
|
|
139
|
-
if (this.#
|
|
363
|
+
if (this.#destroyPromise !== void 0) return this.#destroyPromise;
|
|
364
|
+
if (this.#abortPromise !== void 0) return this.#abortPromise;
|
|
365
|
+
if (this.#stopped && this.#stopPromise !== void 0) return this.#stopPromise;
|
|
366
|
+
const barrier = Promise.withResolvers();
|
|
367
|
+
this.#stopPromise = barrier.promise;
|
|
140
368
|
this.#stopped = true;
|
|
141
|
-
this.#
|
|
369
|
+
this.#generation += 1;
|
|
370
|
+
const existing = [...this.#cleanups.values()];
|
|
371
|
+
const cleanup = [...this.#drain(new QueueError("queue is stopped", { code: "stopped" })), ...this.#cleanOrphans(true)];
|
|
372
|
+
const tasks = [
|
|
373
|
+
...this.#workers,
|
|
374
|
+
...this.#admissions.values(),
|
|
375
|
+
...existing,
|
|
376
|
+
...cleanup
|
|
377
|
+
];
|
|
142
378
|
this.#wakeAll();
|
|
379
|
+
this.#settleBarrier(barrier, tasks, "queue stop cleanup failed");
|
|
380
|
+
return barrier.promise;
|
|
143
381
|
}
|
|
382
|
+
/** Suspend new execution while leaving active entries untouched. */
|
|
144
383
|
pause() {
|
|
145
384
|
if (this.#paused || this.stopped || this.#destroyed) return;
|
|
146
385
|
this.#paused = true;
|
|
147
386
|
}
|
|
387
|
+
/** Continue execution after a pause. */
|
|
148
388
|
resume() {
|
|
149
389
|
if (!this.#paused || this.stopped || this.#destroyed) return;
|
|
150
390
|
this.#paused = false;
|
|
151
391
|
this.#wakeAll();
|
|
152
392
|
}
|
|
393
|
+
/**
|
|
394
|
+
* Cancel the queue and await owned cleanup.
|
|
395
|
+
*
|
|
396
|
+
* @param reason - Optional cause carried by the coded abort error
|
|
397
|
+
* @returns The stable abort barrier
|
|
398
|
+
*/
|
|
153
399
|
abort(reason) {
|
|
154
|
-
if (this.#
|
|
400
|
+
if (this.#abortPromise !== void 0) return this.#abortPromise;
|
|
401
|
+
const barrier = Promise.withResolvers();
|
|
402
|
+
this.#abortPromise = barrier.promise;
|
|
155
403
|
this.#aborted = true;
|
|
156
|
-
this.#
|
|
157
|
-
this.#
|
|
404
|
+
this.#stopped = true;
|
|
405
|
+
this.#generation += 1;
|
|
406
|
+
const error = new QueueError(reason instanceof Error ? reason.message : "queue is aborted", {
|
|
407
|
+
code: "aborted",
|
|
408
|
+
...reason === void 0 ? {} : { cause: reason }
|
|
409
|
+
});
|
|
410
|
+
this.#abort.abort(error);
|
|
411
|
+
const existing = [...this.#cleanups.values()];
|
|
412
|
+
const cleanup = [...this.#drain(error), ...this.#cleanOrphans(true)];
|
|
413
|
+
const tasks = [
|
|
414
|
+
...this.#workers,
|
|
415
|
+
...this.#admissions.values(),
|
|
416
|
+
...existing,
|
|
417
|
+
...cleanup
|
|
418
|
+
];
|
|
158
419
|
this.#wakeAll();
|
|
159
|
-
this.#emitter.emit("abort",
|
|
420
|
+
this.#emitter.emit("abort", error);
|
|
421
|
+
this.#settleBarrier(barrier, tasks, "queue abort cleanup failed");
|
|
422
|
+
return barrier.promise;
|
|
160
423
|
}
|
|
424
|
+
/** Reject non-active work and await its durable cleanup. */
|
|
161
425
|
clear() {
|
|
162
|
-
this.#
|
|
426
|
+
if (this.#destroyed) return Promise.reject(new QueueError("queue is destroyed", { code: "destroyed" }));
|
|
427
|
+
const existing = [];
|
|
428
|
+
for (const [token, cleanup] of this.#cleanups) if (!this.#claims.has(token)) existing.push(cleanup);
|
|
429
|
+
const cleanup = [...this.#drain(new QueueError("queue is cleared", { code: "cleared" })), ...this.#cleanOrphans(false)];
|
|
430
|
+
return this.#finish([
|
|
431
|
+
...this.#admissions.values(),
|
|
432
|
+
...existing,
|
|
433
|
+
...cleanup
|
|
434
|
+
], "queue clear cleanup failed");
|
|
163
435
|
}
|
|
436
|
+
/** Tear down once, destroying the emitter only after cleanup finishes. */
|
|
164
437
|
destroy() {
|
|
165
|
-
if (this.#
|
|
438
|
+
if (this.#destroyPromise !== void 0) return this.#destroyPromise;
|
|
439
|
+
const barrier = Promise.withResolvers();
|
|
440
|
+
this.#destroyPromise = barrier.promise;
|
|
166
441
|
this.#destroyed = true;
|
|
167
|
-
this.abort();
|
|
168
|
-
this.#
|
|
169
|
-
|
|
442
|
+
const aborting = this.abort(new QueueError("queue is destroyed", { code: "destroyed" }));
|
|
443
|
+
this.#settleDestroy(barrier, aborting);
|
|
444
|
+
return barrier.promise;
|
|
445
|
+
}
|
|
446
|
+
#reserve(id, input, options, attempts) {
|
|
447
|
+
const token = Promise.withResolvers();
|
|
448
|
+
this.#entries.set(token, {
|
|
449
|
+
id,
|
|
450
|
+
input,
|
|
451
|
+
options,
|
|
452
|
+
attempts,
|
|
453
|
+
settled: false
|
|
454
|
+
});
|
|
455
|
+
this.#live.set(id, token);
|
|
456
|
+
this.#drained = false;
|
|
457
|
+
return token;
|
|
458
|
+
}
|
|
459
|
+
#schedule(token) {
|
|
460
|
+
const task = this.#admission.then(() => this.#admit(token));
|
|
461
|
+
this.#admissions.set(token, task);
|
|
462
|
+
this.#admission = task.catch(() => {});
|
|
463
|
+
task.finally(() => this.#admissions.delete(token)).catch(() => {});
|
|
464
|
+
}
|
|
465
|
+
async #admit(token) {
|
|
466
|
+
const entry = this.#entries.get(token);
|
|
467
|
+
if (entry === void 0 || this.#store === void 0) return;
|
|
468
|
+
try {
|
|
469
|
+
await this.#store.save({
|
|
470
|
+
id: entry.id,
|
|
471
|
+
input: entry.input,
|
|
472
|
+
attempts: entry.attempts
|
|
473
|
+
});
|
|
474
|
+
} catch (error) {
|
|
475
|
+
try {
|
|
476
|
+
await this.#cleanup(token);
|
|
477
|
+
} catch (cleanup) {
|
|
478
|
+
this.#settleToken(token, {
|
|
479
|
+
success: false,
|
|
480
|
+
error: cleanup
|
|
481
|
+
});
|
|
482
|
+
this.#emitDrain();
|
|
483
|
+
throw cleanup;
|
|
484
|
+
}
|
|
485
|
+
this.#settleToken(token, {
|
|
486
|
+
success: false,
|
|
487
|
+
error: new QueueError(error instanceof Error ? error.message : "queue admission save failed", {
|
|
488
|
+
code: "store",
|
|
489
|
+
cause: error,
|
|
490
|
+
context: {
|
|
491
|
+
id: entry.id,
|
|
492
|
+
operation: "save"
|
|
493
|
+
}
|
|
494
|
+
})
|
|
495
|
+
});
|
|
496
|
+
this.#emitDrain();
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (entry.settled || this.#aborted || this.#destroyed || this.#stopped) {
|
|
500
|
+
await this.#discard(token);
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
this.#accept(token);
|
|
504
|
+
}
|
|
505
|
+
#accept(token) {
|
|
506
|
+
const entry = this.#entries.get(token);
|
|
507
|
+
if (entry === void 0) return;
|
|
508
|
+
this.#pending.push(token);
|
|
509
|
+
this.#emitter.emit("enqueue", entry.id);
|
|
510
|
+
this.#spawn();
|
|
511
|
+
this.#wake();
|
|
170
512
|
}
|
|
171
513
|
#spawn() {
|
|
172
514
|
if (this.#stopped || this.#aborted || this.#destroyed) return;
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
this.#
|
|
515
|
+
const demand = Math.min(this.#concurrency, this.#claims.size + this.#pending.length);
|
|
516
|
+
while (this.#workers.size < demand) {
|
|
517
|
+
const generation = this.#generation;
|
|
518
|
+
const worker = this.#worker(generation);
|
|
519
|
+
this.#workers.add(worker);
|
|
520
|
+
worker.finally(() => {
|
|
521
|
+
this.#workers.delete(worker);
|
|
522
|
+
this.#spawn();
|
|
523
|
+
}).catch(() => {});
|
|
176
524
|
}
|
|
177
525
|
}
|
|
178
|
-
async #worker() {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
this.#
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
this.#active -= 1;
|
|
188
|
-
if (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit("drain");
|
|
189
|
-
}
|
|
526
|
+
async #worker(generation) {
|
|
527
|
+
while (generation === this.#generation) {
|
|
528
|
+
const token = await this.#next(generation);
|
|
529
|
+
if (token === void 0) return;
|
|
530
|
+
try {
|
|
531
|
+
await this.#run(token);
|
|
532
|
+
} catch (error) {
|
|
533
|
+
await this.#fail(token, error);
|
|
534
|
+
throw error;
|
|
190
535
|
}
|
|
191
|
-
} finally {
|
|
192
|
-
this.#running -= 1;
|
|
193
536
|
}
|
|
194
537
|
}
|
|
195
|
-
#next() {
|
|
196
|
-
return new Promise((resolve) =>
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
538
|
+
#next(generation) {
|
|
539
|
+
return new Promise((resolve) => this.#take(generation, resolve));
|
|
540
|
+
}
|
|
541
|
+
#take(generation, resolve) {
|
|
542
|
+
if (generation !== this.#generation || this.#stopped || this.#aborted || this.#destroyed) {
|
|
543
|
+
resolve(void 0);
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (this.#paused || this.#pending.length === 0) {
|
|
547
|
+
this.#wakes.push(() => this.#take(generation, resolve));
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const token = this.#pending.shift();
|
|
551
|
+
if (token === void 0) {
|
|
552
|
+
this.#wakes.push(() => this.#take(generation, resolve));
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
if (this.#entries.get(token) === void 0) {
|
|
556
|
+
this.#take(generation, resolve);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
this.#claims.add(token);
|
|
560
|
+
resolve(token);
|
|
210
561
|
}
|
|
211
562
|
#wake() {
|
|
212
563
|
const resolver = this.#wakes.shift();
|
|
@@ -217,107 +568,186 @@ var Queue = class {
|
|
|
217
568
|
for (const resolver of resolvers) resolver();
|
|
218
569
|
}
|
|
219
570
|
#drain(error) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
571
|
+
for (const token of this.#admissions.keys()) this.#settleToken(token, {
|
|
572
|
+
success: false,
|
|
573
|
+
error
|
|
574
|
+
});
|
|
575
|
+
const tokens = this.#pending.splice(0);
|
|
576
|
+
const cleanup = [];
|
|
577
|
+
for (const token of tokens) {
|
|
578
|
+
this.#settleToken(token, {
|
|
579
|
+
success: false,
|
|
580
|
+
error
|
|
581
|
+
});
|
|
582
|
+
cleanup.push(this.#discard(token));
|
|
226
583
|
}
|
|
584
|
+
return cleanup;
|
|
227
585
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
await
|
|
236
|
-
|
|
586
|
+
#cleanOrphans(claimed) {
|
|
587
|
+
const cleanup = [];
|
|
588
|
+
for (const token of this.#orphans) if (claimed || !this.#claims.has(token)) cleanup.push(this.#discard(token));
|
|
589
|
+
return cleanup;
|
|
590
|
+
}
|
|
591
|
+
async #discard(token) {
|
|
592
|
+
try {
|
|
593
|
+
await this.#cleanup(token);
|
|
594
|
+
} finally {
|
|
595
|
+
this.#emitDrain();
|
|
237
596
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
597
|
+
}
|
|
598
|
+
#cleanup(token) {
|
|
599
|
+
const current = this.#cleanups.get(token);
|
|
600
|
+
if (current !== void 0) return current;
|
|
601
|
+
const barrier = Promise.withResolvers();
|
|
602
|
+
this.#cleanups.set(token, barrier.promise);
|
|
603
|
+
this.#clean(token, barrier);
|
|
604
|
+
return barrier.promise;
|
|
605
|
+
}
|
|
606
|
+
async #clean(token, barrier) {
|
|
607
|
+
const entry = this.#entries.get(token);
|
|
608
|
+
if (entry === void 0) {
|
|
609
|
+
barrier.resolve();
|
|
610
|
+
this.#cleanups.delete(token);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
if (this.#store !== void 0) await this.#store.remove(entry.id);
|
|
615
|
+
this.#release(token);
|
|
616
|
+
barrier.resolve();
|
|
617
|
+
} catch (error) {
|
|
618
|
+
if (this.#live.get(entry.id) === token) this.#orphans.add(token);
|
|
619
|
+
barrier.reject(new QueueError("queue entry cleanup failed", {
|
|
620
|
+
code: "cleanup",
|
|
621
|
+
cause: error,
|
|
622
|
+
context: {
|
|
623
|
+
id: entry.id,
|
|
624
|
+
operation: "remove"
|
|
625
|
+
}
|
|
626
|
+
}));
|
|
627
|
+
} finally {
|
|
628
|
+
if (this.#cleanups.get(token) === barrier.promise) this.#cleanups.delete(token);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
#release(token) {
|
|
632
|
+
const entry = this.#entries.get(token);
|
|
633
|
+
if (entry === void 0 || this.#live.get(entry.id) !== token) return;
|
|
634
|
+
this.#live.delete(entry.id);
|
|
635
|
+
this.#orphans.delete(token);
|
|
636
|
+
if (entry.settled) this.#entries.delete(token);
|
|
637
|
+
}
|
|
638
|
+
async #run(token) {
|
|
639
|
+
const entry = this.#entries.get(token);
|
|
640
|
+
if (entry === void 0) return;
|
|
641
|
+
const retries = entry.options?.retries ?? this.#retries;
|
|
642
|
+
const timeout = entry.options?.timeout ?? this.#timeout;
|
|
643
|
+
const signal = entry.options?.signal;
|
|
644
|
+
let completed = entry.attempts;
|
|
645
|
+
this.#emitter.emit("start", entry.id);
|
|
646
|
+
while (true) {
|
|
647
|
+
if (await this.#interrupt(token, signal)) return;
|
|
648
|
+
const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
|
|
649
|
+
completed += 1;
|
|
650
|
+
if (outcome.success) {
|
|
651
|
+
await this.#settle(token, outcome);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (await this.#interrupt(token, signal)) return;
|
|
655
|
+
if (completed > retries) {
|
|
656
|
+
await this.#settle(token, outcome);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
await this.#saveAttempt(token, completed);
|
|
660
|
+
this.#emitter.emit("retry", entry.id, completed);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async #interrupt(token, signal) {
|
|
664
|
+
const entry = this.#entries.get(token);
|
|
665
|
+
if (entry === void 0) return true;
|
|
666
|
+
if (this.#abort.aborted) {
|
|
667
|
+
await this.#settle(token, {
|
|
668
|
+
success: false,
|
|
669
|
+
error: this.#abort.signal.reason
|
|
247
670
|
});
|
|
248
|
-
|
|
249
|
-
|
|
671
|
+
return true;
|
|
672
|
+
}
|
|
673
|
+
if (!signal?.aborted) return false;
|
|
674
|
+
await this.#settle(token, {
|
|
675
|
+
success: false,
|
|
676
|
+
error: new QueueError(signal.reason instanceof Error ? signal.reason.message : "queue entry is aborted", {
|
|
677
|
+
code: "aborted",
|
|
678
|
+
cause: signal.reason,
|
|
679
|
+
context: { id: entry.id }
|
|
680
|
+
})
|
|
250
681
|
});
|
|
682
|
+
return true;
|
|
251
683
|
}
|
|
252
|
-
async #saveAttempt(
|
|
684
|
+
async #saveAttempt(token, attempts) {
|
|
685
|
+
const entry = this.#entries.get(token);
|
|
686
|
+
if (this.#store === void 0 || entry === void 0) return;
|
|
253
687
|
try {
|
|
254
|
-
await this.#store
|
|
688
|
+
await this.#store.save({
|
|
255
689
|
id: entry.id,
|
|
256
690
|
input: entry.input,
|
|
257
691
|
attempts
|
|
258
692
|
});
|
|
259
693
|
} catch {}
|
|
260
694
|
}
|
|
261
|
-
async #
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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, {
|
|
695
|
+
async #fail(token, error) {
|
|
696
|
+
if (!this.#claims.has(token)) return;
|
|
697
|
+
try {
|
|
698
|
+
await this.#cleanup(token);
|
|
699
|
+
} catch (cleanup) {
|
|
700
|
+
this.#finishEntry(token, {
|
|
289
701
|
success: false,
|
|
290
|
-
error:
|
|
702
|
+
error: cleanup
|
|
291
703
|
});
|
|
292
|
-
|
|
293
|
-
|
|
704
|
+
throw cleanup;
|
|
705
|
+
}
|
|
706
|
+
this.#finishEntry(token, {
|
|
707
|
+
success: false,
|
|
708
|
+
error
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
async #settle(token, outcome) {
|
|
712
|
+
try {
|
|
713
|
+
await this.#cleanup(token);
|
|
714
|
+
} catch (error) {
|
|
715
|
+
this.#finishEntry(token, {
|
|
294
716
|
success: false,
|
|
295
|
-
error
|
|
717
|
+
error
|
|
296
718
|
});
|
|
719
|
+
throw error;
|
|
297
720
|
}
|
|
721
|
+
this.#finishEntry(token, outcome);
|
|
298
722
|
}
|
|
299
|
-
#
|
|
300
|
-
this.#
|
|
301
|
-
|
|
302
|
-
|
|
723
|
+
#finishEntry(token, outcome) {
|
|
724
|
+
if (!this.#claims.delete(token)) return;
|
|
725
|
+
const entry = this.#entries.get(token);
|
|
726
|
+
const drain = this.#latchDrain();
|
|
727
|
+
if (entry === void 0 || !this.#settleToken(token, outcome)) {
|
|
728
|
+
if (drain) this.#emitter.emit("drain");
|
|
303
729
|
return;
|
|
304
730
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
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
|
-
}
|
|
731
|
+
if (outcome.success) this.#emitter.emit("success", entry.id, outcome.value);
|
|
732
|
+
else this.#emitter.emit("failure", entry.id, outcome.error);
|
|
733
|
+
if (drain) this.#emitter.emit("drain");
|
|
315
734
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
735
|
+
#settleToken(token, outcome) {
|
|
736
|
+
const entry = this.#entries.get(token);
|
|
737
|
+
if (entry === void 0 || entry.settled) return false;
|
|
738
|
+
entry.settled = true;
|
|
739
|
+
if (outcome.success) token.resolve(outcome.value);
|
|
740
|
+
else token.reject(outcome.error);
|
|
741
|
+
if (this.#live.get(entry.id) !== token) this.#entries.delete(token);
|
|
742
|
+
return true;
|
|
743
|
+
}
|
|
744
|
+
#latchDrain() {
|
|
745
|
+
if (this.#drained || this.#claims.size !== 0 || this.#live.size !== 0) return false;
|
|
746
|
+
this.#drained = true;
|
|
747
|
+
return true;
|
|
748
|
+
}
|
|
749
|
+
#emitDrain() {
|
|
750
|
+
if (this.#latchDrain()) this.#emitter.emit("drain");
|
|
321
751
|
}
|
|
322
752
|
async #attempt(id, input, timeout, signal) {
|
|
323
753
|
const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
|
|
@@ -339,31 +769,92 @@ var Queue = class {
|
|
|
339
769
|
} catch (error) {
|
|
340
770
|
return {
|
|
341
771
|
success: false,
|
|
342
|
-
error: error instanceof Error ? error : new Error(
|
|
772
|
+
error: error instanceof Error ? error : new Error(preview(error), { cause: error })
|
|
343
773
|
};
|
|
344
774
|
} finally {
|
|
345
775
|
deadline?.clear();
|
|
346
776
|
}
|
|
347
777
|
}
|
|
348
778
|
#race(id, input, signal, deadline) {
|
|
349
|
-
|
|
350
|
-
|
|
779
|
+
if (signal.aborted) return Promise.reject(new QueueError(deadline?.expired === true ? "queue attempt timed out" : "queue attempt aborted", {
|
|
780
|
+
code: deadline?.expired === true ? "timeout" : "aborted",
|
|
781
|
+
cause: signal.reason,
|
|
782
|
+
context: { id }
|
|
783
|
+
}));
|
|
784
|
+
const cleanup = new AbortController();
|
|
351
785
|
return new Promise((resolve, reject) => {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
settle();
|
|
360
|
-
resolve(value);
|
|
361
|
-
}, (error) => {
|
|
362
|
-
settle();
|
|
363
|
-
reject(error);
|
|
786
|
+
signal.addEventListener("abort", () => reject(new QueueError(deadline?.expired === true ? "queue attempt timed out" : "queue attempt aborted", {
|
|
787
|
+
code: deadline?.expired === true ? "timeout" : "aborted",
|
|
788
|
+
cause: signal.reason,
|
|
789
|
+
context: { id }
|
|
790
|
+
})), {
|
|
791
|
+
once: true,
|
|
792
|
+
signal: cleanup.signal
|
|
364
793
|
});
|
|
794
|
+
try {
|
|
795
|
+
Promise.resolve(this.#handler(input, {
|
|
796
|
+
id,
|
|
797
|
+
signal
|
|
798
|
+
})).then((value) => {
|
|
799
|
+
cleanup.abort();
|
|
800
|
+
resolve(value);
|
|
801
|
+
}, (error) => {
|
|
802
|
+
cleanup.abort();
|
|
803
|
+
reject(error);
|
|
804
|
+
});
|
|
805
|
+
} catch (error) {
|
|
806
|
+
cleanup.abort();
|
|
807
|
+
reject(error);
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
async #finish(tasks, message) {
|
|
812
|
+
const results = await Promise.allSettled(tasks);
|
|
813
|
+
const errors = [];
|
|
814
|
+
for (const result of results) if (result.status === "rejected" && !errors.includes(result.reason)) errors.push(result.reason);
|
|
815
|
+
if (errors.length === 0) return;
|
|
816
|
+
const error = errors[0];
|
|
817
|
+
if (errors.length === 1 && isQueueError(error)) throw error;
|
|
818
|
+
throw new QueueError(message, {
|
|
819
|
+
code: "cleanup",
|
|
820
|
+
cause: new AggregateError(errors, message),
|
|
821
|
+
context: { operation: "remove" }
|
|
365
822
|
});
|
|
366
823
|
}
|
|
824
|
+
async #settleBarrier(barrier, tasks, message) {
|
|
825
|
+
try {
|
|
826
|
+
await this.#finish(tasks, message);
|
|
827
|
+
barrier.resolve();
|
|
828
|
+
} catch (error) {
|
|
829
|
+
barrier.reject(error);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
async #settleDestroy(barrier, aborting) {
|
|
833
|
+
let failure;
|
|
834
|
+
try {
|
|
835
|
+
await aborting;
|
|
836
|
+
} catch (error) {
|
|
837
|
+
failure = error;
|
|
838
|
+
}
|
|
839
|
+
try {
|
|
840
|
+
await this.#finish([
|
|
841
|
+
...this.#workers,
|
|
842
|
+
...this.#admissions.values(),
|
|
843
|
+
...this.#cleanups.values(),
|
|
844
|
+
...this.#cleanOrphans(true)
|
|
845
|
+
], "queue destroy cleanup failed");
|
|
846
|
+
} catch (error) {
|
|
847
|
+
failure = failure === void 0 ? error : new QueueError("queue destroy cleanup failed", {
|
|
848
|
+
code: "cleanup",
|
|
849
|
+
cause: new AggregateError([failure, error], "queue destroy cleanup failed"),
|
|
850
|
+
context: { operation: "remove" }
|
|
851
|
+
});
|
|
852
|
+
} finally {
|
|
853
|
+
this.#emitter.destroy();
|
|
854
|
+
}
|
|
855
|
+
if (failure === void 0) barrier.resolve();
|
|
856
|
+
else barrier.reject(failure);
|
|
857
|
+
}
|
|
367
858
|
};
|
|
368
859
|
//#endregion
|
|
369
860
|
//#region src/core/stores/DatabaseQueueStore.ts
|
|
@@ -387,9 +878,11 @@ var Queue = class {
|
|
|
387
878
|
*
|
|
388
879
|
* @example
|
|
389
880
|
* ```ts
|
|
390
|
-
* import {
|
|
881
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
882
|
+
* import { createMemoryDriver } from '@orkestrel/database'
|
|
883
|
+
* import { createDatabaseQueueStore } from '@orkestrel/queue'
|
|
391
884
|
*
|
|
392
|
-
* const store =
|
|
885
|
+
* const store = createDatabaseQueueStore(stringShape(), createMemoryDriver())
|
|
393
886
|
* await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
|
|
394
887
|
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
395
888
|
* ```
|
|
@@ -425,66 +918,94 @@ var DatabaseQueueStore = class {
|
|
|
425
918
|
//#endregion
|
|
426
919
|
//#region src/core/stores/MemoryQueueStore.ts
|
|
427
920
|
/**
|
|
428
|
-
*
|
|
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).
|
|
921
|
+
* An in-memory store owning validated, immutable JSON snapshots of outstanding entries.
|
|
441
922
|
*
|
|
442
|
-
*
|
|
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
|
|
923
|
+
* @typeParam TInput - The contract shape for each stored input
|
|
456
924
|
*
|
|
457
925
|
* @example
|
|
458
926
|
* ```ts
|
|
459
|
-
* import {
|
|
927
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
928
|
+
* import { MemoryQueueStore } from '@orkestrel/queue'
|
|
460
929
|
*
|
|
461
|
-
* const store =
|
|
462
|
-
* await store.save({ id: 'job-1', input: '
|
|
463
|
-
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
464
|
-
* await store.remove('job-1') // a finished entry leaves the store
|
|
930
|
+
* const store = new MemoryQueueStore(stringShape())
|
|
931
|
+
* await store.save({ id: 'job-1', input: 'task', attempts: 0 })
|
|
465
932
|
* ```
|
|
466
933
|
*/
|
|
467
934
|
var MemoryQueueStore = class {
|
|
935
|
+
#contract;
|
|
468
936
|
#entries = /* @__PURE__ */ new Map();
|
|
469
|
-
/**
|
|
937
|
+
/**
|
|
938
|
+
* Create an in-memory queue store.
|
|
939
|
+
*
|
|
940
|
+
* @param input - Runtime contract for each stored input
|
|
941
|
+
*/
|
|
942
|
+
constructor(input) {
|
|
943
|
+
this.#contract = createContract(input);
|
|
944
|
+
}
|
|
945
|
+
/** Upsert a validated, owned snapshot under the entry's id. */
|
|
470
946
|
save(entry) {
|
|
471
|
-
|
|
472
|
-
|
|
947
|
+
try {
|
|
948
|
+
const id = entry.id;
|
|
949
|
+
const input = entry.input;
|
|
950
|
+
const attempts = entry.attempts;
|
|
951
|
+
if (!isString(id) || !isQueueRetries(attempts)) throw new QueueError("queue store entry is invalid", {
|
|
952
|
+
code: "store",
|
|
953
|
+
context: { operation: "save" }
|
|
954
|
+
});
|
|
955
|
+
this.#entries.set(id, this.#snapshot(id, input, attempts, "save"));
|
|
956
|
+
return Promise.resolve();
|
|
957
|
+
} catch (error) {
|
|
958
|
+
return Promise.reject(new QueueError("queue store save failed", {
|
|
959
|
+
code: "store",
|
|
960
|
+
cause: error,
|
|
961
|
+
context: { operation: "save" }
|
|
962
|
+
}));
|
|
963
|
+
}
|
|
473
964
|
}
|
|
474
|
-
/**
|
|
965
|
+
/** Remove an entry; an absent id is a no-op. */
|
|
475
966
|
remove(id) {
|
|
476
967
|
this.#entries.delete(id);
|
|
477
968
|
return Promise.resolve();
|
|
478
969
|
}
|
|
479
|
-
/**
|
|
970
|
+
/** Return fresh immutable snapshots of every outstanding entry. */
|
|
480
971
|
load() {
|
|
481
|
-
|
|
972
|
+
try {
|
|
973
|
+
const snapshots = [];
|
|
974
|
+
for (const entry of this.#entries.values()) {
|
|
975
|
+
const id = entry.id;
|
|
976
|
+
const input = entry.input;
|
|
977
|
+
const attempts = entry.attempts;
|
|
978
|
+
snapshots.push(this.#snapshot(id, input, attempts, "load"));
|
|
979
|
+
}
|
|
980
|
+
return Promise.resolve(snapshots);
|
|
981
|
+
} catch (error) {
|
|
982
|
+
return Promise.reject(new QueueError("queue store load failed", {
|
|
983
|
+
code: "store",
|
|
984
|
+
cause: error,
|
|
985
|
+
context: { operation: "load" }
|
|
986
|
+
}));
|
|
987
|
+
}
|
|
482
988
|
}
|
|
483
|
-
/**
|
|
989
|
+
/** Remove every outstanding entry. */
|
|
484
990
|
clear() {
|
|
485
991
|
this.#entries.clear();
|
|
486
992
|
return Promise.resolve();
|
|
487
993
|
}
|
|
994
|
+
#snapshot(id, input, attempts, operation) {
|
|
995
|
+
const snapshot = cloneJSONValue(input);
|
|
996
|
+
if (!this.#contract.is(snapshot)) throw new QueueError("queue store input does not satisfy its contract", {
|
|
997
|
+
code: "store",
|
|
998
|
+
context: {
|
|
999
|
+
id,
|
|
1000
|
+
operation
|
|
1001
|
+
}
|
|
1002
|
+
});
|
|
1003
|
+
return Object.freeze({
|
|
1004
|
+
id,
|
|
1005
|
+
input: snapshot,
|
|
1006
|
+
attempts
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
488
1009
|
};
|
|
489
1010
|
//#endregion
|
|
490
1011
|
//#region src/core/factories.ts
|
|
@@ -510,7 +1031,7 @@ var MemoryQueueStore = class {
|
|
|
510
1031
|
*
|
|
511
1032
|
* @example
|
|
512
1033
|
* ```ts
|
|
513
|
-
* import { createQueue } from '@
|
|
1034
|
+
* import { createQueue } from '@orkestrel/queue'
|
|
514
1035
|
*
|
|
515
1036
|
* const queue = createQueue<string, number>({
|
|
516
1037
|
* handler: async (url, { signal }) => (await fetch(url, { signal })).status,
|
|
@@ -526,13 +1047,17 @@ function createQueue(options) {
|
|
|
526
1047
|
return new Queue(options);
|
|
527
1048
|
}
|
|
528
1049
|
function createDatabaseQueueStore(input, driver) {
|
|
1050
|
+
const columns = {
|
|
1051
|
+
id: stringShape(),
|
|
1052
|
+
input,
|
|
1053
|
+
attempts: integerShape({
|
|
1054
|
+
min: 0,
|
|
1055
|
+
max: Number.MAX_SAFE_INTEGER
|
|
1056
|
+
})
|
|
1057
|
+
};
|
|
529
1058
|
return new DatabaseQueueStore(createDatabase({
|
|
530
1059
|
driver,
|
|
531
|
-
tables: { entries:
|
|
532
|
-
id: stringShape(),
|
|
533
|
-
input,
|
|
534
|
-
attempts: integerShape({ min: 0 })
|
|
535
|
-
} }
|
|
1060
|
+
tables: { entries: columns }
|
|
536
1061
|
}).table("entries"));
|
|
537
1062
|
}
|
|
538
1063
|
/**
|
|
@@ -540,36 +1065,30 @@ function createDatabaseQueueStore(input, driver) {
|
|
|
540
1065
|
* over a plain `Map` (the twin of {@link DatabaseQueueStore}).
|
|
541
1066
|
*
|
|
542
1067
|
* @remarks
|
|
543
|
-
* The
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
547
|
-
*
|
|
548
|
-
*
|
|
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`).
|
|
1068
|
+
* The entries live in a process-lifetime `Map` and are gone when the process exits. The
|
|
1069
|
+
* supplied shape is compiled and enforced for every save. Exact JSON inputs are cloned
|
|
1070
|
+
* into deeply frozen owned snapshots, and each load returns fresh snapshots, so neither
|
|
1071
|
+
* caller mutation nor a returned object can alias stored state. For durability across
|
|
1072
|
+
* restarts, build the store over a persistent driver with
|
|
1073
|
+
* {@link createDatabaseQueueStore}.
|
|
553
1074
|
*
|
|
554
1075
|
* @typeParam TInput - The contract shape of each entry's `input` payload
|
|
555
|
-
* @param
|
|
556
|
-
*
|
|
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`
|
|
1076
|
+
* @param input - The runtime {@link ContractShape} for the work payload
|
|
1077
|
+
* @returns A validated memory-backed {@link QueueStoreInterface}, typed by `input`
|
|
560
1078
|
*
|
|
561
1079
|
* @example
|
|
562
1080
|
* ```ts
|
|
563
|
-
* import {
|
|
1081
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
1082
|
+
* import { createMemoryQueueStore } from '@orkestrel/queue'
|
|
564
1083
|
*
|
|
565
1084
|
* const store = createMemoryQueueStore(stringShape())
|
|
566
1085
|
* await store.save({ id: 'job-1', input: 'task', attempts: 0 })
|
|
567
1086
|
* ```
|
|
568
1087
|
*/
|
|
569
|
-
function createMemoryQueueStore(
|
|
570
|
-
return new MemoryQueueStore();
|
|
1088
|
+
function createMemoryQueueStore(input) {
|
|
1089
|
+
return new MemoryQueueStore(input);
|
|
571
1090
|
}
|
|
572
1091
|
//#endregion
|
|
573
|
-
export { DatabaseQueueStore, MemoryQueueStore, Queue, createDatabaseQueueStore, createMemoryQueueStore, createQueue };
|
|
1092
|
+
export { DatabaseQueueStore, MemoryQueueStore, Queue, QueueError, createDatabaseQueueStore, createMemoryQueueStore, createQueue, isQueueConcurrency, isQueueError, isQueueRetries, isQueueSignal, isQueueTimeout };
|
|
574
1093
|
|
|
575
1094
|
//# sourceMappingURL=index.js.map
|