@maroonedsoftware/jobbroker 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -40,34 +40,34 @@ Notably **not** a dependency: `kysely`. Transactional enqueue is supported throu
40
40
 
41
41
  ### `.` — abstractions
42
42
 
43
- | Export | Kind | Shape | Notes |
44
- | ------------------------------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
45
- | `Job<Payload>` | abstract class | `@Injectable() abstract run(payload: Payload, signal?: AbortSignal): Promise<void>` | `Payload extends object = object`. |
46
- | `JobBroker` | abstract class | `@Injectable()`. Producer side. | Unsupported operations throw `NotSupportedError` rather than no-op. |
47
- | `#send` | method | `<P extends object>(name: string, payload: P, options?: JobSendOptions) => Promise<string>` | Returns the job id. Throws if `name` is not registered. |
48
- | `#schedule` | method | `<P extends object>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions) => Promise<void>` | Cron or RFC 5545 RRULE. One schedule per name and key; the same key replaces it. |
49
- | `#unschedule` | method | `(name: string, key?: string) => Promise<void>` | Without `key`, removes only the unkeyed schedule. |
50
- | `#getSchedules` | method | `<P extends object>(name: string, key?: string) => Promise<JobSchedule<P>[]>` | With `key`, at most one. Ordered by key. |
51
- | `#previewSchedule` | method | `(recurrence: string, options?: JobSchedulePreviewOptions) => Promise<DateTime[]>` | Stores nothing. Validates as `schedule` does. Results are in `options.timeZone` (UTC by default). |
52
- | `#cancel` / `#resume` / `#deleteJob` | method | `(name: string, id: string \| string[]) => Promise<void>` | `cancel` aborts the signal for a running job. |
53
- | `#getJob` | method | `<P extends object>(name: string, id: string) => Promise<JobInfo<P> \| null>` | — |
54
- | `JobRunner` | abstract class | `@Injectable()`. `start()`, `stop()` | Consumer side. `stop()` waits for in-flight jobs. |
55
- | `JobMonitor` | abstract class | `@Injectable()`. `getQueueStats`, `listJobs`, `redrive`, `deleteJob`, `retryJob` | Operational surface — dashboards, dead-letter drains. |
56
- | `JobContext` | interface + abstract class | `{ id: string; name: string; signal: AbortSignal; expiresIn?: Duration }` | Declaration-merged so one symbol is both the type and the DI token. |
57
- | `registerJobContext` | function | `<T extends Registry>(registry: T) => T` | **Required** if any service injects `JobContext`. Registers a throwing placeholder. |
58
- | `JobSendOptions` | interface | `{ startAfter?: Duration \| DateTime }` | Relative delay or absolute earliest-run time. A lower bound, not exact scheduling. |
59
- | `JobScheduleOptions` | interface | `{ key?: string; timeZone?: string; missed?: 'skip' \| 'once' }` | `timeZone` is IANA, UTC when omitted. `missed` defaults to the backend's (`skip` on pg-boss). |
60
- | `JobSchedule<Payload>` | interface | `{ name, key, recurrence, timeZone, payload? }` | `key` is `''` for the unkeyed schedule. No backend bookkeeping fields. |
61
- | `JobSchedulePreviewOptions` | interface | `{ timeZone?: string; from?: DateTime; count?: number }` | Occurrences are strictly after `from`, so paging passes the last one back in. |
62
- | `JobQueuePolicy` | interface | `{ retryLimit?, retryDelay?: Duration, retryBackoff?, retryDelayMax?: Duration, expiresIn?: Duration, deadLetter?: string }` | Applied per queue when the runner starts. `expiresIn` is what surfaces as `JobContext.expiresIn`. |
63
- | `JobWorkerPolicy` | interface | `{ concurrency?: number, batchSize?: number, pollInterval?: Duration }` | Configures the worker **this node** starts, not the queue. Applied when the runner registers the worker. |
64
- | `JobInfo<Payload>` | interface | `{ id, name, state: JobState, data: Payload }` | Lowest common denominator across backends. |
65
- | `JobState` | type | `'created' \| 'retry' \| 'active' \| 'completed' \| 'cancelled' \| 'failed'` | — |
66
- | `JobQueueStats` | interface | `{ name, queued, active, failed, total }` | `failed` is a **retained** count, not an all-time total. |
67
- | `JobQueryOptions` | interface | `{ id?, data?: Record<string, unknown>, queuedOnly? }` | `data` is a partial-match payload filter. |
68
- | `JobRedriveOptions` | interface | `{ destination?, sourceName?, limit? }` | Without `destination`, each job returns to its original queue. |
69
- | `NotSupportedError` | class | `extends ServerkitError` | Thrown by a backend that cannot honour an operation. |
70
- | `PermanentJobError` | class | `extends ServerkitError`. `new (message, options?: { cause?: unknown })` | Thrown by a job to skip its remaining retries and dead-letter immediately. Matched by direct `instanceof`. |
43
+ | Export | Kind | Shape | Notes |
44
+ | ------------------------------------ | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
45
+ | `Job<Payload>` | abstract class | `@Injectable() abstract run(payload: Payload, signal?: AbortSignal): Promise<void>` | `Payload extends object = object`. |
46
+ | `JobBroker` | abstract class | `@Injectable()`. Producer side. | Unsupported operations throw `NotSupportedError` rather than no-op. |
47
+ | `#send` | method | `<P extends object>(name: string, payload: P, options?: JobSendOptions) => Promise<string>` | Returns the job id. Throws if `name` is not registered. |
48
+ | `#schedule` | method | `<P extends object>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions) => Promise<void>` | Cron or RFC 5545 RRULE. One schedule per name and key; the same key replaces it. |
49
+ | `#unschedule` | method | `(name: string, key?: string) => Promise<void>` | Without `key`, removes only the unkeyed schedule. |
50
+ | `#getSchedules` | method | `<P extends object>(name: string, key?: string) => Promise<JobSchedule<P>[]>` | With `key`, at most one. Ordered by key. |
51
+ | `#previewSchedule` | method | `(recurrence: string, options?: JobSchedulePreviewOptions) => Promise<DateTime[]>` | Stores nothing. Validates as `schedule` does. Results are in `options.timeZone` (UTC by default). |
52
+ | `#cancel` / `#resume` / `#deleteJob` | method | `(name: string, id: string \| string[]) => Promise<void>` | `cancel` aborts the signal for a running job. |
53
+ | `#getJob` | method | `<P extends object>(name: string, id: string) => Promise<JobInfo<P> \| null>` | — |
54
+ | `JobRunner` | abstract class | `@Injectable()`. `start()`, `stop()` | Consumer side. `stop()` waits for in-flight jobs. |
55
+ | `JobMonitor` | abstract class | `@Injectable()`. `getQueueStats`, `listJobs`, `redrive`, `deleteJob`, `retryJob` | Operational surface — dashboards, dead-letter drains. |
56
+ | `JobContext` | interface + abstract class | `{ id: string; name: string; signal: AbortSignal; expiresIn?: Duration }` | Declaration-merged so one symbol is both the type and the DI token. |
57
+ | `registerJobContext` | function | `<T extends Registry>(registry: T) => T` | **Required** if any service injects `JobContext`. Registers a throwing placeholder. |
58
+ | `JobSendOptions` | interface | `{ startAfter?: Duration \| DateTime; group?: { id: string; tier?: string } }` | `startAfter`: a lower bound, not exact scheduling. `group`: only limits anything with a `groupConcurrency`. |
59
+ | `JobScheduleOptions` | interface | `{ key?: string; timeZone?: string; missed?: 'skip' \| 'once' }` | `timeZone` is IANA, UTC when omitted. `missed` defaults to the backend's (`skip` on pg-boss). |
60
+ | `JobSchedule<Payload>` | interface | `{ name, key, recurrence, timeZone, payload? }` | `key` is `''` for the unkeyed schedule. No backend bookkeeping fields. |
61
+ | `JobSchedulePreviewOptions` | interface | `{ timeZone?: string; from?: DateTime; count?: number }` | Occurrences are strictly after `from`, so paging passes the last one back in. |
62
+ | `JobQueuePolicy` | interface | `{ retryLimit?, retryDelay?: Duration, retryBackoff?, retryDelayMax?: Duration, expiresIn?: Duration, deadLetter?: string }` | Applied per queue when the runner starts. `expiresIn` is what surfaces as `JobContext.expiresIn`. |
63
+ | `JobWorkerPolicy` | interface | `{ concurrency?, batchSize?, pollInterval?: Duration, localGroupConcurrency?, groupConcurrency?: number \| { default, tiers? } }` | Configures the worker **this node** starts, not the queue. Applied when the runner registers the worker. |
64
+ | `JobInfo<Payload>` | interface | `{ id, name, state: JobState, data: Payload }` | Lowest common denominator across backends. |
65
+ | `JobState` | type | `'created' \| 'retry' \| 'active' \| 'completed' \| 'cancelled' \| 'failed'` | — |
66
+ | `JobQueueStats` | interface | `{ name, queued, active, failed, total }` | `failed` is a **retained** count, not an all-time total. |
67
+ | `JobQueryOptions` | interface | `{ id?, data?: Record<string, unknown>, queuedOnly? }` | `data` is a partial-match payload filter. |
68
+ | `JobRedriveOptions` | interface | `{ destination?, sourceName?, limit? }` | Without `destination`, each job returns to its original queue. |
69
+ | `NotSupportedError` | class | `extends ServerkitError` | Thrown by a backend that cannot honour an operation. |
70
+ | `PermanentJobError` | class | `extends ServerkitError`. `new (message, options?: { cause?: unknown })` | Thrown by a job to skip its remaining retries and dead-letter immediately. Matched by direct `instanceof`. |
71
71
 
