@maroonedsoftware/jobbroker 1.9.0 → 1.11.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/README.md CHANGED
@@ -23,10 +23,10 @@ pnpm add @maroonedsoftware/jobbroker injectkit pg-boss reflect-metadata
23
23
 
24
24
  `pg-boss` is an optional peer dependency. The pg-boss backend lives behind a subpath export so importing the core (`@maroonedsoftware/jobbroker`) never loads it:
25
25
 
26
- | Import | Contents | Pulls in |
27
- | ------------------------------------ | ---------------------------------------------------------------------------------------- | ------------- |
28
- | `@maroonedsoftware/jobbroker` | `Job`, `JobBroker`, `JobRunner`, `JobMonitor`, `JobInfo`, `JobState`, `JobQueuePolicy`, `NotSupportedError` | nothing extra |
29
- | `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobMonitor`, `PgBossJobRegistryMap`, `PgBossConnectionProvider` | `pg-boss` |
26
+ | Import | Contents | Pulls in |
27
+ | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
28
+ | `@maroonedsoftware/jobbroker` | `Job`, `JobContext`, `registerJobContext`, `JobBroker`, `JobRunner`, `JobMonitor`, `JobInfo`, `JobState`, `JobQueuePolicy`, `NotSupportedError` | nothing extra |
29
+ | `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobMonitor`, `PgBossJobRegistryMap`, `PgBossConnectionProvider`, `KyselyTransactionConnectionProvider` | `pg-boss` |
30
30
 
31
31
  ## Quick Start
32
32
 
@@ -97,7 +97,13 @@ import { PgBoss } from 'pg-boss';
97
97
  import { InjectKitRegistry } from 'injectkit';
98
98
  import { ConsoleLogger, Logger } from '@maroonedsoftware/logger';
99
99
  import { JobBroker, JobRunner, JobMonitor } from '@maroonedsoftware/jobbroker';
