@orkestrel/queue 0.0.4 → 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 +775 -274
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +277 -149
- package/dist/src/core/index.d.ts +277 -149
- package/dist/src/core/index.js +770 -274
- package/dist/src/core/index.js.map +1 -1
- package/package.json +7 -7
package/dist/src/core/index.js
CHANGED
|
@@ -1,68 +1,138 @@
|
|
|
1
|
+
import { cloneJSONValue, createContract, integerShape, isFiniteNumber, isInteger, isString, preview, stringShape } from "@orkestrel/contract";
|
|
1
2
|
import { createAbort } from "@orkestrel/abort";
|
|
2
3
|
import { Emitter } from "@orkestrel/emitter";
|
|
3
4
|
import { createTimeout } from "@orkestrel/timeout";
|
|
4
|
-
import { integerShape, stringShape } from "@orkestrel/contract";
|
|
5
5
|
import { createDatabase } from "@orkestrel/database";
|
|
6
|
-
//#region src/core/
|
|
6
|
+
//#region src/core/errors.ts
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* Error carrying a machine-readable queue category and optional context.
|
|
9
9
|
*
|
|
10
|
-
* @
|
|
11
|
-
*
|
|
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`
|
|
12
37
|
*
|
|
13
38
|
* @example
|
|
14
39
|
* ```ts
|
|
15
|
-
*
|
|
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
|
|
16
61
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* isQueueConcurrency(4) // true
|
|
65
|
+
* isQueueConcurrency(0) // false
|
|
19
66
|
* ```
|
|
20
67
|
*/
|
|
21
|
-
function
|
|
22
|
-
return
|
|
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
|
+
}
|
|
23
122
|
}
|
|
24
123
|
//#endregion
|
|
25
124
|
//#region src/core/Queue.ts
|
|
26
125
|
/**
|
|
27
|
-
* A concurrent, cooperative job queue.
|
|
126
|
+
* A concurrent, cooperative FIFO job queue with optional outstanding-work persistence.
|
|
28
127
|
*
|
|
29
|
-
* @
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* entry waits for a worker to free up.
|
|
38
|
-
* - **Per-attempt deadline + cancellation.** Each attempt's `signal` (handed to the
|
|
39
|
-
* handler) fires on the per-attempt `Timeout` expiring, a queue-level `abort`, or
|
|
40
|
-
* the entry's own `signal`. The handler is RACED against that signal, so an attempt
|
|
41
|
-
* that ignores its `signal` still fails on the deadline. Built on the L1 `Abort` /
|
|
42
|
-
* `Timeout` primitives (a queue / entry abort CLEARS the deadline, never expires it).
|
|
43
|
-
* - **Retries.** A failed attempt (a handler rejection or a per-attempt timeout)
|
|
44
|
-
* retries while attempts remain (`retries` + 1 total). A queue-level abort NEVER
|
|
45
|
-
* retries — it rejects the entry at once; an entry-`signal` abort likewise.
|
|
46
|
-
* - **Lifecycle (§10).** `pause` parks workers; `resume` wakes them; `stop` ends the
|
|
47
|
-
* loops permanently and rejects pending (in-flight settle); `abort` fires the queue
|
|
48
|
-
* signal (cancelling in-flight attempts) and rejects pending; `clear` drops only
|
|
49
|
-
* pending; `destroy` aborts then stops, idempotently.
|
|
50
|
-
* - **Durability (optional `store`).** The store mirrors only OUTSTANDING work: an
|
|
51
|
-
* entry is `save`d on accept (and re-`save`d as its attempt count climbs) and
|
|
52
|
-
* `remove`d the moment it settles (success or terminal failure) or is drained by a
|
|
53
|
-
* lifecycle call. Accepting work durably is NOT best-effort — a failed initial `save`
|
|
54
|
-
* rejects the enqueue; per-attempt persistence IS best-effort (in-memory state is
|
|
55
|
-
* authoritative). A graceful shutdown empties the store; a crash leaves rows that
|
|
56
|
-
* `restore()` re-runs at their persisted attempt count (queue-default retries /
|
|
57
|
-
* timeout, no per-entry signal). At-least-once — handlers should be idempotent.
|
|
58
|
-
* - **Observable (§13).** The owned {@link emitter} ({@link QueueEventMap}) carries the
|
|
59
|
-
* lifecycle moments — `enqueue` / `start` / `retry` / `success` / `failure` / `abort` /
|
|
60
|
-
* `drain` — for fire-and-forget observers. Every event is emitted directly, strictly AFTER
|
|
61
|
-
* the relevant wake / park / settle transition; the emitter isolates a listener throw and
|
|
62
|
-
* routes it to its `error` handler (the `error` option), so a buggy observer can NEVER
|
|
63
|
-
* reorder, throw into, or corrupt the cooperative wake-park / settle-once engine: `active`
|
|
64
|
-
* stays balanced and no parked worker is stranded regardless of what a listener does.
|
|
65
|
-
* Observation is purely a side-channel.
|
|
128
|
+
* @typeParam TInput - The work input each entry carries
|
|
129
|
+
* @typeParam TResult - The value each entry resolves
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* const queue = new Queue<number, number>({ handler: (input) => input * 2 })
|
|
134
|
+
* const result = await queue.enqueue(21)
|
|
135
|
+
* ```
|
|
66
136
|
*/
|
|
67
137
|
var Queue = class {
|
|
68
138
|
#handler;
|
|
@@ -72,35 +142,73 @@ var Queue = class {
|
|
|
72
142
|
#store;
|
|
73
143
|
#abort = createAbort();
|
|
74
144
|
#emitter;
|
|
145
|
+
#entries = /* @__PURE__ */ new Map();
|
|
146
|
+
#live = /* @__PURE__ */ new Map();
|
|
75
147
|
#pending = [];
|
|
76
|
-
#
|
|
148
|
+
#claims = /* @__PURE__ */ new Set();
|
|
77
149
|
#wakes = [];
|
|
78
|
-
#
|
|
79
|
-
#
|
|
150
|
+
#workers = /* @__PURE__ */ new Set();
|
|
151
|
+
#admissions = /* @__PURE__ */ new Map();
|
|
152
|
+
#orphans = /* @__PURE__ */ new Set();
|
|
153
|
+
#cleanups = /* @__PURE__ */ new Map();
|
|
154
|
+
#admission = Promise.resolve();
|
|
155
|
+
#stopPromise;
|
|
156
|
+
#abortPromise;
|
|
157
|
+
#destroyPromise;
|
|
158
|
+
#generation = 0;
|
|
80
159
|
#paused = false;
|
|
81
160
|
#stopped = false;
|
|
82
161
|
#aborted = false;
|
|
83
162
|
#destroyed = false;
|
|
163
|
+
#drained = true;
|
|
164
|
+
/**
|
|
165
|
+
* Create a queue.
|
|
166
|
+
*
|
|
167
|
+
* @param options - Handler, validated execution limits, persistence, and observation hooks
|
|
168
|
+
*/
|
|
84
169
|
constructor(options) {
|
|
170
|
+
const 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
|
+
});
|
|
85
194
|
this.#handler = options.handler;
|
|
86
|
-
this.#concurrency =
|
|
87
|
-
this.#retries =
|
|
88
|
-
this.#timeout =
|
|
195
|
+
this.#concurrency = concurrency;
|
|
196
|
+
this.#retries = retries;
|
|
197
|
+
this.#timeout = timeout;
|
|
89
198
|
this.#store = options.store;
|
|
90
199
|
this.#emitter = new Emitter({
|
|
91
|
-
...options.on
|
|
92
|
-
...options.error
|
|
200
|
+
...options.on === void 0 ? {} : { on: options.on },
|
|
201
|
+
...options.error === void 0 ? {} : { error: options.error }
|
|
93
202
|
});
|
|
94
|
-
this.#spawn();
|
|
95
203
|
}
|
|
96
204
|
get emitter() {
|
|
97
205
|
return this.#emitter;
|
|
98
206
|
}
|
|
99
207
|
get count() {
|
|
100
|
-
return this.#
|
|
208
|
+
return this.#live.size;
|
|
101
209
|
}
|
|
102
210
|
get active() {
|
|
103
|
-
return this.#
|
|
211
|
+
return this.#claims.size;
|
|
104
212
|
}
|
|
105
213
|
get paused() {
|
|
106
214
|
return this.#paused;
|
|
@@ -108,122 +216,348 @@ var Queue = class {
|
|
|
108
216
|
get stopped() {
|
|
109
217
|
return this.#stopped || this.#aborted;
|
|
110
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
|
+
*/
|
|
111
227
|
enqueue(input, options) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
id,
|
|
121
|
-
input,
|
|
122
|
-
options,
|
|
123
|
-
attempts: 0,
|
|
124
|
-
resolve,
|
|
125
|
-
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" }
|
|
126
236
|
});
|
|
127
|
-
|
|
128
|
-
|
|
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
|
+
}
|
|
129
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
|
+
}
|
|
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;
|
|
130
314
|
}
|
|
315
|
+
/** Load and accept every outstanding stored entry from the current lifecycle generation. */
|
|
131
316
|
async restore() {
|
|
132
|
-
if (this.#store === void 0 || this
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
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" }
|
|
146
330
|
});
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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(() => {});
|
|
150
352
|
}
|
|
151
353
|
}
|
|
354
|
+
/** Begin or restart worker execution unless the queue is terminal. */
|
|
152
355
|
start() {
|
|
153
356
|
if (this.#aborted || this.#destroyed) return;
|
|
154
357
|
this.#stopped = false;
|
|
358
|
+
this.#stopPromise = void 0;
|
|
155
359
|
this.#spawn();
|
|
156
360
|
}
|
|
361
|
+
/** Reject non-active work and await current-loop and durable cleanup quiescence. */
|
|
157
362
|
stop() {
|
|
158
|
-
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;
|
|
159
368
|
this.#stopped = true;
|
|
160
|
-
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
|
+
];
|
|
161
378
|
this.#wakeAll();
|
|
379
|
+
this.#settleBarrier(barrier, tasks, "queue stop cleanup failed");
|
|
380
|
+
return barrier.promise;
|
|
162
381
|
}
|
|
382
|
+
/** Suspend new execution while leaving active entries untouched. */
|
|
163
383
|
pause() {
|
|
164
384
|
if (this.#paused || this.stopped || this.#destroyed) return;
|
|
165
385
|
this.#paused = true;
|
|
166
386
|
}
|
|
387
|
+
/** Continue execution after a pause. */
|
|
167
388
|
resume() {
|
|
168
389
|
if (!this.#paused || this.stopped || this.#destroyed) return;
|
|
169
390
|
this.#paused = false;
|
|
170
391
|
this.#wakeAll();
|
|
171
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
|
+
*/
|
|
172
399
|
abort(reason) {
|
|
173
|
-
if (this.#
|
|
400
|
+
if (this.#abortPromise !== void 0) return this.#abortPromise;
|
|
401
|
+
const barrier = Promise.withResolvers();
|
|
402
|
+
this.#abortPromise = barrier.promise;
|
|
174
403
|
this.#aborted = true;
|
|
175
|
-
this.#
|
|
176
|
-
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
|
+
];
|
|
177
419
|
this.#wakeAll();
|
|
178
|
-
this.#emitter.emit("abort",
|
|
420
|
+
this.#emitter.emit("abort", error);
|
|
421
|
+
this.#settleBarrier(barrier, tasks, "queue abort cleanup failed");
|
|
422
|
+
return barrier.promise;
|
|
179
423
|
}
|
|
424
|
+
/** Reject non-active work and await its durable cleanup. */
|
|
180
425
|
clear() {
|
|
181
|
-
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");
|
|
182
435
|
}
|
|
436
|
+
/** Tear down once, destroying the emitter only after cleanup finishes. */
|
|
183
437
|
destroy() {
|
|
184
|
-
if (this.#
|
|
438
|
+
if (this.#destroyPromise !== void 0) return this.#destroyPromise;
|
|
439
|
+
const barrier = Promise.withResolvers();
|
|
440
|
+
this.#destroyPromise = barrier.promise;
|
|
185
441
|
this.#destroyed = true;
|
|
186
|
-
this.abort();
|
|
187
|
-
this.#
|
|
188
|
-
|
|
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();
|
|
189
512
|
}
|
|
190
513
|
#spawn() {
|
|
191
514
|
if (this.#stopped || this.#aborted || this.#destroyed) return;
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
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(() => {});
|
|
195
524
|
}
|
|
196
525
|
}
|
|
197
|
-
async #worker() {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
this.#
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
this.#active -= 1;
|
|
207
|
-
if (this.#active === 0 && this.#pending.length === 0) this.#emitter.emit("drain");
|
|
208
|
-
}
|
|
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;
|
|
209
535
|
}
|
|
210
|
-
} finally {
|
|
211
|
-
this.#running -= 1;
|
|
212
536
|
}
|
|
213
537
|
}
|
|
214
|
-
#next() {
|
|
215
|
-
return new Promise((resolve) => this.#take(resolve));
|
|
538
|
+
#next(generation) {
|
|
539
|
+
return new Promise((resolve) => this.#take(generation, resolve));
|
|
216
540
|
}
|
|
217
|
-
#take(resolve) {
|
|
218
|
-
if (this.#stopped || this.#aborted || this.#destroyed) {
|
|
541
|
+
#take(generation, resolve) {
|
|
542
|
+
if (generation !== this.#generation || this.#stopped || this.#aborted || this.#destroyed) {
|
|
219
543
|
resolve(void 0);
|
|
220
544
|
return;
|
|
221
545
|
}
|
|
222
546
|
if (this.#paused || this.#pending.length === 0) {
|
|
223
|
-
this.#wakes.push(() => this.#take(resolve));
|
|
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);
|
|
224
557
|
return;
|
|
225
558
|
}
|
|
226
|
-
|
|
559
|
+
this.#claims.add(token);
|
|
560
|
+
resolve(token);
|
|
227
561
|
}
|
|
228
562
|
#wake() {
|
|
229
563
|
const resolver = this.#wakes.shift();
|
|
@@ -234,107 +568,186 @@ var Queue = class {
|
|
|
234
568
|
for (const resolver of resolvers) resolver();
|
|
235
569
|
}
|
|
236
570
|
#drain(error) {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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));
|
|
243
583
|
}
|
|
584
|
+
return cleanup;
|
|
244
585
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
await
|
|
253
|
-
|
|
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();
|
|
254
596
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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
|
|
264
670
|
});
|
|
265
|
-
|
|
266
|
-
|
|
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
|
+
})
|
|
267
681
|
});
|
|
682
|
+
return true;
|
|
268
683
|
}
|
|
269
|
-
async #saveAttempt(
|
|
684
|
+
async #saveAttempt(token, attempts) {
|
|
685
|
+
const entry = this.#entries.get(token);
|
|
686
|
+
if (this.#store === void 0 || entry === void 0) return;
|
|
270
687
|
try {
|
|
271
|
-
await this.#store
|
|
688
|
+
await this.#store.save({
|
|
272
689
|
id: entry.id,
|
|
273
690
|
input: entry.input,
|
|
274
691
|
attempts
|
|
275
692
|
});
|
|
276
693
|
} catch {}
|
|
277
694
|
}
|
|
278
|
-
async #
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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 > entry.attempts) {
|
|
293
|
-
await this.#saveAttempt(entry, attempt);
|
|
294
|
-
this.#emitter.emit("retry", entry.id, attempt);
|
|
295
|
-
}
|
|
296
|
-
const outcome = await this.#attempt(entry.id, entry.input, timeout, signal);
|
|
297
|
-
if (outcome.success) return this.#settle(entry, {
|
|
298
|
-
success: true,
|
|
299
|
-
value: outcome.value
|
|
300
|
-
});
|
|
301
|
-
if (this.#abort.aborted) return this.#settle(entry, {
|
|
302
|
-
success: false,
|
|
303
|
-
error: this.#abort.signal.reason
|
|
304
|
-
});
|
|
305
|
-
if (signal?.aborted) return this.#settle(entry, {
|
|
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, {
|
|
306
701
|
success: false,
|
|
307
|
-
error:
|
|
702
|
+
error: cleanup
|
|
308
703
|
});
|
|
309
|
-
|
|
310
|
-
|
|
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, {
|
|
311
716
|
success: false,
|
|
312
|
-
error
|
|
717
|
+
error
|
|
313
718
|
});
|
|
719
|
+
throw error;
|
|
314
720
|
}
|
|
721
|
+
this.#finishEntry(token, outcome);
|
|
315
722
|
}
|
|
316
|
-
#
|
|
317
|
-
this.#
|
|
318
|
-
|
|
319
|
-
|
|
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");
|
|
320
729
|
return;
|
|
321
730
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
if (outcome.success) {
|
|
326
|
-
entry.resolve(outcome.value);
|
|
327
|
-
this.#emitter.emit("success", entry.id, outcome.value);
|
|
328
|
-
} else {
|
|
329
|
-
entry.reject(outcome.error);
|
|
330
|
-
this.#emitter.emit("failure", entry.id, outcome.error);
|
|
331
|
-
}
|
|
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");
|
|
332
734
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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");
|
|
338
751
|
}
|
|
339
752
|
async #attempt(id, input, timeout, signal) {
|
|
340
753
|
const cancel = signal === void 0 ? this.#abort.signal : AbortSignal.any([this.#abort.signal, signal]);
|
|
@@ -356,17 +769,25 @@ var Queue = class {
|
|
|
356
769
|
} catch (error) {
|
|
357
770
|
return {
|
|
358
771
|
success: false,
|
|
359
|
-
error: error instanceof Error ? error : new Error(
|
|
772
|
+
error: error instanceof Error ? error : new Error(preview(error), { cause: error })
|
|
360
773
|
};
|
|
361
774
|
} finally {
|
|
362
775
|
deadline?.clear();
|
|
363
776
|
}
|
|
364
777
|
}
|
|
365
778
|
#race(id, input, signal, deadline) {
|
|
366
|
-
if (signal.aborted) return Promise.reject(
|
|
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
|
+
}));
|
|
367
784
|
const cleanup = new AbortController();
|
|
368
785
|
return new Promise((resolve, reject) => {
|
|
369
|
-
signal.addEventListener("abort", () => reject(
|
|
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
|
+
})), {
|
|
370
791
|
once: true,
|
|
371
792
|
signal: cleanup.signal
|
|
372
793
|
});
|
|
@@ -387,6 +808,53 @@ var Queue = class {
|
|
|
387
808
|
}
|
|
388
809
|
});
|
|
389
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" }
|
|
822
|
+
});
|
|
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
|
+
}
|
|
390
858
|
};
|
|
391
859
|
//#endregion
|
|
392
860
|
//#region src/core/stores/DatabaseQueueStore.ts
|
|
@@ -410,9 +878,11 @@ var Queue = class {
|
|
|
410
878
|
*
|
|
411
879
|
* @example
|
|
412
880
|
* ```ts
|
|
413
|
-
* import {
|
|
881
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
882
|
+
* import { createMemoryDriver } from '@orkestrel/database'
|
|
883
|
+
* import { createDatabaseQueueStore } from '@orkestrel/queue'
|
|
414
884
|
*
|
|
415
|
-
* const store =
|
|
885
|
+
* const store = createDatabaseQueueStore(stringShape(), createMemoryDriver())
|
|
416
886
|
* await store.save({ id: 'job-1', input: 'https://example.com', attempts: 0 })
|
|
417
887
|
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
418
888
|
* ```
|
|
@@ -448,66 +918,94 @@ var DatabaseQueueStore = class {
|
|
|
448
918
|
//#endregion
|
|
449
919
|
//#region src/core/stores/MemoryQueueStore.ts
|
|
450
920
|
/**
|
|
451
|
-
*
|
|
452
|
-
* {@link StoredEntry}s keyed by id, the DEFAULT store
|
|
453
|
-
* {@link import('../factories.js').createMemoryQueueStore} builds.
|
|
921
|
+
* An in-memory store owning validated, immutable JSON snapshots of outstanding entries.
|
|
454
922
|
*
|
|
455
|
-
* @
|
|
456
|
-
* A plain `Map<string, StoredEntry<TInput>>` (AGENTS §21 — the entry is already pure,
|
|
457
|
-
* self-contained JSON, so no `databases` table / driver codec is needed for the memory
|
|
458
|
-
* tier; this is the zero-plumbing twin of {@link DatabaseQueueStore}, which wraps a
|
|
459
|
-
* `TableInterface` for a driver-pluggable durable backend). The store holds ONLY
|
|
460
|
-
* outstanding work, so `load` yields precisely the entries to resume — though a memory
|
|
461
|
-
* store is gone when the process exits, so `restore()` recovers nothing after a real
|
|
462
|
-
* restart. For durability across restarts, build a {@link DatabaseQueueStore} over a
|
|
463
|
-
* server JSON / SQLite driver (the SAME interface, so the queue / worker never knows).
|
|
464
|
-
*
|
|
465
|
-
* - **`save` upserts an entry under its OWN `id`** (a re-`save` of an existing `id`
|
|
466
|
-
* overwrites it — `Map.set`, never a duplicate).
|
|
467
|
-
* - **`remove` drops a finished entry by `id`**; an absent `id` is a no-op (no throw).
|
|
468
|
-
* - **`load` returns every outstanding entry** as a readonly array (the `Map`'s values
|
|
469
|
-
* in insertion order — the work to resume).
|
|
470
|
-
* - **`clear` empties the store** — drop every outstanding entry.
|
|
471
|
-
*
|
|
472
|
-
* Each primitive is async (it returns a resolved `Promise`) to satisfy the
|
|
473
|
-
* {@link QueueStoreInterface} signatures, wrapping the synchronous `Map` op — so the
|
|
474
|
-
* memory and driver-backed stores are interchangeable behind the one interface. The
|
|
475
|
-
* public surface is EXACTLY `save` / `remove` / `load` / `clear` — no extra members (the
|
|
476
|
-
* §22 method bijection with {@link QueueStoreInterface}).
|
|
477
|
-
*
|
|
478
|
-
* @typeParam TInput - The work input each {@link StoredEntry} carries
|
|
923
|
+
* @typeParam TInput - The contract shape for each stored input
|
|
479
924
|
*
|
|
480
925
|
* @example
|
|
481
926
|
* ```ts
|
|
482
|
-
* import {
|
|
927
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
928
|
+
* import { MemoryQueueStore } from '@orkestrel/queue'
|
|
483
929
|
*
|
|
484
|
-
* const store =
|
|
485
|
-
* await store.save({ id: 'job-1', input: '
|
|
486
|
-
* const outstanding = await store.load() // readonly StoredEntry<string>[]
|
|
487
|
-
* 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 })
|
|
488
932
|
* ```
|
|
489
933
|
*/
|
|
490
934
|
var MemoryQueueStore = class {
|
|
935
|
+
#contract;
|
|
491
936
|
#entries = /* @__PURE__ */ new Map();
|
|
492
|
-
/**
|
|
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. */
|
|
493
946
|
save(entry) {
|
|
494
|
-
|
|
495
|
-
|
|
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
|
+
}
|
|
496
964
|
}
|
|
497
|
-
/**
|
|
965
|
+
/** Remove an entry; an absent id is a no-op. */
|
|
498
966
|
remove(id) {
|
|
499
967
|
this.#entries.delete(id);
|
|
500
968
|
return Promise.resolve();
|
|
501
969
|
}
|
|
502
|
-
/**
|
|
970
|
+
/** Return fresh immutable snapshots of every outstanding entry. */
|
|
503
971
|
load() {
|
|
504
|
-
|
|
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
|
+
}
|
|
505
988
|
}
|
|
506
|
-
/**
|
|
989
|
+
/** Remove every outstanding entry. */
|
|
507
990
|
clear() {
|
|
508
991
|
this.#entries.clear();
|
|
509
992
|
return Promise.resolve();
|
|
510
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
|
+
}
|
|
511
1009
|
};
|
|
512
1010
|
//#endregion
|
|
513
1011
|
//#region src/core/factories.ts
|
|
@@ -533,7 +1031,7 @@ var MemoryQueueStore = class {
|
|
|
533
1031
|
*
|
|
534
1032
|
* @example
|
|
535
1033
|
* ```ts
|
|
536
|
-
* import { createQueue } from '@
|
|
1034
|
+
* import { createQueue } from '@orkestrel/queue'
|
|
537
1035
|
*
|
|
538
1036
|
* const queue = createQueue<string, number>({
|
|
539
1037
|
* handler: async (url, { signal }) => (await fetch(url, { signal })).status,
|
|
@@ -549,13 +1047,17 @@ function createQueue(options) {
|
|
|
549
1047
|
return new Queue(options);
|
|
550
1048
|
}
|
|
551
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
|
+
};
|
|
552
1058
|
return new DatabaseQueueStore(createDatabase({
|
|
553
1059
|
driver,
|
|
554
|
-
tables: { entries:
|
|
555
|
-
id: stringShape(),
|
|
556
|
-
input,
|
|
557
|
-
attempts: integerShape({ min: 0 })
|
|
558
|
-
} }
|
|
1060
|
+
tables: { entries: columns }
|
|
559
1061
|
}).table("entries"));
|
|
560
1062
|
}
|
|
561
1063
|
/**
|
|
@@ -563,36 +1065,30 @@ function createDatabaseQueueStore(input, driver) {
|
|
|
563
1065
|
* over a plain `Map` (the twin of {@link DatabaseQueueStore}).
|
|
564
1066
|
*
|
|
565
1067
|
* @remarks
|
|
566
|
-
* The
|
|
567
|
-
*
|
|
568
|
-
*
|
|
569
|
-
*
|
|
570
|
-
*
|
|
571
|
-
*
|
|
572
|
-
* but a plain-`Map` store does not validate the payload — durability + contract narrowing
|
|
573
|
-
* are {@link DatabaseQueueStore}'s job. For durability across restarts, build the store
|
|
574
|
-
* over a server JSON / SQLite driver via {@link createDatabaseQueueStore} (or the server
|
|
575
|
-
* `createJSONQueueStore`).
|
|
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}.
|
|
576
1074
|
*
|
|
577
1075
|
* @typeParam TInput - The contract shape of each entry's `input` payload
|
|
578
|
-
* @param
|
|
579
|
-
*
|
|
580
|
-
* (AGENTS unused-arg convention) while staying in the signature for source-compatibility
|
|
581
|
-
* with the driver-backed family
|
|
582
|
-
* @returns A memory-backed {@link QueueStoreInterface}, typed by `_input`
|
|
1076
|
+
* @param input - The runtime {@link ContractShape} for the work payload
|
|
1077
|
+
* @returns A validated memory-backed {@link QueueStoreInterface}, typed by `input`
|
|
583
1078
|
*
|
|
584
1079
|
* @example
|
|
585
1080
|
* ```ts
|
|
586
|
-
* import {
|
|
1081
|
+
* import { stringShape } from '@orkestrel/contract'
|
|
1082
|
+
* import { createMemoryQueueStore } from '@orkestrel/queue'
|
|
587
1083
|
*
|
|
588
1084
|
* const store = createMemoryQueueStore(stringShape())
|
|
589
1085
|
* await store.save({ id: 'job-1', input: 'task', attempts: 0 })
|
|
590
1086
|
* ```
|
|
591
1087
|
*/
|
|
592
|
-
function createMemoryQueueStore(
|
|
593
|
-
return new MemoryQueueStore();
|
|
1088
|
+
function createMemoryQueueStore(input) {
|
|
1089
|
+
return new MemoryQueueStore(input);
|
|
594
1090
|
}
|
|
595
1091
|
//#endregion
|
|
596
|
-
export { DatabaseQueueStore, MemoryQueueStore, Queue,
|
|
1092
|
+
export { DatabaseQueueStore, MemoryQueueStore, Queue, QueueError, createDatabaseQueueStore, createMemoryQueueStore, createQueue, isQueueConcurrency, isQueueError, isQueueRetries, isQueueSignal, isQueueTimeout };
|
|
597
1093
|
|
|
598
1094
|
//# sourceMappingURL=index.js.map
|