72
72
  ### `./pgboss`
73
73
 
@@ -227,12 +227,26 @@ See [.claude/skills/job](../../.claude/skills/job) for the generator and its exa
227
227
  - **`PermanentJobError` is matched by direct `instanceof`, not by walking the `cause` chain.** The
228
228
  meaning is "this handler declared the failure permanent". Wrapping a transient error in one makes
229
229
  it permanent; a transient error that merely carries one as its cause stays retryable.
230
+ - **Use `localGroupConcurrency`, not `groupConcurrency`, to keep a group's jobs in order.** A queue
231
+ that must run one key's jobs one at a time (one conversation, one account) while different keys
232
+ run in parallel sends each job with `group: { id: key }` and runs with
233
+ `worker: { concurrency: n, localGroupConcurrency: 1 }`. That limit is counted in process, so it is
234
+ exact on the node, but it does not coordinate across nodes: strict order needs one node consuming
235
+ the queue. `groupConcurrency` is counted in the database and spans nodes, but it is checked at
236
+ fetch time, not locked, so two workers fetching at once can both start a job from the same group
237
+ under a limit of 1. Treat it as a load bound, not an ordering guarantee, and give every node the
238
+ same value. Jobs sent without a group ignore both.
239
+ - **`groupConcurrency` and `localGroupConcurrency` are mutually exclusive.** pg-boss rejects both
240
+ together, and the runner checks every queue's merged policy (own `worker` over
241
+ `defaultWorkerPolicy`) before it starts anything, throwing a `ServerkitError` naming the queue. A
242
+ queue clears one inherited from the default by setting it to `undefined`.
230
243
  - **`JobWorkerPolicy` is not stored on the queue.** Unlike `JobQueuePolicy`, which the runner
231
244
  reconciles onto the queue via `createQueue`/`updateQueue`, a worker policy configures only the
232
245
  workers _this process_ starts. Two nodes on the same queue may use different values, and a change
233
246
  takes effect on the next runner start for that node alone.
234
247
  - **The peer floor is pg-boss >= 12.38.0**, and it is load-bearing. `concurrency` maps to
235
248
  `localConcurrency` (added in 12.6.0) and per-job settlement to `perJobResults` (added in 12.21.0).
249
+ `groupConcurrency`, `localGroupConcurrency`, and the `group` send option are 12.x features the same floor covers.
236
250
  An older peer would ignore `perJobResults`, take the handler's `JobResult[]` as the batch's single
237
251
  output, and mark **every job complete, including the failed ones**. Keyed schedules need 12.38:
238
252
  RRULE recurrences, `missed`, `previewSchedule`, and `unschedule` on a caller's connection all
