@maroonedsoftware/jobbroker 1.4.3 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,13 @@ pnpm add @maroonedsoftware/jobbroker injectkit pg-boss reflect-metadata
18
18
 
19
19
  > **Note:** InjectKit requires `reflect-metadata` to be imported at your application entry point and TypeScript configured with `experimentalDecorators: true` and `emitDecoratorMetadata: true`.
20
20
 
21
+ `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:
22
+
23
+ | Import | Contents | Pulls in |
24
+ |--------|----------|----------|
25
+ | `@maroonedsoftware/jobbroker` | `Job`, `JobBroker`, `JobRunner` | nothing extra |
26
+ | `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobRegistryMap`, `PgBossConnectionProvider` | `pg-boss` |
27
+
21
28
  ## Quick Start
22
29
 
23
30
  ### 1. Define a Job
@@ -51,7 +58,7 @@ export class SendEmailJob extends Job<EmailPayload> {
51
58
  Create a registry and register your jobs:
52
59
 
53
60
  ```typescript
54
- import { PgBossJobRegistryMap } from '@maroonedsoftware/jobbroker';
61
+ import { PgBossJobRegistryMap } from '@maroonedsoftware/jobbroker/pgboss';
55
62
 
56
63
  const registry = new PgBossJobRegistryMap();
57
64
 
@@ -72,7 +79,8 @@ import 'reflect-metadata';
72
79
  import { PgBoss } from 'pg-boss';
73
80
  import { InjectKitRegistry } from 'injectkit';
74
81
  import { ConsoleLogger, Logger } from '@maroonedsoftware/logger';
75
- import { PgBossJobBroker, PgBossJobRunner, PgBossJobRegistryMap, JobBroker, JobRunner } from '@maroonedsoftware/jobbroker';
82
+ import { JobBroker, JobRunner } from '@maroonedsoftware/jobbroker';
83
+ import { PgBossJobBroker, PgBossJobRunner, PgBossJobRegistryMap, PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
76
84
 
77
85
  // Initialize pg-boss
78
86
  const pgboss = new PgBoss('postgres://user:pass@localhost/mydb');
@@ -83,6 +91,7 @@ const diRegistry = new InjectKitRegistry();
83
91
  diRegistry.register(PgBossJobRegistryMap).useInstance(registry);
84
92
  diRegistry.register(PgBoss).useInstance(pgboss);
85
93
  diRegistry.register(Logger).useClass(ConsoleLogger).asSingleton();
94
+ diRegistry.register(PgBossConnectionProvider).useClass(PgBossConnectionProvider).asSingleton();
86
95
  diRegistry.register(JobBroker).useClass(PgBossJobBroker).asSingleton();
87
96
  diRegistry.register(JobRunner).useClass(PgBossJobRunner).asSingleton();
88
97
 
@@ -164,7 +173,45 @@ Configuration object for a scheduled job.
164
173
 
165
174
  ### `PgBossJobBroker`
166
175
 
167
- Concrete `JobBroker` implementation backed by pg-boss. Constructor signature: `new PgBossJobBroker(registrations: PgBossJobRegistryMap, pgboss: PgBoss)`. Typically resolved through the DI container rather than instantiated directly.
176
+ Concrete `JobBroker` implementation backed by pg-boss. Constructor signature: `new PgBossJobBroker(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider)`. Each `send`/`schedule` call sources its pg-boss `db` executor from the injected `PgBossConnectionProvider`. Typically resolved through the DI container rather than instantiated directly.
177
+
178
+ ### `PgBossConnectionProvider`
179
+
180
+ Supplies the pg-boss `db` executor used when enqueuing or scheduling jobs.
181
+
182
+ | Method | Description |
183
+ | ------------------------------- | ------------------------------------------------------------------------------------ |
184
+ | `executor(): Db \| undefined` | The executor to run job-insert SQL against; `undefined` uses pg-boss's own pool. |
185
+
186
+ 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).
187
+
188
+ ## Transactional enqueue
189
+
190
+ By default a job row is inserted on pg-boss's own connection, so it commits independently of any database work happening in the same request. To make an enqueue commit (or roll back) together with your business writes, override `PgBossConnectionProvider` in the request scope so its `executor()` returns the active transaction's connection. pg-boss ships adapters for the common query builders (`fromKysely`, `fromKnex`, `fromDrizzle`, `fromPrisma`) that wrap a transaction into the executor shape pg-boss expects:
191
+
192
+ ```typescript
193
+ import { fromKysely } from 'pg-boss';
194
+ import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
195
+
196
+ class TransactionalConnectionProvider extends PgBossConnectionProvider {
197
+ constructor(private readonly trx: Transaction<DB>) {
198
+ super();
199
+ }
200
+
201
+ override executor() {
202
+ return fromKysely(this.trx);
203
+ }
204
+ }
205
+
206
+ // Inside a transaction, bind the provider on the scoped container before resolving the broker:
207
+ await repository.withTransaction(async trx => {
208
+ scopedContainer.override(PgBossConnectionProvider, new TransactionalConnectionProvider(trx));
209
+
210
+ await doBusinessWrites(trx);
211
+ await scopedContainer.get(JobBroker).send('send-email', { to: 'user@example.com' });
212
+ // The job row and the business writes commit together.
213
+ });
214
+ ```
168
215
 
