@dads-framework/job-queue 0.0.0-stage → 0.1.0

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.
Files changed (40) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +12 -2
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/job-queue.tsbuildinfo +1 -0
  8. package/dist/lib/bullmq-job-options.d.ts +5 -0
  9. package/dist/lib/bullmq-job-options.d.ts.map +1 -0
  10. package/dist/lib/bullmq-job-options.js +12 -0
  11. package/dist/lib/bullmq-job-options.js.map +1 -0
  12. package/dist/lib/bullmq-job-queue.d.ts +67 -0
  13. package/dist/lib/bullmq-job-queue.d.ts.map +1 -0
  14. package/dist/lib/bullmq-job-queue.js +264 -0
  15. package/dist/lib/bullmq-job-queue.js.map +1 -0
  16. package/dist/lib/create-job-queue.d.ts +23 -0
  17. package/dist/lib/create-job-queue.d.ts.map +1 -0
  18. package/dist/lib/create-job-queue.js +19 -0
  19. package/dist/lib/create-job-queue.js.map +1 -0
  20. package/dist/lib/in-process-job-queue.d.ts +24 -0
  21. package/dist/lib/in-process-job-queue.d.ts.map +1 -0
  22. package/dist/lib/in-process-job-queue.js +174 -0
  23. package/dist/lib/in-process-job-queue.js.map +1 -0
  24. package/dist/lib/job-actor.d.ts +14 -0
  25. package/dist/lib/job-actor.d.ts.map +1 -0
  26. package/dist/lib/job-actor.js +16 -0
  27. package/dist/lib/job-actor.js.map +1 -0
  28. package/dist/lib/logic/job-attempts.d.ts +30 -0
  29. package/dist/lib/logic/job-attempts.d.ts.map +1 -0
  30. package/dist/lib/logic/job-attempts.js +28 -0
  31. package/dist/lib/logic/job-attempts.js.map +1 -0
  32. package/dist/lib/redis-connection.d.ts +4 -0
  33. package/dist/lib/redis-connection.d.ts.map +1 -0
  34. package/dist/lib/redis-connection.js +61 -0
  35. package/dist/lib/redis-connection.js.map +1 -0
  36. package/dist/testing.d.ts +7 -0
  37. package/dist/testing.d.ts.map +1 -0
  38. package/dist/testing.js +7 -0
  39. package/dist/testing.js.map +1 -0
  40. package/package.json +45 -4