package/README.md CHANGED
@@ -10,7 +10,8 @@ A flexible background job processing library with support for scheduled and on-d
10
10
  - **On-demand jobs** for immediate execution
11
11
  - **Cancellation** of queued _and_ running jobs, plus state lookup, delete, and resume
12
12
  - **Per-queue retry & dead-letter policy** for retry limits, backoff, and poison-message capture
13
- - **Per-queue worker policy** for concurrency, batch size, and poll interval
13
+ - **Per-queue worker policy** for concurrency, batch size, poll interval, and per-group limits (exact on one node, or approximate across nodes)
14
+ - **Job groups** on send, so jobs sharing a key run one at a time while other keys run in parallel
14
15
  - **Per-job settlement** so one failing job in a batch never drags its siblings into retry
15
16
  - **Permanent failures** that skip remaining retries and dead-letter immediately
16
17
  - **Dead-letter monitoring** to inspect, redrive, retry, or discard failed jobs
@@ -150,6 +151,9 @@ await broker.send('send-email', payload, { startAfter: Duration.fromObject({ min
150
151
  // ...or until an absolute moment (Luxon DateTime)
151
152
  await broker.send('send-email', payload, { startAfter: DateTime.now().plus({ hours: 2 }) });
152
153
 
154
+ // Group a job, so a worker's localGroupConcurrency can keep one group's jobs from overlapping
155
+ await broker.send('chat.reply', payload, { group: { id: conversationId } });
156
+
153
157
  // Inspect a job's current state
154
158
  const info = await broker.getJob('send-email', id); // { id, name, state, data } | null
155
159
 
@@ -362,7 +366,31 @@ await runner.start();
362
366
 
363
367
  When a registration declares no worker policy and no default is set, pg-boss's own defaults apply: one worker, one job per fetch.
364
368
 
365
- > `concurrency` maps to pg-boss `localConcurrency` and per-job settlement to `perJobResults`, both of which the package's peer floor (**pg-boss >= 12.38.0**) guarantees.
369
+ ### Ordering within a group
370
+
371
+ Some queues must keep one key's jobs in order (the replies in one conversation, the updates to one account) without making every other key wait. Send each job with a `group`, and give the worker a `localGroupConcurrency`:
372
+
373
+ ```typescript
374
+ registry.set('chat.reply', {
375
+ job: ChatReplyJob,
376
+ worker: {
377
+ concurrency: 3, // three jobs at once on this node...
378
+ localGroupConcurrency: 1, // ...but never two from the same conversation
379
+ },
380
+ });
381
+
382
+ await broker.send('chat.reply', { conversationId, messageId }, { group: { id: conversationId } });
383
+ ```
384
+
385
+ `localGroupConcurrency` is counted in process by the node's own workers, so the limit is exact: with a limit of 1, one conversation's jobs run strictly one after another while other conversations run alongside them. It does not coordinate across nodes, so two nodes consuming the queue can each run one of a group's jobs at the same time. Strict per-group order needs a single node consuming the queue.
386
+
387
+ `groupConcurrency` is the cross-node alternative. pg-boss counts a group's running jobs in the database, so the limit spans every node, but it is checked when a worker fetches rather than held as a lock. Two workers that fetch at nearly the same moment can both see no running job in a group and each take one, so under a limit of 1 two of a group's jobs can still start together. Use it to bound load per group across a fleet, not to guarantee order. Its limit is each worker's own value, so give every node the same one.
388
+
389
+ The two cannot be combined: pg-boss accepts only one, and the runner refuses to start if a queue's effective policy (its own `worker` merged over `defaultWorkerPolicy`) sets both. A queue can clear one it inherits from the default by setting that field to `undefined`. Jobs sent without a `group` are limited by neither.
390
+
391
+ A group may also carry a `tier`, and either limit may give tiers their own values: `{ default: 1, tiers: { priority: 3 } }` lets a group sent with `group: { id, tier: 'priority' }` run three at once while every other group runs one.
392
+
393
+ > `concurrency` maps to pg-boss `localConcurrency`, `localGroupConcurrency` and `groupConcurrency` to the pg-boss options of the same names, a send's `group` to pg-boss's `group` job option, and per-job settlement to `perJobResults`, all of which the package's peer floor (**pg-boss >= 12.38.0**) guarantees.
366
394
 
367
395
  ## Monitoring & draining dead-letter queues
368
396
 
@@ -431,17 +459,17 @@ Injection token describing the job execution in flight, registered by the runner
431
459
 
432
460
  Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
433
461
 
434
- | Method | Description |
435
- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
436
- | `send<P>(name: string, payload: P, options?: JobSendOptions): Promise<string>` | Queue a job; resolves with the new job id. Pass `options.startAfter` (a Luxon `Duration` or `DateTime`) to defer it |
437
- | `schedule<P>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions): Promise<void>` | Create or replace a recurring schedule on a cron expression or RFC 5545 recurrence rule. `options` take `key`, `timeZone` and `missed` |
438
- | `unschedule(name: string, key?: string): Promise<void>` | Remove the schedule with that key, or the unkeyed one when `key` is omitted |
439
- | `getSchedules<P>(name: string, key?: string): Promise<JobSchedule<P>[]>` | List a name's schedules, or the one with `key` |
440
- | `previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]>` | Next occurrences of a recurrence, without storing anything. `options` take `timeZone`, `from` and `count` |
441
- | `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
442
- | `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
443
- | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
444
- | `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
462
+ | Method | Description |
463
+ | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
464
+ | `send<P>(name: string, payload: P, options?: JobSendOptions): Promise<string>` | Queue a job; resolves with the new job id. Pass `options.startAfter` (a Luxon `Duration` or `DateTime`) to defer it, or `options.group` to group it |
465
+ | `schedule<P>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions): Promise<void>` | Create or replace a recurring schedule on a cron expression or RFC 5545 recurrence rule. `options` take `key`, `timeZone` and `missed` |
466
+ | `unschedule(name: string, key?: string): Promise<void>` | Remove the schedule with that key, or the unkeyed one when `key` is omitted |
467
+ | `getSchedules<P>(name: string, key?: string): Promise<JobSchedule<P>[]>` | List a name's schedules, or the one with `key` |
468
+ | `previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]>` | Next occurrences of a recurrence, without storing anything. `options` take `timeZone`, `from` and `count` |
469
+ | `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
470
+ | `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
471
+ | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
472
+ | `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
445
473
 
446
474
  ### `JobScheduleOptions` / `JobSchedule<Payload>` / `JobSchedulePreviewOptions`
447
475
 
@@ -511,11 +539,13 @@ Backend-agnostic per-queue retry and dead-letter policy (see [Retry & dead-lette
511
539
 
512
540
  Per-queue worker throughput, declared on the registration's `worker` field or runner-wide via `defaultWorkerPolicy`. All fields optional.
513
541
 
514
- | Field | Type | Meaning |
515
- | -------------- | ---------- | -------------------------------------------------------------------------------- |
516
- | `concurrency` | `number` | Jobs this node may run at once for the queue. Each unit settles its own job. |
517
- | `batchSize` | `number` | Jobs fetched per trip and handed to the handler as one batch, settled as a unit. |
518
- | `pollInterval` | `Duration` | How long a worker waits between fetches while idle. Passed through unrounded. |
542
+ | Field | Type | Meaning |
543
+ | ----------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
544
+ | `concurrency` | `number` | Jobs this node may run at once for the queue. Each unit settles its own job. |
545
+ | `batchSize` | `number` | Jobs fetched per trip and handed to the handler as one batch, settled as a unit. |
546
+ | `pollInterval` | `Duration` | How long a worker waits between fetches while idle. Passed through unrounded. |
547
+ | `localGroupConcurrency` | `number \| { default: number; tiers?: Record<string, number> }` | Jobs of one `group` that may run at once on this node. Exact, but not coordinated across nodes. |
548
+ | `groupConcurrency` | `number \| { default: number; tiers?: Record<string, number> }` | Jobs of one `group` that may run at once across all nodes, counted in the database. Approximate: simultaneous fetches can exceed it. Not combinable with `localGroupConcurrency`. |
519
549
 
520
550
  Configures the worker this process starts, not the queue. See [Worker concurrency](#worker-concurrency).
521
551
 
@@ -29,5 +29,31 @@ export interface JobSendOptions {
29
29
  * `NotSupportedError`.
30
30
  */
31
31
  startAfter?: Duration | DateTime;
32
+ /**
33
+ * Put the job in a group, so a worker can cap how many jobs of one group run
34
+ * at once (see {@link JobWorkerPolicy.localGroupConcurrency} and
35
+ * {@link JobWorkerPolicy.groupConcurrency}).
36
+ *
37
+ * - `id` names the group. Jobs that must not overlap share an id: with a
38
+ * group concurrency of 1, jobs sharing an id run one after another while
39
+ * jobs in other groups run alongside them.
40
+ * - `tier` optionally places the group in a tier, so a worker can give
41
+ * different tiers different limits (the `tiers` of either limit).
42
+ *
43
+ * Grouping has no effect on its own; it only matters once the queue's
44
+ * worker sets a group limit. Backends map this onto their native
45
+ * grouping (pg-boss's `group` job option). A backend without job groups
46
+ * throws a `NotSupportedError`.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // One conversation's replies stay in order; other conversations run in parallel.
51
+ * await broker.send('chat.reply', payload, { group: { id: conversationId } });
52
+ * ```
53
+ */
54
+ group?: {
55
+ id: string;
56
+ tier?: string;
57
+ };
32
58
  }
33
59
  //# sourceMappingURL=job.send.options.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"job.send.options.d.ts","sourceRoot":"","sources":["../src/job.send.options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;;;;;;;;;;;;OAkBG;IACH,UAAU,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;CAClC"}
1
+ {"version":3,"file":"job.send.options.d.ts","sourceRoot":"","sources":["../src/job.send.options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;;;;;;;;;;;;OAkBG;IACH,UAAU,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAEjC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,KAAK,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvC"}
@@ -55,5 +55,63 @@ export interface JobWorkerPolicy {
55
55
  * it as a fractional second count, not rounded.
56
56
  */
57
57
  pollInterval?: Duration;
58
+ /**
59
+ * The most jobs of one group (see {@link JobSendOptions.group}) that may run
60
+ * at once, counted across every node consuming the queue. pg-boss tracks it
61
+ * in the database. Jobs sent without a group are not limited by it.
62
+ *
63
+ * The limit is checked when a worker fetches, not held as a lock, so it is
64
+ * approximate: two workers that fetch at nearly the same moment can both see
65
+ * no running job in a group and each start one, putting two of that group's
66
+ * jobs in flight under a limit of 1. Use it to bound load per group across
67
+ * nodes. When a group's jobs must never overlap, use
68
+ * {@link localGroupConcurrency} instead.
69
+ *
70
+ * The count is shared, but the limit is still this worker's: each node checks
71
+ * the database against the value it was started with, so give every node
72
+ * consuming the queue the same value.
73
+ *
74
+ * Pass a number for one limit on every group, or `{ default, tiers }` to give
75
+ * groups in particular tiers their own limit, with `default` covering the
76
+ * rest. Cannot be combined with {@link localGroupConcurrency}: the runner
77
+ * refuses to start a queue whose effective policy sets both.
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * // Up to two of a tenant's jobs at a time across the fleet, roughly.
82
+ * const worker: JobWorkerPolicy = { concurrency: 8, groupConcurrency: 2 };
83
+ * ```
84
+ */
85
+ groupConcurrency?: number | {
86
+ default: number;
87
+ tiers?: Record<string, number>;
88
+ };
89
+ /**
90
+ * The most jobs of one group (see {@link JobSendOptions.group}) that may run
91
+ * at once on this node. The runner's workers for the queue share an
92
+ * in-process count, so the limit is exact within the node: with a limit of 1,
93
+ * a group's jobs run strictly one at a time while {@link concurrency} still
94
+ * lets different groups run side by side. Jobs sent without a group are not
95
+ * limited by it.
96
+ *
97
+ * It does not coordinate across nodes. Two nodes consuming the same queue can
98
+ * each run one of a group's jobs at the same time, so strict per-group order
99
+ * needs a single node consuming the queue (or another way of pinning a group
100
+ * to one node).
101
+ *
102
+ * Takes the same shapes as {@link groupConcurrency}: a number, or
103
+ * `{ default, tiers }`. Cannot be combined with {@link groupConcurrency}: the
104
+ * runner refuses to start a queue whose effective policy sets both.
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * // Three jobs at once on this node, but never two from the same group.
109
+ * const worker: JobWorkerPolicy = { concurrency: 3, localGroupConcurrency: 1 };
110
+ * ```
111
+ */
112
+ localGroupConcurrency?: number | {
113
+ default: number;
114
+ tiers?: Record<string, number>;
115
+ };
58
116
  }
59
117
  //# sourceMappingURL=job.worker.policy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"job.worker.policy.d.ts","sourceRoot":"","sources":["../src/job.worker.policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,QAAQ,CAAC;CACzB"}
1
+ {"version":3,"file":"job.worker.policy.d.ts","sourceRoot":"","sources":["../src/job.worker.policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,QAAQ,CAAC;IAExB;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAEhF;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,qBAAqB,CAAC,EAAE,MAAM,GAAG;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;CACtF"}
@@ -63,10 +63,15 @@ export declare class PgBossJobBroker extends JobBroker {
63
63
  * {@link Duration} is converted to a relative number of seconds and a
64
64
  * {@link DateTime} to an absolute `Date`.
65
65
  *
66
+ * When `options.group` is supplied it is passed through as pg-boss's `group`
67
+ * job option, so a worker's `localGroupConcurrency` or `groupConcurrency` can
68
+ * limit how many jobs of that
69
+ * group run at once.
70
+ *
66
71
  * @typeParam Payload - The type of the job payload.
67
72
  * @param name - The name of the registered job to execute.
68
73
  * @param payload - The data to pass to the job handler.
69
- * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
74
+ * @param options - Optional enqueue options, e.g. `startAfter` to defer the job or `group` to group it.
70
75
  * @returns A promise that resolves with the id of the queued job.
71
76
  * @throws Error if the job name is not found in the registry.
72
77
  * @throws Error if pg-boss does not return a job id (e.g. the job was
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.broker.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAuC,MAAM,SAAS,CAAC;AAEtE,OAAO,EAAE,QAAQ,EAAY,MAAM,OAAO,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,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AAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IAyBvG,mFAAmF;IACnF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAQ;IAEhD,iFAAiF;IACjF,OAAO,CAAC,aAAa;IAUrB;;;;;;;;;;;;;OAaG;IACG,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAWnG;;;;;;;;;;;;;OAaG;IACG,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQhE;;;;;;;;;OASG;IACG,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQhE;;;;;;;OAOG;IACG,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQnE;;;;;;;;;OASG;IACG,MAAM,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CAYjG"}
@@ -131,6 +131,9 @@ export declare class PgBossJobRunner extends JobRunner {
131
131
  * immediately.
132
132
  *
133
133
  * @returns A promise that resolves when all workers are registered with pg-boss.
134
+ * @throws ServerkitError before anything is created or started, if a queue's
135
+ * effective worker policy sets both `groupConcurrency` and
136
+ * `localGroupConcurrency`.
134
137
  */
135
138
  start(): Promise<void>;
136
139
  /**
@@ -189,11 +192,29 @@ export declare class PgBossJobRunner extends JobRunner {
189
192
  * @internal
190
193
  */
191
194
  private resolveWorkerPolicy;
195
+ /**
196
+ * Rejects an effective worker policy that sets both `groupConcurrency` and
197
+ * `localGroupConcurrency`. pg-boss accepts only one, and because the runner's
198
+ * {@link defaultWorkerPolicy} is merged beneath each queue's own policy, the
199
+ * two can meet without either declaration setting both. Failing here names
200
+ * the queue; a queue that inherits one from the default can opt out of it by
201
+ * setting that field to `undefined` in its own policy.
202
+ *
203
+ * @param name - The queue the policy applies to.
204
+ * @param policy - The effective worker policy for the queue, or `undefined`.
205
+ * @throws ServerkitError if the policy sets both group limits.
206
+ * @internal
207
+ */
208
+ private assertWorkerPolicy;
192
209
  /**
193
210
  * Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work
194
211
  * options. `pollInterval` is passed as a fractional second count rather than
195
212
  * rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a
196
213
  * deliberate sub-second poll into either 0 (rejected) or 1.
214
+ * `groupConcurrency` maps to pg-boss's database-tracked `groupConcurrency`
215
+ * (counted across nodes, approximate under simultaneous fetches) and
216
+ * `localGroupConcurrency` to pg-boss's in-process `localGroupConcurrency`
217
+ * (exact, but within this node only).
197
218
  *
198
219
  * Always returns options, because `perJobResults` is always on: it is what makes
199
220
  * pg-boss settle each job in a batch individually, and what gives
@@ -1 +1 @@
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;;;;;;;;;;;;;;;;;;;;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AC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
package/dist/pgboss.js CHANGED
@@ -101,10 +101,15 @@ var PgBossJobBroker = class _PgBossJobBroker extends JobBroker {
101
101
  * {@link Duration} is converted to a relative number of seconds and a
102
102
  * {@link DateTime} to an absolute `Date`.
103
103
  *
104
+ * When `options.group` is supplied it is passed through as pg-boss's `group`
105
+ * job option, so a worker's `localGroupConcurrency` or `groupConcurrency` can
106
+ * limit how many jobs of that
107
+ * group run at once.
108
+ *
104
109
  * @typeParam Payload - The type of the job payload.
105
110
  * @param name - The name of the registered job to execute.
106
111
  * @param payload - The data to pass to the job handler.
107
- * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
112
+ * @param options - Optional enqueue options, e.g. `startAfter` to defer the job or `group` to group it.
108
113
  * @returns A promise that resolves with the id of the queued job.
109
114
  * @throws Error if the job name is not found in the registry.
110
115
  * @throws Error if pg-boss does not return a job id (e.g. the job was
@@ -116,7 +121,10 @@ var PgBossJobBroker = class _PgBossJobBroker extends JobBroker {
116
121
  }
117
122
  const id = await this.pgboss.send(name, payload, {
118
123
  db: this.connectionProvider.executor(),
119
- ...this.toStartAfter(options?.startAfter)
124
+ ...this.toStartAfter(options?.startAfter),
125
+ ...options?.group ? {
126
+ group: options.group
127
+ } : {}
120
128
  });
121
129
  if (!id) {
122
130
  throw new Error(`Failed to enqueue job ${name}`);
@@ -639,8 +647,14 @@ var PgBossJobRunner = class extends JobRunner {
639
647
  * immediately.
640
648
  *
641
649
  * @returns A promise that resolves when all workers are registered with pg-boss.
650
+ * @throws ServerkitError before anything is created or started, if a queue's
651
+ * effective worker policy sets both `groupConcurrency` and
652
+ * `localGroupConcurrency`.
642
653
  */
643
654
  async start() {
655
+ for (const [name, registration] of this.registrations.entries()) {
656
+ this.assertWorkerPolicy(name, this.resolveWorkerPolicy(registration));
657
+ }
644
658
  await this.pgboss.start();
645
659
  const ensured = /* @__PURE__ */ new Set();
646
660
  for (const [name, registration] of this.registrations.entries()) {
@@ -833,10 +847,34 @@ var PgBossJobRunner = class extends JobRunner {
833
847
  };
834
848
  }
835
849
  /**
850
+ * Rejects an effective worker policy that sets both `groupConcurrency` and
851
+ * `localGroupConcurrency`. pg-boss accepts only one, and because the runner's
852
+ * {@link defaultWorkerPolicy} is merged beneath each queue's own policy, the
853
+ * two can meet without either declaration setting both. Failing here names
854
+ * the queue; a queue that inherits one from the default can opt out of it by
855
+ * setting that field to `undefined` in its own policy.
856
+ *
857
+ * @param name - The queue the policy applies to.
858
+ * @param policy - The effective worker policy for the queue, or `undefined`.
859
+ * @throws ServerkitError if the policy sets both group limits.
860
+ * @internal
861
+ */
862
+ assertWorkerPolicy(name, policy) {
863
+ if (policy?.groupConcurrency !== void 0 && policy.localGroupConcurrency !== void 0) {
864
+ throw new ServerkitError(`Worker policy for queue "${name}" sets both groupConcurrency and localGroupConcurrency; set one (a queue can clear one inherited from defaultWorkerPolicy by setting it to undefined)`).withDetails({
865
+ queue: name
866
+ });
867
+ }
868
+ }
869
+ /**
836
870
  * Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work
837
871
  * options. `pollInterval` is passed as a fractional second count rather than
838
872
  * rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a
839
873
  * deliberate sub-second poll into either 0 (rejected) or 1.
874
+ * `groupConcurrency` maps to pg-boss's database-tracked `groupConcurrency`
875
+ * (counted across nodes, approximate under simultaneous fetches) and
876
+ * `localGroupConcurrency` to pg-boss's in-process `localGroupConcurrency`
877
+ * (exact, but within this node only).
840
878
  *
841
879
  * Always returns options, because `perJobResults` is always on: it is what makes
842
880
  * pg-boss settle each job in a batch individually, and what gives
@@ -860,6 +898,12 @@ var PgBossJobRunner = class extends JobRunner {
860
898
  if (policy?.pollInterval !== void 0) {
861
899
  options.pollingIntervalSeconds = policy.pollInterval.as("seconds");
862
900
  }
901
+ if (policy?.groupConcurrency !== void 0) {
902
+ options.groupConcurrency = policy.groupConcurrency;
903
+ }
904
+ if (policy?.localGroupConcurrency !== void 0) {
905
+ options.localGroupConcurrency = policy.localGroupConcurrency;
906
+ }
863
907
  return options;
864
908
  }
865
909
  /**
@@ -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, type Schedule, type ScheduleOptions } 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 { JobSchedule } from '../job.schedule.js';\nimport { JobScheduleOptions, JobSchedulePreviewOptions } from '../job.schedule.options.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 recurring schedules on cron expressions or RFC 5545 recurrence rules,\n * many per queue when each has its own key.\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 on a cron expression or an RFC 5545 recurrence rule.\n *\n * pg-boss decides the format from the expression itself and stores one row\n * per job name and key, so scheduling again with the same name and key\n * replaces that row. The options map onto pg-boss's own: `key` to `key`,\n * `timeZone` to `tz`, and `missed` to `missed`. pg-boss validates the\n * recurrence and the zone before writing and throws on either.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the schedule commits or rolls back with it.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param payload - Optional data to pass to the job on each execution.\n * @param options - Optional key, time zone and missed-occurrence policy.\n * @returns A promise that resolves when the schedule has been created or replaced.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the key.\n */\n async schedule<Payload extends object>(name: string, recurrence: string, payload?: Payload, options?: JobScheduleOptions): 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, recurrence, payload, {\n db: this.connectionProvider.executor(),\n ...this.toScheduleOptions(options),\n });\n }\n\n /**\n * Maps backend-agnostic schedule options onto pg-boss's `key`, `tz` and\n * `missed`, leaving out any that were not given so pg-boss applies its own\n * defaults (the unkeyed schedule, UTC, and `skip`).\n */\n private toScheduleOptions(options: JobScheduleOptions | undefined): Pick<ScheduleOptions, 'key' | 'tz' | 'missed'> {\n return {\n ...(options?.key !== undefined && { key: options.key }),\n ...(options?.timeZone !== undefined && { tz: options.timeZone }),\n ...(options?.missed !== undefined && { missed: options.missed }),\n };\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the schedule with the given name and key.\n * Jobs that are already queued will still be processed. pg-boss reads a\n * missing key as the empty key, so `unschedule(name)` removes only the\n * unkeyed schedule and leaves keyed ones in place.\n *\n * The delete runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}, so inside a transaction it rolls back\n * with the transaction.\n *\n * @param name - The name of the scheduled job.\n * @param key - The key the schedule was created with, if any.\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, key?: 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, key, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Lists the schedules on a job name from pg-boss.\n *\n * With a key this reads the one row by its primary key. Without one it pages\n * through every schedule on the name, so a queue with many keyed schedules is\n * returned whole rather than cut off at pg-boss's page size.\n *\n * pg-boss offers no connection option for this read, so it always runs on\n * pg-boss's own pool: a schedule written inside a transaction that has not\n * committed yet is not visible here.\n *\n * @typeParam Payload - The type of the scheduled payload.\n * @param name - The name of the registered job.\n * @param key - When given, only the schedule with this key.\n * @returns A promise that resolves with the matching schedules, ordered by key.\n * @throws Error if the job name is not found in the registry.\n */\n async getSchedules<Payload extends object>(name: string, key?: string): Promise<JobSchedule<Payload>[]> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n if (key !== undefined) {\n const schedule = await this.pgboss.getSchedule(name, key);\n return schedule ? [this.toJobSchedule<Payload>(schedule)] : [];\n }\n\n const schedules: Schedule[] = [];\n let after: Pick<Schedule, 'name' | 'key'> | undefined;\n for (;;) {\n const page = await this.pgboss.getSchedules(name, undefined, { limit: PgBossJobBroker.schedulePageSize, ...(after && { after }) });\n schedules.push(...page);\n const last = page.at(-1);\n if (page.length < PgBossJobBroker.schedulePageSize || !last) {\n break;\n }\n after = { name: last.name, key: last.key };\n }\n\n return schedules.map(schedule => this.toJobSchedule<Payload>(schedule));\n }\n\n /** Rows read per page when {@link getSchedules} lists every schedule on a name. */\n private static readonly schedulePageSize = 1000;\n\n /** Maps a pg-boss schedule row onto the backend-agnostic {@link JobSchedule}. */\n private toJobSchedule<Payload extends object>(schedule: Schedule): JobSchedule<Payload> {\n return {\n name: schedule.name,\n key: schedule.key,\n recurrence: schedule.cron,\n timeZone: schedule.timezone || 'UTC',\n ...(schedule.data != null && { payload: schedule.data as Payload }),\n };\n }\n\n /**\n * Computes the next occurrences of a recurrence with pg-boss's\n * `previewSchedule`, which validates exactly as {@link schedule} does and\n * touches neither the database nor the schedule table.\n *\n * `from` defaults to pg-boss's reading of database time, which on an instance\n * that runs schedules accounts for clock skew against the database. The\n * returned `DateTime`s are in `options.timeZone`, or UTC when omitted.\n *\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param options - Optional time zone, starting point and count.\n * @returns A promise that resolves with the occurrences, earliest first.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the count.\n */\n async previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]> {\n const zone = options?.timeZone ?? 'UTC';\n const occurrences = this.pgboss.previewSchedule(recurrence, {\n tz: zone,\n ...(options?.from !== undefined && { from: options.from.toJSDate() }),\n ...(options?.count !== undefined && { count: options.count }),\n });\n\n return occurrences.map(occurrence => DateTime.fromJSDate(occurrence, { zone }));\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,cAAmD;AAC5D,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAyGhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACzGhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFLO,IAAMC,kBAAN,MAAMA,yBAAwBC,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,KAA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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","recurrence","toScheduleOptions","key","undefined","timeZone","tz","missed","unschedule","getSchedules","getSchedule","toJobSchedule","schedules","after","page","limit","schedulePageSize","push","last","at","length","map","cron","timezone","data","previewSchedule","zone","occurrences","from","count","occurrence","fromJSDate","cancel","resume","deleteJob","getJob","job","findJobs","state","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"]}
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, type Schedule, type ScheduleOptions } 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 { JobSchedule } from '../job.schedule.js';\nimport { JobScheduleOptions, JobSchedulePreviewOptions } from '../job.schedule.options.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 recurring schedules on cron expressions or RFC 5545 recurrence rules,\n * many per queue when each has its own key.\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 * When `options.group` is supplied it is passed through as pg-boss's `group`\n * job option, so a worker's `localGroupConcurrency` or `groupConcurrency` can\n * limit how many jobs of that\n * group run at once.\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 or `group` to group it.\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 ...(options?.group ? { group: options.group } : {}),\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 on a cron expression or an RFC 5545 recurrence rule.\n *\n * pg-boss decides the format from the expression itself and stores one row\n * per job name and key, so scheduling again with the same name and key\n * replaces that row. The options map onto pg-boss's own: `key` to `key`,\n * `timeZone` to `tz`, and `missed` to `missed`. pg-boss validates the\n * recurrence and the zone before writing and throws on either.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the schedule commits or rolls back with it.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param payload - Optional data to pass to the job on each execution.\n * @param options - Optional key, time zone and missed-occurrence policy.\n * @returns A promise that resolves when the schedule has been created or replaced.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the key.\n */\n async schedule<Payload extends object>(name: string, recurrence: string, payload?: Payload, options?: JobScheduleOptions): 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, recurrence, payload, {\n db: this.connectionProvider.executor(),\n ...this.toScheduleOptions(options),\n });\n }\n\n /**\n * Maps backend-agnostic schedule options onto pg-boss's `key`, `tz` and\n * `missed`, leaving out any that were not given so pg-boss applies its own\n * defaults (the unkeyed schedule, UTC, and `skip`).\n */\n private toScheduleOptions(options: JobScheduleOptions | undefined): Pick<ScheduleOptions, 'key' | 'tz' | 'missed'> {\n return {\n ...(options?.key !== undefined && { key: options.key }),\n ...(options?.timeZone !== undefined && { tz: options.timeZone }),\n ...(options?.missed !== undefined && { missed: options.missed }),\n };\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the schedule with the given name and key.\n * Jobs that are already queued will still be processed. pg-boss reads a\n * missing key as the empty key, so `unschedule(name)` removes only the\n * unkeyed schedule and leaves keyed ones in place.\n *\n * The delete runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}, so inside a transaction it rolls back\n * with the transaction.\n *\n * @param name - The name of the scheduled job.\n * @param key - The key the schedule was created with, if any.\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, key?: 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, key, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Lists the schedules on a job name from pg-boss.\n *\n * With a key this reads the one row by its primary key. Without one it pages\n * through every schedule on the name, so a queue with many keyed schedules is\n * returned whole rather than cut off at pg-boss's page size.\n *\n * pg-boss offers no connection option for this read, so it always runs on\n * pg-boss's own pool: a schedule written inside a transaction that has not\n * committed yet is not visible here.\n *\n * @typeParam Payload - The type of the scheduled payload.\n * @param name - The name of the registered job.\n * @param key - When given, only the schedule with this key.\n * @returns A promise that resolves with the matching schedules, ordered by key.\n * @throws Error if the job name is not found in the registry.\n */\n async getSchedules<Payload extends object>(name: string, key?: string): Promise<JobSchedule<Payload>[]> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n if (key !== undefined) {\n const schedule = await this.pgboss.getSchedule(name, key);\n return schedule ? [this.toJobSchedule<Payload>(schedule)] : [];\n }\n\n const schedules: Schedule[] = [];\n let after: Pick<Schedule, 'name' | 'key'> | undefined;\n for (;;) {\n const page = await this.pgboss.getSchedules(name, undefined, { limit: PgBossJobBroker.schedulePageSize, ...(after && { after }) });\n schedules.push(...page);\n const last = page.at(-1);\n if (page.length < PgBossJobBroker.schedulePageSize || !last) {\n break;\n }\n after = { name: last.name, key: last.key };\n }\n\n return schedules.map(schedule => this.toJobSchedule<Payload>(schedule));\n }\n\n /** Rows read per page when {@link getSchedules} lists every schedule on a name. */\n private static readonly schedulePageSize = 1000;\n\n /** Maps a pg-boss schedule row onto the backend-agnostic {@link JobSchedule}. */\n private toJobSchedule<Payload extends object>(schedule: Schedule): JobSchedule<Payload> {\n return {\n name: schedule.name,\n key: schedule.key,\n recurrence: schedule.cron,\n timeZone: schedule.timezone || 'UTC',\n ...(schedule.data != null && { payload: schedule.data as Payload }),\n };\n }\n\n /**\n * Computes the next occurrences of a recurrence with pg-boss's\n * `previewSchedule`, which validates exactly as {@link schedule} does and\n * touches neither the database nor the schedule table.\n *\n * `from` defaults to pg-boss's reading of database time, which on an instance\n * that runs schedules accounts for clock skew against the database. The\n * returned `DateTime`s are in `options.timeZone`, or UTC when omitted.\n *\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param options - Optional time zone, starting point and count.\n * @returns A promise that resolves with the occurrences, earliest first.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the count.\n */\n async previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]> {\n const zone = options?.timeZone ?? 'UTC';\n const occurrences = this.pgboss.previewSchedule(recurrence, {\n tz: zone,\n ...(options?.from !== undefined && { from: options.from.toJSDate() }),\n ...(options?.count !== undefined && { count: options.count }),\n });\n\n return occurrences.map(occurrence => DateTime.fromJSDate(occurrence, { zone }));\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 * @throws ServerkitError before anything is created or started, if a queue's\n * effective worker policy sets both `groupConcurrency` and\n * `localGroupConcurrency`.\n */\n async start(): Promise<void> {\n // Checked up front so a conflicting policy fails before anything is created or started.\n for (const [name, registration] of this.registrations.entries()) {\n this.assertWorkerPolicy(name, this.resolveWorkerPolicy(registration));\n }\n\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 * Rejects an effective worker policy that sets both `groupConcurrency` and\n * `localGroupConcurrency`. pg-boss accepts only one, and because the runner's\n * {@link defaultWorkerPolicy} is merged beneath each queue's own policy, the\n * two can meet without either declaration setting both. Failing here names\n * the queue; a queue that inherits one from the default can opt out of it by\n * setting that field to `undefined` in its own policy.\n *\n * @param name - The queue the policy applies to.\n * @param policy - The effective worker policy for the queue, or `undefined`.\n * @throws ServerkitError if the policy sets both group limits.\n * @internal\n */\n private assertWorkerPolicy(name: string, policy: JobWorkerPolicy | undefined): void {\n if (policy?.groupConcurrency !== undefined && policy.localGroupConcurrency !== undefined) {\n throw new ServerkitError(\n `Worker policy for queue \"${name}\" sets both groupConcurrency and localGroupConcurrency; set one (a queue can clear one inherited from defaultWorkerPolicy by setting it to undefined)`,\n ).withDetails({ queue: name });\n }\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 * `groupConcurrency` maps to pg-boss's database-tracked `groupConcurrency`\n * (counted across nodes, approximate under simultaneous fetches) and\n * `localGroupConcurrency` to pg-boss's in-process `localGroupConcurrency`\n * (exact, but within this node only).\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 if (policy?.groupConcurrency !== undefined) {\n options.groupConcurrency = policy.groupConcurrency;\n }\n if (policy?.localGroupConcurrency !== undefined) {\n options.localGroupConcurrency = policy.localGroupConcurrency;\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,cAAmD;AAC5D,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAyGhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACzGhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFLO,IAAMC,kBAAN,MAAMA,yBAAwBC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4BA,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,mB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AO;IAChB;AAEA,UAAMiG,QAAQC,YAAY,YAAA;AACxB,UAAI;AACF,cAAM,CAAC9E,GAAAA,IAAO,MAAM,KAAKf,OAAO8F,SAAS3F,MAAM;UAAEoC;QAAG,CAAA;AACpD,YAAI,CAACxB,OAAOA,IAAIgF,UAAU,aAAa;AACrCrE,qBAAWsE,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAASlD,OAAO;AACd,aAAKzC,OAAOyC,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAK/C,4BAA4B,GAAA;AAGpCiG,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKnG,OAAOmG,KAAI;EACxB;AACF;;;;;;;;;;;;;AChhBA,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","group","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","recurrence","toScheduleOptions","key","undefined","timeZone","tz","missed","unschedule","getSchedules","getSchedule","toJobSchedule","schedules","after","page","limit","schedulePageSize","push","last","at","length","map","cron","timezone","data","previewSchedule","zone","occurrences","from","count","occurrence","fromJSDate","cancel","resume","deleteJob","getJob","job","findJobs","state","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","name","entries","assertWorkerPolicy","resolveWorkerPolicy","ensured","Set","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","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","worker","groupConcurrency","localGroupConcurrency","withDetails","perJobResults","concurrency","localConcurrency","batchSize","pollInterval","pollingIntervalSeconds","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "A flexible background job processing library with support for scheduled and on-demand jobs.",
5
5
  "author": {
6
6
  "name": "Marooned Software",