@maroonedsoftware/jobbroker 1.11.5 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +69 -31
- package/README.md +98 -7
- package/dist/{chunk-TIW3NS7E.js → chunk-MR3BBUMG.js} +22 -2
- package/dist/chunk-MR3BBUMG.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/job.worker.policy.d.ts +59 -0
- package/dist/job.worker.policy.d.ts.map +1 -0
- package/dist/permanent.job.error.d.ts +58 -0
- package/dist/permanent.job.error.d.ts.map +1 -0
- package/dist/pgboss/pgboss.job.registration.d.ts +28 -6
- package/dist/pgboss/pgboss.job.registration.d.ts.map +1 -1
- package/dist/pgboss/pgboss.job.runner.d.ts +61 -1
- package/dist/pgboss/pgboss.job.runner.d.ts.map +1 -1
- package/dist/pgboss.js +99 -8
- package/dist/pgboss.js.map +1 -1
- package/package.json +10 -10
- package/dist/chunk-TIW3NS7E.js.map +0 -1
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
import { Identifier } from 'injectkit';
|
|
2
2
|
import { Job } from '../job.js';
|
|
3
3
|
import { JobQueuePolicy } from '../job.queue.policy.js';
|
|
4
|
+
import { JobWorkerPolicy } from '../job.worker.policy.js';
|
|
4
5
|
/**
|
|
5
6
|
* Configuration object for a job registration.
|
|
6
7
|
*
|
|
7
8
|
* Use the object form (rather than a bare job identifier) when you need to
|
|
8
|
-
* attach a cron schedule, a per-queue {@link JobQueuePolicy},
|
|
9
|
-
*
|
|
9
|
+
* attach a cron schedule, a per-queue {@link JobQueuePolicy}, a per-queue
|
|
10
|
+
* {@link JobWorkerPolicy}, or any combination of them. Every field beyond `job`
|
|
11
|
+
* is optional, so this shape covers:
|
|
10
12
|
*
|
|
11
13
|
* - `{ job }` — an on-demand job (equivalent to registering the bare identifier).
|
|
12
14
|
* - `{ job, cron }` — a job that also runs on a schedule.
|
|
13
|
-
* - `{ job, policy }`
|
|
14
|
-
*
|
|
15
|
+
* - `{ job, policy }` — retry and dead-letter behavior declared where the job is
|
|
16
|
+
* mapped.
|
|
17
|
+
* - `{ job, worker }` — how much concurrency this node gives the job's queue.
|
|
18
|
+
*
|
|
19
|
+
* The two policies are independent and answer different questions: `policy` is
|
|
20
|
+
* stored on the queue and governs what happens to a job that fails, `worker`
|
|
21
|
+
* configures the worker this process starts and governs how fast jobs are taken
|
|
22
|
+
* off the queue.
|
|
15
23
|
*
|
|
16
24
|
* @example
|
|
17
25
|
* ```typescript
|
|
@@ -30,6 +38,7 @@ import { JobQueuePolicy } from '../job.queue.policy.js';
|
|
|
30
38
|
* retryBackoff: true,
|
|
31
39
|
* deadLetter: 'deliver.webhook.dead',
|
|
32
40
|
* },
|
|
41
|
+
* worker: { concurrency: 8 },
|
|
33
42
|
* };
|
|
34
43
|
* ```
|
|
35
44
|
*/
|
|
@@ -43,14 +52,21 @@ export type PgBossJobRegistration = {
|
|
|
43
52
|
* queue when the runner starts. See {@link JobQueuePolicy}.
|
|
44
53
|
*/
|
|
45
54
|
policy?: JobQueuePolicy;
|
|
55
|
+
/**
|
|
56
|
+
* An optional per-queue worker policy — concurrency, batch size, and poll
|
|
57
|
+
* interval — applied when this node starts a worker for the job's queue. It
|
|
58
|
+
* configures this process only, not the queue. See {@link JobWorkerPolicy}.
|
|
59
|
+
*/
|
|
60
|
+
worker?: JobWorkerPolicy;
|
|
46
61
|
};
|
|
47
62
|
/**
|
|
48
63
|
* Registry map for PgBoss job registrations.
|
|
49
64
|
*
|
|
50
65
|
* This map holds all job registrations, mapping job names to either:
|
|
51
66
|
* - A bare job class identifier (for a plain on-demand job)
|
|
52
|
-
* - A {@link PgBossJobRegistration} object, which adds an optional cron schedule
|
|
53
|
-
*
|
|
67
|
+
* - A {@link PgBossJobRegistration} object, which adds an optional cron schedule,
|
|
68
|
+
* an optional per-queue {@link JobQueuePolicy}, and/or an optional per-queue
|
|
69
|
+
* {@link JobWorkerPolicy}
|
|
54
70
|
*
|
|
55
71
|
* The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}
|
|
56
72
|
* to validate job names and resolve job handlers.
|
|
@@ -74,6 +90,12 @@ export type PgBossJobRegistration = {
|
|
|
74
90
|
* policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }
|
|
75
91
|
* });
|
|
76
92
|
*
|
|
93
|
+
* // Register a hot queue that this node runs eight at a time
|
|
94
|
+
* registry.set('image.thumbnail', {
|
|
95
|
+
* job: ThumbnailJob,
|
|
96
|
+
* worker: { concurrency: 8 }
|
|
97
|
+
* });
|
|
98
|
+
*
|
|
77
99
|
* // Use with dependency injection
|
|
78
100
|
* container.bind(PgBossJobRegistryMap).toValue(registry);
|
|
79
101
|
* ```
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pgboss.job.registration.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"pgboss.job.registration.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,iEAAiE;IACjE,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC;IACrB,oEAAoE;IACpE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB;;;;OAIG;IACH,MAAM,CAAC,EAAE,eAAe,CAAC;CAC1B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,qBACa,oBAAqB,SAAQ,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,qBAAqB,CAAC;CAAG"}
|
|
@@ -2,6 +2,7 @@ import { PgBoss } from 'pg-boss';
|
|
|
2
2
|
import { Container } from 'injectkit';
|
|
3
3
|
import { JobQueuePolicy } from '../job.queue.policy.js';
|
|
4
4
|
import { JobRunner } from '../job.runner.js';
|
|
5
|
+
import { JobWorkerPolicy } from '../job.worker.policy.js';
|
|
5
6
|
import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
|
|
6
7
|
import { Logger } from '@maroonedsoftware/logger';
|
|
7
8
|
/**
|
|
@@ -11,6 +12,12 @@ import { Logger } from '@maroonedsoftware/logger';
|
|
|
11
12
|
* automatically creates queues for registered jobs, sets up scheduled
|
|
12
13
|
* jobs, and handles job execution with error logging.
|
|
13
14
|
*
|
|
15
|
+
* Each job settles on its own: the runner reports a per-job outcome to pg-boss
|
|
16
|
+
* rather than throwing, so one failure retries and dead-letters alone instead of
|
|
17
|
+
* dragging the rest of its batch with it. A job that throws
|
|
18
|
+
* {@link PermanentJobError} skips its remaining retries and dead-letters on the
|
|
19
|
+
* first attempt.
|
|
20
|
+
*
|
|
14
21
|
* @example
|
|
15
22
|
* ```typescript
|
|
16
23
|
* // Setup
|
|
@@ -63,6 +70,24 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
63
70
|
* @default undefined
|
|
64
71
|
*/
|
|
65
72
|
defaultQueuePolicy?: JobQueuePolicy;
|
|
73
|
+
/**
|
|
74
|
+
* A base {@link JobWorkerPolicy} applied to *every* queue this runner starts a
|
|
75
|
+
* worker for, beneath each queue's own `worker` policy. Set it to give all
|
|
76
|
+
* queues the same concurrency or poll interval without repeating them on each
|
|
77
|
+
* registration; a field a queue sets on its own `worker` overrides the same
|
|
78
|
+
* field here.
|
|
79
|
+
*
|
|
80
|
+
* Unlike {@link defaultQueuePolicy} this is not stored on the queue — it
|
|
81
|
+
* configures the workers *this process* starts, so another node consuming the
|
|
82
|
+
* same queues may use different values.
|
|
83
|
+
*
|
|
84
|
+
* Leave it unset (the default) to opt in per queue only. A queue with no policy
|
|
85
|
+
* from either side runs on pg-boss's own worker defaults: one worker, one job
|
|
86
|
+
* per fetch.
|
|
87
|
+
*
|
|
88
|
+
* @default undefined
|
|
89
|
+
*/
|
|
90
|
+
defaultWorkerPolicy?: JobWorkerPolicy;
|
|
66
91
|
/**
|
|
67
92
|
* Creates a new PgBossJobRunner instance.
|
|
68
93
|
*
|
|
@@ -85,7 +110,9 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
85
110
|
* an existing queue to match; when no policy applies, the queue is created
|
|
86
111
|
* with the name only (unchanged pre-policy behavior)
|
|
87
112
|
* 4. Sets up the cron schedule (for scheduled jobs)
|
|
88
|
-
* 5. Starts a worker to process jobs from the queue
|
|
113
|
+
* 5. Starts a worker to process jobs from the queue, with the effective worker
|
|
114
|
+
* policy (the runner's {@link defaultWorkerPolicy} merged with the
|
|
115
|
+
* registration's own `worker`, if any) applied
|
|
89
116
|
*
|
|
90
117
|
* Each item in a batch runs in its own scoped container, created from the
|
|
91
118
|
* injected root container and disposed once the item settles, so `scoped`
|
|
@@ -97,6 +124,12 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
97
124
|
* until every job has actually finished and one job's failure cannot suppress
|
|
98
125
|
* its sibling's logs.
|
|
99
126
|
*
|
|
127
|
+
* Workers run with pg-boss's `perJobResults`, so the handler reports each job's
|
|
128
|
+
* outcome rather than throwing: a job that fails is retried and dead-lettered on
|
|
129
|
+
* its own, without dragging the rest of its batch along. A job that throws
|
|
130
|
+
* {@link PermanentJobError} skips its remaining retries and dead-letters
|
|
131
|
+
* immediately.
|
|
132
|
+
*
|
|
100
133
|
* @returns A promise that resolves when all workers are registered with pg-boss.
|
|
101
134
|
*/
|
|
102
135
|
start(): Promise<void>;
|
|
@@ -145,6 +178,33 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
145
178
|
* @internal
|
|
146
179
|
*/
|
|
147
180
|
private toQueueOptions;
|
|
181
|
+
/**
|
|
182
|
+
* Merges the runner-wide {@link defaultWorkerPolicy} with a registration's own
|
|
183
|
+
* `worker` policy, letting the registration override individual fields. Returns
|
|
184
|
+
* `undefined` when neither supplies a policy, so a queue with no policy keeps
|
|
185
|
+
* pg-boss's own worker defaults.
|
|
186
|
+
*
|
|
187
|
+
* @param registration - The registry entry (a bare identifier or an object).
|
|
188
|
+
* @returns The effective worker policy for the queue, or `undefined` if none applies.
|
|
189
|
+
* @internal
|
|
190
|
+
*/
|
|
191
|
+
private resolveWorkerPolicy;
|
|
192
|
+
/**
|
|
193
|
+
* Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work
|
|
194
|
+
* options. `pollInterval` is passed as a fractional second count rather than
|
|
195
|
+
* rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a
|
|
196
|
+
* deliberate sub-second poll into either 0 (rejected) or 1.
|
|
197
|
+
*
|
|
198
|
+
* Always returns options, because `perJobResults` is always on: it is what makes
|
|
199
|
+
* pg-boss settle each job in a batch individually, and what gives
|
|
200
|
+
* {@link PermanentJobError} somewhere to land. A queue with no worker policy
|
|
201
|
+
* still gets that, and nothing else.
|
|
202
|
+
*
|
|
203
|
+
* @param policy - The effective worker policy for a queue, or `undefined`.
|
|
204
|
+
* @returns The pg-boss work options.
|
|
205
|
+
* @internal
|
|
206
|
+
*/
|
|
207
|
+
private toWorkOptions;
|
|
148
208
|
/**
|
|
149
209
|
* Polls pg-boss for a running job and aborts the given controller when the job
|
|
150
210
|
* has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,MAAM,EAAE,MAAM,SAAS,CAAC;AAE1D,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAGlD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1D,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAiClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAuD1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAzDzB;;;;;;;;OAQG;IACH,yBAAyB,SAAK;IAE9B;;;;;;;;;;;OAWG;IACH,kBAAkB,CAAC,EAAE,cAAc,CAAC;IAEpC;;;;;;;;;;;;;;;;OAgBG;IACH,mBAAmB,CAAC,EAAE,eAAe,CAAC;IAEtC;;;;;;;;OAQG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA2G5B;;;;;;;;OAQG;IACH,OAAO,CAAC,YAAY;IAYpB;;;;;;;;;OASG;IACH,OAAO,CAAC,aAAa;IAQrB;;;;;;;;;;;OAWG;YACW,WAAW;IAuBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,cAAc;IAuBtB;;;;;;;;;OASG;IACH,OAAO,CAAC,mBAAmB;IAQ3B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,aAAa;IAcrB;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
|
package/dist/pgboss.js
CHANGED
|
@@ -3,8 +3,9 @@ import {
|
|
|
3
3
|
JobContext,
|
|
4
4
|
JobMonitor,
|
|
5
5
|
JobRunner,
|
|
6
|
+
PermanentJobError,
|
|
6
7
|
__name
|
|
7
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-MR3BBUMG.js";
|
|
8
9
|
|
|
9
10
|
// src/pgboss/pgboss.job.broker.ts
|
|
10
11
|
import { PgBoss } from "pg-boss";
|
|
@@ -406,6 +407,7 @@ import { PgBoss as PgBoss3 } from "pg-boss";
|
|
|
406
407
|
import { Duration as Duration2 } from "luxon";
|
|
407
408
|
import { Container, Injectable as Injectable5 } from "injectkit";
|
|
408
409
|
import { Logger } from "@maroonedsoftware/logger";
|
|
410
|
+
import { ServerkitError } from "@maroonedsoftware/errors";
|
|
409
411
|
function _ts_decorate5(decorators, target, key, desc) {
|
|
410
412
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
411
413
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -452,6 +454,24 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
452
454
|
*/
|
|
453
455
|
defaultQueuePolicy;
|
|
454
456
|
/**
|
|
457
|
+
* A base {@link JobWorkerPolicy} applied to *every* queue this runner starts a
|
|
458
|
+
* worker for, beneath each queue's own `worker` policy. Set it to give all
|
|
459
|
+
* queues the same concurrency or poll interval without repeating them on each
|
|
460
|
+
* registration; a field a queue sets on its own `worker` overrides the same
|
|
461
|
+
* field here.
|
|
462
|
+
*
|
|
463
|
+
* Unlike {@link defaultQueuePolicy} this is not stored on the queue — it
|
|
464
|
+
* configures the workers *this process* starts, so another node consuming the
|
|
465
|
+
* same queues may use different values.
|
|
466
|
+
*
|
|
467
|
+
* Leave it unset (the default) to opt in per queue only. A queue with no policy
|
|
468
|
+
* from either side runs on pg-boss's own worker defaults: one worker, one job
|
|
469
|
+
* per fetch.
|
|
470
|
+
*
|
|
471
|
+
* @default undefined
|
|
472
|
+
*/
|
|
473
|
+
defaultWorkerPolicy;
|
|
474
|
+
/**
|
|
455
475
|
* Creates a new PgBossJobRunner instance.
|
|
456
476
|
*
|
|
457
477
|
* @param container - The root DI container. Each job execution resolves from a
|
|
@@ -475,7 +495,9 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
475
495
|
* an existing queue to match; when no policy applies, the queue is created
|
|
476
496
|
* with the name only (unchanged pre-policy behavior)
|
|
477
497
|
* 4. Sets up the cron schedule (for scheduled jobs)
|
|
478
|
-
* 5. Starts a worker to process jobs from the queue
|
|
498
|
+
* 5. Starts a worker to process jobs from the queue, with the effective worker
|
|
499
|
+
* policy (the runner's {@link defaultWorkerPolicy} merged with the
|
|
500
|
+
* registration's own `worker`, if any) applied
|
|
479
501
|
*
|
|
480
502
|
* Each item in a batch runs in its own scoped container, created from the
|
|
481
503
|
* injected root container and disposed once the item settles, so `scoped`
|
|
@@ -487,6 +509,12 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
487
509
|
* until every job has actually finished and one job's failure cannot suppress
|
|
488
510
|
* its sibling's logs.
|
|
489
511
|
*
|
|
512
|
+
* Workers run with pg-boss's `perJobResults`, so the handler reports each job's
|
|
513
|
+
* outcome rather than throwing: a job that fails is retried and dead-lettered on
|
|
514
|
+
* its own, without dragging the rest of its batch along. A job that throws
|
|
515
|
+
* {@link PermanentJobError} skips its remaining retries and dead-letters
|
|
516
|
+
* immediately.
|
|
517
|
+
*
|
|
490
518
|
* @returns A promise that resolves when all workers are registered with pg-boss.
|
|
491
519
|
*/
|
|
492
520
|
async start() {
|
|
@@ -507,7 +535,7 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
507
535
|
} else {
|
|
508
536
|
identifier = registration;
|
|
509
537
|
}
|
|
510
|
-
|
|
538
|
+
const handler = /* @__PURE__ */ __name(async (jobs) => {
|
|
511
539
|
const results = await Promise.allSettled(jobs.map(async (job) => {
|
|
512
540
|
const scope = this.container.createScopedContainer();
|
|
513
541
|
const controller = new AbortController();
|
|
@@ -534,13 +562,26 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
534
562
|
}
|
|
535
563
|
}));
|
|
536
564
|
const failures = results.filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
537
|
-
if (failures.length === 1) {
|
|
538
|
-
throw failures[0];
|
|
539
|
-
}
|
|
540
565
|
if (failures.length > 1) {
|
|
541
|
-
|
|
566
|
+
this.logger.error(new ServerkitError(`${failures.length} of ${jobs.length} jobs in queue "${name}" failed`).withCause(new AggregateError(failures)));
|
|
542
567
|
}
|
|
543
|
-
|
|
568
|
+
return jobs.map((job, index) => {
|
|
569
|
+
const result = results[index];
|
|
570
|
+
if (result?.status === "fulfilled") {
|
|
571
|
+
return {
|
|
572
|
+
id: job.id,
|
|
573
|
+
status: "completed"
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
const status = result?.reason instanceof PermanentJobError ? "deadletter" : "failed";
|
|
577
|
+
return {
|
|
578
|
+
id: job.id,
|
|
579
|
+
status,
|
|
580
|
+
output: result?.reason
|
|
581
|
+
};
|
|
582
|
+
});
|
|
583
|
+
}, "handler");
|
|
584
|
+
await this.pgboss.work(name, this.toWorkOptions(this.resolveWorkerPolicy(registration)), handler);
|
|
544
585
|
}
|
|
545
586
|
}
|
|
546
587
|
/**
|
|
@@ -649,6 +690,56 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
649
690
|
return Object.keys(options).length > 0 ? options : void 0;
|
|
650
691
|
}
|
|
651
692
|
/**
|
|
693
|
+
* Merges the runner-wide {@link defaultWorkerPolicy} with a registration's own
|
|
694
|
+
* `worker` policy, letting the registration override individual fields. Returns
|
|
695
|
+
* `undefined` when neither supplies a policy, so a queue with no policy keeps
|
|
696
|
+
* pg-boss's own worker defaults.
|
|
697
|
+
*
|
|
698
|
+
* @param registration - The registry entry (a bare identifier or an object).
|
|
699
|
+
* @returns The effective worker policy for the queue, or `undefined` if none applies.
|
|
700
|
+
* @internal
|
|
701
|
+
*/
|
|
702
|
+
resolveWorkerPolicy(registration) {
|
|
703
|
+
const own = isPgBossJobRegistration(registration) ? registration.worker : void 0;
|
|
704
|
+
if (!this.defaultWorkerPolicy && !own) {
|
|
705
|
+
return void 0;
|
|
706
|
+
}
|
|
707
|
+
return {
|
|
708
|
+
...this.defaultWorkerPolicy,
|
|
709
|
+
...own
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work
|
|
714
|
+
* options. `pollInterval` is passed as a fractional second count rather than
|
|
715
|
+
* rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a
|
|
716
|
+
* deliberate sub-second poll into either 0 (rejected) or 1.
|
|
717
|
+
*
|
|
718
|
+
* Always returns options, because `perJobResults` is always on: it is what makes
|
|
719
|
+
* pg-boss settle each job in a batch individually, and what gives
|
|
720
|
+
* {@link PermanentJobError} somewhere to land. A queue with no worker policy
|
|
721
|
+
* still gets that, and nothing else.
|
|
722
|
+
*
|
|
723
|
+
* @param policy - The effective worker policy for a queue, or `undefined`.
|
|
724
|
+
* @returns The pg-boss work options.
|
|
725
|
+
* @internal
|
|
726
|
+
*/
|
|
727
|
+
toWorkOptions(policy) {
|
|
728
|
+
const options = {
|
|
729
|
+
perJobResults: true
|
|
730
|
+
};
|
|
731
|
+
if (policy?.concurrency !== void 0) {
|
|
732
|
+
options.localConcurrency = policy.concurrency;
|
|
733
|
+
}
|
|
734
|
+
if (policy?.batchSize !== void 0) {
|
|
735
|
+
options.batchSize = policy.batchSize;
|
|
736
|
+
}
|
|
737
|
+
if (policy?.pollInterval !== void 0) {
|
|
738
|
+
options.pollingIntervalSeconds = policy.pollInterval.as("seconds");
|
|
739
|
+
}
|
|
740
|
+
return options;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
652
743
|
* Polls pg-boss for a running job and aborts the given controller when the job
|
|
653
744
|
* has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
|
|
654
745
|
*
|
package/dist/pgboss.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts","../src/pgboss/kysely.transaction.connection.provider.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, or both. Every\n * field beyond `job` is optional, so this shape covers three cases:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` / `{ job, cron, policy }` — either of the above with retry\n * and dead-letter behavior declared where the job is mapped.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule\n * and/or an optional per-queue {@link JobQueuePolicy}\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to delete.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to retry.\n */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Duration } from 'luxon';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobContext } from '../job.context.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * the installed pg-boss types so the mapping tracks the peer's exact shape.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['updateQueue']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The root DI container. Each job execution resolves from a\n * scope created off it, not from the container itself.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue\n *\n * Each item in a batch runs in its own scoped container, created from the\n * injected root container and disposed once the item settles, so `scoped`\n * registrations behave per execution (the job-side equivalent of a request\n * scope) and any disposables the execution created are released. Each scope\n * carries a {@link JobContext} describing the running job, so the job and its\n * collaborators can inject it. Execution is\n * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch\n * until every job has actually finished and one job's failure cannot suppress\n * its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n // Every execution resolves from its own scope, never the root container.\n // InjectKit caches a `scoped` registration in whichever container first\n // resolves it, and child scopes inherit a parent's cache, so resolving a\n // scoped token at the root would turn it into a process-lifetime singleton\n // shared by every job *and* inherited by every later request scope.\n const scope = this.container.createScopedContainer();\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n // Assigned once the watch starts; until then there is nothing to stop, so\n // `finally` can run unconditionally even if resolution threw.\n let stopWatching = () => {};\n try {\n // Override before resolving, so a job (or anything it depends on) may\n // take JobContext as a constructor dependency.\n scope.override(JobContext, this.toJobContext(name, job, signal));\n const jobRunner = scope.get<Job>(identifier);\n stopWatching = this.watchForCancellation(name, job.id, controller);\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n // Stop the poll before disposing: resolving from a disposed scope throws,\n // and a late tick must not turn a finished job into a logged error.\n stopWatching();\n // Log rather than rethrow, so a disposal failure can't replace the job's\n // real error and mislead pg-boss's retry/dead-letter accounting.\n await scope.disposeAsync().catch((error: unknown) => this.logger.error(error));\n }\n }),\n );\n\n // Every job in the batch is isolated (they run concurrently and each logs its own\n // error), but the work handler itself must reject when any job threw. Otherwise\n // pg-boss treats the whole batch as completed and never applies retryLimit or\n // dead-lettering to the jobs that actually failed.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length === 1) {\n throw failures[0];\n }\n if (failures.length > 1) {\n throw new AggregateError(failures, `${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`);\n }\n });\n }\n }\n\n /**\n * Builds the {@link JobContext} registered in an execution's scoped container.\n *\n * @param name - The queue the job was dequeued from.\n * @param job - The pg-boss job being executed.\n * @param signal - The combined cancellation signal handed to {@link Job.run}.\n * @returns The context describing this execution.\n * @internal\n */\n private toJobContext(name: string, job: PgJob<object>, signal: AbortSignal): JobContext {\n // Typed as always present, but absent when jobs are faked in tests, so it is\n // read defensively and simply omitted when the backend reports no limit.\n const expireInSeconds = (job as { expireInSeconds?: number }).expireInSeconds;\n return {\n id: job.id,\n name,\n signal,\n ...(expireInSeconds === undefined ? {} : { expiresIn: Duration.fromObject({ seconds: expireInSeconds }) }),\n };\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n","import { PgBossConnectionProvider } from './pgboss.connection.provider.js';\nimport { fromKysely, type Db } from 'pg-boss';\n\n/**\n * Structural shape of a Kysely instance or transaction, matching what pg-boss's\n * `fromKysely` adapter consumes.\n *\n * Declared structurally rather than as `Kysely<DB>` so the package carries no\n * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`\n * and `Transaction<DB>` are accepted without a type argument or a cast.\n */\nexport interface KyselyLike {\n withoutPlugins(): Parameters<typeof fromKysely>[0];\n}\n\n/**\n * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so\n * jobs enqueued while that transaction is open commit or roll back with it.\n *\n * Register it as a request-scoped override of {@link PgBossConnectionProvider}\n * alongside whatever binds the transaction itself, and every enqueue performed\n * during the request inserts on the transaction's connection instead of\n * pg-boss's pool — closing the dual-write gap between domain writes and job\n * enqueues.\n *\n * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL\n * straight through `executeQuery`, so a column-rewriting plugin on the caller's\n * instance (a camel-case mapper, for example) would corrupt pg-boss's own\n * result columns. `withoutPlugins()` returns an instance sharing the same\n * connection-bound executor, so atomicity is preserved.\n *\n * @example\n * ```typescript\n * await db.transaction().execute(async trx => {\n * const scope = container.createScope();\n * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));\n *\n * await repository.createOrder(trx, order);\n * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));\n * });\n * ```\n */\nexport class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {\n /**\n * @param trx - The active Kysely transaction (or any Kysely instance) whose\n * connection job inserts should run on.\n */\n constructor(private readonly trx: KyselyLike) {\n super();\n }\n\n /**\n * Returns the transaction's connection adapted to pg-boss's executor shape,\n * with the caller's Kysely plugins stripped.\n *\n * @returns A {@link Db} executor bound to the transaction's connection.\n */\n override executor(): Db {\n return fromKysely(this.trx.withoutPlugins());\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAmFhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACnFhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;;;;;;;;;EAuBA,MAAMC,KAA6BC,MAAcC,SAAkBC,SAA2C;AAC5G,QAAI,CAAC,KAAKN,cAAcO,IAAIH,IAAAA,GAAO;AACjC,YAAM,IAAII,MAAM,OAAOJ,IAAAA,oBAAwB;IACjD;AAEA,UAAMK,KAAK,MAAM,KAAKR,OAAOE,KAAKC,MAAMC,SAAS;MAC/CK,IAAI,KAAKR,mBAAmBS,SAAQ;MACpC,GAAG,KAAKC,aAAaN,SAAS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;;;;;;;;;EAiBQyB,qBAAqB/B,MAAcgC,IAAYb,YAAyC;AAC9F,QAAI,KAAK5B,6BAA6B,GAAG;AACvC,aAAO,MAAA;MAAO;IAChB;AAEA,UAAM6E,QAAQC,YAAY,YAAA;AACxB,UAAI;AACF,cAAM,CAAC7D,GAAAA,IAAO,MAAM,KAAKb,OAAO2E,SAAStE,MAAM;UAAEgC;QAAG,CAAA;AACpD,YAAI,CAACxB,OAAOA,IAAI+D,UAAU,aAAa;AACrCpD,qBAAWqD,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAASjC,OAAO;AACd,aAAKvC,OAAOuC,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAK5C,4BAA4B,GAAA;AAGpC6E,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKhF,OAAOgF,KAAI;EACxB;AACF;;;;;;;;;;;;;ACtXA,SAASC,kBAA2B;AAyC7B,IAAMC,sCAAN,cAAkDC,yBAAAA;EA1CzD,OA0CyDA;;;;;;;;EAKvD,YAA6BC,KAAiB;AAC5C,UAAK,GAAA,KADsBA,MAAAA;EAE7B;;;;;;;EAQSC,WAAe;AACtB,WAAOC,WAAW,KAAKF,IAAIG,eAAc,CAAA;EAC3C;AACF;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Duration","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","work","jobs","results","Promise","allSettled","map","scope","createScopedContainer","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","override","JobContext","toJobContext","jobRunner","get","watchForCancellation","id","run","data","error","disposeAsync","catch","failures","filter","result","status","reason","length","AggregateError","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
|
|
1
|
+
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts","../src/pgboss/kysely.transaction.connection.provider.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, a per-queue\n * {@link JobWorkerPolicy}, or any combination of them. Every field beyond `job`\n * is optional, so this shape covers:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` — retry and dead-letter behavior declared where the job is\n * mapped.\n * - `{ job, worker }` — how much concurrency this node gives the job's queue.\n *\n * The two policies are independent and answer different questions: `policy` is\n * stored on the queue and governs what happens to a job that fails, `worker`\n * configures the worker this process starts and governs how fast jobs are taken\n * off the queue.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * worker: { concurrency: 8 },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n /**\n * An optional per-queue worker policy — concurrency, batch size, and poll\n * interval — applied when this node starts a worker for the job's queue. It\n * configures this process only, not the queue. See {@link JobWorkerPolicy}.\n */\n worker?: JobWorkerPolicy;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule,\n * an optional per-queue {@link JobQueuePolicy}, and/or an optional per-queue\n * {@link JobWorkerPolicy}\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Register a hot queue that this node runs eight at a time\n * registry.set('image.thumbnail', {\n * job: ThumbnailJob,\n * worker: { concurrency: 8 }\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to delete.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to retry.\n */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, JobResult, PgBoss } from 'pg-boss';\nimport { Duration } from 'luxon';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobContext } from '../job.context.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\nimport { PermanentJobError } from '../permanent.job.error.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * `createQueue`, whose options are the strict (no-`null`) subset of\n * `UpdateQueueOptions` — {@link JobQueuePolicy} never clears a setting, so the\n * narrower shape satisfies both calls.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['createQueue']>[1]>;\n\n/**\n * pg-boss work options as accepted by the three-argument `work` overload.\n * Derived from the installed pg-boss types so the mapping tracks the peer's\n * exact shape.\n * @internal\n */\ntype PgBossWorkOptions = NonNullable<Parameters<PgBoss['work']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * Each job settles on its own: the runner reports a per-job outcome to pg-boss\n * rather than throwing, so one failure retries and dead-letters alone instead of\n * dragging the rest of its batch with it. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters on the\n * first attempt.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * A base {@link JobWorkerPolicy} applied to *every* queue this runner starts a\n * worker for, beneath each queue's own `worker` policy. Set it to give all\n * queues the same concurrency or poll interval without repeating them on each\n * registration; a field a queue sets on its own `worker` overrides the same\n * field here.\n *\n * Unlike {@link defaultQueuePolicy} this is not stored on the queue — it\n * configures the workers *this process* starts, so another node consuming the\n * same queues may use different values.\n *\n * Leave it unset (the default) to opt in per queue only. A queue with no policy\n * from either side runs on pg-boss's own worker defaults: one worker, one job\n * per fetch.\n *\n * @default undefined\n */\n defaultWorkerPolicy?: JobWorkerPolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The root DI container. Each job execution resolves from a\n * scope created off it, not from the container itself.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue, with the effective worker\n * policy (the runner's {@link defaultWorkerPolicy} merged with the\n * registration's own `worker`, if any) applied\n *\n * Each item in a batch runs in its own scoped container, created from the\n * injected root container and disposed once the item settles, so `scoped`\n * registrations behave per execution (the job-side equivalent of a request\n * scope) and any disposables the execution created are released. Each scope\n * carries a {@link JobContext} describing the running job, so the job and its\n * collaborators can inject it. Execution is\n * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch\n * until every job has actually finished and one job's failure cannot suppress\n * its sibling's logs.\n *\n * Workers run with pg-boss's `perJobResults`, so the handler reports each job's\n * outcome rather than throwing: a job that fails is retried and dead-lettered on\n * its own, without dragging the rest of its batch along. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters\n * immediately.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n const handler = async (jobs: PgJob<object>[]): Promise<JobResult[]> => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n // Every execution resolves from its own scope, never the root container.\n // InjectKit caches a `scoped` registration in whichever container first\n // resolves it, and child scopes inherit a parent's cache, so resolving a\n // scoped token at the root would turn it into a process-lifetime singleton\n // shared by every job *and* inherited by every later request scope.\n const scope = this.container.createScopedContainer();\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n // Assigned once the watch starts; until then there is nothing to stop, so\n // `finally` can run unconditionally even if resolution threw.\n let stopWatching = () => {};\n try {\n // Override before resolving, so a job (or anything it depends on) may\n // take JobContext as a constructor dependency.\n scope.override(JobContext, this.toJobContext(name, job, signal));\n const jobRunner = scope.get<Job>(identifier);\n stopWatching = this.watchForCancellation(name, job.id, controller);\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n // Stop the poll before disposing: resolving from a disposed scope throws,\n // and a late tick must not turn a finished job into a logged error.\n stopWatching();\n // Log rather than rethrow, so a disposal failure can't replace the job's\n // real error and mislead pg-boss's retry/dead-letter accounting.\n await scope.disposeAsync().catch((error: unknown) => this.logger.error(error));\n }\n }),\n );\n\n // Under `perJobResults` the handler reports each job's outcome instead of\n // throwing, so pg-boss settles them individually: one poisoned job fails (and\n // retries, and dead-letters) alone rather than dragging its whole batch with it.\n // Throwing from here still fails the entire batch, which is what a runner-level\n // bug — as opposed to a job-level one — should do.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length > 1) {\n // The per-job errors are already logged above and are about to be persisted as\n // each job's own output. This adds back the batch-wide view that the pre-\n // `perJobResults` AggregateError carried, as a log line rather than as a\n // settlement decision — the cause keeps every individual error reachable.\n this.logger.error(\n new ServerkitError(`${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`).withCause(new AggregateError(failures)),\n );\n }\n\n // Map over `jobs`, not `results`: pg-boss matches dispositions by job id and\n // fails any job the handler omits, so the batch itself must drive the output.\n return jobs.map((job, index) => {\n const result = results[index];\n // `allSettled` returns one entry per input, so a missing entry is impossible;\n // treat it as a failure anyway rather than silently completing a job that may\n // never have run.\n if (result?.status === 'fulfilled') {\n return { id: job.id, status: 'completed' };\n }\n // A job that declares its own failure permanent skips its remaining retries\n // and goes straight to the queue's dead-letter queue.\n const status = result?.reason instanceof PermanentJobError ? 'deadletter' : 'failed';\n return { id: job.id, status, output: result?.reason };\n });\n };\n\n await this.pgboss.work(name, this.toWorkOptions(this.resolveWorkerPolicy(registration)), handler);\n }\n }\n\n /**\n * Builds the {@link JobContext} registered in an execution's scoped container.\n *\n * @param name - The queue the job was dequeued from.\n * @param job - The pg-boss job being executed.\n * @param signal - The combined cancellation signal handed to {@link Job.run}.\n * @returns The context describing this execution.\n * @internal\n */\n private toJobContext(name: string, job: PgJob<object>, signal: AbortSignal): JobContext {\n // Typed as always present, but absent when jobs are faked in tests, so it is\n // read defensively and simply omitted when the backend reports no limit.\n const expireInSeconds = (job as { expireInSeconds?: number }).expireInSeconds;\n return {\n id: job.id,\n name,\n signal,\n ...(expireInSeconds === undefined ? {} : { expiresIn: Duration.fromObject({ seconds: expireInSeconds }) }),\n };\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Merges the runner-wide {@link defaultWorkerPolicy} with a registration's own\n * `worker` policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy keeps\n * pg-boss's own worker defaults.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective worker policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolveWorkerPolicy(registration: unknown): JobWorkerPolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.worker : undefined;\n if (!this.defaultWorkerPolicy && !own) {\n return undefined;\n }\n return { ...this.defaultWorkerPolicy, ...own };\n }\n\n /**\n * Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work\n * options. `pollInterval` is passed as a fractional second count rather than\n * rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a\n * deliberate sub-second poll into either 0 (rejected) or 1.\n *\n * Always returns options, because `perJobResults` is always on: it is what makes\n * pg-boss settle each job in a batch individually, and what gives\n * {@link PermanentJobError} somewhere to land. A queue with no worker policy\n * still gets that, and nothing else.\n *\n * @param policy - The effective worker policy for a queue, or `undefined`.\n * @returns The pg-boss work options.\n * @internal\n */\n private toWorkOptions(policy: JobWorkerPolicy | undefined): PgBossWorkOptions {\n const options: PgBossWorkOptions = { perJobResults: true };\n if (policy?.concurrency !== undefined) {\n options.localConcurrency = policy.concurrency;\n }\n if (policy?.batchSize !== undefined) {\n options.batchSize = policy.batchSize;\n }\n if (policy?.pollInterval !== undefined) {\n options.pollingIntervalSeconds = policy.pollInterval.as('seconds');\n }\n return options;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n","import { PgBossConnectionProvider } from './pgboss.connection.provider.js';\nimport { fromKysely, type Db } from 'pg-boss';\n\n/**\n * Structural shape of a Kysely instance or transaction, matching what pg-boss's\n * `fromKysely` adapter consumes.\n *\n * Declared structurally rather than as `Kysely<DB>` so the package carries no\n * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`\n * and `Transaction<DB>` are accepted without a type argument or a cast.\n */\nexport interface KyselyLike {\n withoutPlugins(): Parameters<typeof fromKysely>[0];\n}\n\n/**\n * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so\n * jobs enqueued while that transaction is open commit or roll back with it.\n *\n * Register it as a request-scoped override of {@link PgBossConnectionProvider}\n * alongside whatever binds the transaction itself, and every enqueue performed\n * during the request inserts on the transaction's connection instead of\n * pg-boss's pool — closing the dual-write gap between domain writes and job\n * enqueues.\n *\n * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL\n * straight through `executeQuery`, so a column-rewriting plugin on the caller's\n * instance (a camel-case mapper, for example) would corrupt pg-boss's own\n * result columns. `withoutPlugins()` returns an instance sharing the same\n * connection-bound executor, so atomicity is preserved.\n *\n * @example\n * ```typescript\n * await db.transaction().execute(async trx => {\n * const scope = container.createScope();\n * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));\n *\n * await repository.createOrder(trx, order);\n * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));\n * });\n * ```\n */\nexport class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {\n /**\n * @param trx - The active Kysely transaction (or any Kysely instance) whose\n * connection job inserts should run on.\n */\n constructor(private readonly trx: KyselyLike) {\n super();\n }\n\n /**\n * Returns the transaction's connection adapted to pg-boss's executor shape,\n * with the caller's Kysely plugins stripped.\n *\n * @returns A {@link Db} executor bound to the transaction's connection.\n */\n override executor(): Db {\n return fromKysely(this.trx.withoutPlugins());\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAyGhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACzGhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAM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C;AACF;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Duration","Container","Injectable","Logger","ServerkitError","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","defaultWorkerPolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","handler","jobs","results","Promise","allSettled","map","scope","createScopedContainer","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","override","JobContext","toJobContext","jobRunner","get","watchForCancellation","id","run","data","error","disposeAsync","catch","failures","filter","result","status","reason","length","ServerkitError","withCause","AggregateError","index","PermanentJobError","output","work","toWorkOptions","resolveWorkerPolicy","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","worker","perJobResults","concurrency","localConcurrency","batchSize","pollInterval","pollingIntervalSeconds","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
|