100
- import { PgBossJobBroker, PgBossJobRunner, PgBossJobMonitor, PgBossJobRegistryMap, PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
100
+ import {
101
+ PgBossJobBroker,
102
+ PgBossJobRunner,
103
+ PgBossJobMonitor,
104
+ PgBossJobRegistryMap,
105
+ PgBossConnectionProvider,
106
+ } from '@maroonedsoftware/jobbroker/pgboss';
101
107
 
102
108
  // Initialize pg-boss
103
109
  const pgboss = new PgBoss('postgres://user:pass@localhost/mydb');
@@ -158,6 +164,49 @@ await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
158
164
  await broker.unschedule('cleanup');
159
165
  ```
160
166
 
167
+ ## Job execution scope and `JobContext`
168
+
169
+ Each job execution runs in its own scoped DI container, created from the root container and disposed once the execution settles. This is the job-side counterpart of the per-request scope `serverKitContextMiddleware` creates: a service registered `asScoped()` gets a fresh instance per job, and any container-owned disposables the execution created are released when it finishes.
170
+
171
+ The scope carries a `JobContext` describing the job in flight, so a job — or anything it depends on, however deep — can inject it instead of having the metadata threaded through by hand:
172
+
173
+ ```typescript
174
+ import { Injectable } from 'injectkit';
175
+ import { Job, JobContext } from '@maroonedsoftware/jobbroker';
176
+
177
+ @Injectable()
178
+ class AuditLog {
179
+ constructor(private readonly context: JobContext) {}
180
+
181
+ record(message: string): void {
182
+ logger.info({ jobId: this.context.id, queue: this.context.name }, message);
183
+ }
184
+ }
185
+
186
+ @Injectable()
187
+ class SendEmailJob extends Job<EmailPayload> {
188
+ constructor(private readonly audit: AuditLog) {
189
+ super();
190
+ }
191
+
192
+ async run(payload: EmailPayload): Promise<void> {
193
+ this.audit.record('sending'); // attributed to this job, no plumbing at the call site
194
+ }
195
+ }
196
+ ```
197
+
198
+ `JobContext` exposes `id`, `name` (the queue), `signal` (the same cancellation signal handed to `run`), and `expiresIn` when the backend reports a limit. There is deliberately no attempt/retry counter: pg-boss hands the work handler a bare job, and the retry count would cost an extra query per execution. Read it from `JobMonitor` when you need it.
199
+
200
+ **Register the token whenever anything injects it.** `Registry.build()` validates the dependency graph up front, and the runner's per-execution override cannot satisfy that check because it only exists at runtime, inside a scope:
201
+
202
+ ```typescript
203
+ import { registerJobContext } from '@maroonedsoftware/jobbroker';
204
+
205
+ registerJobContext(diRegistry); // before diRegistry.build()
206
+ ```
207
+
208
+ That registers a placeholder which the runner's scoped override shadows during a job. Resolving `JobContext` anywhere else — at boot, in a request, from a singleton — throws with an explanation rather than returning a stale or fake context. So a service that has to work both inside and outside a job should not depend on it directly.
209
+
161
210
  ## Cancelling jobs
162
211
 
163
212
  `broker.cancel(name, id)` requests cancellation of a job **whatever state it is in**:
@@ -198,7 +247,7 @@ registry.set('deliver-webhook', {
198
247
 
199
248
  The policy is applied to the queue when `runner.start()` runs: an absent queue is **created** with these options, and an existing queue is **updated** to match, so changing a policy and restarting reconciles it. When a registration declares no policy, its queue is created exactly as before — this feature is fully backward-compatible.
200
249
 
201
- **Dead-letter queues are auto-created.** If `deadLetter` names a queue that does not yet exist, the runner creates it (as a plain queue) before the source queue that references it, so you don't have to register a placeholder. A DLQ you actually want to *drain* is just another registered job whose name matches — give it its own handler (and, if you like, its own policy). A DLQ you only want to inspect can be left unregistered; jobs simply accumulate there for manual review or redrive.
250
+ **Dead-letter queues are auto-created.** If `deadLetter` names a queue that does not yet exist, the runner creates it (as a plain queue) before the source queue that references it, so you don't have to register a placeholder. A DLQ you actually want to _drain_ is just another registered job whose name matches — give it its own handler (and, if you like, its own policy). A DLQ you only want to inspect can be left unregistered; jobs simply accumulate there for manual review or redrive.
202
251
 
203
252
  To apply the same defaults to **every** queue without repeating them, set `defaultQueuePolicy` on the runner. Each queue's own policy is layered on top, so a field a queue sets wins over the default:
204
253
 
@@ -238,13 +287,13 @@ if (stats && stats.total > 0) {
238
287
  }
239
288
  ```
240
289
 
241
- | Method | Description |
242
- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
243
- | `getQueueStats(name)` | Point-in-time `{ name, queued, active, failed, total }`, or `null` if the queue does not exist. |
244
- | `listJobs<P>(name, options?)` | List retained jobs as `JobInfo<P>[]`; filter by `id`, partial `data`, or `queuedOnly`. |
245
- | `redrive(name, options?)` | Move dead-lettered jobs back to their source (or a `destination`), oldest first; returns count. |
246
- | `deleteJob(name, id)` | Permanently discard one or more jobs (no registry check, so DLQ sinks are serviceable). |
247
- | `retryJob(name, id)` | Re-attempt failed jobs **in place**; for a DLQ sink prefer `redrive`, which moves them to a worker. |
290
+ | Method | Description |
291
+ | ----------------------------- | --------------------------------------------------------------------------------------------------- |
292
+ | `getQueueStats(name)` | Point-in-time `{ name, queued, active, failed, total }`, or `null` if the queue does not exist. |
293
+ | `listJobs<P>(name, options?)` | List retained jobs as `JobInfo<P>[]`; filter by `id`, partial `data`, or `queuedOnly`. |
294
+ | `redrive(name, options?)` | Move dead-lettered jobs back to their source (or a `destination`), oldest first; returns count. |
295
+ | `deleteJob(name, id)` | Permanently discard one or more jobs (no registry check, so DLQ sinks are serviceable). |
296
+ | `retryJob(name, id)` | Re-attempt failed jobs **in place**; for a DLQ sink prefer `redrive`, which moves them to a worker. |
248
297
 
249
298
  `redrive` returns each job to the queue it was dead-lettered from by default, so a worker can process it again. Pass `destination` to funnel everything into one queue, `sourceName` to drain just one source's jobs from a shared DLQ, and `limit` to move in controlled batches. All operations source their pg-boss `db` executor from `PgBossConnectionProvider`, so a remediation can run inside a transaction when you override the provider (see [Transactional enqueue](#transactional-enqueue)).
250
299
 
@@ -252,7 +301,7 @@ if (stats && stats.total > 0) {
252
301
 
253
302
  `cancel`, `resume`, `deleteJob`, and `getJob` are best-effort by contract: a backend that cannot honor an operation throws `NotSupportedError` rather than silently doing nothing. `JobState` (`created | retry | active | completed | cancelled | failed`) is the normalized, lowest-common-denominator lifecycle; alternative backends map their native states to the nearest value. The bundled pg-boss backend supports every operation.
254
303
 
255
- `send`'s `startAfter` is deliberately expressed as *intent* (a relative `Duration` or an absolute `DateTime`), not a wire format, so it maps cleanly onto each backend's native deferral mechanism — pg-boss `startAfter` (unbounded), SQS `DelaySeconds` (max 15 minutes), Cloud Tasks `scheduleTime` (up to 30 days). A backend that cannot honor a requested delay (e.g. an SQS backend asked for a 1-hour delay) throws `NotSupportedError` rather than clamping silently.
304
+ `send`'s `startAfter` is deliberately expressed as _intent_ (a relative `Duration` or an absolute `DateTime`), not a wire format, so it maps cleanly onto each backend's native deferral mechanism — pg-boss `startAfter` (unbounded), SQS `DelaySeconds` (max 15 minutes), Cloud Tasks `scheduleTime` (up to 30 days). A backend that cannot honor a requested delay (e.g. an SQS backend asked for a 1-hour delay) throws `NotSupportedError` rather than clamping silently.
256
305
 
257
306
  ## API Reference
258
307
 
@@ -264,19 +313,32 @@ Abstract base class for job handlers.
264
313
  | ------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
265
314
  | `run(payload: Payload, signal?: AbortSignal): Promise<void>` | Execute the job. `signal` is aborted on cancellation/shutdown; honoring it is optional. |
266
315
 
316
+ ### `JobContext`
317
+
318
+ Injection token describing the job execution in flight, registered by the runner in the per-execution scoped container. See [Job execution scope and `JobContext`](#job-execution-scope-and-jobcontext).
319
+
320
+ | Property | Description |
321
+ | ---------------------- | ---------------------------------------------------------------------------- |
322
+ | `id: string` | Backend-assigned job id, matching what `JobBroker.send` returned. |
323
+ | `name: string` | Queue the job was dequeued from, which is also its registered job name. |
324
+ | `signal: AbortSignal` | Aborted on cancellation or runner shutdown; the same signal passed to `run`. |
325
+ | `expiresIn?: Duration` | How long the backend allows this execution to run, when it reports a limit. |
326
+
327
+ `registerJobContext(registry)` registers the token so `build()`'s dependency validation passes. Required whenever a registered service injects `JobContext`.
328
+
267
329
  ### `JobBroker`
268
330
 
269
331
  Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
270
332
 
271
- | Method | Description |
272
- | --------------------------------------------------------------------- | ------------------------------------------------------------------ |
333
+ | Method | Description |
334
+ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
273
335
  | `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 |
274
- | `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
275
- | `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
276
- | `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
277
- | `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
278
- | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
279
- | `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
336
+ | `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
337
+ | `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
338
+ | `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
339
+ | `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
340
+ | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
341
+ | `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
280
342
 
281
343
  ### `JobInfo<Payload>` / `JobState`
282
344
 
@@ -295,13 +357,13 @@ Abstract base class for processing jobs from the queue.
295
357
 
296
358
  Abstract base class for observing queues and remediating dead-letter queues. Operates on raw queue names (no registry check). Operations a backend cannot honor throw `NotSupportedError`. See [Monitoring & draining dead-letter queues](#monitoring--draining-dead-letter-queues).
297
359
 
298
- | Method | Description |
299
- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
300
- | `getQueueStats(name: string): Promise<JobQueueStats \| null>` | Queue depth/health counts, or `null` if the queue does not exist |
301
- | `listJobs<P>(name: string, options?: JobQueryOptions): Promise<JobInfo<P>[]>` | List retained jobs, optionally filtered by `id`, `data`, or `queuedOnly` |
302
- | `redrive(name: string, options?: JobRedriveOptions): Promise<number>` | Move dead-lettered jobs back to source (or a `destination`); returns count moved |
303
- | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently discard jobs |
304
- | `retryJob(name: string, id: string \| string[]): Promise<void>` | Re-attempt failed jobs in place |
360
+ | Method | Description |
361
+ | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
362
+ | `getQueueStats(name: string): Promise<JobQueueStats \| null>` | Queue depth/health counts, or `null` if the queue does not exist |
363
+ | `listJobs<P>(name: string, options?: JobQueryOptions): Promise<JobInfo<P>[]>` | List retained jobs, optionally filtered by `id`, `data`, or `queuedOnly` |
364
+ | `redrive(name: string, options?: JobRedriveOptions): Promise<number>` | Move dead-lettered jobs back to source (or a `destination`); returns count moved |
365
+ | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently discard jobs |
366
+ | `retryJob(name: string, id: string \| string[]): Promise<void>` | Re-attempt failed jobs in place |
305
367
 
306
368
  `JobQueueStats` is `{ name, queued, active, failed, total }`. `JobQueryOptions` is `{ id?, data?, queuedOnly? }`. `JobRedriveOptions` is `{ destination?, sourceName?, limit? }`.
307
369
 
@@ -319,23 +381,23 @@ Entries can be either:
319
381
  Configuration object for a job. Only `job` is required, so it covers on-demand jobs (`{ job }`), scheduled jobs (`{ job, cron }`), and either with a retry/dead-letter policy attached.
320
382
 
321
383
  | Property | Type | Description |
322
- | -------- | ----------------- | ------------------------------------------------------------------- |
323
- | `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
324
- | `cron` | `string` | Optional cron expression defining when the job should run. |
384
+ | -------- | ----------------- | -------------------------------------------------------------------- |
385
+ | `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
386
+ | `cron` | `string` | Optional cron expression defining when the job should run. |
325
387
  | `policy` | `JobQueuePolicy` | Optional per-queue retry and dead-letter policy for the job's queue. |
326
388
 
327
389
  ### `JobQueuePolicy`
328
390
 
329
391
  Backend-agnostic per-queue retry and dead-letter policy (see [Retry & dead-letter policy](#retry--dead-letter-policy)). Every field is optional; durations are Luxon `Duration`s.
330
392
 
331
- | Property | Type | Description |
332
- | --------------- | ---------- | --------------------------------------------------------------------------------------- |
333
- | `retryLimit` | `number` | Attempts before a job is failed (and dead-lettered, if `deadLetter` is set). |
334
- | `retryDelay` | `Duration` | Delay before retrying; the base of the curve when `retryBackoff` is on. |
335
- | `retryBackoff` | `boolean` | Grow the retry delay exponentially (with jitter) from `retryDelay` instead of fixed. |
336
- | `retryDelayMax` | `Duration` | Upper bound on the backoff delay. Only used when `retryBackoff` is on. |
337
- | `expiresIn` | `Duration` | How long a run may take before it is considered stuck and made eligible for retry. |
338
- | `deadLetter` | `string` | Name of the dead-letter queue that receives jobs which exhaust their retries. |
393
+ | Property | Type | Description |
394
+ | --------------- | ---------- | ------------------------------------------------------------------------------------ |
395
+ | `retryLimit` | `number` | Attempts before a job is failed (and dead-lettered, if `deadLetter` is set). |
396
+ | `retryDelay` | `Duration` | Delay before retrying; the base of the curve when `retryBackoff` is on. |
397
+ | `retryBackoff` | `boolean` | Grow the retry delay exponentially (with jitter) from `retryDelay` instead of fixed. |
398
+ | `retryDelayMax` | `Duration` | Upper bound on the backoff delay. Only used when `retryBackoff` is on. |
399
+ | `expiresIn` | `Duration` | How long a run may take before it is considered stuck and made eligible for retry. |
400
+ | `deadLetter` | `string` | Name of the dead-letter queue that receives jobs which exhaust their retries. |
339
401
 
340
402
  ### `PgBossJobBroker`
341
403
 
@@ -351,27 +413,26 @@ Supplies the pg-boss `db` executor used when enqueuing or scheduling jobs.
351
413
 
352
414
  The default implementation returns `undefined`, so pg-boss uses its own connection pool (standard, non-transactional behavior). Override it on a request-scoped DI container to return a transaction-bound executor and enqueue jobs atomically with the surrounding database transaction — see [Transactional enqueue](#transactional-enqueue).
353
415
 
354
- ## Transactional enqueue
416
+ ### `KyselyTransactionConnectionProvider`
355
417
 
356
- By default a job row is inserted on pg-boss's own connection, so it commits independently of any database work happening in the same request. To make an enqueue commit (or roll back) together with your business writes, override `PgBossConnectionProvider` in the request scope so its `executor()` returns the active transaction's connection. pg-boss ships adapters for the common query builders (`fromKysely`, `fromKnex`, `fromDrizzle`, `fromPrisma`) that wrap a transaction into the executor shape pg-boss expects:
418
+ `PgBossConnectionProvider` bound to an active Kysely transaction. Constructor signature: `new KyselyTransactionConnectionProvider(trx: KyselyLike)`. Register it as a request-scoped override of `PgBossConnectionProvider` and every enqueue performed during the request inserts on the transaction's connection, so the job row and the surrounding writes commit or roll back together.
357
419
 
358
- ```typescript
359
- import { fromKysely } from 'pg-boss';
360
- import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
420
+ The constructor takes `KyselyLike`, a structural type satisfied by both `Kysely<DB>` and `Transaction<DB>` with no type argument or cast. Declaring it structurally means the package has no dependency on `kysely`, not even an optional peer.
361
421
 
362
- class TransactionalConnectionProvider extends PgBossConnectionProvider {
363
- constructor(private readonly trx: Transaction<DB>) {
364
- super();
365
- }
422
+ Plugins are stripped (`withoutPlugins()`) before the transaction is adapted: pg-boss runs raw SQL straight through `executeQuery`, so a column-rewriting plugin on the caller's instance would corrupt pg-boss's own result columns. The stripped instance shares the same connection-bound executor, so atomicity is preserved.
366
423
 
367
- override executor() {
368
- return fromKysely(this.trx);
369
- }
370
- }
424
+ ## Transactional enqueue
425
+
426
+ By default a job row is inserted on pg-boss's own connection, so it commits independently of any database work happening in the same request. To make an enqueue commit (or roll back) together with your business writes, override `PgBossConnectionProvider` in the request scope so its `executor()` returns the active transaction's connection.
427
+
428
+ For Kysely, `KyselyTransactionConnectionProvider` does this for you:
429
+
430
+ ```typescript
431
+ import { PgBossConnectionProvider, KyselyTransactionConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
371
432
 
372
433
  // Inside a transaction, bind the provider on the scoped container before resolving the broker:
373
434
  await repository.withTransaction(async trx => {
374
- scopedContainer.override(PgBossConnectionProvider, new TransactionalConnectionProvider(trx));
435
+ scopedContainer.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));
375
436
 
376
437
  await doBusinessWrites(trx);
377
438
  await scopedContainer.get(JobBroker).send('send-email', { to: 'user@example.com' });
@@ -379,9 +440,28 @@ await repository.withTransaction(async trx => {
379
440
  });
380
441
  ```
381
442
 
443
+ For the other query builders, pg-boss ships adapters (`fromKnex`, `fromDrizzle`, `fromPrisma`) that wrap a transaction into the executor shape pg-boss expects. Subclass the provider yourself:
444
+
445
+ ```typescript
446
+ import { fromKnex } from 'pg-boss';
447
+ import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
448
+
449
+ class KnexTransactionConnectionProvider extends PgBossConnectionProvider {
450
+ constructor(private readonly trx: Knex.Transaction) {
451
+ super();
452
+ }
453
+
454
+ override executor() {
455
+ return fromKnex(this.trx);
456
+ }
457
+ }
458
+ ```
459
+
382
460
  ### `PgBossJobRunner`
383
461
 
384
- Concrete `JobRunner` implementation backed by pg-boss. Constructor signature: `new PgBossJobRunner(container: Container, registrations: PgBossJobRegistryMap, pgboss: PgBoss, logger: Logger)`. Calls `pgboss.start()` during `start()` and `pgboss.stop()` during `stop()`. Job instances are resolved from the DI container on each invocation. Typically resolved through the DI container rather than instantiated directly.
462
+ Concrete `JobRunner` implementation backed by pg-boss. Constructor signature: `new PgBossJobRunner(container: Container, registrations: PgBossJobRegistryMap, pgboss: PgBoss, logger: Logger)`. Calls `pgboss.start()` during `start()` and `pgboss.stop()` during `stop()`. Typically resolved through the DI container rather than instantiated directly.
463
+
464
+ Each job execution runs in its own scoped container carrying a `JobContext`, created from the injected root container via `createScopedContainer()` and disposed once the execution settles — see [Job execution scope and `JobContext`](#job-execution-scope-and-jobcontext). Resolving a scoped registration from the root would instead cache it at the root for the lifetime of the process, where it would be shared by every job and inherited by every scope created later.
385
465
 
386
466
  Exposes a `cancelPollIntervalSeconds` property (default `5`) that controls how often a running job is polled for cancellation; set it to `0` to disable polling. See [Cancelling jobs](#cancelling-jobs).
387
467
 
@@ -19,7 +19,7 @@ JobBroker = _ts_decorate([
19
19
  Injectable()
20
20
  ], JobBroker);
21
21
 
22
- // src/job.monitor.ts
22
+ // src/job.context.ts
23
23
  import { Injectable as Injectable2 } from "injectkit";
24
24
  function _ts_decorate2(decorators, target, key, desc) {
25
25
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -28,16 +28,22 @@ function _ts_decorate2(decorators, target, key, desc) {
28
28
  return c > 3 && r && Object.defineProperty(target, key, r), r;
29
29
  }
30
30
  __name(_ts_decorate2, "_ts_decorate");
31
- var JobMonitor = class {
31
+ var JobContext = class {
32
32
  static {
33
- __name(this, "JobMonitor");
33
+ __name(this, "JobContext");
34
34
  }
35
35
  };
36
- JobMonitor = _ts_decorate2([
36
+ JobContext = _ts_decorate2([
37
37
  Injectable2()
38
- ], JobMonitor);
38
+ ], JobContext);
39
+ var registerJobContext = /* @__PURE__ */ __name((registry) => {
40
+ registry.register(JobContext).useFactory(() => {
41
+ throw new Error("JobContext is only available during a job execution. It cannot be resolved at boot, from a request scope, or from a singleton.");
42
+ }).asScoped();
43
+ return registry;
44
+ }, "registerJobContext");
39
45
 
40
- // src/job.runner.ts
46
+ // src/job.monitor.ts
41
47
  import { Injectable as Injectable3 } from "injectkit";
42
48
  function _ts_decorate3(decorators, target, key, desc) {
43
49
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -46,19 +52,39 @@ function _ts_decorate3(decorators, target, key, desc) {
46
52
  return c > 3 && r && Object.defineProperty(target, key, r), r;
47
53
  }
48
54
  __name(_ts_decorate3, "_ts_decorate");
55
+ var JobMonitor = class {
56
+ static {
57
+ __name(this, "JobMonitor");
58
+ }
59
+ };
60
+ JobMonitor = _ts_decorate3([
61
+ Injectable3()
62
+ ], JobMonitor);
63
+
64
+ // src/job.runner.ts
65
+ import { Injectable as Injectable4 } from "injectkit";
66
+ function _ts_decorate4(decorators, target, key, desc) {
67
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
68
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
69
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
70
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
71
+ }
72
+ __name(_ts_decorate4, "_ts_decorate");
49
73
  var JobRunner = class {
50
74
  static {
51
75
  __name(this, "JobRunner");
52
76
  }
53
77
  };
54
- JobRunner = _ts_decorate3([
55
- Injectable3()
78
+ JobRunner = _ts_decorate4([
79
+ Injectable4()
56
80
  ], JobRunner);
57
81
 
58
82
  export {
59
83
  __name,
60
84
  JobBroker,
85
+ JobContext,
86
+ registerJobContext,
61
87
  JobMonitor,
62
88
  JobRunner
63
89
  };
64
- //# sourceMappingURL=chunk-VCGAI6CK.js.map
90
+ //# sourceMappingURL=chunk-TIW3NS7E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/job.broker.ts","../src/job.context.ts","../src/job.monitor.ts","../src/job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\nimport { JobSendOptions } from './job.send.options.js';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue, cancelling and\n * inspecting jobs, and managing scheduled jobs. It provides the producer-side\n * interface for the job processing system.\n *\n * Backends differ in what they can do. Operations a backend cannot honor throw\n * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // Sending a job immediately (returns the job id)\n * const id = await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Deferring a job: run it no earlier than five minutes from now\n * await jobBroker.send('send-email', payload, {\n * startAfter: Duration.fromObject({ minutes: 5 })\n * });\n *\n * // Deferring to an absolute time\n * await jobBroker.send('send-email', payload, {\n * startAfter: DateTime.now().plus({ hours: 2 })\n * });\n *\n * // Cancelling it later, whether it is still queued or already running\n * await jobBroker.cancel('send-email', id);\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue.\n *\n * By default the job is eligible for immediate processing and will be picked\n * up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}\n * to defer it: the job becomes eligible only once the given delay has elapsed\n * (a {@link Duration}) or the given moment has passed (a {@link DateTime}).\n * Deferral is a lower bound, not a guarantee of exact-time execution — the job\n * runs at the first opportunity after it becomes eligible.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\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. The id can\n * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or\n * {@link getJob}.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if `options.startAfter` requests a deferral the\n * backend cannot honor (e.g. a delay beyond the backend's maximum).\n */\n abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n\n /**\n * Requests cancellation of one or more jobs.\n *\n * Cancellation is best-effort and applies regardless of the job's state: a\n * job that is still queued is prevented from running, and a job that is\n * already running is asked to stop. For a running job, cancellation is\n * cooperative — the job's handler receives an aborted `AbortSignal` (see\n * {@link Job.run}) and must honor it. A handler that ignores the signal runs\n * to completion. Some backends may forcefully terminate the running compute\n * instead; this contract only guarantees the request is delivered.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot cancel jobs.\n */\n abstract cancel(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs in the `cancelled` state can be resumed; other states are\n * unaffected.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot resume jobs.\n */\n abstract resume(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Permanently deletes one or more jobs.\n *\n * Removes the job records entirely. Unlike {@link cancel}, a deleted job\n * leaves no `cancelled` record behind and cannot be resumed.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\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 type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot report per-job state.\n */\n abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;\n}\n","import { Injectable, Registry } from 'injectkit';\nimport { Duration } from 'luxon';\n\n/**\n * Metadata describing the job execution currently in flight.\n *\n * A {@link JobRunner} registers this against the {@link JobContext} injection token\n * in the per-execution scoped container, so any service resolved during that\n * execution can declare `JobContext` as a constructor dependency and see which\n * job it is running under. This is the job-side counterpart of ServerKit's\n * request context: it is what lets a logger, a metrics recorder, or an outbox\n * writer sitting deep in the dependency graph attribute its work to a job\n * without every layer threading the metadata through by hand.\n *\n * Only fields every backend can supply are declared here. In particular there is\n * no attempt/retry counter: pg-boss hands the work handler a bare `Job`, and the\n * retry count lives on `JobWithMetadata`, which would cost an extra query per\n * execution to fetch. Read it from {@link JobMonitor} when you need it.\n *\n * @example\n * ```typescript\n * @Injectable()\n * class AuditLog {\n * constructor(private readonly context: JobContext) {}\n *\n * record(message: string): void {\n * // Attributed to the job automatically, with no plumbing at the call site.\n * logger.info({ jobId: this.context.id, queue: this.context.name }, message);\n * }\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport interface JobContext {\n /** Backend-assigned identifier of the running job. Matches the id `JobBroker.send` returned. */\n id: string;\n /** Name of the queue the job was dequeued from, which is also its registered job name. */\n name: string;\n /**\n * Aborted when the job is cancelled (see {@link JobBroker.cancel}) or when the\n * runner shuts down. The same signal the runner passes to {@link Job.run}, exposed\n * here so collaborators can observe cancellation without the handler forwarding it.\n */\n signal: AbortSignal;\n /**\n * How long the backend allows this execution to run before it is considered\n * expired, when the backend reports a limit. Useful for deciding whether there\n * is time left to start another unit of work.\n */\n expiresIn?: Duration;\n}\n\n/**\n * Abstract class merged with the {@link JobContext} interface so it can serve as an\n * injectkit injection token. A {@link JobRunner} registers the live context against\n * this token in the execution-scoped container, so services can inject `JobContext`\n * and receive the job currently being run.\n *\n * Resolving it outside a job execution throws, exactly as resolving ServerKit's\n * request context outside a request does. A service that must work in both places\n * should not depend on it directly.\n */\n@Injectable()\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport abstract class JobContext implements JobContext {}\n\n/**\n * Registers the {@link JobContext} token so services may declare it as a dependency.\n *\n * Call this on the registry whenever any registered service injects `JobContext`.\n * `Registry.build()` validates the dependency graph up front and rejects a service\n * whose dependency has no registration, and the runner's per-execution override\n * cannot satisfy that check because it only exists at runtime, inside a scope.\n *\n * What this registers is a placeholder that throws when resolved. During a job the\n * runner's scoped override shadows it, so the real context is what gets injected;\n * anywhere else (at boot, in a request, from a singleton) resolution fails with an\n * explanation rather than handing back a fake context.\n *\n * @param registry - The registry to register into, before `build()`.\n * @returns The registry, for chaining.\n *\n * @example\n * ```typescript\n * const registry = new InjectKitRegistry();\n * registerJobContext(registry);\n * registry.register(SendEmailJob).useClass(SendEmailJob).asTransient();\n * const container = registry.build();\n * ```\n */\nexport const registerJobContext = <T extends Registry>(registry: T): T => {\n registry\n .register(JobContext)\n .useFactory(() => {\n throw new Error(\n 'JobContext is only available during a job execution. It cannot be resolved at boot, from a request scope, or from a singleton.',\n );\n })\n .asScoped();\n return registry;\n};\n","import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\n\n/**\n * A backend-agnostic snapshot of a single queue's depth and health, as returned\n * by {@link JobMonitor.getQueueStats}. Every count is a point-in-time reading;\n * poll it on a schedule (for example from a reconciliation job) to drive\n * alerting on a backlog or a growing dead-letter queue.\n *\n * The counts are the lowest common denominator every supported backend can\n * report. `failed` in particular is a *retained* count: it reflects failures\n * still held in the queue subject to the queue's retention policy, not an\n * all-time total.\n */\nexport interface JobQueueStats {\n /** The queue name these stats describe. */\n name: string;\n /** Jobs waiting to be processed (enqueued but not yet active). */\n queued: number;\n /** Jobs currently being executed by a worker. */\n active: number;\n /** Failed jobs still retained in the queue (bounded by the retention policy). */\n failed: number;\n /** All jobs still retained for the queue across every state. */\n total: number;\n}\n\n/**\n * Filters for {@link JobMonitor.listJobs}. All fields are optional; omitting them\n * lists every job currently retained in the queue (the common case when\n * inspecting a small dead-letter queue).\n */\nexport interface JobQueryOptions {\n /** Match a single job by its id. */\n id?: string;\n /** Match jobs whose payload contains these fields (a partial-match filter). */\n data?: Record<string, unknown>;\n /** Restrict the result to jobs still waiting to be processed. */\n queuedOnly?: boolean;\n}\n\n/**\n * Options for {@link JobMonitor.redrive}, which moves dead-lettered jobs out of a\n * queue and back into circulation.\n */\nexport interface JobRedriveOptions {\n /**\n * The queue to move jobs into. When omitted, each job returns to the queue it\n * originally came from before it was dead-lettered — the usual \"reprocess\"\n * behavior. Supply this to funnel everything into a specific queue instead.\n */\n destination?: string;\n /**\n * Only redrive jobs that originated from this source queue. Useful when a\n * single dead-letter queue collects failures from several source queues and\n * you want to drain just one source's worth.\n */\n sourceName?: string;\n /**\n * Maximum number of jobs to move in this call, oldest first. Call repeatedly\n * (or on a schedule) to drain a large dead-letter queue at a controlled rate.\n */\n limit?: number;\n}\n\n/**\n * Read-and-remediate interface for job queues, and in particular for\n * *dead-letter queues*: the queues that collect jobs which have exhausted their\n * retries (see the queue policy on the pg-boss backend's registration).\n *\n * Where {@link JobBroker} is the producer side (enqueue, cancel, inspect a job\n * you hold the id for) and {@link JobRunner} is the consumer side, `JobMonitor`\n * is the operator side: it lets a consumer answer \"how deep is this queue?\",\n * \"what is stuck in this dead-letter queue?\", and \"reprocess / discard those\n * jobs\". Unlike the broker, it operates on raw queue names and does **not**\n * require the queue to be registered, because a dead-letter queue is often an\n * unregistered sink with no worker of its own.\n *\n * Backends that cannot honor an operation throw a `NotSupportedError` rather than\n * silently doing nothing, matching the rest of the package. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // A reconciliation sweep over a money-critical dead-letter queue.\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * const stuck = await monitor.listJobs('charge.webhook.dead'); // inspect / log / alert\n * const moved = await monitor.redrive('charge.webhook.dead', { limit: 100 }); // drain back\n * }\n * ```\n */\n@Injectable()\nexport abstract class JobMonitor {\n /**\n * Reports the current depth and health of a queue.\n *\n * @param name - The queue name to inspect (may be an unregistered dead-letter queue).\n * @returns A promise resolving to the {@link JobQueueStats}, or `null` if no\n * queue with that name exists.\n * @throws `NotSupportedError` if the backend cannot report queue statistics.\n */\n abstract getQueueStats(name: string): Promise<JobQueueStats | null>;\n\n /**\n * Lists the jobs currently retained in a queue, optionally filtered.\n *\n * The primary use is inspecting a dead-letter queue: the returned\n * {@link JobInfo} objects expose each poison message's id, state, and original\n * payload so a consumer can decide whether to reprocess ({@link redrive}),\n * discard ({@link deleteJob}), or escalate it.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list (may be an unregistered dead-letter queue).\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns A promise resolving to the matching jobs (empty if none / no such queue).\n * @throws `NotSupportedError` if the backend cannot enumerate jobs.\n */\n abstract listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]>;\n\n /**\n * Moves dead-lettered jobs out of a queue and back into circulation, returning\n * the number of jobs moved.\n *\n * By default each job goes back to the source queue it was dead-lettered from,\n * so a worker can process it again; pass {@link JobRedriveOptions.destination}\n * to route them elsewhere, {@link JobRedriveOptions.sourceName} to drain only\n * one source's jobs from a shared dead-letter queue, and\n * {@link JobRedriveOptions.limit} to move at a controlled rate.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns A promise resolving to the count of jobs moved.\n * @throws `NotSupportedError` if the backend cannot redrive jobs.\n */\n abstract redrive(name: string, options?: JobRedriveOptions): Promise<number>;\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * This is the \"discard\" action for a dead-letter queue: a poison message that\n * should not be reprocessed is removed outright. Unlike {@link JobBroker.deleteJob},\n * it does not require the queue to be registered.\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 * @returns A promise that resolves once the jobs have been deleted.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Re-attempts one or more failed jobs *in place*, re-queuing them within their\n * current queue.\n *\n * Use this to re-run a job that failed in a queue that has its own worker. To\n * reprocess a job sitting in a dead-letter *sink* (a queue with no worker),\n * prefer {@link redrive}, which moves it back to a queue that can run it.\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 * @returns A promise that resolves once the jobs have been re-queued.\n * @throws `NotSupportedError` if the backend cannot retry jobs.\n */\n abstract retryJob(name: string, id: string | string[]): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+CpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAgHtB;;;;;;AC/JA,SAASC,cAAAA,mBAA4B;;;;;;;;AAgE9B,IAAeC,aAAf,MAAeA;SAAAA;;;AAAkC;;;;AA0BjD,IAAMC,qBAAqB,wBAAqBC,aAAAA;AACrDA,WACGC,SAASH,UAAAA,EACTI,WAAW,MAAA;AACV,UAAM,IAAIC,MACR,gIAAA;EAEJ,CAAA,EACCC,SAAQ;AACX,SAAOJ;AACT,GAVkC;;;AC1FlC,SAASK,cAAAA,mBAAkB;;;;;;;;AA6FpB,IAAeC,aAAf,MAAeA;SAAAA;;;AAwEtB;;;;;;ACrKA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;","names":["Injectable","JobBroker","Injectable","JobContext","registerJobContext","registry","register","useFactory","Error","asScoped","Injectable","JobMonitor","Injectable","JobRunner"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './job.broker.js';
2
2
  export * from './job.js';
3
+ export * from './job.context.js';
3
4
  export * from './job.info.js';
4
5
  export * from './job.send.options.js';
5
6
  export * from './job.queue.policy.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC"}
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  JobBroker,
3
+ JobContext,
3
4
  JobMonitor,
4
5
  JobRunner,
5
- __name
6
- } from "./chunk-VCGAI6CK.js";
6
+ __name,
7
+ registerJobContext
8
+ } from "./chunk-TIW3NS7E.js";
7
9
 
8
10
  // src/job.ts
9
11
  import { Injectable } from "injectkit";
@@ -49,8 +51,10 @@ var NotSupportedError = class extends ServerkitError {
49
51
  export {
50
52
  Job,
51
53
  JobBroker,
54
+ JobContext,
52
55
  JobMonitor,
53
56
  JobRunner,
54
- NotSupportedError
57
+ NotSupportedError,
58
+ registerJobContext
55
59
  };
56
60
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/job.ts","../src/not.supported.error.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload, signal?: AbortSignal): Promise<void> {\n * // Long-running work should honor the signal so the job can be cancelled.\n * await emailService.send(payload.to, payload.subject, payload.body, { signal });\n * if (signal?.aborted) return;\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * The optional `signal` is aborted when the job is cancelled (see\n * {@link JobBroker.cancel}) or when the runner shuts down. Cancellation is\n * cooperative: long-running handlers should forward `signal` to the async\n * operations they perform (fetch, database queries, etc.) or periodically\n * check `signal.aborted` and return early. A handler that ignores the signal\n * cannot be interrupted and will run to completion.\n *\n * @param payload - The data required to execute the job.\n * @param signal - An {@link AbortSignal} that fires when the job is cancelled\n * or the runner stops. Optional; handlers may ignore it.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload, signal?: AbortSignal): Promise<void>;\n}\n","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Thrown by a {@link JobBroker} when a requested operation is not supported by\n * the underlying backend.\n *\n * Backends vary in what they can do: some queue implementations can cancel a\n * queued job but not look up its state, others cannot cancel individual jobs at\n * all. Rather than silently doing nothing (which hides bugs), a backend throws\n * this error from any capability it cannot honor.\n *\n * Extends {@link ServerkitError}, so `errorMiddleware` renders it (as a 500) and\n * the `withDetails` / `withCause` / `withInternalDetails` setters apply.\n *\n * The bundled pg-boss backend supports every operation and never throws this;\n * it exists as the shared vocabulary for future backends (e.g. SQS, Pub/Sub).\n *\n * @example\n * ```typescript\n * async cancel(): Promise<void> {\n * throw new NotSupportedError('cancel', 'sqs');\n * }\n * ```\n */\nexport class NotSupportedError extends ServerkitError {\n /** The name of the operation that is not supported (e.g. `'cancel'`). */\n readonly operation: string;\n /** The backend that does not support the operation, when known (e.g. `'sqs'`). */\n readonly backend?: string;\n\n /**\n * Creates a new NotSupportedError.\n *\n * @param operation - The name of the unsupported operation.\n * @param backend - The backend that does not support it, if known.\n */\n constructor(operation: string, backend?: string) {\n super(\n backend\n ? `Operation \"${operation}\" is not supported by the ${backend} job broker`\n : `Operation \"${operation}\" is not supported by this job broker`,\n );\n this.name = 'NotSupportedError';\n this.operation = operation;\n this.backend = backend;\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;ACrDA,SAASC,sBAAsB;AAwBxB,IAAMC,oBAAN,cAAgCC,eAAAA;EAxBvC,OAwBuCA;;;;EAE5BC;;EAEAC;;;;;;;EAQT,YAAYD,WAAmBC,SAAkB;AAC/C,UACEA,UACI,cAAcD,SAAAA,6BAAsCC,OAAAA,gBACpD,cAAcD,SAAAA,uCAAgD;AAEpE,SAAKE,OAAO;AACZ,SAAKF,YAAYA;AACjB,SAAKC,UAAUA;EACjB;AACF;","names":["Injectable","Job","ServerkitError","NotSupportedError","ServerkitError","operation","backend","name"]}
1
+ {"version":3,"sources":["../src/job.ts","../src/not.supported.error.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload, signal?: AbortSignal): Promise<void> {\n * // Long-running work should honor the signal so the job can be cancelled.\n * await emailService.send(payload.to, payload.subject, payload.body, { signal });\n * if (signal?.aborted) return;\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * The optional `signal` is aborted when the job is cancelled (see\n * {@link JobBroker.cancel}) or when the runner shuts down. Cancellation is\n * cooperative: long-running handlers should forward `signal` to the async\n * operations they perform (fetch, database queries, etc.) or periodically\n * check `signal.aborted` and return early. A handler that ignores the signal\n * cannot be interrupted and will run to completion.\n *\n * @param payload - The data required to execute the job.\n * @param signal - An {@link AbortSignal} that fires when the job is cancelled\n * or the runner stops. Optional; handlers may ignore it.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload, signal?: AbortSignal): Promise<void>;\n}\n","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Thrown by a {@link JobBroker} when a requested operation is not supported by\n * the underlying backend.\n *\n * Backends vary in what they can do: some queue implementations can cancel a\n * queued job but not look up its state, others cannot cancel individual jobs at\n * all. Rather than silently doing nothing (which hides bugs), a backend throws\n * this error from any capability it cannot honor.\n *\n * Extends {@link ServerkitError}, so `errorMiddleware` renders it (as a 500) and\n * the `withDetails` / `withCause` / `withInternalDetails` setters apply.\n *\n * The bundled pg-boss backend supports every operation and never throws this;\n * it exists as the shared vocabulary for future backends (e.g. SQS, Pub/Sub).\n *\n * @example\n * ```typescript\n * async cancel(): Promise<void> {\n * throw new NotSupportedError('cancel', 'sqs');\n * }\n * ```\n */\nexport class NotSupportedError extends ServerkitError {\n /** The name of the operation that is not supported (e.g. `'cancel'`). */\n readonly operation: string;\n /** The backend that does not support the operation, when known (e.g. `'sqs'`). */\n readonly backend?: string;\n\n /**\n * Creates a new NotSupportedError.\n *\n * @param operation - The name of the unsupported operation.\n * @param backend - The backend that does not support it, if known.\n */\n constructor(operation: string, backend?: string) {\n super(\n backend\n ? `Operation \"${operation}\" is not supported by the ${backend} job broker`\n : `Operation \"${operation}\" is not supported by this job broker`,\n );\n this.name = 'NotSupportedError';\n this.operation = operation;\n this.backend = backend;\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;ACrDA,SAASC,sBAAsB;AAwBxB,IAAMC,oBAAN,cAAgCC,eAAAA;EAxBvC,OAwBuCA;;;;EAE5BC;;EAEAC;;;;;;;EAQT,YAAYD,WAAmBC,SAAkB;AAC/C,UACEA,UACI,cAAcD,SAAAA,6BAAsCC,OAAAA,gBACpD,cAAcD,SAAAA,uCAAgD;AAEpE,SAAKE,OAAO;AACZ,SAAKF,YAAYA;AACjB,SAAKC,UAAUA;EACjB;AACF;","names":["Injectable","Job","ServerkitError","NotSupportedError","ServerkitError","operation","backend","name"]}
@@ -0,0 +1,87 @@
1
+ import { Registry } from 'injectkit';
2
+ import { Duration } from 'luxon';
3
+ /**
4
+ * Metadata describing the job execution currently in flight.
5
+ *
6
+ * A {@link JobRunner} registers this against the {@link JobContext} injection token
7
+ * in the per-execution scoped container, so any service resolved during that
8
+ * execution can declare `JobContext` as a constructor dependency and see which
9
+ * job it is running under. This is the job-side counterpart of ServerKit's
10
+ * request context: it is what lets a logger, a metrics recorder, or an outbox
11
+ * writer sitting deep in the dependency graph attribute its work to a job
12
+ * without every layer threading the metadata through by hand.
13
+ *
14
+ * Only fields every backend can supply are declared here. In particular there is
15
+ * no attempt/retry counter: pg-boss hands the work handler a bare `Job`, and the
16
+ * retry count lives on `JobWithMetadata`, which would cost an extra query per
17
+ * execution to fetch. Read it from {@link JobMonitor} when you need it.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * @Injectable()
22
+ * class AuditLog {
23
+ * constructor(private readonly context: JobContext) {}
24
+ *
25
+ * record(message: string): void {
26
+ * // Attributed to the job automatically, with no plumbing at the call site.
27
+ * logger.info({ jobId: this.context.id, queue: this.context.name }, message);
28
+ * }
29
+ * }
30
+ * ```
31
+ */
32
+ export interface JobContext {
33
+ /** Backend-assigned identifier of the running job. Matches the id `JobBroker.send` returned. */
34
+ id: string;
35
+ /** Name of the queue the job was dequeued from, which is also its registered job name. */
36
+ name: string;
37
+ /**
38
+ * Aborted when the job is cancelled (see {@link JobBroker.cancel}) or when the
39
+ * runner shuts down. The same signal the runner passes to {@link Job.run}, exposed
40
+ * here so collaborators can observe cancellation without the handler forwarding it.
41
+ */
42
+ signal: AbortSignal;
43
+ /**
44
+ * How long the backend allows this execution to run before it is considered
45
+ * expired, when the backend reports a limit. Useful for deciding whether there
46
+ * is time left to start another unit of work.
47
+ */
48
+ expiresIn?: Duration;
49
+ }
50
+ /**
51
+ * Abstract class merged with the {@link JobContext} interface so it can serve as an
52
+ * injectkit injection token. A {@link JobRunner} registers the live context against
53
+ * this token in the execution-scoped container, so services can inject `JobContext`
54
+ * and receive the job currently being run.
55
+ *
56
+ * Resolving it outside a job execution throws, exactly as resolving ServerKit's
57
+ * request context outside a request does. A service that must work in both places
58
+ * should not depend on it directly.
59
+ */
60
+ export declare abstract class JobContext implements JobContext {
61
+ }
62
+ /**
63
+ * Registers the {@link JobContext} token so services may declare it as a dependency.
64
+ *
65
+ * Call this on the registry whenever any registered service injects `JobContext`.
66
+ * `Registry.build()` validates the dependency graph up front and rejects a service
67
+ * whose dependency has no registration, and the runner's per-execution override
68
+ * cannot satisfy that check because it only exists at runtime, inside a scope.
69
+ *
70
+ * What this registers is a placeholder that throws when resolved. During a job the
71
+ * runner's scoped override shadows it, so the real context is what gets injected;
72
+ * anywhere else (at boot, in a request, from a singleton) resolution fails with an
73
+ * explanation rather than handing back a fake context.
74
+ *
75
+ * @param registry - The registry to register into, before `build()`.
76
+ * @returns The registry, for chaining.
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const registry = new InjectKitRegistry();
81
+ * registerJobContext(registry);
82
+ * registry.register(SendEmailJob).useClass(SendEmailJob).asTransient();
83
+ * const container = registry.build();
84
+ * ```
85
+ */
86
+ export declare const registerJobContext: <T extends Registry>(registry: T) => T;
87
+ //# sourceMappingURL=job.context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job.context.d.ts","sourceRoot":"","sources":["../src/job.context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,QAAQ,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,MAAM,WAAW,UAAU;IACzB,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAC;IACX,0FAA0F;IAC1F,IAAI,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,MAAM,EAAE,WAAW,CAAC;IACpB;;;;OAIG;IACH,SAAS,CAAC,EAAE,QAAQ,CAAC;CACtB;AAED;;;;;;;;;GASG;AACH,8BAEsB,UAAW,YAAW,UAAU;CAAG;AAEzD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,kBAAkB,GAAI,CAAC,SAAS,QAAQ,EAAE,UAAU,CAAC,KAAG,CAUpE,CAAC"}
@@ -0,0 +1,56 @@
1
+ import { PgBossConnectionProvider } from './pgboss.connection.provider.js';
2
+ import { fromKysely, type Db } from 'pg-boss';
3
+ /**
4
+ * Structural shape of a Kysely instance or transaction, matching what pg-boss's
5
+ * `fromKysely` adapter consumes.
6
+ *
7
+ * Declared structurally rather than as `Kysely<DB>` so the package carries no
8
+ * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`
9
+ * and `Transaction<DB>` are accepted without a type argument or a cast.
10
+ */
11
+ export interface KyselyLike {
12
+ withoutPlugins(): Parameters<typeof fromKysely>[0];
13
+ }
14
+ /**
15
+ * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so
16
+ * jobs enqueued while that transaction is open commit or roll back with it.
17
+ *
18
+ * Register it as a request-scoped override of {@link PgBossConnectionProvider}
19
+ * alongside whatever binds the transaction itself, and every enqueue performed
20
+ * during the request inserts on the transaction's connection instead of
21
+ * pg-boss's pool — closing the dual-write gap between domain writes and job
22
+ * enqueues.
23
+ *
24
+ * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL
25
+ * straight through `executeQuery`, so a column-rewriting plugin on the caller's
26
+ * instance (a camel-case mapper, for example) would corrupt pg-boss's own
27
+ * result columns. `withoutPlugins()` returns an instance sharing the same
28
+ * connection-bound executor, so atomicity is preserved.
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * await db.transaction().execute(async trx => {
33
+ * const scope = container.createScope();
34
+ * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));
35
+ *
36
+ * await repository.createOrder(trx, order);
37
+ * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));
38
+ * });
39
+ * ```
40
+ */
41
+ export declare class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {
42
+ private readonly trx;
43
+ /**
44
+ * @param trx - The active Kysely transaction (or any Kysely instance) whose
45
+ * connection job inserts should run on.
46
+ */
47
+ constructor(trx: KyselyLike);
48
+ /**
49
+ * Returns the transaction's connection adapted to pg-boss's executor shape,
50
+ * with the caller's Kysely plugins stripped.
51
+ *
52
+ * @returns A {@link Db} executor bound to the transaction's connection.
53
+ */
54
+ executor(): Db;
55
+ }
56
+ //# sourceMappingURL=kysely.transaction.connection.provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kysely.transaction.connection.provider.d.ts","sourceRoot":"","sources":["../../src/pgboss/kysely.transaction.connection.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,MAAM,SAAS,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB,cAAc,IAAI,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;CACpD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,mCAAoC,SAAQ,wBAAwB;IAKnE,OAAO,CAAC,QAAQ,CAAC,GAAG;IAJhC;;;OAGG;gBAC0B,GAAG,EAAE,UAAU;IAI5C;;;;;OAKG;IACM,QAAQ,IAAI,EAAE;CAGxB"}
@@ -66,7 +66,8 @@ export declare class PgBossJobRunner extends JobRunner {
66
66
  /**
67
67
  * Creates a new PgBossJobRunner instance.
68
68
  *
69
- * @param container - The DI container for resolving job instances.
69
+ * @param container - The root DI container. Each job execution resolves from a
70
+ * scope created off it, not from the container itself.
70
71
  * @param registrations - The registry map containing all registered jobs.
71
72
  * @param pgboss - The pg-boss instance to use for queue operations.
72
73
  * @param logger - The logger for recording job execution errors.
@@ -86,14 +87,29 @@ export declare class PgBossJobRunner extends JobRunner {
86
87
  * 4. Sets up the cron schedule (for scheduled jobs)
87
88
  * 5. Starts a worker to process jobs from the queue
88
89
  *
89
- * Each item in a batch resolves its `Job` instance from the DI container
90
- * individually and execution is awaited via `Promise.allSettled`, so pg-boss
91
- * does not acknowledge a batch until every job has actually finished and
92
- * one job's failure cannot suppress its sibling's logs.
90
+ * Each item in a batch runs in its own scoped container, created from the
91
+ * injected root container and disposed once the item settles, so `scoped`
92
+ * registrations behave per execution (the job-side equivalent of a request
93
+ * scope) and any disposables the execution created are released. Each scope
94
+ * carries a {@link JobContext} describing the running job, so the job and its
95
+ * collaborators can inject it. Execution is
96
+ * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch
97
+ * until every job has actually finished and one job's failure cannot suppress
98
+ * its sibling's logs.
93
99
  *
94
100
  * @returns A promise that resolves when all workers are registered with pg-boss.
95
101
  */
96
102
  start(): Promise<void>;
103
+ /**
104
+ * Builds the {@link JobContext} registered in an execution's scoped container.
105
+ *
106
+ * @param name - The queue the job was dequeued from.
107
+ * @param job - The pg-boss job being executed.
108
+ * @param signal - The combined cancellation signal handed to {@link Job.run}.
109
+ * @returns The context describing this execution.
110
+ * @internal
111
+ */
112
+ private toJobContext;
97
113
  /**
98
114
  * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own
99
115
  * policy, letting the registration override individual fields. Returns
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAsBlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAmC1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAA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C,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAtCzB;;;;;;;;OAQG;IACH,yBAAyB,SAAK;IAE9B;;;;;;;;;;;OAWG;IACH,kBAAkB,CAAC,EAAE,cAAc,CAAC;IAEpC;;;;;;;;OAQG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAqF5B;;;;;;;;OAQG;IACH,OAAO,CAAC,YAAY;IAYpB;;;;;;;;;OASG;IACH,OAAO,CAAC,aAAa;IAQrB;;;;;;;;;;;OAWG;YACW,WAAW;IAuBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,cAAc;IAuBtB;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
package/dist/pgboss.d.ts CHANGED
@@ -3,4 +3,5 @@ export * from './pgboss/pgboss.job.monitor.js';
3
3
  export * from './pgboss/pgboss.job.runner.js';
4
4
  export * from './pgboss/pgboss.job.registration.js';
5
5
  export * from './pgboss/pgboss.connection.provider.js';
6
+ export * from './pgboss/kysely.transaction.connection.provider.js';
6
7
  //# sourceMappingURL=pgboss.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.d.ts","sourceRoot":"","sources":["../src/pgboss.ts"],"names":[],"mappings":"AAEA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC"}
1
+ {"version":3,"file":"pgboss.d.ts","sourceRoot":"","sources":["../src/pgboss.ts"],"names":[],"mappings":"AAEA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC;AACvD,cAAc,oDAAoD,CAAC"}
package/dist/pgboss.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  JobBroker,
3
+ JobContext,
3
4
  JobMonitor,
4
5
  JobRunner,
5
6
  __name
6
- } from "./chunk-VCGAI6CK.js";
7
+ } from "./chunk-TIW3NS7E.js";
7
8
 
8
9
  // src/pgboss/pgboss.job.broker.ts
9
10
  import { PgBoss } from "pg-boss";
@@ -402,6 +403,7 @@ PgBossJobMonitor = _ts_decorate4([
402
403
 
403
404
  // src/pgboss/pgboss.job.runner.ts
404
405
  import { PgBoss as PgBoss3 } from "pg-boss";
406
+ import { Duration as Duration2 } from "luxon";
405
407
  import { Container, Injectable as Injectable5 } from "injectkit";
406
408
  import { Logger } from "@maroonedsoftware/logger";
407
409
  function _ts_decorate5(decorators, target, key, desc) {
@@ -452,7 +454,8 @@ var PgBossJobRunner = class extends JobRunner {
452
454
  /**
453
455
  * Creates a new PgBossJobRunner instance.
454
456
  *
455
- * @param container - The DI container for resolving job instances.
457
+ * @param container - The root DI container. Each job execution resolves from a
458
+ * scope created off it, not from the container itself.
456
459
  * @param registrations - The registry map containing all registered jobs.
457
460
  * @param pgboss - The pg-boss instance to use for queue operations.
458
461
  * @param logger - The logger for recording job execution errors.
@@ -474,10 +477,15 @@ var PgBossJobRunner = class extends JobRunner {
474
477
  * 4. Sets up the cron schedule (for scheduled jobs)
475
478
  * 5. Starts a worker to process jobs from the queue
476
479
  *
477
- * Each item in a batch resolves its `Job` instance from the DI container
478
- * individually and execution is awaited via `Promise.allSettled`, so pg-boss
479
- * does not acknowledge a batch until every job has actually finished and
480
- * one job's failure cannot suppress its sibling's logs.
480
+ * Each item in a batch runs in its own scoped container, created from the
481
+ * injected root container and disposed once the item settles, so `scoped`
482
+ * registrations behave per execution (the job-side equivalent of a request
483
+ * scope) and any disposables the execution created are released. Each scope
484
+ * carries a {@link JobContext} describing the running job, so the job and its
485
+ * collaborators can inject it. Execution is
486
+ * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch
487
+ * until every job has actually finished and one job's failure cannot suppress
488
+ * its sibling's logs.
481
489
  *
482
490
  * @returns A promise that resolves when all workers are registered with pg-boss.
483
491
  */
@@ -501,7 +509,7 @@ var PgBossJobRunner = class extends JobRunner {
501
509
  }
502
510
  await this.pgboss.work(name, async (jobs) => {
503
511
  const results = await Promise.allSettled(jobs.map(async (job) => {
504
- const jobRunner = this.container.get(identifier);
512
+ const scope = this.container.createScopedContainer();
505
513
  const controller = new AbortController();
506
514
  const pgSignal = job.signal;
507
515
  const signal = AbortSignal.any(pgSignal ? [
@@ -510,14 +518,19 @@ var PgBossJobRunner = class extends JobRunner {
510
518
  ] : [
511
519
  controller.signal
512
520
  ]);
513
- const stopWatching = this.watchForCancellation(name, job.id, controller);
521
+ let stopWatching = /* @__PURE__ */ __name(() => {
522
+ }, "stopWatching");
514
523
  try {
524
+ scope.override(JobContext, this.toJobContext(name, job, signal));
525
+ const jobRunner = scope.get(identifier);
526
+ stopWatching = this.watchForCancellation(name, job.id, controller);
515
527
  await jobRunner.run(job.data, signal);
516
528
  } catch (error) {
517
529
  this.logger.error(error);
518
530
  throw error;
519
531
  } finally {
520
532
  stopWatching();
533
+ await scope.disposeAsync().catch((error) => this.logger.error(error));
521
534
  }
522
535
  }));
523
536
  const failures = results.filter((result) => result.status === "rejected").map((result) => result.reason);
@@ -531,6 +544,28 @@ var PgBossJobRunner = class extends JobRunner {
531
544
  }
532
545
  }
533
546
  /**
547
+ * Builds the {@link JobContext} registered in an execution's scoped container.
548
+ *
549
+ * @param name - The queue the job was dequeued from.
550
+ * @param job - The pg-boss job being executed.
551
+ * @param signal - The combined cancellation signal handed to {@link Job.run}.
552
+ * @returns The context describing this execution.
553
+ * @internal
554
+ */
555
+ toJobContext(name, job, signal) {
556
+ const expireInSeconds = job.expireInSeconds;
557
+ return {
558
+ id: job.id,
559
+ name,
560
+ signal,
561
+ ...expireInSeconds === void 0 ? {} : {
562
+ expiresIn: Duration2.fromObject({
563
+ seconds: expireInSeconds
564
+ })
565
+ }
566
+ };
567
+ }
568
+ /**
534
569
  * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own
535
570
  * policy, letting the registration override individual fields. Returns
536
571
  * `undefined` when neither supplies a policy, so a queue with no policy is left
@@ -673,7 +708,33 @@ PgBossJobRunner = _ts_decorate5([
673
708
  typeof Logger === "undefined" ? Object : Logger
674
709
  ])
675
710
  ], PgBossJobRunner);
711
+
712
+ // src/pgboss/kysely.transaction.connection.provider.ts
713
+ import { fromKysely } from "pg-boss";
714
+ var KyselyTransactionConnectionProvider = class extends PgBossConnectionProvider {
715
+ static {
716
+ __name(this, "KyselyTransactionConnectionProvider");
717
+ }
718
+ trx;
719
+ /**
720
+ * @param trx - The active Kysely transaction (or any Kysely instance) whose
721
+ * connection job inserts should run on.
722
+ */
723
+ constructor(trx) {
724
+ super(), this.trx = trx;
725
+ }
726
+ /**
727
+ * Returns the transaction's connection adapted to pg-boss's executor shape,
728
+ * with the caller's Kysely plugins stripped.
729
+ *
730
+ * @returns A {@link Db} executor bound to the transaction's connection.
731
+ */
732
+ executor() {
733
+ return fromKysely(this.trx.withoutPlugins());
734
+ }
735
+ };
676
736
  export {
737
+ KyselyTransactionConnectionProvider,
677
738
  PgBossConnectionProvider,
678
739
  PgBossJobBroker,
679
740
  PgBossJobMonitor,
@@ -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"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, or both. Every\n * field beyond `job` is optional, so this shape covers three cases:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` / `{ job, cron, policy }` — either of the above with retry\n * and dead-letter behavior declared where the job is mapped.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule\n * and/or an optional per-queue {@link JobQueuePolicy}\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to delete.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to retry.\n */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * the installed pg-boss types so the mapping tracks the peer's exact shape.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['updateQueue']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The DI container for resolving job instances.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue\n *\n * Each item in a batch resolves its `Job` instance from the DI container\n * individually and execution is awaited via `Promise.allSettled`, so pg-boss\n * does not acknowledge a batch until every job has actually finished and\n * one job's failure cannot suppress its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\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 const stopWatching = this.watchForCancellation(name, job.id, controller);\n try {\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 stopWatching();\n }\n }),\n );\n\n // Every job in the batch is isolated (they run concurrently and each logs its own\n // error), but the work handler itself must reject when any job threw. Otherwise\n // pg-boss treats the whole batch as completed and never applies retryLimit or\n // dead-lettering to the jobs that actually failed.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length === 1) {\n throw failures[0];\n }\n if (failures.length > 1) {\n throw new AggregateError(failures, `${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`);\n }\n });\n }\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAmFhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACn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AOE;IAC9B;AACA,WAAOoD,OAAOC,KAAKhB,OAAAA,EAASL,SAAS,IAAIK,UAAUnC;EACrD;;;;;;;;;;;;;;;;EAiBQoB,qBAAqB1B,MAAc2B,IAAYR,YAAyC;AAC9F,QAAI,KAAK5B,6BAA6B,GAAG;AACvC,aAAO,MAAA;MAAO;IAChB;AAEA,UAAMmE,QAAQC,YAAY,YAAA;AACxB,UAAI;AACF,cAAM,CAACnD,GAAAA,IAAO,MAAM,KAAKb,OAAOiE,SAAS5D,MAAM;UAAE2B;QAAG,CAAA;AACpD,YAAI,CAACnB,OAAOA,IAAIqD,UAAU,aAAa;AACrC1C,qBAAW2C,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAAS5B,OAAO;AACd,aAAKlC,OAAOkC,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAKvC,4BAA4B,GAAA;AAGpCmE,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKtE,OAAOsE,KAAI;EACxB;AACF;;;;;;;;;;;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","work","jobs","results","Promise","allSettled","map","jobRunner","get","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","watchForCancellation","id","run","data","error","failures","filter","result","status","reason","length","AggregateError","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","expiresIn","expireInSeconds","Object","keys","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop"]}
1
+ {"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts","../src/pgboss/kysely.transaction.connection.provider.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, or both. Every\n * field beyond `job` is optional, so this shape covers three cases:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` / `{ job, cron, policy }` — either of the above with retry\n * and dead-letter behavior declared where the job is mapped.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule\n * and/or an optional per-queue {@link JobQueuePolicy}\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to delete.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to retry.\n */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Duration } from 'luxon';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobContext } from '../job.context.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * the installed pg-boss types so the mapping tracks the peer's exact shape.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['updateQueue']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The root DI container. Each job execution resolves from a\n * scope created off it, not from the container itself.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue\n *\n * Each item in a batch runs in its own scoped container, created from the\n * injected root container and disposed once the item settles, so `scoped`\n * registrations behave per execution (the job-side equivalent of a request\n * scope) and any disposables the execution created are released. Each scope\n * carries a {@link JobContext} describing the running job, so the job and its\n * collaborators can inject it. Execution is\n * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch\n * until every job has actually finished and one job's failure cannot suppress\n * its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n // Every execution resolves from its own scope, never the root container.\n // InjectKit caches a `scoped` registration in whichever container first\n // resolves it, and child scopes inherit a parent's cache, so resolving a\n // scoped token at the root would turn it into a process-lifetime singleton\n // shared by every job *and* inherited by every later request scope.\n const scope = this.container.createScopedContainer();\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n // Assigned once the watch starts; until then there is nothing to stop, so\n // `finally` can run unconditionally even if resolution threw.\n let stopWatching = () => {};\n try {\n // Override before resolving, so a job (or anything it depends on) may\n // take JobContext as a constructor dependency.\n scope.override(JobContext, this.toJobContext(name, job, signal));\n const jobRunner = scope.get<Job>(identifier);\n stopWatching = this.watchForCancellation(name, job.id, controller);\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n // Stop the poll before disposing: resolving from a disposed scope throws,\n // and a late tick must not turn a finished job into a logged error.\n stopWatching();\n // Log rather than rethrow, so a disposal failure can't replace the job's\n // real error and mislead pg-boss's retry/dead-letter accounting.\n await scope.disposeAsync().catch((error: unknown) => this.logger.error(error));\n }\n }),\n );\n\n // Every job in the batch is isolated (they run concurrently and each logs its own\n // error), but the work handler itself must reject when any job threw. Otherwise\n // pg-boss treats the whole batch as completed and never applies retryLimit or\n // dead-lettering to the jobs that actually failed.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length === 1) {\n throw failures[0];\n }\n if (failures.length > 1) {\n throw new AggregateError(failures, `${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`);\n }\n });\n }\n }\n\n /**\n * Builds the {@link JobContext} registered in an execution's scoped container.\n *\n * @param name - The queue the job was dequeued from.\n * @param job - The pg-boss job being executed.\n * @param signal - The combined cancellation signal handed to {@link Job.run}.\n * @returns The context describing this execution.\n * @internal\n */\n private toJobContext(name: string, job: PgJob<object>, signal: AbortSignal): JobContext {\n // Typed as always present, but absent when jobs are faked in tests, so it is\n // read defensively and simply omitted when the backend reports no limit.\n const expireInSeconds = (job as { expireInSeconds?: number }).expireInSeconds;\n return {\n id: job.id,\n name,\n signal,\n ...(expireInSeconds === undefined ? {} : { expiresIn: Duration.fromObject({ seconds: expireInSeconds }) }),\n };\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n","import { PgBossConnectionProvider } from './pgboss.connection.provider.js';\nimport { fromKysely, type Db } from 'pg-boss';\n\n/**\n * Structural shape of a Kysely instance or transaction, matching what pg-boss's\n * `fromKysely` adapter consumes.\n *\n * Declared structurally rather than as `Kysely<DB>` so the package carries no\n * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`\n * and `Transaction<DB>` are accepted without a type argument or a cast.\n */\nexport interface KyselyLike {\n withoutPlugins(): Parameters<typeof fromKysely>[0];\n}\n\n/**\n * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so\n * jobs enqueued while that transaction is open commit or roll back with it.\n *\n * Register it as a request-scoped override of {@link PgBossConnectionProvider}\n * alongside whatever binds the transaction itself, and every enqueue performed\n * during the request inserts on the transaction's connection instead of\n * pg-boss's pool — closing the dual-write gap between domain writes and job\n * enqueues.\n *\n * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL\n * straight through `executeQuery`, so a column-rewriting plugin on the caller's\n * instance (a camel-case mapper, for example) would corrupt pg-boss's own\n * result columns. `withoutPlugins()` returns an instance sharing the same\n * connection-bound executor, so atomicity is preserved.\n *\n * @example\n * ```typescript\n * await db.transaction().execute(async trx => {\n * const scope = container.createScope();\n * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));\n *\n * await repository.createOrder(trx, order);\n * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));\n * });\n * ```\n */\nexport class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {\n /**\n * @param trx - The active Kysely transaction (or any Kysely instance) whose\n * connection job inserts should run on.\n */\n constructor(private readonly trx: KyselyLike) {\n super();\n }\n\n /**\n * Returns the transaction's connection adapted to pg-boss's executor shape,\n * with the caller's Kysely plugins stripped.\n *\n * @returns A {@link Db} executor bound to the transaction's connection.\n */\n override executor(): Db {\n return fromKysely(this.trx.withoutPlugins());\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAmFhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACnFhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;;;;;;;;;EAuBA,MAAMC,KAA6BC,MAAcC,SAAkBC,SAA2C;AAC5G,QAAI,CAAC,KAAKN,cAAcO,IAAIH,IAAAA,GAAO;AACjC,YAAM,IAAII,MAAM,OAAOJ,IAAAA,oBAAwB;IACjD;AAEA,UAAMK,KAAK,MAAM,KAAKR,OAAOE,KAAKC,MAAMC,SAAS;MAC/CK,IAAI,KAAKR,mBAAmBS,SAAQ;MACpC,GAAG,KAAKC,aAAaN,SAASO,UAAAA;IAChC,CAAA;AACA,QAAI,CAACJ,IAAI;AACP,YAAM,IAAID,MAAM,yBAAyBJ,IAAAA,EAAM;IACjD;AAEA,WAAOK;EACT;;;;;;;;;EAUQG,aAAaC,YAA0E;AAC7F,QAAIC,SAASC,WAAWF,UAAAA,GAAa;AACnC,aAAO;QAAEA,YAAYA,W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2E,SAAStE,MAAM;UAAEgC;QAAG,CAAA;AACpD,YAAI,CAACxB,OAAOA,IAAI+D,UAAU,aAAa;AACrCpD,qBAAWqD,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAASjC,OAAO;AACd,aAAKvC,OAAOuC,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAK5C,4BAA4B,GAAA;AAGpC6E,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKhF,OAAOgF,KAAI;EACxB;AACF;;;;;;;;;;;;;ACtXA,SAASC,kBAA2B;AAyC7B,IAAMC,sCAAN,cAAkDC,yBAAAA;EA1CzD,OA0CyDA;;;;;;;;EAKvD,YAA6BC,KAAiB;AAC5C,UAAK,GAAA,KADsBA,MAAAA;EAE7B;;;;;;;EAQSC,WAAe;AACtB,WAAOC,WAAW,KAAKF,IAAIG,eAAc,CAAA;EAC3C;AACF;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Duration","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","work","jobs","results","Promise","allSettled","map","scope","createScopedContainer","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","override","JobContext","toJobContext","jobRunner","get","watchForCancellation","id","run","data","error","disposeAsync","catch","failures","filter","result","status","reason","length","AggregateError","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.9.0",
3
+ "version": "1.11.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",
@@ -52,6 +52,7 @@
52
52
  },
53
53
  "devDependencies": {
54
54
  "@types/luxon": "^3.7.2",
55
+ "kysely": "^0.29.2",
55
56
  "pg-boss": "^12.24.1",
56
57
  "@repo/config-eslint": "0.2.1",
57
58
  "@repo/config-typescript": "0.1.0"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/job.broker.ts","../src/job.monitor.ts","../src/job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\nimport { JobSendOptions } from './job.send.options.js';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue, cancelling and\n * inspecting jobs, and managing scheduled jobs. It provides the producer-side\n * interface for the job processing system.\n *\n * Backends differ in what they can do. Operations a backend cannot honor throw\n * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // Sending a job immediately (returns the job id)\n * const id = await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Deferring a job: run it no earlier than five minutes from now\n * await jobBroker.send('send-email', payload, {\n * startAfter: Duration.fromObject({ minutes: 5 })\n * });\n *\n * // Deferring to an absolute time\n * await jobBroker.send('send-email', payload, {\n * startAfter: DateTime.now().plus({ hours: 2 })\n * });\n *\n * // Cancelling it later, whether it is still queued or already running\n * await jobBroker.cancel('send-email', id);\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue.\n *\n * By default the job is eligible for immediate processing and will be picked\n * up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}\n * to defer it: the job becomes eligible only once the given delay has elapsed\n * (a {@link Duration}) or the given moment has passed (a {@link DateTime}).\n * Deferral is a lower bound, not a guarantee of exact-time execution — the job\n * runs at the first opportunity after it becomes eligible.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\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. The id can\n * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or\n * {@link getJob}.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if `options.startAfter` requests a deferral the\n * backend cannot honor (e.g. a delay beyond the backend's maximum).\n */\n abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n\n /**\n * Requests cancellation of one or more jobs.\n *\n * Cancellation is best-effort and applies regardless of the job's state: a\n * job that is still queued is prevented from running, and a job that is\n * already running is asked to stop. For a running job, cancellation is\n * cooperative — the job's handler receives an aborted `AbortSignal` (see\n * {@link Job.run}) and must honor it. A handler that ignores the signal runs\n * to completion. Some backends may forcefully terminate the running compute\n * instead; this contract only guarantees the request is delivered.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot cancel jobs.\n */\n abstract cancel(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs in the `cancelled` state can be resumed; other states are\n * unaffected.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot resume jobs.\n */\n abstract resume(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Permanently deletes one or more jobs.\n *\n * Removes the job records entirely. Unlike {@link cancel}, a deleted job\n * leaves no `cancelled` record behind and cannot be resumed.\n *\n * @param name - The name of the registered job type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\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 type.\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 If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot report per-job state.\n */\n abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;\n}\n","import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\n\n/**\n * A backend-agnostic snapshot of a single queue's depth and health, as returned\n * by {@link JobMonitor.getQueueStats}. Every count is a point-in-time reading;\n * poll it on a schedule (for example from a reconciliation job) to drive\n * alerting on a backlog or a growing dead-letter queue.\n *\n * The counts are the lowest common denominator every supported backend can\n * report. `failed` in particular is a *retained* count: it reflects failures\n * still held in the queue subject to the queue's retention policy, not an\n * all-time total.\n */\nexport interface JobQueueStats {\n /** The queue name these stats describe. */\n name: string;\n /** Jobs waiting to be processed (enqueued but not yet active). */\n queued: number;\n /** Jobs currently being executed by a worker. */\n active: number;\n /** Failed jobs still retained in the queue (bounded by the retention policy). */\n failed: number;\n /** All jobs still retained for the queue across every state. */\n total: number;\n}\n\n/**\n * Filters for {@link JobMonitor.listJobs}. All fields are optional; omitting them\n * lists every job currently retained in the queue (the common case when\n * inspecting a small dead-letter queue).\n */\nexport interface JobQueryOptions {\n /** Match a single job by its id. */\n id?: string;\n /** Match jobs whose payload contains these fields (a partial-match filter). */\n data?: Record<string, unknown>;\n /** Restrict the result to jobs still waiting to be processed. */\n queuedOnly?: boolean;\n}\n\n/**\n * Options for {@link JobMonitor.redrive}, which moves dead-lettered jobs out of a\n * queue and back into circulation.\n */\nexport interface JobRedriveOptions {\n /**\n * The queue to move jobs into. When omitted, each job returns to the queue it\n * originally came from before it was dead-lettered — the usual \"reprocess\"\n * behavior. Supply this to funnel everything into a specific queue instead.\n */\n destination?: string;\n /**\n * Only redrive jobs that originated from this source queue. Useful when a\n * single dead-letter queue collects failures from several source queues and\n * you want to drain just one source's worth.\n */\n sourceName?: string;\n /**\n * Maximum number of jobs to move in this call, oldest first. Call repeatedly\n * (or on a schedule) to drain a large dead-letter queue at a controlled rate.\n */\n limit?: number;\n}\n\n/**\n * Read-and-remediate interface for job queues, and in particular for\n * *dead-letter queues*: the queues that collect jobs which have exhausted their\n * retries (see the queue policy on the pg-boss backend's registration).\n *\n * Where {@link JobBroker} is the producer side (enqueue, cancel, inspect a job\n * you hold the id for) and {@link JobRunner} is the consumer side, `JobMonitor`\n * is the operator side: it lets a consumer answer \"how deep is this queue?\",\n * \"what is stuck in this dead-letter queue?\", and \"reprocess / discard those\n * jobs\". Unlike the broker, it operates on raw queue names and does **not**\n * require the queue to be registered, because a dead-letter queue is often an\n * unregistered sink with no worker of its own.\n *\n * Backends that cannot honor an operation throw a `NotSupportedError` rather than\n * silently doing nothing, matching the rest of the package. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // A reconciliation sweep over a money-critical dead-letter queue.\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * const stuck = await monitor.listJobs('charge.webhook.dead'); // inspect / log / alert\n * const moved = await monitor.redrive('charge.webhook.dead', { limit: 100 }); // drain back\n * }\n * ```\n */\n@Injectable()\nexport abstract class JobMonitor {\n /**\n * Reports the current depth and health of a queue.\n *\n * @param name - The queue name to inspect (may be an unregistered dead-letter queue).\n * @returns A promise resolving to the {@link JobQueueStats}, or `null` if no\n * queue with that name exists.\n * @throws `NotSupportedError` if the backend cannot report queue statistics.\n */\n abstract getQueueStats(name: string): Promise<JobQueueStats | null>;\n\n /**\n * Lists the jobs currently retained in a queue, optionally filtered.\n *\n * The primary use is inspecting a dead-letter queue: the returned\n * {@link JobInfo} objects expose each poison message's id, state, and original\n * payload so a consumer can decide whether to reprocess ({@link redrive}),\n * discard ({@link deleteJob}), or escalate it.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list (may be an unregistered dead-letter queue).\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns A promise resolving to the matching jobs (empty if none / no such queue).\n * @throws `NotSupportedError` if the backend cannot enumerate jobs.\n */\n abstract listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]>;\n\n /**\n * Moves dead-lettered jobs out of a queue and back into circulation, returning\n * the number of jobs moved.\n *\n * By default each job goes back to the source queue it was dead-lettered from,\n * so a worker can process it again; pass {@link JobRedriveOptions.destination}\n * to route them elsewhere, {@link JobRedriveOptions.sourceName} to drain only\n * one source's jobs from a shared dead-letter queue, and\n * {@link JobRedriveOptions.limit} to move at a controlled rate.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns A promise resolving to the count of jobs moved.\n * @throws `NotSupportedError` if the backend cannot redrive jobs.\n */\n abstract redrive(name: string, options?: JobRedriveOptions): Promise<number>;\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * This is the \"discard\" action for a dead-letter queue: a poison message that\n * should not be reprocessed is removed outright. Unlike {@link JobBroker.deleteJob},\n * it does not require the queue to be registered.\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 * @returns A promise that resolves once the jobs have been deleted.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Re-attempts one or more failed jobs *in place*, re-queuing them within their\n * current queue.\n *\n * Use this to re-run a job that failed in a queue that has its own worker. To\n * reprocess a job sitting in a dead-letter *sink* (a queue with no worker),\n * prefer {@link redrive}, which moves it back to a queue that can run it.\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 * @returns A promise that resolves once the jobs have been re-queued.\n * @throws `NotSupportedError` if the backend cannot retry jobs.\n */\n abstract retryJob(name: string, id: string | string[]): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+CpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAgHtB;;;;;;AC/JA,SAASC,cAAAA,mBAAkB;;;;;;;;AA6FpB,IAAeC,aAAf,MAAeA;SAAAA;;;AAwEtB;;;;;;ACrKA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;","names":["Injectable","JobBroker","Injectable","JobMonitor","Injectable","JobRunner"]}