@maroonedsoftware/jobbroker 1.9.0 → 1.10.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 +76 -54
- package/dist/pgboss/kysely.transaction.connection.provider.d.ts +56 -0
- package/dist/pgboss/kysely.transaction.connection.provider.d.ts.map +1 -0
- package/dist/pgboss.d.ts +1 -0
- package/dist/pgboss.d.ts.map +1 -1
- package/dist/pgboss.js +26 -0
- package/dist/pgboss.js.map +1 -1
- package/package.json +2 -1
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
|
|
27
|
-
| ------------------------------------ |
|
|
28
|
-
| `@maroonedsoftware/jobbroker` | `Job`, `JobBroker`, `JobRunner`, `JobMonitor`, `JobInfo`, `JobState`, `JobQueuePolicy`, `NotSupportedError`
|
|
29
|
-
| `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobMonitor`, `PgBossJobRegistryMap`, `PgBossConnectionProvider` | `pg-boss` |
|
|
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`, `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 {
|
|
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');
|
|
@@ -198,7 +204,7 @@ registry.set('deliver-webhook', {
|
|
|
198
204
|
|
|
199
205
|
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
206
|
|
|
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
|
|
207
|
+
**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
208
|
|
|
203
209
|
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
210
|
|
|
@@ -238,13 +244,13 @@ if (stats && stats.total > 0) {
|
|
|
238
244
|
}
|
|
239
245
|
```
|
|
240
246
|
|
|
241
|
-
| Method
|
|
242
|
-
|
|
|
243
|
-
| `getQueueStats(name)`
|
|
244
|
-
| `listJobs<P>(name, options?)`
|
|
245
|
-
| `redrive(name, options?)`
|
|
246
|
-
| `deleteJob(name, id)`
|
|
247
|
-
| `retryJob(name, id)`
|
|
247
|
+
| Method | Description |
|
|
248
|
+
| ----------------------------- | --------------------------------------------------------------------------------------------------- |
|
|
249
|
+
| `getQueueStats(name)` | Point-in-time `{ name, queued, active, failed, total }`, or `null` if the queue does not exist. |
|
|
250
|
+
| `listJobs<P>(name, options?)` | List retained jobs as `JobInfo<P>[]`; filter by `id`, partial `data`, or `queuedOnly`. |
|
|
251
|
+
| `redrive(name, options?)` | Move dead-lettered jobs back to their source (or a `destination`), oldest first; returns count. |
|
|
252
|
+
| `deleteJob(name, id)` | Permanently discard one or more jobs (no registry check, so DLQ sinks are serviceable). |
|
|
253
|
+
| `retryJob(name, id)` | Re-attempt failed jobs **in place**; for a DLQ sink prefer `redrive`, which moves them to a worker. |
|
|
248
254
|
|
|
249
255
|
`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
256
|
|
|
@@ -252,7 +258,7 @@ if (stats && stats.total > 0) {
|
|
|
252
258
|
|
|
253
259
|
`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
260
|
|
|
255
|
-
`send`'s `startAfter` is deliberately expressed as
|
|
261
|
+
`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
262
|
|
|
257
263
|
## API Reference
|
|
258
264
|
|
|
@@ -268,15 +274,15 @@ Abstract base class for job handlers.
|
|
|
268
274
|
|
|
269
275
|
Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
|
|
270
276
|
|
|
271
|
-
| Method
|
|
272
|
-
|
|
|
277
|
+
| Method | Description |
|
|
278
|
+
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
|
|
273
279
|
| `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>`
|
|
275
|
-
| `unschedule(name: string): Promise<void>`
|
|
276
|
-
| `cancel(name: string, id: string \| string[]): Promise<void>`
|
|
277
|
-
| `resume(name: string, id: string \| string[]): Promise<void>`
|
|
278
|
-
| `deleteJob(name: string, id: string \| string[]): Promise<void>`
|
|
279
|
-
| `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>`
|
|
280
|
+
| `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
|
|
281
|
+
| `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
|
|
282
|
+
| `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
|
|
283
|
+
| `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
|
|
284
|
+
| `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
|
|
285
|
+
| `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
286
|
|
|
281
287
|
### `JobInfo<Payload>` / `JobState`
|
|
282
288
|
|
|
@@ -295,13 +301,13 @@ Abstract base class for processing jobs from the queue.
|
|
|
295
301
|
|
|
296
302
|
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
303
|
|
|
298
|
-
| Method
|
|
299
|
-
|
|
|
300
|
-
| `getQueueStats(name: string): Promise<JobQueueStats \| null>`
|
|
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>`
|
|
303
|
-
| `deleteJob(name: string, id: string \| string[]): Promise<void>`
|
|
304
|
-
| `retryJob(name: string, id: string \| string[]): Promise<void>`
|
|
304
|
+
| Method | Description |
|
|
305
|
+
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
|
|
306
|
+
| `getQueueStats(name: string): Promise<JobQueueStats \| null>` | Queue depth/health counts, or `null` if the queue does not exist |
|
|
307
|
+
| `listJobs<P>(name: string, options?: JobQueryOptions): Promise<JobInfo<P>[]>` | List retained jobs, optionally filtered by `id`, `data`, or `queuedOnly` |
|
|
308
|
+
| `redrive(name: string, options?: JobRedriveOptions): Promise<number>` | Move dead-lettered jobs back to source (or a `destination`); returns count moved |
|
|
309
|
+
| `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently discard jobs |
|
|
310
|
+
| `retryJob(name: string, id: string \| string[]): Promise<void>` | Re-attempt failed jobs in place |
|
|
305
311
|
|
|
306
312
|
`JobQueueStats` is `{ name, queued, active, failed, total }`. `JobQueryOptions` is `{ id?, data?, queuedOnly? }`. `JobRedriveOptions` is `{ destination?, sourceName?, limit? }`.
|
|
307
313
|
|
|
@@ -319,23 +325,23 @@ Entries can be either:
|
|
|
319
325
|
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
326
|
|
|
321
327
|
| 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.
|
|
328
|
+
| -------- | ----------------- | -------------------------------------------------------------------- |
|
|
329
|
+
| `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
|
|
330
|
+
| `cron` | `string` | Optional cron expression defining when the job should run. |
|
|
325
331
|
| `policy` | `JobQueuePolicy` | Optional per-queue retry and dead-letter policy for the job's queue. |
|
|
326
332
|
|
|
327
333
|
### `JobQueuePolicy`
|
|
328
334
|
|
|
329
335
|
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
336
|
|
|
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.
|
|
337
|
+
| Property | Type | Description |
|
|
338
|
+
| --------------- | ---------- | ------------------------------------------------------------------------------------ |
|
|
339
|
+
| `retryLimit` | `number` | Attempts before a job is failed (and dead-lettered, if `deadLetter` is set). |
|
|
340
|
+
| `retryDelay` | `Duration` | Delay before retrying; the base of the curve when `retryBackoff` is on. |
|
|
341
|
+
| `retryBackoff` | `boolean` | Grow the retry delay exponentially (with jitter) from `retryDelay` instead of fixed. |
|
|
342
|
+
| `retryDelayMax` | `Duration` | Upper bound on the backoff delay. Only used when `retryBackoff` is on. |
|
|
343
|
+
| `expiresIn` | `Duration` | How long a run may take before it is considered stuck and made eligible for retry. |
|
|
344
|
+
| `deadLetter` | `string` | Name of the dead-letter queue that receives jobs which exhaust their retries. |
|
|
339
345
|
|
|
340
346
|
### `PgBossJobBroker`
|
|
341
347
|
|
|
@@ -351,27 +357,26 @@ Supplies the pg-boss `db` executor used when enqueuing or scheduling jobs.
|
|
|
351
357
|
|
|
352
358
|
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
359
|
|
|
354
|
-
|
|
360
|
+
### `KyselyTransactionConnectionProvider`
|
|
355
361
|
|
|
356
|
-
|
|
362
|
+
`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
363
|
|
|
358
|
-
|
|
359
|
-
import { fromKysely } from 'pg-boss';
|
|
360
|
-
import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
|
|
364
|
+
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
365
|
|
|
362
|
-
|
|
363
|
-
constructor(private readonly trx: Transaction<DB>) {
|
|
364
|
-
super();
|
|
365
|
-
}
|
|
366
|
+
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
367
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
368
|
+
## Transactional enqueue
|
|
369
|
+
|
|
370
|
+
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.
|
|
371
|
+
|
|
372
|
+
For Kysely, `KyselyTransactionConnectionProvider` does this for you:
|
|
373
|
+
|
|
374
|
+
```typescript
|
|
375
|
+
import { PgBossConnectionProvider, KyselyTransactionConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
|
|
371
376
|
|
|
372
377
|
// Inside a transaction, bind the provider on the scoped container before resolving the broker:
|
|
373
378
|
await repository.withTransaction(async trx => {
|
|
374
|
-
scopedContainer.override(PgBossConnectionProvider, new
|
|
379
|
+
scopedContainer.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));
|
|
375
380
|
|
|
376
381
|
await doBusinessWrites(trx);
|
|
377
382
|
await scopedContainer.get(JobBroker).send('send-email', { to: 'user@example.com' });
|
|
@@ -379,6 +384,23 @@ await repository.withTransaction(async trx => {
|
|
|
379
384
|
});
|
|
380
385
|
```
|
|
381
386
|
|
|
387
|
+
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:
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
import { fromKnex } from 'pg-boss';
|
|
391
|
+
import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
|
|
392
|
+
|
|
393
|
+
class KnexTransactionConnectionProvider extends PgBossConnectionProvider {
|
|
394
|
+
constructor(private readonly trx: Knex.Transaction) {
|
|
395
|
+
super();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
override executor() {
|
|
399
|
+
return fromKnex(this.trx);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
```
|
|
403
|
+
|
|
382
404
|
### `PgBossJobRunner`
|
|
383
405
|
|
|
384
406
|
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.
|
|
@@ -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"}
|
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
|
package/dist/pgboss.d.ts.map
CHANGED
|
@@ -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
|
@@ -673,7 +673,33 @@ PgBossJobRunner = _ts_decorate5([
|
|
|
673
673
|
typeof Logger === "undefined" ? Object : Logger
|
|
674
674
|
])
|
|
675
675
|
], PgBossJobRunner);
|
|
676
|
+
|
|
677
|
+
// src/pgboss/kysely.transaction.connection.provider.ts
|
|
678
|
+
import { fromKysely } from "pg-boss";
|
|
679
|
+
var KyselyTransactionConnectionProvider = class extends PgBossConnectionProvider {
|
|
680
|
+
static {
|
|
681
|
+
__name(this, "KyselyTransactionConnectionProvider");
|
|
682
|
+
}
|
|
683
|
+
trx;
|
|
684
|
+
/**
|
|
685
|
+
* @param trx - The active Kysely transaction (or any Kysely instance) whose
|
|
686
|
+
* connection job inserts should run on.
|
|
687
|
+
*/
|
|
688
|
+
constructor(trx) {
|
|
689
|
+
super(), this.trx = trx;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Returns the transaction's connection adapted to pg-boss's executor shape,
|
|
693
|
+
* with the caller's Kysely plugins stripped.
|
|
694
|
+
*
|
|
695
|
+
* @returns A {@link Db} executor bound to the transaction's connection.
|
|
696
|
+
*/
|
|
697
|
+
executor() {
|
|
698
|
+
return fromKysely(this.trx.withoutPlugins());
|
|
699
|
+
}
|
|
700
|
+
};
|
|
676
701
|
export {
|
|
702
|
+
KyselyTransactionConnectionProvider,
|
|
677
703
|
PgBossConnectionProvider,
|
|
678
704
|
PgBossJobBroker,
|
|
679
705
|
PgBossJobMonitor,
|
package/dist/pgboss.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts"],"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;;;;;;ACnFhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC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A,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 { 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","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,WAAWG,GAAG,SAAA;MAAW;IAChD;AACA,Q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AOC,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","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","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.
|
|
3
|
+
"version": "1.10.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"
|