@@ -0,0 +1,264 @@
1
+ import { Queue, Worker } from "bullmq";
2
+ import { runWithAuditActor } from "@dads-framework/audit-actor";
3
+ import { bullMqJobOptions } from "./bullmq-job-options.js";
4
+ import { jobRunActor } from "./job-actor.js";
5
+ import { describeJobs, } from "@dads-framework/job-queue-core";
6
+ import { JobRegistry } from "@dads-framework/job-queue-core/provider";
7
+ import { attemptsOf, isTerminalAttempt, } from "./logic/job-attempts.js";
8
+ import { redisConnection } from "./redis-connection.js";
9
+ /** BullMQ adapter: Redis owns durable work, retries, and recurring schedules. */
10
+ export class BullMqJobQueue {
11
+ log;
12
+ queueName;
13
+ concurrency;
14
+ diagnostics;
15
+ registry = new JobRegistry();
16
+ queue;
17
+ connection;
18
+ worker;
19
+ started = false;
20
+ // The lifecycle is serialized: a `close()` that overlaps a `start()` waits
21
+ // for that start to settle, and each worker is torn down exactly once no
22
+ // matter which path gets there first. Otherwise a shutdown lands in the
23
+ // middle of the worker's Redis handshake — the `Connection is closed.`
24
+ // window described on `waitUntilReady` below.
25
+ /** The in-flight `start()`, while one is running. */
26
+ starting;
27
+ /**
28
+ * The one `worker.close()` per worker; every other caller awaits that same
29
+ * promise. Keyed by the worker because a `start()` that fails leaves
30
+ * `started` false, so a retry builds a replacement worker — shared state
31
+ * here would report that replacement as already closed and leave it holding
32
+ * its Redis connections.
33
+ */
34
+ closingWorkers = new WeakMap();
35
+ /**
36
+ * The in-flight or finished `close()`; a second `close()` awaits it. Sticky
37
+ * on purpose: `close()` closes the queue too, and the driver has no
38
+ * restart-after-close lifecycle (see docs/reference/job-queue.md).
39
+ */
40
+ closing;
41
+ /**
42
+ * One failed attempt, logged — and reported only if it was the last one.
43
+ *
44
+ * `willRetry` is the difference between "this job is having a bad minute"
45
+ * and "this work is lost". A line that does not say which makes every
46
+ * failure look equally alarming, and the ones that matter become
47
+ * indistinguishable from the ones that do not. For the same reason only the
48
+ * final attempt is captured: reporting every retry would make one flaky job
49
+ * look like a hundred bugs.
50
+ */
51
+ reportFailedJob(jobName, jobId, attempts, error) {
52
+ this.log.error({
53
+ event: "job.failed",
54
+ jobName: jobName ?? "unknown",
55
+ jobId,
56
+ attemptsMade: attempts.made,
57
+ attempts: attempts.allowed,
58
+ willRetry: !isTerminalAttempt(attempts),
59
+ err: error,
60
+ }, "job failed");
61
+ if (!isTerminalAttempt(attempts))
62
+ return;
63
+ this.diagnostics?.captureException({
64
+ error,
65
+ source: "job",
66
+ ...(jobName === undefined ? {} : { jobName }),
67
+ });
68
+ }
69
+ constructor(redisUrl, log, queueName, concurrency = 5,
70
+ /**
71
+ * Where a permanently failed job goes besides the log line.
72
+ * Optional: a queue built without one behaves exactly as it does today.
73
+ */
74
+ diagnostics) {
75
+ this.log = log;
76
+ this.queueName = queueName;
77
+ this.concurrency = concurrency;
78
+ this.diagnostics = diagnostics;
79
+ if (queueName.trim().length === 0) {
80
+ throw new Error("BullMQ queue name must not be empty");
81
+ }
82
+ this.connection = redisConnection(redisUrl);
83
+ this.queue = new Queue(queueName, { connection: this.connection });
84
+ this.queue.on("error", (error) => {
85
+ this.log.error({ event: "job.queue.error", err: error }, "job queue error");
86
+ });
87
+ }
88
+ register(jobs) {
89
+ if (this.started) {
90
+ throw new Error("Jobs must be registered before the job queue starts");
91
+ }
92
+ this.registry.register(jobs);
93
+ }
94
+ async start() {
95
+ if (this.started) {
96
+ throw new Error("Job queue has already been started");
97
+ }
98
+ this.started = true;
99
+ // Published before the first await, so a `close()` arriving in the very
100
+ // next tick already has something to wait on.
101
+ this.starting = this.startConsuming();
102
+ try {
103
+ await this.starting;
104
+ }
105
+ finally {
106
+ this.starting = undefined;
107
+ }
108
+ }
109
+ async startConsuming() {
110
+ try {
111
+ await this.reconcileSchedules();
112
+ this.worker = new Worker(this.queueName, async (job) => {
113
+ const definition = this.registry.get(job.name);
114
+ // Attributed to the job, with a per-run request id — see jobRunActor
115
+ // and ADR-0112. Logged so one run's audit rows can be found.
116
+ const actor = jobRunActor(job.name);
117
+ this.log.info({
118
+ event: "job.started",
119
+ jobName: job.name,
120
+ jobId: job.id,
121
+ requestId: actor.requestId,
122
+ }, "job started");
123
+ await runWithAuditActor(actor, () => definition.run(job.data));
124
+ }, { connection: this.connection, concurrency: this.concurrency });
125
+ this.worker.on("completed", (job) => {
126
+ this.log.info({ event: "job.completed", jobName: job.name, jobId: job.id }, "job completed");
127
+ });
128
+ this.worker.on("failed", (job, error) => {
129
+ this.reportFailedJob(job?.name, job?.id, attemptsOf(job), error);
130
+ });
131
+ this.worker.on("error", (error) => {
132
+ this.log.error({ event: "job.worker.error", err: error }, "job worker error");
133
+ });
134
+ // Started means consuming. BullMQ opens the worker's two connections in
135
+ // its constructor and finishes them asynchronously, and closing one that
136
+ // is still initializing makes BullMQ drop its own listeners and then emit
137
+ // `error` on the listener-less connection — an unhandled
138
+ // `Error: Connection is closed.` nobody can catch. Resolving only once
139
+ // both connections are ready keeps `close()` out of that window.
140
+ await this.worker.waitUntilReady();
141
+ }
142
+ catch (error) {
143
+ this.started = false;
144
+ // `started = false` claims nothing is running, so nothing may be left
145
+ // holding a Redis connection.
146
+ const abandoned = this.worker;
147
+ this.worker = undefined;
148
+ if (abandoned) {
149
+ await this.closeWorkerOnce(abandoned);
150
+ }
151
+ throw error;
152
+ }
153
+ }
154
+ async enqueue(jobName, payload) {
155
+ const definition = this.registry.get(jobName);
156
+ await this.queue.add(jobName, payload, bullMqJobOptions(definition));
157
+ }
158
+ async inspect() {
159
+ const [schedulers, counts] = await Promise.all([
160
+ this.queue.getJobSchedulers(0, -1, true),
161
+ this.queue.getJobCounts("waiting", "active", "delayed", "completed", "failed"),
162
+ ]);
163
+ return {
164
+ driver: "bullmq",
165
+ queueName: this.queueName,
166
+ jobs: describeJobs(this.registry.list()),
167
+ schedules: schedulers.map(describeBullMqSchedule),
168
+ counts: {
169
+ waiting: counts["waiting"] ?? 0,
170
+ active: counts["active"] ?? 0,
171
+ delayed: counts["delayed"] ?? 0,
172
+ completed: counts["completed"] ?? 0,
173
+ failed: counts["failed"] ?? 0,
174
+ },
175
+ };
176
+ }
177
+ async close() {
178
+ this.closing ??= this.closeOnce();
179
+ await this.closing;
180
+ }
181
+ async closeOnce() {
182
+ const starting = this.starting;
183
+ if (starting) {
184
+ // Wait out the readiness handshake before touching the worker. Only the
185
+ // ordering is taken from it — the failure itself is still delivered to
186
+ // `start()`'s own caller, which is the one that asked for it.
187
+ await starting.catch(() => undefined);
188
+ }
189
+ const running = this.worker;
190
+ this.worker = undefined;
191
+ if (running) {
192
+ await this.closeWorkerOnce(running);
193
+ }
194
+ await this.queue.close();
195
+ }
196
+ /**
197
+ * Whichever arrives first — `start()`'s failure path or `close()` — performs
198
+ * the single `worker.close()` for that worker; the other awaits that same
199
+ * promise. A worker the driver has abandoned never answers for the one that
200
+ * replaced it.
201
+ */
202
+ closeWorkerOnce(worker) {
203
+ const alreadyClosing = this.closingWorkers.get(worker);
204
+ if (alreadyClosing) {
205
+ return alreadyClosing;
206
+ }
207
+ const closingWorker = worker.close();
208
+ this.closingWorkers.set(worker, closingWorker);
209
+ return closingWorker;
210
+ }
211
+ async reconcileSchedules() {
212
+ const expectedScheduleIds = new Set(this.registry
213
+ .list()
214
+ .flatMap((definition) => definition.schedules.map((schedule) => schedule.id)));
215
+ const existingSchedules = await this.queue.getJobSchedulers(0, -1, true);
216
+ for (const schedule of existingSchedules) {
217
+ if (!expectedScheduleIds.has(schedule.key)) {
218
+ await this.queue.removeJobScheduler(schedule.key);
219
+ this.log.info({
220
+ event: "job.schedule.removed",
221
+ jobName: schedule.name,
222
+ scheduleId: schedule.key,
223
+ }, "stale job schedule removed");
224
+ }
225
+ }
226
+ for (const definition of this.registry.list()) {
227
+ for (const schedule of definition.schedules) {
228
+ const repeat = schedule.kind === "cron"
229
+ ? { pattern: schedule.pattern, tz: schedule.timeZone }
230
+ : { every: schedule.everyMs };
231
+ await this.queue.upsertJobScheduler(schedule.id, repeat, {
232
+ name: definition.name,
233
+ data: schedule.payload,
234
+ opts: bullMqJobOptions(definition),
235
+ });
236
+ this.log.info({
237
+ event: "job.schedule.registered",
238
+ jobName: definition.name,
239
+ scheduleId: schedule.id,
240
+ }, "job schedule registered");
241
+ }
242
+ }
243
+ }
244
+ }
245
+ function describeBullMqSchedule(scheduler) {
246
+ if (scheduler.pattern) {
247
+ return {
248
+ id: scheduler.key,
249
+ jobName: scheduler.name,
250
+ kind: "cron",
251
+ pattern: scheduler.pattern,
252
+ ...(scheduler.tz === undefined ? {} : { timeZone: scheduler.tz }),
253
+ nextRunAt: scheduler.next ? new Date(scheduler.next).toISOString() : null,
254
+ };
255
+ }
256
+ return {
257
+ id: scheduler.key,
258
+ jobName: scheduler.name,
259
+ kind: "interval",
260
+ ...(scheduler.every === undefined ? {} : { everyMs: scheduler.every }),
261
+ nextRunAt: scheduler.next ? new Date(scheduler.next).toISOString() : null,
262
+ };
263
+ }
264
+ //# sourceMappingURL=bullmq-job-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bullmq-job-queue.js","sourceRoot":"","sources":["../../src/lib/bullmq-job-queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAGhE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EACL,YAAY,GAMb,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,yCAAyC,CAAC;AACtE,OAAO,EACL,UAAU,EACV,iBAAiB,GAElB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;A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AE,SAAS,CAAC,GAAG;QACjB,OAAO,EAAE,SAAS,CAAC,IAAI;QACvB,IAAI,EAAE,UAAU;QAChB,GAAG,CAAC,SAAS,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;QACtE,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI;KAC1E,CAAC;AACJ,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { DiagnosticsReporter } from "@dads-framework/diagnostics";
2
+ import type { JobLog, JobQueue } from "@dads-framework/job-queue-core";
3
+ export type CreateJobQueueOptions = {
4
+ /** Stable application namespace; different applications use different queues. */
5
+ readonly queueName: string;
6
+ /** "in-process" (tests, container-free dev) or "bullmq" (compose, prod). */
7
+ readonly driver: "in-process" | "bullmq";
8
+ /** required when driver is "bullmq" */
9
+ readonly redisUrl?: string;
10
+ /** Explicit worker bound (process-discipline bar). */
11
+ readonly concurrency?: number;
12
+ /**
13
+ * Where a permanently failed job goes besides its log line.
14
+ * Only the LAST attempt is reported; a retry is not a fault yet.
15
+ */
16
+ readonly diagnostics?: DiagnosticsReporter;
17
+ };
18
+ /**
19
+ * Pick the in-process or BullMQ driver from JOBS_DRIVER. The driver is an
20
+ * env decision, never a code one.
21
+ */
22
+ export declare function createJobQueue(options: CreateJobQueueOptions, log: JobLog): JobQueue;
23
+ //# sourceMappingURL=create-job-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-job-queue.d.ts","sourceRoot":"","sources":["../../src/lib/create-job-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAGvE,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAEvE,MAAM,MAAM,qBAAqB,GAAG;IAClC,iFAAiF;IACjF,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,4EAA4E;IAC5E,QAAQ,CAAC,MAAM,EAAE,YAAY,GAAG,QAAQ,CAAC;IACzC,uCAAuC;IACvC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,mBAAmB,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,qBAAqB,EAC9B,GAAG,EAAE,MAAM,GACV,QAAQ,CAiBV"}
@@ -0,0 +1,19 @@
1
+ import { BullMqJobQueue } from "./bullmq-job-queue.js";
2
+ import { InProcessJobQueue } from "./in-process-job-queue.js";
3
+ /**
4
+ * Pick the in-process or BullMQ driver from JOBS_DRIVER. The driver is an
5
+ * env decision, never a code one.
6
+ */
7
+ export function createJobQueue(options, log) {
8
+ if (options.queueName.trim().length === 0) {
9
+ throw new Error("Job queue name must not be empty");
10
+ }
11
+ if (options.driver === "bullmq") {
12
+ if (!options.redisUrl) {
13
+ throw new Error("JOBS_DRIVER=bullmq requires REDIS_URL");
14
+ }
15
+ return new BullMqJobQueue(options.redisUrl, log, options.queueName, options.concurrency ?? 5, options.diagnostics);
16
+ }
17
+ return new InProcessJobQueue(log, options.queueName);
18
+ }
19
+ //# sourceMappingURL=create-job-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-job-queue.js","sourceRoot":"","sources":["../../src/lib/create-job-queue.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAmB9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAC5B,OAA8B,EAC9B,GAAW;IAEX,IAAI,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACtD,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO,IAAI,cAAc,CACvB,OAAO,CAAC,QAAQ,EAChB,GAAG,EACH,OAAO,CAAC,SAAS,EACjB,OAAO,CAAC,WAAW,IAAI,CAAC,EACxB,OAAO,CAAC,WAAW,CACpB,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,iBAAiB,CAAC,GAAG,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;AACvD,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { type JobDefinition, type JobLog, type JobQueue, type JobQueueInspection } from "@dads-framework/job-queue-core";
2
+ /**
3
+ * Container-free driver for tests and local development. It uses BullMQ's
4
+ * cron calculation, but is intentionally not durable and does not retry.
5
+ */
6
+ export declare class InProcessJobQueue implements JobQueue {
7
+ private readonly log;
8
+ private readonly queueName;
9
+ private readonly registry;
10
+ private readonly timers;
11
+ private readonly activeRuns;
12
+ private counts;
13
+ private started;
14
+ constructor(log: JobLog, queueName?: string);
15
+ register(jobs: readonly JobDefinition[]): void;
16
+ start(): Promise<void>;
17
+ enqueue(jobName: string, payload: unknown): Promise<void>;
18
+ inspect(): Promise<JobQueueInspection>;
19
+ close(): Promise<void>;
20
+ private runJob;
21
+ private cancelTimers;
22
+ private scheduleNextRun;
23
+ }
24
+ //# sourceMappingURL=in-process-job-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-process-job-queue.d.ts","sourceRoot":"","sources":["../../src/lib/in-process-job-queue.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,aAAa,EAElB,KAAK,MAAM,EACX,KAAK,QAAQ,EAEb,KAAK,kBAAkB,EAExB,MAAM,gCAAgC,CAAC;AAUxC;;;GAGG;AACH,qBAAa,iBAAkB,YAAW,QAAQ;IAQ9C,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAR5B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqC;IAC5D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA4B;IACvD,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,OAAO,CAAS;IAExB,YACmB,GAAG,EAAE,MAAM,EACX,SAAS,SAAa,EACrC;IAEJ,QAAQ,CAAC,IAAI,EAAE,SAAS,aAAa,EAAE,GAAG,IAAI,CAK7C;IAED,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAmCrB;IAED,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAWxD;IAED,OAAO,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAQrC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAG3B;YAEa,MAAM;IAuCpB,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,eAAe;CAkBxB"}
@@ -0,0 +1,174 @@
1
+ import { getNextMillis } from "bullmq";
2
+ import { runWithAuditActor } from "@dads-framework/audit-actor";
3
+ import { jobRunActor } from "./job-actor.js";
4
+ import { describeJobs, } from "@dads-framework/job-queue-core";
5
+ import { JobRegistry } from "@dads-framework/job-queue-core/provider";
6
+ /**
7
+ * Container-free driver for tests and local development. It uses BullMQ's
8
+ * cron calculation, but is intentionally not durable and does not retry.
9
+ */
10
+ export class InProcessJobQueue {
11
+ log;
12
+ queueName;
13
+ registry = new JobRegistry();
14
+ timers = new Map();
15
+ activeRuns = new Set();
16
+ counts = emptyCounts();
17
+ started = false;
18
+ constructor(log, queueName = "dads-api") {
19
+ this.log = log;
20
+ this.queueName = queueName;
21
+ }
22
+ register(jobs) {
23
+ if (this.started) {
24
+ throw new Error("Jobs must be registered before the job queue starts");
25
+ }
26
+ this.registry.register(jobs);
27
+ }
28
+ start() {
29
+ if (this.started) {
30
+ return Promise.reject(new Error("Job queue has already been started"));
31
+ }
32
+ this.started = true;
33
+ try {
34
+ for (const definition of this.registry.list()) {
35
+ for (const schedule of definition.schedules) {
36
+ const scheduled = {
37
+ jobName: definition.name,
38
+ schedule,
39
+ timer: undefined,
40
+ nextRunAt: null,
41
+ };
42
+ this.timers.set(schedule.id, scheduled);
43
+ this.scheduleNextRun(scheduled);
44
+ this.log.info({
45
+ event: "job.schedule.registered",
46
+ jobName: definition.name,
47
+ scheduleId: schedule.id,
48
+ }, "job schedule registered");
49
+ }
50
+ }
51
+ return Promise.resolve();
52
+ }
53
+ catch (error) {
54
+ this.cancelTimers();
55
+ this.timers.clear();
56
+ this.started = false;
57
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
58
+ }
59
+ }
60
+ enqueue(jobName, payload) {
61
+ const definition = this.registry.get(jobName);
62
+ this.counts = { ...this.counts, waiting: this.counts.waiting + 1 };
63
+ const execution = Promise.resolve().then(() => this.runJob(jobName, payload, definition));
64
+ this.activeRuns.add(execution);
65
+ void execution.finally(() => {
66
+ this.activeRuns.delete(execution);
67
+ });
68
+ return Promise.resolve();
69
+ }
70
+ inspect() {
71
+ return Promise.resolve({
72
+ driver: "in-process",
73
+ queueName: this.queueName,
74
+ jobs: describeJobs(this.registry.list()),
75
+ schedules: [...this.timers.values()].map(describeRunningSchedule),
76
+ counts: this.counts,
77
+ });
78
+ }
79
+ async close() {
80
+ this.cancelTimers();
81
+ await Promise.all([...this.activeRuns]);
82
+ }
83
+ async runJob(jobName, payload, definition) {
84
+ this.counts = {
85
+ ...this.counts,
86
+ waiting: this.counts.waiting - 1,
87
+ active: this.counts.active + 1,
88
+ };
89
+ // Nobody asked for this run, so it is attributed to the job itself.
90
+ // The request id is logged because it is the only handle on
91
+ // the `audit_log` rows one run produced.
92
+ const actor = jobRunActor(jobName);
93
+ this.log.info({ event: "job.started", jobName, requestId: actor.requestId }, "job started");
94
+ try {
95
+ await runWithAuditActor(actor, () => definition.run(payload));
96
+ this.counts = {
97
+ ...this.counts,
98
+ active: this.counts.active - 1,
99
+ completed: this.counts.completed + 1,
100
+ };
101
+ this.log.info({ event: "job.completed", jobName }, "job completed");
102
+ }
103
+ catch (error) {
104
+ this.counts = {
105
+ ...this.counts,
106
+ active: this.counts.active - 1,
107
+ failed: this.counts.failed + 1,
108
+ };
109
+ this.log.error({ event: "job.failed", jobName, err: error }, "job failed");
110
+ }
111
+ }
112
+ cancelTimers() {
113
+ for (const scheduled of this.timers.values()) {
114
+ if (scheduled.timer) {
115
+ clearTimeout(scheduled.timer);
116
+ }
117
+ scheduled.timer = undefined;
118
+ scheduled.nextRunAt = null;
119
+ }
120
+ }
121
+ scheduleNextRun(scheduled) {
122
+ const now = Date.now();
123
+ const next = nextRunMillis(now, scheduled.schedule);
124
+ if (next === undefined) {
125
+ throw new Error(`Schedule "${scheduled.schedule.id}" has no next run`);
126
+ }
127
+ scheduled.nextRunAt = new Date(next).toISOString();
128
+ scheduled.timer = setTimeout(() => {
129
+ scheduled.timer = undefined;
130
+ scheduled.nextRunAt = null;
131
+ void this.enqueue(scheduled.jobName, scheduled.schedule.payload);
132
+ this.scheduleNextRun(scheduled);
133
+ }, Math.max(0, next - now));
134
+ scheduled.timer.unref();
135
+ }
136
+ }
137
+ function nextRunMillis(now, schedule) {
138
+ if (schedule.kind === "cron") {
139
+ return getNextMillis(now, {
140
+ pattern: schedule.pattern,
141
+ tz: schedule.timeZone,
142
+ });
143
+ }
144
+ return getNextMillis(now, { every: schedule.everyMs });
145
+ }
146
+ function describeRunningSchedule(scheduled) {
147
+ if (scheduled.schedule.kind === "cron") {
148
+ return {
149
+ id: scheduled.schedule.id,
150
+ jobName: scheduled.jobName,
151
+ kind: scheduled.schedule.kind,
152
+ pattern: scheduled.schedule.pattern,
153
+ timeZone: scheduled.schedule.timeZone,
154
+ nextRunAt: scheduled.nextRunAt,
155
+ };
156
+ }
157
+ return {
158
+ id: scheduled.schedule.id,
159
+ jobName: scheduled.jobName,
160
+ kind: scheduled.schedule.kind,
161
+ everyMs: scheduled.schedule.everyMs,
162
+ nextRunAt: scheduled.nextRunAt,
163
+ };
164
+ }
165
+ function emptyCounts() {
166
+ return {
167
+ waiting: 0,
168
+ active: 0,
169
+ delayed: 0,
170
+ completed: 0,
171
+ failed: 0,
172
+ };
173
+ }
174
+ //# sourceMappingURL=in-process-job-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-process-job-queue.js","sourceRoot":"","sources":["../../src/lib/in-process-job-queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAEvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EACL,YAAY,GAQb,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,yCAAyC,CAAC;AAStE;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAQT,GAAG;IACH,SAAS;IARX,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC;IAC7B,MAAM,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC3C,UAAU,GAAG,IAAI,GAAG,EAAiB,CAAC;IAC/C,MAAM,GAAmB,WAAW,EAAE,CAAC;IACvC,OAAO,GAAG,KAAK,CAAC;IAExB,YACmB,GAAW,EACX,SAAS,GAAG,UAAU;mBADtB,GAAG;yBACH,SAAS;IACzB,CAAC;IAEJ,QAAQ,CAAC,IAA8B;QACrC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,MAAM,IAAI,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dads-framework/audit-actor";
2
+ /**
3
+ * Who a job run writes as.
4
+ *
5
+ * Background work has no human and no request behind it, but the audit trigger
6
+ * still refuses an unattributed write — so a run is attributed to the job. The
7
+ * name is spelled here rather than in each driver so the in-process and BullMQ
8
+ * paths cannot record the same job under two different ids.
9
+ *
10
+ * Each call mints a fresh request id: one run's rows belong together, and the
11
+ * drivers log that id with `job.started` so they can be found.
12
+ */
13
+ export declare function jobRunActor(jobName: string): AuditActor;
14
+ //# sourceMappingURL=job-actor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-actor.d.ts","sourceRoot":"","sources":["../../src/lib/job-actor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAE3E;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAEvD"}
@@ -0,0 +1,16 @@
1
+ import { systemActor } from "@dads-framework/audit-actor";
2
+ /**
3
+ * Who a job run writes as.
4
+ *
5
+ * Background work has no human and no request behind it, but the audit trigger
6
+ * still refuses an unattributed write — so a run is attributed to the job. The
7
+ * name is spelled here rather than in each driver so the in-process and BullMQ
8
+ * paths cannot record the same job under two different ids.
9
+ *
10
+ * Each call mints a fresh request id: one run's rows belong together, and the
11
+ * drivers log that id with `job.started` so they can be found.
12
+ */
13
+ export function jobRunActor(jobName) {
14
+ return systemActor(`job:${jobName}`);
15
+ }
16
+ //# sourceMappingURL=job-actor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-actor.js","sourceRoot":"","sources":["../../src/lib/job-actor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmB,MAAM,6BAA6B,CAAC;AAE3E;;;;;;;;;;GAUG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,OAAO,WAAW,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * How many tries a job gets, and whether this one was the last.
3
+ *
4
+ * Pure and its own file because the rule it encodes is easy to get subtly
5
+ * wrong and impossible to see in a queue driver: **only the final failure is a
6
+ * fault.** Reporting every retry would make one flaky job look like a hundred
7
+ * bugs, and a log line that does not say which kind of failure it is makes all
8
+ * of them look equally alarming.
9
+ *
10
+ * BullMQ counts `attemptsMade` INCLUSIVE of the attempt that just failed, so
11
+ * the third failure of a three-attempt job has `attemptsMade === 3`. That is
12
+ * why the comparison below is `>=` and not `>`, and it is the detail this file
13
+ * exists to pin.
14
+ */
15
+ export type JobAttempts = {
16
+ /** Attempts finished, including the one that just failed. */
17
+ readonly made: number;
18
+ /** Attempts the job was configured to get, at least one. */
19
+ readonly allowed: number;
20
+ };
21
+ /** What BullMQ knows about this job's attempts, defaulted for a job it lost. */
22
+ export declare function attemptsOf(job: {
23
+ attemptsMade?: number;
24
+ opts?: {
25
+ attempts?: number;
26
+ };
27
+ } | undefined): JobAttempts;
28
+ /** True when there is no retry left, which is the only failure worth reporting. */
29
+ export declare function isTerminalAttempt(attempts: JobAttempts): boolean;
30
+ //# sourceMappingURL=job-attempts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-attempts.d.ts","sourceRoot":"","sources":["../../../src/lib/logic/job-attempts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,MAAM,WAAW,GAAG;IACxB,6DAA6D;IAC7D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4DAA4D;IAC5D,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,gFAAgF;AAChF,wBAAgB,UAAU,CACxB,GAAG,EAAE;IAAE,YAAY,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG,SAAS,GACvE,WAAW,CAOb;AAED,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,WAAW,GAAG,OAAO,CAEhE"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * How many tries a job gets, and whether this one was the last.
3
+ *
4
+ * Pure and its own file because the rule it encodes is easy to get subtly
5
+ * wrong and impossible to see in a queue driver: **only the final failure is a
6
+ * fault.** Reporting every retry would make one flaky job look like a hundred
7
+ * bugs, and a log line that does not say which kind of failure it is makes all
8
+ * of them look equally alarming.
9
+ *
10
+ * BullMQ counts `attemptsMade` INCLUSIVE of the attempt that just failed, so
11
+ * the third failure of a three-attempt job has `attemptsMade === 3`. That is
12
+ * why the comparison below is `>=` and not `>`, and it is the detail this file
13
+ * exists to pin.
14
+ */
15
+ /** What BullMQ knows about this job's attempts, defaulted for a job it lost. */
16
+ export function attemptsOf(job) {
17
+ return {
18
+ made: job?.attemptsMade ?? 0,
19
+ // A job with no configured attempts gets one. Defaulting to zero would
20
+ // make every failure look non-terminal and report nothing, ever.
21
+ allowed: Math.max(job?.opts?.attempts ?? 1, 1),
22
+ };
23
+ }
24
+ /** True when there is no retry left, which is the only failure worth reporting. */
25
+ export function isTerminalAttempt(attempts) {
26
+ return attempts.made >= attempts.allowed;
27
+ }
28
+ //# sourceMappingURL=job-attempts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-attempts.js","sourceRoot":"","sources":["../../../src/lib/logic/job-attempts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AASH,gFAAgF;AAChF,MAAM,UAAU,UAAU,CACxB,GAAwE;IAExE,OAAO;QACL,IAAI,EAAE,GAAG,EAAE,YAAY,IAAI,CAAC;QAC5B,uEAAuE;QACvE,iEAAiE;QACjE,OAAO,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,IAAI,CAAC,EAAE,CAAC,CAAC;KAC/C,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,iBAAiB,CAAC,QAAqB;IACrD,OAAO,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,OAAO,CAAC;AAC3C,CAAC"}