169
216
  ### `PgBossJobRunner`
170
217
 
@@ -0,0 +1,45 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/job.broker.ts
5
+ import { Injectable } from "injectkit";
6
+ function _ts_decorate(decorators, target, key, desc) {
7
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
9
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
10
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
11
+ }
12
+ __name(_ts_decorate, "_ts_decorate");
13
+ var JobBroker = class {
14
+ static {
15
+ __name(this, "JobBroker");
16
+ }
17
+ };
18
+ JobBroker = _ts_decorate([
19
+ Injectable()
20
+ ], JobBroker);
21
+
22
+ // src/job.runner.ts
23
+ import { Injectable as Injectable2 } from "injectkit";
24
+ function _ts_decorate2(decorators, target, key, desc) {
25
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
29
+ }
30
+ __name(_ts_decorate2, "_ts_decorate");
31
+ var JobRunner = class {
32
+ static {
33
+ __name(this, "JobRunner");
34
+ }
35
+ };
36
+ JobRunner = _ts_decorate2([
37
+ Injectable2()
38
+ ], JobRunner);
39
+
40
+ export {
41
+ __name,
42
+ JobBroker,
43
+ JobRunner
44
+ };
45
+ //# sourceMappingURL=chunk-AMXA75BW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/job.broker.ts","../src/job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue and managing\n * scheduled jobs. It provides the producer-side interface for the job\n * processing system.\n *\n * @example\n * ```typescript\n * // Sending a job immediately\n * await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue for immediate processing.\n *\n * The job will be picked up by a worker as soon as one is available.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws If the job name is not registered.\n */\n abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA4BpB,IAAeC,YAAf,MAAeA;SAAAA;;;AA0CtB;;;;;;ACtEA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;","names":["Injectable","JobBroker","Injectable","JobRunner"]}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,4 @@
1
1
  export * from './job.broker.js';
2
2
  export * from './job.js';
3
3
  export * from './job.runner.js';
4
- export * from './pgboss/pgboss.job.broker.js';
5
- export * from './pgboss/pgboss.job.runner.js';
6
- export * from './pgboss/pgboss.job.registration.js';
7
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
1
+ import {
2
+ JobBroker,
3
+ JobRunner,
4
+ __name
5
+ } from "./chunk-AMXA75BW.js";
3
6
 
4
- // src/job.broker.ts
7
+ // src/job.ts
5
8
  import { Injectable } from "injectkit";
