@aponiajs/queue 0.0.0-stage → 1.0.0-beta.64

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/index.mjs ADDED
@@ -0,0 +1,1001 @@
1
+ import { AponiaError, ConfigurableModuleBuilder, Inject, Injectable, Module, ModuleRef, createToken, provideAlias, provideClass, provideFactory, runOutsideAsyncContexts } from "@aponiajs/common";
2
+ import { randomUUID } from "node:crypto";
3
+ import { createStateMachine } from "@aponiajs/compiler";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+ // src/decorators/inject-queue.decorator.ts
6
+ const defaultQueueName = "default";
7
+ /**
8
+ * The token a named queue is injectable under.
9
+ *
10
+ * `@nestjs/bullmq` spells this `BullQueue_<name>`; this package names its
11
+ * in-process queue registration instead, and never presents the token as a
12
+ * broker queue.
13
+ *
14
+ * @param name - The registration's name; omitted is the default queue.
15
+ * @returns The injection token.
16
+ */
17
+ function getQueueToken(name) {
18
+ return `AponiaQueue_${name ?? defaultQueueName}`;
19
+ }
20
+ /**
21
+ * Injects the in-process queue a registration provides.
22
+ *
23
+ * @param name - The registration's name; omitted is the default queue.
24
+ * @returns The parameter decorator.
25
+ */
26
+ const InjectQueue = (name) => Inject(getQueueToken(name));
27
+ // src/outbox/outbox.service.ts
28
+ /**
29
+ * Records messages inside the transaction boundary and delivers them after it.
30
+ *
31
+ * The built-in outbox is process-local: a restart loses it, and two instances
32
+ * keep separate outboxes. It records intent, not durable state.
33
+ */
34
+ var OutboxService = class {
35
+ #messages = [];
36
+ #maxEntries;
37
+ #now;
38
+ #store;
39
+ #flushing = false;
40
+ constructor(options = {}) {
41
+ const maxEntries = options.maxEntries ?? 1e3;
42
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The outbox registration is invalid.", { issues: Object.freeze(["maxEntries must be a positive integer"]) });
43
+ this.#maxEntries = maxEntries;
44
+ this.#now = options.now ?? Date.now;
45
+ this.#store = options.store;
46
+ if (this.#store !== void 0) {
47
+ const stored = this.#store.list();
48
+ const retained = stored.slice(Math.max(0, stored.length - this.#maxEntries));
49
+ this.#messages.push(...retained.map(toMutable));
50
+ }
51
+ }
52
+ /** Records one message and returns its frozen form. */
53
+ record(name, payload) {
54
+ if (typeof name !== "string" || name.trim() === "") throw new AponiaError("INVALID_QUEUE_JOB", "An outbox message name must be a non-empty string.");
55
+ if (this.#messages.length >= this.#maxEntries) this.#messages.shift();
56
+ const message = {
57
+ id: randomUUID(),
58
+ name,
59
+ payload,
60
+ attempts: 0,
61
+ recordedAt: this.#now()
62
+ };
63
+ this.#messages.push(message);
64
+ this.#store?.append(freezeMessage(message));
65
+ return freezeMessage(message);
66
+ }
67
+ /** The recorded messages, oldest first. */
68
+ pending() {
69
+ return Object.freeze(this.#messages.map((message) => freezeMessage(message)));
70
+ }
71
+ /**
72
+ * Delivers recorded messages in order and removes the ones the sink accepted.
73
+ * A rejected message stays at the front of the outbox for the next flush.
74
+ */
75
+ async flush(sink, options = {}) {
76
+ if (typeof sink !== "function") throw new AponiaError("INVALID_QUEUE_JOB", "An outbox sink must be a function.");
77
+ if (this.#flushing) throw new AponiaError("INVALID_QUEUE_JOB", "An outbox flush is already running.");
78
+ this.#flushing = true;
79
+ let delivered = 0;
80
+ try {
81
+ while (this.#messages.length > 0) {
82
+ if (options.signal?.aborted === true) break;
83
+ const message = this.#messages[0];
84
+ message.attempts += 1;
85
+ this.#store?.update(freezeMessage(message));
86
+ try {
87
+ await sink(freezeMessage(message));
88
+ } catch (error) {
89
+ throw new AponiaError("OUTBOX_DELIVERY_FAILED", "An outbox message was not delivered.", {
90
+ messageId: message.id,
91
+ attempts: message.attempts,
92
+ cause: error instanceof Error ? error.message : String(error)
93
+ });
94
+ }
95
+ this.#messages.shift();
96
+ this.#store?.remove(message.id);
97
+ delivered += 1;
98
+ }
99
+ } finally {
100
+ this.#flushing = false;
101
+ }
102
+ return Object.freeze({
103
+ delivered,
104
+ remaining: this.#messages.length
105
+ });
106
+ }
107
+ /** Drops every recorded message. */
108
+ clear() {
109
+ this.#messages.length = 0;
110
+ this.#store?.clear();
111
+ }
112
+ };
113
+ function toMutable(message) {
114
+ return {
115
+ id: message.id,
116
+ name: message.name,
117
+ payload: message.payload,
118
+ attempts: message.attempts,
119
+ recordedAt: message.recordedAt
120
+ };
121
+ }
122
+ function freezeMessage(message) {
123
+ return Object.freeze({
124
+ id: message.id,
125
+ name: message.name,
126
+ payload: message.payload,
127
+ attempts: message.attempts,
128
+ recordedAt: message.recordedAt
129
+ });
130
+ }
131
+ // src/decorators/processor.decorator.ts
132
+ const processorMetadataKey = Symbol.for("aponia.queue.processor.metadata");
133
+ const processedClasses = /* @__PURE__ */ new Set();
134
+ /**
135
+ * Marks a `WorkerHost` as the processor for one job name.
136
+ *
137
+ * The in-process queue runs a handler per job name, so the processor's `name`
138
+ * is the job name it handles — there is no broker queue to subscribe to.
139
+ *
140
+ * @param queueNameOrOptions - A job name or processor options.
141
+ * @returns The class decorator.
142
+ * @throws A `TypeError` when the name is empty.
143
+ */
144
+ function Processor(queueNameOrOptions) {
145
+ const options = typeof queueNameOrOptions === "string" ? { name: queueNameOrOptions } : queueNameOrOptions ?? {};
146
+ const name = options.name ?? "default";
147
+ if (typeof name !== "string" || name.trim() === "") throw new TypeError("Processor() requires a non-empty name.");
148
+ return (target) => {
149
+ Reflect.defineMetadata(processorMetadataKey, Object.freeze({
150
+ ...options,
151
+ name
152
+ }), target);
153
+ processedClasses.add(target);
154
+ };
155
+ }
156
+ /** @internal The classes `@Processor()` marked, in declaration order. */
157
+ function getProcessorClasses() {
158
+ return Object.freeze([...processedClasses]);
159
+ }
160
+ /** @internal Reads the processor options a class declared. */
161
+ function getProcessorOptions(target) {
162
+ const value = Reflect.getOwnMetadata(processorMetadataKey, target);
163
+ return typeof value === "object" && value !== null ? value : void 0;
164
+ }
165
+ /**
166
+ * Refuses a processor whose class does not implement `process`.
167
+ */
168
+ function assertProcessor(instance) {
169
+ if (typeof instance.process !== "function") throw new AponiaError("INVALID_QUEUE_JOB", "A @Processor() class must implement process(job).");
170
+ }
171
+ // src/queue/queue-job-machine.ts
172
+ /**
173
+ * The one lifecycle every job follows.
174
+ *
175
+ * Keeping it as a typestate machine is what makes an invalid transition a
176
+ * `tsc` error in this package and an `INVALID_STATE_TRANSITION` at runtime when
177
+ * a stored job names a state the queue does not know.
178
+ */
179
+ const queueJobDefinition = Object.freeze({
180
+ initial: "pending",
181
+ transitions: {
182
+ pending: { run: "running" },
183
+ running: {
184
+ complete: "completed",
185
+ retry: "pending",
186
+ fail: "failed"
187
+ },
188
+ failed: { revive: "pending" },
189
+ completed: {}
190
+ }
191
+ });
192
+ /** A machine at the initial pending state. */
193
+ function queueJobMachine() {
194
+ return createStateMachine(queueJobDefinition);
195
+ }
196
+ /**
197
+ * Validates a persisted state before the queue hydrates a job.
198
+ *
199
+ * @param state - The state the store recorded.
200
+ * @throws An `AponiaError` with `INVALID_STATE_TRANSITION` for an unknown state.
201
+ */
202
+ function validateQueueJobState(state) {
203
+ createStateMachine(queueJobDefinition, { from: state });
204
+ }
205
+ /** The state a dead letter returns to when revived. */
206
+ function revivedQueueJobState() {
207
+ return queueJobMachine().transition("run").transition("fail").transition("revive").state;
208
+ }
209
+ // src/queue/job-ref.service.ts
210
+ /**
211
+ * The current job inside a processor.
212
+ *
213
+ * `@nestjs/bullmq` aliases this token to its request-scoped `REQUEST`, so a
214
+ * provider injected into a processor can read the job being handled. This
215
+ * package has no per-job request scope, so the value here is a forwarding view:
216
+ * its properties read the job the queue is running in the current async chain,
217
+ * and they are `undefined` outside a handler.
218
+ */
219
+ const JOB_REF = createToken("JOB_REF");
220
+ /** Holds the job a processor is handling for the current async chain. */
221
+ var JobRefService = class {
222
+ #storage = new AsyncLocalStorage();
223
+ /** The job the current async chain is handling, if any. */
224
+ current() {
225
+ return this.#storage.getStore();
226
+ }
227
+ /** @internal Runs one handler with its job as the ambient value. */
228
+ run(job, work) {
229
+ return this.#storage.run(job, work);
230
+ }
231
+ /**
232
+ * The value `JOB_REF` resolves to.
233
+ *
234
+ * `@nestjs/bullmq` injects the job directly. A forwarding view keeps that
235
+ * shape: reading `job.id`, `job.name`, or `job.payload` answers the job the
236
+ * current async chain is handling, and nothing outside a handler.
237
+ */
238
+ proxy() {
239
+ const current = () => this.current();
240
+ return new Proxy({}, {
241
+ get: (_target, property) => current()?.[property],
242
+ has: (_target, property) => current() !== void 0 && property in current(),
243
+ ownKeys: () => current() === void 0 ? [] : Reflect.ownKeys(current()),
244
+ getOwnPropertyDescriptor: (_target, property) => current() === void 0 ? void 0 : {
245
+ configurable: true,
246
+ enumerable: true,
247
+ value: current()[property]
248
+ }
249
+ });
250
+ }
251
+ };
252
+ // src/queue/queue.service.ts
253
+ const zeroSummary = Object.freeze({
254
+ completed: 0,
255
+ retried: 0,
256
+ deadLettered: 0,
257
+ skipped: 0
258
+ });
259
+ /**
260
+ * An in-process job queue with bounded retries, exponential backoff, a dead
261
+ * letter queue, and idempotent enqueue.
262
+ *
263
+ * The queue is process-local. It survives no restart and shares no state with
264
+ * another application instance; a deployment that needs either needs a broker.
265
+ */
266
+ var QueueService = class {
267
+ #options;
268
+ #jobs = /* @__PURE__ */ new Map();
269
+ #deadLetters = /* @__PURE__ */ new Map();
270
+ #handlers = /* @__PURE__ */ new Map();
271
+ #idempotency = /* @__PURE__ */ new Map();
272
+ #running = /* @__PURE__ */ new Set();
273
+ #controllers = /* @__PURE__ */ new Set();
274
+ #idleWaiters = [];
275
+ #store;
276
+ #writes = [];
277
+ #jobRef;
278
+ #scheduled;
279
+ #closed = false;
280
+ #paused = false;
281
+ #writeError;
282
+ /** @internal Construct through `QueueModule.register`. */
283
+ constructor(options = {}, jobRef = new JobRefService()) {
284
+ this.#options = resolveQueueOptions(options);
285
+ this.#jobRef = jobRef;
286
+ if (options.store !== void 0) assertStore(options.store);
287
+ this.#store = options.store;
288
+ }
289
+ /** Registers the handler one job name runs. A later call replaces it. */
290
+ registerHandler(name, handler) {
291
+ this.#assertOpen();
292
+ if (typeof name !== "string" || name.trim() === "") throw invalidJob("A job name must be a non-empty string.");
293
+ if (typeof handler !== "function") throw invalidJob("A queue handler must be a function.");
294
+ this.#handlers.set(name, handler);
295
+ }
296
+ /** Adds one job and returns a frozen snapshot of it. */
297
+ enqueue(name, payload, options = {}) {
298
+ this.#assertOpen();
299
+ if (typeof name !== "string" || name.trim() === "") throw invalidJob("A job name must be a non-empty string.");
300
+ const idempotencyKey = options.idempotencyKey;
301
+ if (idempotencyKey !== void 0) {
302
+ if (typeof idempotencyKey !== "string" || idempotencyKey.trim() === "") throw invalidJob("An idempotency key must be a non-empty string.");
303
+ const existingId = this.#idempotency.get(idempotencyKey);
304
+ const existing = existingId === void 0 ? void 0 : this.#jobs.get(existingId) ?? this.#deadLetters.get(existingId);
305
+ if (existing !== void 0) return freezeJob(existing);
306
+ }
307
+ const maxAttempts = options.maxAttempts ?? this.#options.maxAttempts;
308
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw invalidJob("maxAttempts must be a positive integer.");
309
+ const now = this.#options.now();
310
+ const availableAt = options.availableAt ?? now;
311
+ if (!Number.isFinite(availableAt)) throw invalidJob("availableAt must be a finite timestamp.");
312
+ const priority = options.priority ?? 0;
313
+ if (!Number.isSafeInteger(priority)) throw invalidJob("priority must be a safe integer.");
314
+ const timeoutMs = options.timeoutMs ?? this.#options.jobTimeoutMs;
315
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 0) throw invalidJob("timeoutMs must be a non-negative integer.");
316
+ if (this.#jobs.size >= this.#options.maxJobs) throw new AponiaError("QUEUE_CAPACITY_EXCEEDED", "The queue is full; no job was enqueued.", Object.freeze({ maxJobs: this.#options.maxJobs }));
317
+ const job = {
318
+ id: randomUUID(),
319
+ name,
320
+ payload,
321
+ attempts: 0,
322
+ maxAttempts,
323
+ priority,
324
+ timeoutMs,
325
+ state: "pending",
326
+ enqueuedAt: now,
327
+ availableAt,
328
+ ...idempotencyKey === void 0 ? {} : { idempotencyKey }
329
+ };
330
+ this.#jobs.set(job.id, job);
331
+ if (idempotencyKey !== void 0) this.#idempotency.set(idempotencyKey, job.id);
332
+ this.#persist(job);
333
+ this.#schedule();
334
+ return freezeJob(job);
335
+ }
336
+ /** Runs every job whose next attempt is due, in batches of the concurrency. */
337
+ async drain() {
338
+ this.#cancelSchedule();
339
+ if (this.#closed) return zeroSummary;
340
+ let completed = 0;
341
+ let retried = 0;
342
+ let deadLettered = 0;
343
+ for (;;) {
344
+ const due = this.#dueJobs().slice(0, this.#options.concurrency);
345
+ if (due.length === 0) break;
346
+ const outcomes = await Promise.all(due.map((job) => this.#process(job)));
347
+ for (const outcome of outcomes) if (outcome === "completed") completed += 1;
348
+ else if (outcome === "retried") retried += 1;
349
+ else deadLettered += 1;
350
+ }
351
+ this.#schedule();
352
+ this.#notifyIdle();
353
+ return Object.freeze({
354
+ completed,
355
+ retried,
356
+ deadLettered,
357
+ skipped: 0
358
+ });
359
+ }
360
+ /** Resolves once nothing is running and no pending job is due right now. */
361
+ async waitForIdle() {
362
+ if (this.#isIdle()) return;
363
+ await new Promise((resolve) => {
364
+ this.#idleWaiters.push(resolve);
365
+ });
366
+ }
367
+ /** The pending and running jobs. */
368
+ pending() {
369
+ return Object.freeze([...this.#jobs.values()].map((job) => freezeJob(job)));
370
+ }
371
+ /** The jobs that exhausted their attempt budget. */
372
+ deadLetters() {
373
+ return Object.freeze([...this.#deadLetters.values()].map((job) => freezeJob(job)));
374
+ }
375
+ /** Moves one dead letter back to pending with a fresh attempt budget. */
376
+ retryDeadLetter(id) {
377
+ this.#assertOpen();
378
+ const job = this.#deadLetters.get(id);
379
+ if (job === void 0) throw invalidJob(`No dead letter job named ${id} exists.`);
380
+ this.#deadLetters.delete(id);
381
+ const revived = {
382
+ ...job,
383
+ attempts: 0,
384
+ state: revivedQueueJobState(),
385
+ availableAt: this.#options.now(),
386
+ lastError: void 0
387
+ };
388
+ this.#jobs.set(id, revived);
389
+ this.#persist(revived);
390
+ this.#schedule();
391
+ return freezeJob(revived);
392
+ }
393
+ /** The current job counts. */
394
+ stats() {
395
+ let pending = 0;
396
+ let running = 0;
397
+ for (const job of this.#jobs.values()) if (job.state === "running") running += 1;
398
+ else pending += 1;
399
+ return Object.freeze({
400
+ pending,
401
+ running,
402
+ deadLettered: this.#deadLetters.size
403
+ });
404
+ }
405
+ /** Stops background draining. Later `enqueue` calls refuse. */
406
+ close() {
407
+ this.#closed = true;
408
+ this.#cancelSchedule();
409
+ for (const controller of this.#controllers) controller.abort();
410
+ this.#notifyIdle();
411
+ }
412
+ /** Stops automatic draining; an explicit `drain()` still runs. */
413
+ pause() {
414
+ this.#paused = true;
415
+ this.#cancelSchedule();
416
+ }
417
+ /** Resumes automatic draining after `pause()`. */
418
+ resume() {
419
+ if (this.#closed) return;
420
+ this.#paused = false;
421
+ this.#schedule();
422
+ }
423
+ /** Whether automatic draining is paused. */
424
+ get paused() {
425
+ return this.#paused;
426
+ }
427
+ /** Drops every job, dead letter, and idempotency key. */
428
+ clear() {
429
+ this.#cancelSchedule();
430
+ this.#jobs.clear();
431
+ this.#deadLetters.clear();
432
+ this.#idempotency.clear();
433
+ this.#track(this.#store?.clear());
434
+ this.#notifyIdle();
435
+ }
436
+ /** Awaits the writes the store has accepted, and rethrows the first failure. */
437
+ async flush() {
438
+ while (this.#writes.length > 0) await Promise.all(this.#writes.splice(0));
439
+ const error = this.#writeError;
440
+ this.#writeError = void 0;
441
+ if (error !== void 0) throw error;
442
+ }
443
+ /** @internal Rebuilds the backlog a store holds when the module initializes. */
444
+ async onModuleInit() {
445
+ const store = this.#store;
446
+ if (store === void 0) return;
447
+ const stored = await store.load();
448
+ for (const job of stored) {
449
+ validateQueueJobState(job.state);
450
+ const revived = mutableJob(job);
451
+ if (revived.state === "failed") {
452
+ this.#setDeadLetter(revived);
453
+ continue;
454
+ }
455
+ revived.state = "pending";
456
+ revived.availableAt = Math.min(revived.availableAt, this.#options.now());
457
+ this.#jobs.set(revived.id, revived);
458
+ if (revived.idempotencyKey !== void 0) this.#idempotency.set(revived.idempotencyKey, revived.id);
459
+ }
460
+ this.#schedule();
461
+ }
462
+ /** @internal The module destroy hook stops background work. */
463
+ async onModuleDestroy() {
464
+ await this.drain();
465
+ this.close();
466
+ await this.flush();
467
+ }
468
+ async #process(job) {
469
+ const running = queueJobMachine().transition("run");
470
+ this.#running.add(job.id);
471
+ job.state = running.state;
472
+ job.attempts += 1;
473
+ const controller = new AbortController();
474
+ this.#controllers.add(controller);
475
+ try {
476
+ const handler = this.#handlers.get(job.name);
477
+ if (handler === void 0) throw new AponiaError("QUEUE_HANDLER_MISSING", `No queue handler is registered for ${job.name}.`, Object.freeze({ name: job.name }));
478
+ await runOutsideAsyncContexts(() => this.#jobRef.run(freezeJob(job), () => {
479
+ const result = handler(job.payload, freezeJob(job), controller.signal);
480
+ return job.timeoutMs > 0 ? withTimeout(result, job.timeoutMs, this.#options.timer, controller) : result;
481
+ }));
482
+ job.state = running.transition("complete").state;
483
+ this.#jobs.delete(job.id);
484
+ this.#forgetIdempotency(job);
485
+ this.#forget(job.id);
486
+ return "completed";
487
+ } catch (error) {
488
+ job.lastError = describeError(error);
489
+ this.#options.onError(error, freezeJob(job));
490
+ if (job.attempts >= job.maxAttempts) {
491
+ this.#jobs.delete(job.id);
492
+ const dead = {
493
+ ...job,
494
+ state: running.transition("fail").state
495
+ };
496
+ this.#setDeadLetter(dead);
497
+ this.#persist(dead);
498
+ return "deadLettered";
499
+ }
500
+ job.state = running.transition("retry").state;
501
+ job.availableAt = this.#options.now() + this.#backoff(job.attempts);
502
+ this.#persist(job);
503
+ return "retried";
504
+ } finally {
505
+ this.#controllers.delete(controller);
506
+ this.#running.delete(job.id);
507
+ }
508
+ }
509
+ #forgetIdempotency(job) {
510
+ if (job.idempotencyKey !== void 0) this.#idempotency.delete(job.idempotencyKey);
511
+ }
512
+ #setDeadLetter(job) {
513
+ if (!this.#deadLetters.has(job.id) && this.#deadLetters.size >= this.#options.maxDeadLetters) {
514
+ const oldest = this.#deadLetters.keys().next().value;
515
+ if (oldest !== void 0) {
516
+ const evicted = this.#deadLetters.get(oldest);
517
+ this.#deadLetters.delete(oldest);
518
+ if (evicted !== void 0) this.#forgetIdempotency(evicted);
519
+ }
520
+ }
521
+ this.#deadLetters.set(job.id, job);
522
+ }
523
+ #persist(job) {
524
+ this.#track(this.#store?.save(freezeJob(job)));
525
+ }
526
+ #forget(id) {
527
+ this.#track(this.#store?.remove(id));
528
+ }
529
+ #track(operation) {
530
+ if (operation === void 0) return;
531
+ this.#writes.push(Promise.resolve(operation).then(() => void 0, (error) => {
532
+ this.#writeError ??= error;
533
+ }));
534
+ }
535
+ #dueJobs() {
536
+ const now = this.#options.now();
537
+ return [...this.#jobs.values()].filter((job) => job.state === "pending" && job.availableAt <= now).toSorted((left, right) => right.priority - left.priority || left.enqueuedAt - right.enqueuedAt || left.id.localeCompare(right.id));
538
+ }
539
+ #backoff(attempts) {
540
+ const delay = this.#options.backoffMs * 2 ** (attempts - 1);
541
+ return Math.min(delay, this.#options.maxBackoffMs);
542
+ }
543
+ #schedule() {
544
+ if (this.#closed || this.#paused || !this.#options.autoStart) return;
545
+ const now = this.#options.now();
546
+ let delay = Number.POSITIVE_INFINITY;
547
+ for (const job of this.#jobs.values()) if (job.state === "pending") delay = Math.min(delay, Math.max(0, job.availableAt - now));
548
+ if (!Number.isFinite(delay)) return;
549
+ if (this.#scheduled !== void 0 && this.#scheduled.delay <= delay) return;
550
+ this.#cancelSchedule();
551
+ const handle = this.#options.timer.setTimeout(() => {
552
+ this.#scheduled = void 0;
553
+ this.drain();
554
+ }, delay);
555
+ this.#scheduled = {
556
+ handle,
557
+ delay
558
+ };
559
+ }
560
+ #cancelSchedule() {
561
+ if (this.#scheduled !== void 0) {
562
+ this.#options.timer.clearTimeout(this.#scheduled.handle);
563
+ this.#scheduled = void 0;
564
+ }
565
+ }
566
+ #isIdle() {
567
+ if (this.#closed) return true;
568
+ return this.#running.size === 0 && this.#dueJobs().length === 0;
569
+ }
570
+ #notifyIdle() {
571
+ if (!this.#isIdle()) return;
572
+ const waiters = this.#idleWaiters.splice(0);
573
+ for (const resolve of waiters) resolve();
574
+ }
575
+ #assertOpen() {
576
+ if (this.#closed) throw invalidJob("The queue is closed.");
577
+ }
578
+ };
579
+ function freezeJob(job) {
580
+ return Object.freeze({
581
+ id: job.id,
582
+ name: job.name,
583
+ payload: job.payload,
584
+ attempts: job.attempts,
585
+ maxAttempts: job.maxAttempts,
586
+ priority: job.priority,
587
+ timeoutMs: job.timeoutMs,
588
+ state: job.state,
589
+ enqueuedAt: job.enqueuedAt,
590
+ availableAt: job.availableAt,
591
+ ...job.idempotencyKey === void 0 ? {} : { idempotencyKey: job.idempotencyKey },
592
+ ...job.lastError === void 0 ? {} : { lastError: job.lastError }
593
+ });
594
+ }
595
+ function mutableJob(job) {
596
+ return {
597
+ id: job.id,
598
+ name: job.name,
599
+ payload: job.payload,
600
+ attempts: job.attempts,
601
+ maxAttempts: job.maxAttempts,
602
+ priority: typeof job.priority === "number" ? job.priority : 0,
603
+ timeoutMs: typeof job.timeoutMs === "number" ? job.timeoutMs : 0,
604
+ state: job.state,
605
+ enqueuedAt: job.enqueuedAt,
606
+ availableAt: job.availableAt,
607
+ ...job.idempotencyKey === void 0 ? {} : { idempotencyKey: job.idempotencyKey },
608
+ ...job.lastError === void 0 ? {} : { lastError: job.lastError }
609
+ };
610
+ }
611
+ function assertStore(store) {
612
+ if (typeof store !== "object" || store === null) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The queue store is invalid.", { issues: Object.freeze(["store must implement QueueStore"]) });
613
+ const missing = [
614
+ "load",
615
+ "save",
616
+ "remove",
617
+ "clear"
618
+ ].filter((method) => typeof store[method] !== "function");
619
+ if (missing.length > 0) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The queue store is invalid.", { issues: Object.freeze([`store is missing ${missing.join(", ")}`]) });
620
+ }
621
+ function withTimeout(value, timeoutMs, timer, controller) {
622
+ return new Promise((resolve, reject) => {
623
+ const handle = timer.setTimeout(() => {
624
+ controller?.abort();
625
+ reject(new AponiaError("QUEUE_JOB_TIMEOUT", "The job exceeded its timeout.", { timeoutMs }));
626
+ }, timeoutMs);
627
+ Promise.resolve(value).then((result) => {
628
+ timer.clearTimeout(handle);
629
+ resolve(result);
630
+ }, (error) => {
631
+ timer.clearTimeout(handle);
632
+ reject(error);
633
+ });
634
+ });
635
+ }
636
+ function describeError(error) {
637
+ return error instanceof Error ? error.message : String(error);
638
+ }
639
+ function invalidJob(issue) {
640
+ return new AponiaError("INVALID_QUEUE_JOB", issue);
641
+ }
642
+ const defaultTimer = Object.freeze({
643
+ setTimeout: (handler, delayMs) => setTimeout(handler, delayMs),
644
+ clearTimeout: (handle) => clearTimeout(handle)
645
+ });
646
+ function resolveQueueOptions(options) {
647
+ const concurrency = options.concurrency ?? 1;
648
+ const maxAttempts = options.maxAttempts ?? 3;
649
+ const backoffMs = options.backoffMs ?? 100;
650
+ const maxBackoffMs = options.maxBackoffMs ?? 3e4;
651
+ const maxJobs = options.maxJobs ?? 1e3;
652
+ const maxDeadLetters = options.maxDeadLetters ?? maxJobs;
653
+ const jobTimeoutMs = options.jobTimeoutMs ?? 0;
654
+ const autoStart = options.autoStart ?? true;
655
+ const issues = [];
656
+ if (!Number.isInteger(concurrency) || concurrency < 1) issues.push("concurrency must be a positive integer");
657
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) issues.push("maxAttempts must be a positive integer");
658
+ if (!Number.isFinite(backoffMs) || backoffMs < 0) issues.push("backoffMs must be a non-negative finite number");
659
+ if (!Number.isFinite(maxBackoffMs) || maxBackoffMs < 0) issues.push("maxBackoffMs must be a non-negative finite number");
660
+ if (!Number.isInteger(maxJobs) || maxJobs < 1) issues.push("maxJobs must be a positive integer");
661
+ if (!Number.isInteger(maxDeadLetters) || maxDeadLetters < 1) issues.push("maxDeadLetters must be a positive integer");
662
+ if (!Number.isInteger(jobTimeoutMs) || jobTimeoutMs < 0) issues.push("jobTimeoutMs must be a non-negative integer");
663
+ if (typeof autoStart !== "boolean") issues.push("autoStart must be a boolean");
664
+ if (options.onError !== void 0 && typeof options.onError !== "function") issues.push("onError must be a function");
665
+ if (options.now !== void 0 && typeof options.now !== "function") issues.push("now must be a function");
666
+ if (issues.length > 0) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The queue registration is invalid.", { issues: Object.freeze([...issues]) });
667
+ return Object.freeze({
668
+ concurrency,
669
+ maxAttempts,
670
+ backoffMs,
671
+ maxBackoffMs,
672
+ maxJobs,
673
+ maxDeadLetters,
674
+ jobTimeoutMs,
675
+ autoStart,
676
+ now: options.now ?? Date.now,
677
+ timer: options.timer ?? defaultTimer,
678
+ onError: options.onError ?? (() => {})
679
+ });
680
+ }
681
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorateMetadata.js
682
+ function __decorateMetadata(k, v) {
683
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
684
+ }
685
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorateParam.js
686
+ function __decorateParam(paramIndex, decorator) {
687
+ return function(target, key) {
688
+ decorator(target, key, paramIndex);
689
+ };
690
+ }
691
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorate.js
692
+ function __decorate(decorators, target, key, desc) {
693
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
694
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
695
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
696
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
697
+ }
698
+ // src/processors/processor.explorer.ts
699
+ let ProcessorExplorer = class ProcessorExplorer {
700
+ #queue;
701
+ #moduleRef;
702
+ constructor(queue, moduleRef) {
703
+ this.#queue = queue;
704
+ this.#moduleRef = moduleRef;
705
+ }
706
+ onModuleInit() {
707
+ for (const processorClass of getProcessorClasses()) {
708
+ const options = getProcessorOptions(processorClass);
709
+ if (options === void 0) continue;
710
+ let instance;
711
+ try {
712
+ instance = this.#moduleRef.get(processorClass, { strict: false });
713
+ } catch {
714
+ continue;
715
+ }
716
+ assertProcessor(instance);
717
+ const processor = instance;
718
+ this.#queue.registerHandler(options.name ?? "default", (_payload, job) => processor.process(job));
719
+ }
720
+ }
721
+ };
722
+ ProcessorExplorer = __decorate([
723
+ Injectable(),
724
+ __decorateParam(0, Inject(QueueService)),
725
+ __decorateParam(1, Inject(ModuleRef)),
726
+ __decorateMetadata("design:paramtypes", [typeof QueueService === "undefined" ? Object : QueueService, typeof ModuleRef === "undefined" ? Object : ModuleRef])
727
+ ], ProcessorExplorer);
728
+ // src/queue.module-definition.ts
729
+ const builder = new ConfigurableModuleBuilder({ moduleName: "Queue" }).setExtras({
730
+ isGlobal: false,
731
+ name: "default"
732
+ }, (definition, extras) => ({
733
+ ...definition,
734
+ global: extras.isGlobal ?? false
735
+ })).build();
736
+ /**
737
+ * The generated registration class, options token, and type markers.
738
+ *
739
+ * `MODULE_OPTIONS_TOKEN` is the `QUEUE_MODULE_OPTIONS` token; `OPTIONS_TYPE` and
740
+ * `ASYNC_OPTIONS_TYPE` are type markers that throw when read as values.
741
+ */
742
+ const { ConfigurableModuleClass, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = builder;
743
+ /** The options token, narrowed to the explicit token the builder mints. */
744
+ const MODULE_OPTIONS_TOKEN = builder.MODULE_OPTIONS_TOKEN;
745
+ // src/queue.module.ts
746
+ var _QueueModule;
747
+ const QUEUE_OPTIONS = createToken("aponia.queue.options");
748
+ let QueueModule = _QueueModule = class QueueModule extends ConfigurableModuleClass {
749
+ /**
750
+ * Builds one queue registration.
751
+ *
752
+ * Both the queue and the outbox options are validated at registration, so a
753
+ * malformed bound or store fails before the module is imported.
754
+ *
755
+ * @param options - The queue and outbox options, and the queue name.
756
+ * @returns A frozen dynamic module an application imports.
757
+ * @throws An `AponiaError` with `INVALID_QUEUE_OPTIONS` when an option is invalid.
758
+ */
759
+ static forRoot(options = {}) {
760
+ resolveOptions(options);
761
+ assertExtras(options);
762
+ return registration(super.register(options), options.name ?? "default");
763
+ }
764
+ /**
765
+ * Builds a queue registration whose options a factory, a class, or an
766
+ * existing provider resolves.
767
+ *
768
+ * The options are resolved once when the options token first resolves, and
769
+ * validated then, so a refused boot names the same issues `forRoot` reports.
770
+ *
771
+ * @param options - The imports, injected tokens, factory, extras, and extra providers.
772
+ * @returns A frozen dynamic module an application imports.
773
+ */
774
+ static forRootAsync(options) {
775
+ assertExtras(options);
776
+ return registration(super.registerAsync(options), options.name ?? "default", options.extraProviders);
777
+ }
778
+ /**
779
+ * Builds one queue registration.
780
+ *
781
+ * @deprecated Use {@link QueueModule.forRoot}; retained for the beta line.
782
+ */
783
+ static register(options = {}) {
784
+ return _QueueModule.forRoot(options);
785
+ }
786
+ /**
787
+ * Builds a queue registration whose options a factory resolves.
788
+ *
789
+ * @deprecated Use {@link QueueModule.forRootAsync}; retained for the beta line.
790
+ */
791
+ static registerAsync(options) {
792
+ return _QueueModule.forRootAsync(options);
793
+ }
794
+ };
795
+ QueueModule = _QueueModule = __decorate([Module({})], QueueModule);
796
+ function registration(definition, name, extraProviders = []) {
797
+ const queueToken = getQueueToken(name);
798
+ return Object.freeze({
799
+ ...definition,
800
+ module: QueueModule,
801
+ imports: Object.freeze([...definition.imports ?? []]),
802
+ controllers: Object.freeze([...definition.controllers ?? []]),
803
+ providers: Object.freeze([
804
+ ...definition.providers ?? [],
805
+ provideFactory(QUEUE_OPTIONS, [MODULE_OPTIONS_TOKEN], (options) => resolveOptions(options)),
806
+ provideFactory(JobRefService, [], () => new JobRefService()),
807
+ provideFactory(QueueService, [QUEUE_OPTIONS, JobRefService], (options, jobRef) => new QueueService(options.queue, jobRef)),
808
+ provideFactory(OutboxService, [QUEUE_OPTIONS], (options) => new OutboxService(options.outbox)),
809
+ provideFactory(JOB_REF, [JobRefService], (jobRef) => jobRef.proxy()),
810
+ provideAlias(queueToken, QueueService),
811
+ provideClass(ProcessorExplorer, [QueueService, ModuleRef]),
812
+ ...extraProviders
813
+ ]),
814
+ exports: Object.freeze([
815
+ MODULE_OPTIONS_TOKEN,
816
+ queueToken,
817
+ JOB_REF,
818
+ QueueService,
819
+ OutboxService
820
+ ])
821
+ });
822
+ }
823
+ function assertExtras(options) {
824
+ const issues = [];
825
+ if (options.isGlobal !== void 0 && typeof options.isGlobal !== "boolean") issues.push("isGlobal must be a boolean");
826
+ if (options.name !== void 0 && (typeof options.name !== "string" || options.name.trim() === "")) issues.push("name must be a non-empty string");
827
+ if (issues.length > 0) throw invalid(issues);
828
+ }
829
+ /**
830
+ * Validates one registration's queue and outbox options.
831
+ *
832
+ * The issue list is total: every field that fails is reported, so a refused
833
+ * boot names the whole set rather than the first one found.
834
+ *
835
+ * @param options - The registration options to validate.
836
+ * @returns The frozen options the queue and outbox read.
837
+ * @throws An `AponiaError` with `INVALID_QUEUE_OPTIONS`.
838
+ */
839
+ function resolveOptions(options) {
840
+ if (typeof options !== "object" || options === null) throw invalid(["options must be an object"]);
841
+ const issues = [...validateQueue(options.queue), ...validateOutbox(options.outbox)];
842
+ if (issues.length > 0) throw invalid(issues);
843
+ return Object.freeze({ ...options });
844
+ }
845
+ function validateQueue(options) {
846
+ if (options === void 0) return [];
847
+ if (typeof options !== "object" || options === null) return ["queue must be an object when present"];
848
+ const issues = [];
849
+ for (const name of [
850
+ "concurrency",
851
+ "maxAttempts",
852
+ "maxJobs",
853
+ "maxDeadLetters"
854
+ ]) {
855
+ const value = options[name];
856
+ if (value !== void 0 && (!Number.isInteger(value) || value < 1)) issues.push(`${name} must be a positive integer`);
857
+ }
858
+ for (const name of ["backoffMs", "maxBackoffMs"]) {
859
+ const value = options[name];
860
+ if (value !== void 0 && (!Number.isFinite(value) || value < 0)) issues.push(`${name} must be a non-negative finite number`);
861
+ }
862
+ if (options.jobTimeoutMs !== void 0 && (!Number.isInteger(options.jobTimeoutMs) || options.jobTimeoutMs < 0)) issues.push("jobTimeoutMs must be a non-negative integer");
863
+ for (const name of ["autoStart"]) if (options[name] !== void 0 && typeof options[name] !== "boolean") issues.push(`${name} must be a boolean`);
864
+ for (const name of ["onError", "now"]) if (options[name] !== void 0 && typeof options[name] !== "function") issues.push(`${name} must be a function`);
865
+ issues.push(...validateQueueStore(options.store));
866
+ return issues;
867
+ }
868
+ function validateQueueStore(store) {
869
+ if (store === void 0) return [];
870
+ if (typeof store !== "object" || store === null) return ["store must implement QueueStore"];
871
+ const missing = [
872
+ "load",
873
+ "save",
874
+ "remove",
875
+ "clear"
876
+ ].filter((method) => typeof store[method] !== "function");
877
+ return missing.length > 0 ? [`store is missing ${missing.join(", ")}`] : [];
878
+ }
879
+ function validateOutbox(options) {
880
+ if (options === void 0) return [];
881
+ if (typeof options !== "object" || options === null) return ["outbox must be an object when present"];
882
+ const issues = [];
883
+ if (options.maxEntries !== void 0 && (!Number.isInteger(options.maxEntries) || options.maxEntries < 1)) issues.push("outbox.maxEntries must be a positive integer");
884
+ if (options.now !== void 0 && typeof options.now !== "function") issues.push("outbox.now must be a function");
885
+ issues.push(...validateOutboxStore(options.store));
886
+ return issues;
887
+ }
888
+ function validateOutboxStore(store) {
889
+ if (store === void 0) return [];
890
+ if (typeof store !== "object" || store === null) return ["outbox.store must implement OutboxStore"];
891
+ const missing = [
892
+ "list",
893
+ "append",
894
+ "update",
895
+ "remove",
896
+ "clear"
897
+ ].filter((method) => typeof store[method] !== "function");
898
+ return missing.length > 0 ? [`outbox.store is missing ${missing.join(", ")}`] : [];
899
+ }
900
+ function invalid(issues) {
901
+ return new AponiaError("INVALID_QUEUE_OPTIONS", "The queue registration is invalid.", { issues: Object.freeze([...issues]) });
902
+ }
903
+ // src/hosts/worker-host.ts
904
+ /**
905
+ * The base class a `@Processor()` implements.
906
+ *
907
+ * `@nestjs/bullmq`'s `WorkerHost` exposes a BullMQ `Worker` and an abstract
908
+ * `process(job)`. This package has no broker worker: `process` receives the
909
+ * in-process queue's frozen job snapshot, and `worker` refuses rather than
910
+ * inventing one.
911
+ *
912
+ * @example
913
+ * ```ts
914
+ * @Processor("email")
915
+ * class EmailProcessor extends WorkerHost {
916
+ * async process(job: QueueJob<{ to: string }>): Promise<void> { ... }
917
+ * }
918
+ * ```
919
+ */
920
+ var WorkerHost = class {
921
+ /**
922
+ * The broker worker, which this package does not have.
923
+ *
924
+ * @throws An `AponiaError` with `INVALID_QUEUE_JOB`; use the `process(job)`
925
+ * argument.
926
+ */
927
+ get worker() {
928
+ throw new AponiaError("INVALID_QUEUE_JOB", "WorkerHost.worker is unavailable: this package runs an in-process queue with no broker worker.");
929
+ }
930
+ };
931
+ // src/outbox/sqlite-outbox.store.ts
932
+ const validTableName = /^[A-Za-z_][A-Za-z0-9_]*$/;
933
+ /**
934
+ * A durable outbox over SQLite.
935
+ *
936
+ * The application owns the database and its file; this class owns one table and
937
+ * creates it if it is absent. Payloads are stored as JSON, so a value that
938
+ * `JSON.stringify` cannot state is stored as `null` rather than losing the
939
+ * message.
940
+ */
941
+ var SqliteOutboxStore = class {
942
+ #database;
943
+ #table;
944
+ constructor(options) {
945
+ const table = options.table ?? "aponia_outbox";
946
+ if (!validTableName.test(table)) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The SQLite outbox table name must be a plain identifier.", { issues: Object.freeze(["table must match /^[A-Za-z_][A-Za-z0-9_]*$/"]) });
947
+ this.#database = options.database;
948
+ this.#table = table;
949
+ this.#database.run(`CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, payload TEXT NOT NULL, attempts INTEGER NOT NULL, recorded_at INTEGER NOT NULL)`);
950
+ }
951
+ list() {
952
+ const rows = this.#database.query(`SELECT id, name, payload, attempts, recorded_at FROM "${this.#table}" ORDER BY recorded_at ASC, id ASC`).all();
953
+ return Object.freeze(rows.map((row) => Object.freeze({
954
+ id: row.id,
955
+ name: row.name,
956
+ payload: JSON.parse(row.payload),
957
+ attempts: row.attempts,
958
+ recordedAt: row.recorded_at
959
+ })));
960
+ }
961
+ append(message) {
962
+ this.#database.query(`INSERT OR REPLACE INTO "${this.#table}" (id, name, payload, attempts, recorded_at) VALUES (?, ?, ?, ?, ?)`).run(message.id, message.name, JSON.stringify(message.payload) ?? "null", message.attempts, message.recordedAt);
963
+ }
964
+ update(message) {
965
+ this.#database.query(`UPDATE "${this.#table}" SET attempts = ? WHERE id = ?`).run(message.attempts, message.id);
966
+ }
967
+ remove(id) {
968
+ this.#database.query(`DELETE FROM "${this.#table}" WHERE id = ?`).run(id);
969
+ }
970
+ clear() {
971
+ this.#database.run(`DELETE FROM "${this.#table}"`);
972
+ }
973
+ };
974
+ // src/queue/memory-queue.store.ts
975
+ /** A bounded in-memory backlog, for tests and single-process durability checks. */
976
+ var MemoryQueueStore = class {
977
+ #jobs = /* @__PURE__ */ new Map();
978
+ #maxJobs;
979
+ constructor(options = {}) {
980
+ const maxJobs = options.maxJobs ?? 1e3;
981
+ if (!Number.isInteger(maxJobs) || maxJobs < 1) throw new AponiaError("INVALID_QUEUE_OPTIONS", "The queue store is invalid.", { issues: Object.freeze(["maxJobs must be a positive integer"]) });
982
+ this.#maxJobs = maxJobs;
983
+ }
984
+ load() {
985
+ return Object.freeze([...this.#jobs.values()]);
986
+ }
987
+ save(job) {
988
+ if (!this.#jobs.has(job.id) && this.#jobs.size >= this.#maxJobs) {
989
+ const oldest = this.#jobs.keys().next().value;
990
+ if (oldest !== void 0) this.#jobs.delete(oldest);
991
+ }
992
+ this.#jobs.set(job.id, job);
993
+ }
994
+ remove(id) {
995
+ this.#jobs.delete(id);
996
+ }
997
+ clear() {
998
+ this.#jobs.clear();
999
+ }
1000
+ };
1001
+ export { InjectQueue, JOB_REF, JobRefService, MODULE_OPTIONS_TOKEN, MemoryQueueStore, OutboxService, Processor, QueueModule, QueueService, SqliteOutboxStore, WorkerHost, getQueueToken };