6
9
  function _ts_decorate(decorators, target, key, desc) {
7
10
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -10,269 +13,17 @@ function _ts_decorate(decorators, target, key, desc) {
10
13
  return c > 3 && r && Object.defineProperty(target, key, r), r;
11
14
  }
12
15
  __name(_ts_decorate, "_ts_decorate");
13
- var JobBroker = class {
14
- static {
15
- __name(this, "JobBroker");
16
- }
17
- };
18
- JobBroker = _ts_decorate([
19
- Injectable()
20
- ], JobBroker);
21
-
22
- // src/job.ts
23
- import { Injectable as Injectable2 } from "injectkit";
24
- function _ts_decorate2(decorators, target, key, desc) {
25
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
- return c > 3 && r && Object.defineProperty(target, key, r), r;
29
- }
30
- __name(_ts_decorate2, "_ts_decorate");
31
16
  var Job = class {
32
17
  static {
33
18
  __name(this, "Job");
34
19
  }
35
20
  };
36
- Job = _ts_decorate2([
37
- Injectable2()
21
+ Job = _ts_decorate([
22
+ Injectable()
38
23
  ], Job);
39
-
40
- // src/job.runner.ts
41
- import { Injectable as Injectable3 } from "injectkit";
42
- function _ts_decorate3(decorators, target, key, desc) {
43
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
44
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
45
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
46
- return c > 3 && r && Object.defineProperty(target, key, r), r;
47
- }
48
- __name(_ts_decorate3, "_ts_decorate");
49
- var JobRunner = class {
50
- static {
51
- __name(this, "JobRunner");
52
- }
53
- };
54
- JobRunner = _ts_decorate3([
55
- Injectable3()
56
- ], JobRunner);
57
-
58
- // src/pgboss/pgboss.job.broker.ts
59
- import { PgBoss } from "pg-boss";
60
- import { Injectable as Injectable5 } from "injectkit";
61
-
62
- // src/pgboss/pgboss.job.registration.ts
63
- import { Injectable as Injectable4 } from "injectkit";
64
- function _ts_decorate4(decorators, target, key, desc) {
65
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
66
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
67
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
68
- return c > 3 && r && Object.defineProperty(target, key, r), r;
69
- }
70
- __name(_ts_decorate4, "_ts_decorate");
71
- var PgBossJobRegistryMap = class extends Map {
72
- static {
73
- __name(this, "PgBossJobRegistryMap");
74
- }
75
- };
76
- PgBossJobRegistryMap = _ts_decorate4([
77
- Injectable4()
78
- ], PgBossJobRegistryMap);
79
-
80
- // src/pgboss/pgboss.job.broker.ts
81
- function _ts_decorate5(decorators, target, key, desc) {
82
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
83
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
84
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
85
- return c > 3 && r && Object.defineProperty(target, key, r), r;
86
- }
87
- __name(_ts_decorate5, "_ts_decorate");
88
- function _ts_metadata(k, v) {
89
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
90
- }
91
- __name(_ts_metadata, "_ts_metadata");
92
- var PgBossJobBroker = class extends JobBroker {
93
- static {
94
- __name(this, "PgBossJobBroker");
95
- }
96
- registrations;
97
- pgboss;
98
- /**
99
- * Creates a new PgBossJobBroker instance.
100
- *
101
- * @param registrations - The registry map containing all registered jobs.
102
- * @param pgboss - The pg-boss instance to use for queue operations.
103
- */
104
- constructor(registrations, pgboss) {
105
- super(), this.registrations = registrations, this.pgboss = pgboss;
106
- }
107
- /**
108
- * Sends a job to the PgBoss queue for immediate processing.
109
- *
110
- * @typeParam Payload - The type of the job payload.
111
- * @param name - The name of the registered job to execute.
112
- * @param payload - The data to pass to the job handler.
113
- * @returns A promise that resolves when the job has been queued.
114
- * @throws Error if the job name is not found in the registry.
115
- */
116
- async send(name, payload) {
117
- if (!this.registrations.has(name)) {
118
- throw new Error(`Job ${name} is not registered`);
119
- }
120
- await this.pgboss.send(name, payload);
121
- }
122
- /**
123
- * Schedules a recurring job using a cron expression.
124
- *
125
- * The job will be automatically enqueued by pg-boss according to the
126
- * specified cron schedule. If a schedule already exists for this job,
127
- * it will be updated with the new cron expression and payload.
128
- *
129
- * @typeParam Payload - The type of the job payload.
130
- * @param name - The name of the registered job to schedule.
131
- * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).
132
- * @param payload - Optional data to pass to the job on each execution.
133
- * @returns A promise that resolves when the schedule has been created.
134
- * @throws Error if the job name is not found in the registry.
135
- */
136
- async schedule(name, cron, payload) {
137
- if (!this.registrations.has(name)) {
138
- throw new Error(`Job ${name} is not registered`);
139
- }
140
- await this.pgboss.schedule(name, cron, payload);
141
- }
142
- /**
143
- * Removes a scheduled job from pg-boss.
144
- *
145
- * This stops future executions of the scheduled job. Jobs that are
146
- * already queued will still be processed.
147
- *
148
- * @param name - The name of the scheduled job to remove.
149
- * @returns A promise that resolves when the schedule has been removed.
150
- * @throws Error if the job name is not found in the registry.
151
- */
152
- async unschedule(name) {
153
- if (!this.registrations.has(name)) {
154
- throw new Error(`Job ${name} is not registered`);
155
- }
156
- await this.pgboss.unschedule(name);
157
- }
158
- };
159
- PgBossJobBroker = _ts_decorate5([
160
- Injectable5(),
161
- _ts_metadata("design:type", Function),
162
- _ts_metadata("design:paramtypes", [
163
- typeof PgBossJobRegistryMap === "undefined" ? Object : PgBossJobRegistryMap,
164
- typeof PgBoss === "undefined" ? Object : PgBoss
165
- ])
166
- ], PgBossJobBroker);
167
-
168
- // src/pgboss/pgboss.job.runner.ts
169
- import { PgBoss as PgBoss2 } from "pg-boss";
170
- import { Container, Injectable as Injectable6 } from "injectkit";
171
- import { Logger } from "@maroonedsoftware/logger";
172
- function _ts_decorate6(decorators, target, key, desc) {
173
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
174
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
175
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
176
- return c > 3 && r && Object.defineProperty(target, key, r), r;
177
- }
178
- __name(_ts_decorate6, "_ts_decorate");
179
- function _ts_metadata2(k, v) {
180
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
181
- }
182
- __name(_ts_metadata2, "_ts_metadata");
183
- var isPgBossJobRegistration = /* @__PURE__ */ __name((registration) => {
184
- return registration && "job" in registration && "cron" in registration;
185
- }, "isPgBossJobRegistration");
186
- var PgBossJobRunner = class extends JobRunner {
187
- static {
188
- __name(this, "PgBossJobRunner");
189
- }
190
- container;
191
- registrations;
192
- pgboss;
193
- logger;
194
- /**
195
- * Creates a new PgBossJobRunner instance.
196
- *
197
- * @param container - The DI container for resolving job instances.
198
- * @param registrations - The registry map containing all registered jobs.
199
- * @param pgboss - The pg-boss instance to use for queue operations.
200
- * @param logger - The logger for recording job execution errors.
201
- */
202
- constructor(container, registrations, pgboss, logger) {
203
- super(), this.container = container, this.registrations = registrations, this.pgboss = pgboss, this.logger = logger;
204
- }
205
- /**
206
- * Starts the job runner and begins processing registered jobs.
207
- *
208
- * For each registered job, this method:
209
- * 1. Creates the queue if it doesn't exist
210
- * 2. Sets up the cron schedule (for scheduled jobs)
211
- * 3. Starts a worker to process jobs from the queue
212
- *
213
- * Each item in a batch resolves its `Job` instance from the DI container
214
- * individually and execution is awaited via `Promise.allSettled`, so pg-boss
215
- * does not acknowledge a batch until every job has actually finished and
216
- * one job's failure cannot suppress its sibling's logs.
217
- *
218
- * @returns A promise that resolves when all workers are registered with pg-boss.
219
- */
220
- async start() {
221
- await this.pgboss.start();
222
- for (const [name, registration] of this.registrations.entries()) {
223
- const queue = await this.pgboss.getQueue(name);
224
- if (!queue) {
225
- await this.pgboss.createQueue(name);
226
- }
227
- let identifier;
228
- if (isPgBossJobRegistration(registration)) {
229
- identifier = registration.job;
230
- await this.pgboss.schedule(name, registration.cron);
231
- } else {
232
- identifier = registration;
233
- }
234
- await this.pgboss.work(name, async (jobs) => {
235
- await Promise.allSettled(jobs.map(async (job) => {
236
- const jobRunner = this.container.get(identifier);
237
- try {
238
- await jobRunner.run(job.data);
239
- } catch (error) {
240
- this.logger.error(error);
241
- }
242
- }));
243
- });
244
- }
245
- }
246
- /**
247
- * Stops the job runner gracefully.
248
- *
249
- * This method stops the pg-boss instance, which will:
250
- * - Stop accepting new jobs
251
- * - Wait for currently executing jobs to complete
252
- * - Clean up database connections
253
- *
254
- * @returns A promise that resolves when the runner has stopped.
255
- */
256
- async stop() {
257
- await this.pgboss.stop();
258
- }
259
- };
260
- PgBossJobRunner = _ts_decorate6([
261
- Injectable6(),
262
- _ts_metadata2("design:type", Function),
263
- _ts_metadata2("design:paramtypes", [
264
- typeof Container === "undefined" ? Object : Container,
265
- typeof PgBossJobRegistryMap === "undefined" ? Object : PgBossJobRegistryMap,
266
- typeof PgBoss2 === "undefined" ? Object : PgBoss2,
267
- typeof Logger === "undefined" ? Object : Logger
268
- ])
269
- ], PgBossJobRunner);
270
24
  export {
271
25
  Job,
272
26
  JobBroker,
273
- JobRunner,
274
- PgBossJobBroker,
275
- PgBossJobRegistryMap,
276
- PgBossJobRunner
27
+ JobRunner
277
28
  };
278
29
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/job.broker.ts","../src/job.ts","../src/job.runner.ts","../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue and managing\n * scheduled jobs. It provides the producer-side interface for the job\n * processing system.\n *\n * @example\n * ```typescript\n * // Sending a job immediately\n * await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue for immediate processing.\n *\n * The job will be picked up by a worker as soon as one is available.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws If the job name is not registered.\n */\n abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload): Promise<void> {\n * await emailService.send(payload.to, payload.subject, payload.body);\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * @param payload - The data required to execute the job.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobBroker } from '../job.broker.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.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 * @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);\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 */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue for immediate processing.\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 * @returns A promise that resolves when the job has been queued.\n * @throws Error if the job name is not found in the registry.\n */\n async send<Payload extends object>(name: 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.send(name, payload);\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 * @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);\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","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\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 job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\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 * // 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 { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPgBossJobRegistration = (registration: any): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' 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 * 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. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. 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 for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\n try {\n await jobRunner.run(job.data);\n } catch (error) {\n this.logger.error(error);\n }\n }),\n );\n });\n }\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":"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","names":["Injectable","JobBroker","Injectable","Job","Injectable","JobRunner","PgBoss","Injectable","Injectable","PgBossJobRegistryMap","Map","PgBossJobBroker","JobBroker","registrations","pgboss","send","name","payload","has","Error","schedule","cron","unschedule","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","Promise","allSettled","map","jobRunner","get","run","data","error","stop"]}
1
+ {"version":3,"sources":["../src/job.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload): Promise<void> {\n * await emailService.send(payload.to, payload.subject, payload.body);\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * @param payload - The data required to execute the job.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload): Promise<void>;\n}\n"],"mappings":";;;;;;;AAAA,SAASA,kBAAkB;;;;;;;;AA6BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAatB;;;;","names":["Injectable","Job"]}
@@ -0,0 +1,44 @@
1
+ import { Db } from 'pg-boss';
2
+ /**
3
+ * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.
4
+ *
5
+ * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When
6
+ * provided, the job-insert SQL runs on that executor's connection instead of
7
+ * pg-boss's own pool — letting an enqueue participate in an in-flight database
8
+ * transaction so the job row and the surrounding business writes commit or roll
9
+ * back together.
10
+ *
11
+ * The default implementation returns `undefined`, which makes pg-boss fall back
12
+ * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue
13
+ * jobs transactionally, register an override on a request-scoped DI container whose
14
+ * {@link executor} returns a transaction-bound executor — for example pg-boss's
15
+ * `fromKysely(trx)` adapter wrapping the active Kysely transaction.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { fromKysely } from 'pg-boss';
20
+ * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';
21
+ *
22
+ * // In request scope, bind a provider backed by the active transaction.
23
+ * class TransactionalConnectionProvider extends PgBossConnectionProvider {
24
+ * constructor(private readonly trx: Transaction<DB>) {
25
+ * super();
26
+ * }
27
+ *
28
+ * override executor() {
29
+ * return fromKysely(this.trx);
30
+ * }
31
+ * }
32
+ * ```
33
+ */
34
+ export declare class PgBossConnectionProvider {
35
+ /**
36
+ * Returns the pg-boss executor to run job-insert SQL against, or `undefined`
37
+ * to use pg-boss's internal connection pool.
38
+ *
39
+ * @returns A transaction-bound {@link Db} executor, or `undefined` for the
40
+ * default pooled (non-transactional) behavior.
41
+ */
42
+ executor(): Db | undefined;
43
+ }
44
+ //# sourceMappingURL=pgboss.connection.provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgboss.connection.provider.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.connection.provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,qBACa,wBAAwB;IACnC;;;;;;OAMG;IACH,QAAQ,IAAI,EAAE,GAAG,SAAS;CAG3B"}
@@ -1,6 +1,7 @@
1
1
  import { PgBoss } from 'pg-boss';
2
2
  import { JobBroker } from '../job.broker.js';
3
3
  import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
4
+ import { PgBossConnectionProvider } from './pgboss.connection.provider.js';
4
5
  /**
5
6
  * PgBoss implementation of the {@link JobBroker} interface.
6
7
  *
@@ -8,6 +9,12 @@ import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
8
9
  * processing. It provides reliable, transactional job queuing with support
9
10
  * for scheduled jobs using cron expressions.
10
11
  *
12
+ * Each enqueue and schedule call sources its pg-boss `db` executor from the
13
+ * injected {@link PgBossConnectionProvider}. The default provider returns
14
+ * `undefined` (pg-boss uses its own pool), but a request-scoped override can
15
+ * supply a transaction-bound executor so jobs are enqueued atomically with the
16
+ * surrounding database transaction.
17
+ *
11
18
  * @example
12
19
  * ```typescript
13
20
  * // Setup with dependency injection
@@ -15,7 +22,7 @@ import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
15
22
  * const registry = new PgBossJobRegistryMap();
16
23
  * registry.set('send-email', SendEmailJob);
17
24
  *
18
- * const broker = new PgBossJobBroker(registry, pgboss);
25
+ * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());
19
26
  *
20
27
  * // Send a job
21
28
  * await broker.send('send-email', {
@@ -27,16 +34,24 @@ import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
27
34
  export declare class PgBossJobBroker extends JobBroker {
28
35
  private readonly registrations;
29
36
  private readonly pgboss;
37
+ private readonly connectionProvider;
30
38
  /**
31
39
  * Creates a new PgBossJobBroker instance.
32
40
  *
33
41
  * @param registrations - The registry map containing all registered jobs.
34
42
  * @param pgboss - The pg-boss instance to use for queue operations.
43
+ * @param connectionProvider - Supplies the pg-boss `db` executor for each
44
+ * enqueue/schedule; the default returns `undefined` (pg-boss's own
45
+ * pool), while a request-scoped override enables transactional enqueue.
35
46
  */
36
- constructor(registrations: PgBossJobRegistryMap, pgboss: PgBoss);
47
+ constructor(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider);
37
48
  /**
38
49
  * Sends a job to the PgBoss queue for immediate processing.
39
50
  *
51
+ * The job-insert SQL runs against the executor returned by the injected
52
+ * {@link PgBossConnectionProvider}; when that executor is bound to an active
53
+ * transaction, the job is enqueued atomically with that transaction.
54
+ *
40
55
  * @typeParam Payload - The type of the job payload.
41
56
  * @param name - The name of the registered job to execute.
42
57
  * @param payload - The data to pass to the job handler.
@@ -51,6 +66,10 @@ export declare class PgBossJobBroker extends JobBroker {
51
66
  * specified cron schedule. If a schedule already exists for this job,
52
67
  * it will be updated with the new cron expression and payload.
53
68
  *
69
+ * The schedule-insert SQL runs against the executor returned by the injected
70
+ * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own
71
+ * pool, which is the expected behavior for bootstrap-time scheduling.
72
+ *
54
73
  * @typeParam Payload - The type of the job payload.
55
74
  * @param name - The name of the registered job to schedule.
56
75
  * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.broker.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAQ1C,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IARzB;;;;;OAKG;gBAEgB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM;IAKjC;;;;;;;;OAQG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQjF;;;;;;;;;;;;;OAaG;IACG,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpG;;;;;;;;;OASG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO9C"}
1
+ {"version":3,"file":"pgboss.job.broker.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAW1C,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IAZrC;;;;;;;;OAQG;gBAEgB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,wBAAwB;IAK/D;;;;;;;;;;;;OAYG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQjF;;;;;;;;;;;;;;;;;OAiBG;IACG,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpG;;;;;;;;;OASG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO9C"}
@@ -0,0 +1,5 @@
1
+ export * from './pgboss/pgboss.job.broker.js';
2
+ export * from './pgboss/pgboss.job.runner.js';
3
+ export * from './pgboss/pgboss.job.registration.js';
4
+ export * from './pgboss/pgboss.connection.provider.js';
5
+ //# sourceMappingURL=pgboss.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgboss.d.ts","sourceRoot":"","sources":["../src/pgboss.ts"],"names":[],"mappings":"AAEA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC"}
package/dist/pgboss.js ADDED
@@ -0,0 +1,270 @@
1
+ import {
2
+ JobBroker,
3
+ JobRunner,
4
+ __name
5
+ } from "./chunk-AMXA75BW.js";
6
+
7
+ // src/pgboss/pgboss.job.broker.ts
8
+ import { PgBoss } from "pg-boss";
9
+ import { Injectable as Injectable3 } from "injectkit";
10
+
11
+ // src/pgboss/pgboss.job.registration.ts
12
+ import { Injectable } from "injectkit";
13
+ function _ts_decorate(decorators, target, key, desc) {
14
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
16
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
18
+ }
19
+ __name(_ts_decorate, "_ts_decorate");
20
+ var PgBossJobRegistryMap = class extends Map {
21
+ static {
22
+ __name(this, "PgBossJobRegistryMap");
23
+ }
24
+ };
25
+ PgBossJobRegistryMap = _ts_decorate([
26
+ Injectable()
27
+ ], PgBossJobRegistryMap);
28
+
29
+ // src/pgboss/pgboss.connection.provider.ts
30
+ import { Injectable as Injectable2 } from "injectkit";
31
+ function _ts_decorate2(decorators, target, key, desc) {
32
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
33
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
34
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
35
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
36
+ }
37
+ __name(_ts_decorate2, "_ts_decorate");
38
+ var PgBossConnectionProvider = class {
39
+ static {
40
+ __name(this, "PgBossConnectionProvider");
41
+ }
42
+ /**
43
+ * Returns the pg-boss executor to run job-insert SQL against, or `undefined`
44
+ * to use pg-boss's internal connection pool.
45
+ *
46
+ * @returns A transaction-bound {@link Db} executor, or `undefined` for the
47
+ * default pooled (non-transactional) behavior.
48
+ */
49
+ executor() {
50
+ return void 0;
51
+ }
52
+ };
53
+ PgBossConnectionProvider = _ts_decorate2([
54
+ Injectable2()
55
+ ], PgBossConnectionProvider);
56
+
57
+ // src/pgboss/pgboss.job.broker.ts
58
+ function _ts_decorate3(decorators, target, key, desc) {
59
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
60
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
61
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
62
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
63
+ }
64
+ __name(_ts_decorate3, "_ts_decorate");
65
+ function _ts_metadata(k, v) {
66
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
67
+ }
68
+ __name(_ts_metadata, "_ts_metadata");
69
+ var PgBossJobBroker = class extends JobBroker {
70
+ static {
71
+ __name(this, "PgBossJobBroker");
72
+ }
73
+ registrations;
74
+ pgboss;
75
+ connectionProvider;
76
+ /**
77
+ * Creates a new PgBossJobBroker instance.
78
+ *
79
+ * @param registrations - The registry map containing all registered jobs.
80
+ * @param pgboss - The pg-boss instance to use for queue operations.
81
+ * @param connectionProvider - Supplies the pg-boss `db` executor for each
82
+ * enqueue/schedule; the default returns `undefined` (pg-boss's own
83
+ * pool), while a request-scoped override enables transactional enqueue.
84
+ */
85
+ constructor(registrations, pgboss, connectionProvider) {
86
+ super(), this.registrations = registrations, this.pgboss = pgboss, this.connectionProvider = connectionProvider;
87
+ }
88
+ /**
89
+ * Sends a job to the PgBoss queue for immediate processing.
90
+ *
91
+ * The job-insert SQL runs against the executor returned by the injected
92
+ * {@link PgBossConnectionProvider}; when that executor is bound to an active
93
+ * transaction, the job is enqueued atomically with that transaction.
94
+ *
95
+ * @typeParam Payload - The type of the job payload.
96
+ * @param name - The name of the registered job to execute.
97
+ * @param payload - The data to pass to the job handler.
98
+ * @returns A promise that resolves when the job has been queued.
99
+ * @throws Error if the job name is not found in the registry.
100
+ */
101
+ async send(name, payload) {
102
+ if (!this.registrations.has(name)) {
103
+ throw new Error(`Job ${name} is not registered`);
104
+ }
105
+ await this.pgboss.send(name, payload, {
106
+ db: this.connectionProvider.executor()
107
+ });
108
+ }
109
+ /**
110
+ * Schedules a recurring job using a cron expression.
111
+ *
112
+ * The job will be automatically enqueued by pg-boss according to the
113
+ * specified cron schedule. If a schedule already exists for this job,
114
+ * it will be updated with the new cron expression and payload.
115
+ *
116
+ * The schedule-insert SQL runs against the executor returned by the injected
117
+ * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own
118
+ * pool, which is the expected behavior for bootstrap-time scheduling.
119
+ *
120
+ * @typeParam Payload - The type of the job payload.
121
+ * @param name - The name of the registered job to schedule.
122
+ * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).
123
+ * @param payload - Optional data to pass to the job on each execution.
124
+ * @returns A promise that resolves when the schedule has been created.
125
+ * @throws Error if the job name is not found in the registry.
126
+ */
127
+ async schedule(name, cron, payload) {
128
+ if (!this.registrations.has(name)) {
129
+ throw new Error(`Job ${name} is not registered`);
130
+ }
131
+ await this.pgboss.schedule(name, cron, payload, {
132
+ db: this.connectionProvider.executor()
133
+ });
134
+ }
135
+ /**
136
+ * Removes a scheduled job from pg-boss.
137
+ *
138
+ * This stops future executions of the scheduled job. Jobs that are
139
+ * already queued will still be processed.
140
+ *
141
+ * @param name - The name of the scheduled job to remove.
142
+ * @returns A promise that resolves when the schedule has been removed.
143
+ * @throws Error if the job name is not found in the registry.
144
+ */
145
+ async unschedule(name) {
146
+ if (!this.registrations.has(name)) {
147
+ throw new Error(`Job ${name} is not registered`);
148
+ }
149
+ await this.pgboss.unschedule(name);
150
+ }
151
+ };
152
+ PgBossJobBroker = _ts_decorate3([
153
+ Injectable3(),
154
+ _ts_metadata("design:type", Function),
155
+ _ts_metadata("design:paramtypes", [
156
+ typeof PgBossJobRegistryMap === "undefined" ? Object : PgBossJobRegistryMap,
157
+ typeof PgBoss === "undefined" ? Object : PgBoss,
158
+ typeof PgBossConnectionProvider === "undefined" ? Object : PgBossConnectionProvider
159
+ ])
160
+ ], PgBossJobBroker);
161
+
162
+ // src/pgboss/pgboss.job.runner.ts
163
+ import { PgBoss as PgBoss2 } from "pg-boss";
164
+ import { Container, Injectable as Injectable4 } from "injectkit";
165
+ import { Logger } from "@maroonedsoftware/logger";
166
+ function _ts_decorate4(decorators, target, key, desc) {
167
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
168
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
169
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
170
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
171
+ }
172
+ __name(_ts_decorate4, "_ts_decorate");
173
+ function _ts_metadata2(k, v) {
174
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
175
+ }
176
+ __name(_ts_metadata2, "_ts_metadata");
177
+ var isPgBossJobRegistration = /* @__PURE__ */ __name((registration) => {
178
+ return registration && "job" in registration && "cron" in registration;
179
+ }, "isPgBossJobRegistration");
180
+ var PgBossJobRunner = class extends JobRunner {
181
+ static {
182
+ __name(this, "PgBossJobRunner");
183
+ }
184
+ container;
185
+ registrations;
186
+ pgboss;
187
+ logger;
188
+ /**
189
+ * Creates a new PgBossJobRunner instance.
190
+ *
191
+ * @param container - The DI container for resolving job instances.
192
+ * @param registrations - The registry map containing all registered jobs.
193
+ * @param pgboss - The pg-boss instance to use for queue operations.
194
+ * @param logger - The logger for recording job execution errors.
195
+ */
196
+ constructor(container, registrations, pgboss, logger) {
197
+ super(), this.container = container, this.registrations = registrations, this.pgboss = pgboss, this.logger = logger;
198
+ }
199
+ /**
200
+ * Starts the job runner and begins processing registered jobs.
201
+ *
202
+ * For each registered job, this method:
203
+ * 1. Creates the queue if it doesn't exist
204
+ * 2. Sets up the cron schedule (for scheduled jobs)
205
+ * 3. Starts a worker to process jobs from the queue
206
+ *
207
+ * Each item in a batch resolves its `Job` instance from the DI container
208
+ * individually and execution is awaited via `Promise.allSettled`, so pg-boss
209
+ * does not acknowledge a batch until every job has actually finished and
210
+ * one job's failure cannot suppress its sibling's logs.
211
+ *
212
+ * @returns A promise that resolves when all workers are registered with pg-boss.
213
+ */
214
+ async start() {
215
+ await this.pgboss.start();
216
+ for (const [name, registration] of this.registrations.entries()) {
217
+ const queue = await this.pgboss.getQueue(name);
218
+ if (!queue) {
219
+ await this.pgboss.createQueue(name);
220
+ }
221
+ let identifier;
222
+ if (isPgBossJobRegistration(registration)) {
223
+ identifier = registration.job;
224
+ await this.pgboss.schedule(name, registration.cron);
225
+ } else {
226
+ identifier = registration;
227
+ }
228
+ await this.pgboss.work(name, async (jobs) => {
229
+ await Promise.allSettled(jobs.map(async (job) => {
230
+ const jobRunner = this.container.get(identifier);
231
+ try {
232
+ await jobRunner.run(job.data);
233
+ } catch (error) {
234
+ this.logger.error(error);
235
+ }
236
+ }));
237
+ });
238
+ }
239
+ }
240
+ /**
241
+ * Stops the job runner gracefully.
242
+ *
243
+ * This method stops the pg-boss instance, which will:
244
+ * - Stop accepting new jobs
245
+ * - Wait for currently executing jobs to complete
246
+ * - Clean up database connections
247
+ *
248
+ * @returns A promise that resolves when the runner has stopped.
249
+ */
250
+ async stop() {
251
+ await this.pgboss.stop();
252
+ }
253
+ };
254
+ PgBossJobRunner = _ts_decorate4([
255
+ Injectable4(),
256
+ _ts_metadata2("design:type", Function),
257
+ _ts_metadata2("design:paramtypes", [
258
+ typeof Container === "undefined" ? Object : Container,
259
+ typeof PgBossJobRegistryMap === "undefined" ? Object : PgBossJobRegistryMap,
260
+ typeof PgBoss2 === "undefined" ? Object : PgBoss2,
261
+ typeof Logger === "undefined" ? Object : Logger
262
+ ])
263
+ ], PgBossJobRunner);
264
+ export {
265
+ PgBossConnectionProvider,
266
+ PgBossJobBroker,
267
+ PgBossJobRegistryMap,
268
+ PgBossJobRunner
269
+ };
270
+ //# sourceMappingURL=pgboss.js.map
@@ -0,0 +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.runner.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobBroker } from '../job.broker.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 for immediate processing.\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 * @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 * @returns A promise that resolves when the job has been queued.\n * @throws Error if the job name is not found in the registry.\n */\n async send<Payload extends object>(name: 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.send(name, payload, { db: this.connectionProvider.executor() });\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","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\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 job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\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 * // 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 { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPgBossJobRegistration = (registration: any): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' 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 * 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. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. 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 for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\n try {\n await jobRunner.run(job.data);\n } catch (error) {\n this.logger.error(error);\n }\n }),\n );\n });\n }\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":"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","names":["PgBoss","Injectable","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","has","Error","db","executor","schedule","cron","unschedule","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","Promise","allSettled","map","jobRunner","get","run","data","error","stop"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.4.3",
3
+ "version": "1.6.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",
@@ -29,24 +29,40 @@
29
29
  "main": "./dist/index.js",
30
30
  "module": "./dist/index.js",
31
31
  "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js"
36
+ },
37
+ "./pgboss": {
38
+ "types": "./dist/pgboss.d.ts",
39
+ "import": "./dist/pgboss.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
32
43
  "license": "MIT",
33
44
  "files": [
34
45
  "dist/**"
35
46
  ],
36
47
  "dependencies": {
37
- "injectkit": "^1.4.1",
48
+ "injectkit": "^1.5.0",
38
49
  "@maroonedsoftware/logger": "1.1.1"
39
50
  },
40
51
  "devDependencies": {
41
- "pg-boss": "^12.18.2",
42
- "@repo/config-typescript": "0.1.0",
43
- "@repo/config-eslint": "0.2.1"
52
+ "pg-boss": "^12.20.0",
53
+ "@repo/config-eslint": "0.2.1",
54
+ "@repo/config-typescript": "0.1.0"
44
55
  },
45
56
  "peerDependencies": {
46
57
  "pg-boss": "^12.5.4"
47
58
  },
59
+ "peerDependenciesMeta": {
60
+ "pg-boss": {
61
+ "optional": true
62
+ }
63
+ },
48
64
  "scripts": {
49
- "build": "tsup src/index.ts --format esm --sourcemap --dts && tsc --emitDeclarationOnly --declaration",
65
+ "build": "tsup src/index.ts src/pgboss.ts --format esm --sourcemap && tsc --emitDeclarationOnly --declaration",
50
66
  "build:ci": "eslint --max-warnings=0 && pnpm run build",
51
67
  "lint": "eslint --fix",
52
68
  "format": "prettier --write .",