@maroonedsoftware/jobbroker 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Marooned Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # @maroonedsoftware/jobbroker
2
+
3
+ A flexible background job processing library with support for scheduled and on-demand jobs. Currently ships with a [pg-boss](https://github.com/timgit/pg-boss) implementation for PostgreSQL-backed job queues.
4
+
5
+ ## Features
6
+
7
+ - **Abstract interfaces** for easy testing and alternative implementations
8
+ - **Dependency injection** support via [injectkit](https://www.npmjs.com/package/injectkit)
9
+ - **Scheduled jobs** using cron expressions
10
+ - **On-demand jobs** for immediate execution
11
+ - **PostgreSQL backing** for reliability and transactional guarantees
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @maroonedsoftware/jobbroker injectkit pg-boss reflect-metadata
17
+ ```
18
+
19
+ > **Note:** InjectKit requires `reflect-metadata` to be imported at your application entry point and TypeScript configured with `experimentalDecorators: true` and `emitDecoratorMetadata: true`.
20
+
21
+ ## Quick Start
22
+
23
+ ### 1. Define a Job
24
+
25
+ Create a job by extending the `Job` base class:
26
+
27
+ ```typescript
28
+ import { Injectable } from 'injectkit';
29
+ import { Job } from '@maroonedsoftware/jobbroker';
30
+
31
+ interface EmailPayload {
32
+ to: string;
33
+ subject: string;
34
+ body: string;
35
+ }
36
+
37
+ @Injectable()
38
+ export class SendEmailJob extends Job<EmailPayload> {
39
+ constructor(private readonly emailService: EmailService) {
40
+ super();
41
+ }
42
+
43
+ async run(payload: EmailPayload): Promise<void> {
44
+ await this.emailService.send(payload.to, payload.subject, payload.body);
45
+ }
46
+ }
47
+ ```
48
+
49
+ ### 2. Register Jobs
50
+
51
+ Create a registry and register your jobs:
52
+
53
+ ```typescript
54
+ import { PgBossJobRegistryMap } from '@maroonedsoftware/jobbroker';
55
+
56
+ const registry = new PgBossJobRegistryMap();
57
+
58
+ // On-demand job (triggered manually)
59
+ registry.set('send-email', SendEmailJob);
60
+
61
+ // Scheduled job (runs on a cron schedule)
62
+ registry.set('daily-report', {
63
+ job: DailyReportJob,
64
+ cron: '0 9 * * *', // Every day at 9 AM
65
+ });
66
+ ```
67
+
68
+ ### 3. Set Up the Broker and Runner
69
+
70
+ ```typescript
71
+ import 'reflect-metadata';
72
+ import { PgBoss } from 'pg-boss';
73
+ import { InjectKitRegistry } from 'injectkit';
74
+ import { PgBossJobBroker, PgBossJobRunner, PgBossJobRegistryMap, JobBroker, JobRunner } from '@maroonedsoftware/jobbroker';
75
+
76
+ // Initialize pg-boss
77
+ const pgboss = new PgBoss('postgres://user:pass@localhost/mydb');
78
+ await pgboss.start();
79
+
80
+ // Set up dependency injection registry
81
+ const diRegistry = new InjectKitRegistry();
82
+
83
+ diRegistry.register(PgBossJobRegistryMap).useInstance(registry);
84
+ diRegistry.register(PgBoss).useInstance(pgboss);
85
+ diRegistry.register(JobBroker).useClass(PgBossJobBroker).asSingleton();
86
+ diRegistry.register(JobRunner).useClass(PgBossJobRunner).asSingleton();
87
+
88
+ // Build the container
89
+ const container = diRegistry.build();
90
+
91
+ // Start the job runner
92
+ const runner = container.get(JobRunner);
93
+ await runner.start();
94
+ ```
95
+
96
+ ### 4. Send Jobs
97
+
98
+ Use the broker to queue jobs for processing:
99
+
100
+ ```typescript
101
+ const broker = container.get(JobBroker);
102
+
103
+ // Send an immediate job
104
+ await broker.send('send-email', {
105
+ to: 'user@example.com',
106
+ subject: 'Welcome!',
107
+ body: 'Thanks for signing up.',
108
+ });
109
+
110
+ // Schedule a recurring job programmatically
111
+ await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
112
+
113
+ // Remove a schedule
114
+ await broker.unschedule('cleanup');
115
+ ```
116
+
117
+ ## API Reference
118
+
119
+ ### `Job<Payload>`
120
+
121
+ Abstract base class for job handlers.
122
+
123
+ | Method | Description |
124
+ | -------------------------------------- | -------------------------------------- |
125
+ | `run(payload: Payload): Promise<void>` | Execute the job with the given payload |
126
+
127
+ ### `JobBroker`
128
+
129
+ Abstract interface for sending jobs to the queue.
130
+
131
+ | Method | Description |
132
+ | --------------------------------------------------------------------- | ------------------------------------ |
133
+ | `send<P>(name: string, payload: P): Promise<void>` | Queue a job for immediate processing |
134
+ | `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
135
+ | `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
136
+
137
+ ### `JobRunner`
138
+
139
+ Abstract interface for processing jobs from the queue.
140
+
141
+ | Method | Description |
142
+ | ------------------------ | -------------------------- |
143
+ | `start(): Promise<void>` | Start processing jobs |
144
+ | `stop(): Promise<void>` | Gracefully stop processing |
145
+
146
+ ### `PgBossJobRegistryMap`
147
+
148
+ A `Map<string, Identifier<Job> | PgBossJobRegistration>` for registering jobs.
149
+
150
+ Entries can be either:
151
+
152
+ - A job class identifier (for on-demand jobs)
153
+ - A `PgBossJobRegistration` object with `job` and `cron` properties (for scheduled jobs)
154
+
155
+ ## Graceful Shutdown
156
+
157
+ Ensure you stop the runner during application shutdown:
158
+
159
+ ```typescript
160
+ process.on('SIGTERM', async () => {
161
+ await runner.stop();
162
+ await pgboss.stop();
163
+ process.exit(0);
164
+ });
165
+ ```
166
+
167
+ ## Peer Dependencies
168
+
169
+ - `pg-boss` ^12.5.4 - PostgreSQL-based job queue
170
+ - `reflect-metadata` - Required by InjectKit for decorator metadata
171
+
172
+ ## License
173
+
174
+ MIT
@@ -0,0 +1,7 @@
1
+ export * from './job.broker.js';
2
+ export * from './job.js';
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.registeration.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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,sCAAsC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,275 @@
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.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 Job = class {
32
+ static {
33
+ __name(this, "Job");
34
+ }
35
+ };
36
+ Job = _ts_decorate2([
37
+ Injectable2()
38
+ ], 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.registeration.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
+ * Job instances are resolved from the DI container for each execution,
214
+ * allowing for proper scoping and dependency injection.
215
+ *
216
+ * @returns A promise that resolves when all workers are set up.
217
+ */
218
+ async start() {
219
+ for (const [name, registration] of this.registrations.entries()) {
220
+ const queue = await this.pgboss.getQueue(name);
221
+ if (!queue) {
222
+ await this.pgboss.createQueue(name);
223
+ }
224
+ let identifier;
225
+ if (isPgBossJobRegistration(registration)) {
226
+ identifier = registration.job;
227
+ await this.pgboss.schedule(name, registration.cron);
228
+ } else {
229
+ identifier = registration;
230
+ }
231
+ this.pgboss.work(name, async (jobs) => {
232
+ const jobRunner = this.container.get(identifier);
233
+ jobs.map(async (job) => {
234
+ try {
235
+ await jobRunner.run(job.data);
236
+ } catch (error) {
237
+ this.logger.error(error);
238
+ }
239
+ });
240
+ });
241
+ }
242
+ }
243
+ /**
244
+ * Stops the job runner gracefully.
245
+ *
246
+ * This method stops the pg-boss instance, which will:
247
+ * - Stop accepting new jobs
248
+ * - Wait for currently executing jobs to complete
249
+ * - Clean up database connections
250
+ *
251
+ * @returns A promise that resolves when the runner has stopped.
252
+ */
253
+ async stop() {
254
+ await this.pgboss.stop();
255
+ }
256
+ };
257
+ PgBossJobRunner = _ts_decorate6([
258
+ Injectable6(),
259
+ _ts_metadata2("design:type", Function),
260
+ _ts_metadata2("design:paramtypes", [
261
+ typeof Container === "undefined" ? Object : Container,
262
+ typeof PgBossJobRegistryMap === "undefined" ? Object : PgBossJobRegistryMap,
263
+ typeof PgBoss2 === "undefined" ? Object : PgBoss2,
264
+ typeof Logger === "undefined" ? Object : Logger
265
+ ])
266
+ ], PgBossJobRunner);
267
+ export {
268
+ Job,
269
+ JobBroker,
270
+ JobRunner,
271
+ PgBossJobBroker,
272
+ PgBossJobRegistryMap,
273
+ PgBossJobRunner
274
+ };
275
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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.registeration.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.registeration.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.registeration.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 */\nconst isPgBossJobRegistration = (registration: object): 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 * Job instances are resolved from the DI container for each execution,\n * allowing for proper scoping and dependency injection.\n *\n * @returns A promise that resolves when all workers are set up.\n */\n async start(): Promise<void> {\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 this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const jobRunner = this.container.get<Job>(identifier);\n jobs.map(async job => {\n try {\n await jobRunner.run(job.data);\n } catch (error) {\n this.logger.error(error);\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":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA4BpB,IAAeC,YAAf,MAAeA;SAAAA;;;AA0CtB;;;;;;ACtEA,SAASC,cAAAA,mBAAkB;;;;;;;;AA6BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAatB;;;;;;AC1CA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;AC5CA,SAASC,cAAc;AACvB,SAASC,cAAAA,mBAAkB;;;ACD3B,SAAqBC,cAAAA,mBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;;;;;;;;;;;;ADvBzF,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;EAOnC,YACmBC,eACAC,QACjB;AACA,UAAK,GAAA,KAHYD,gBAAAA,eAAAA,KACAC,SAAAA;EAGnB;;;;;;;;;;EAWA,MAAMC,KAA6BC,MAAcC,SAAiC;AAChF,QAAI,CAAC,KAAKJ,cAAcK,IAAIF,IAAAA,GAAO;AACjC,YAAM,IAAIG,MAAM,OAAOH,IAAAA,oBAAwB;IACjD;AAEA,UAAM,KAAKF,OAAOC,KAAKC,MAAMC,OAAAA;EAC/B;;;;;;;;;;;;;;;EAgBA,MAAMG,SAAiCJ,MAAcK,MAAcJ,SAAkC;AACnG,QAAI,CAAC,KAAKJ,cAAcK,IAAIF,IAAAA,GAAO;AACjC,YAAM,IAAIG,MAAM,OAAOH,IAAAA,oBAAwB;IACjD;AAEA,UAAM,KAAKF,OAAOM,SAASJ,MAAMK,MAAMJ,OAAAA;EACzC;;;;;;;;;;;EAYA,MAAMK,WAAWN,MAA6B;AAC5C,QAAI,CAAC,KAAKH,cAAcK,IAAIF,IAAAA,GAAO;AACjC,YAAM,IAAIG,MAAM,OAAOH,IAAAA,oBAAwB;IACjD;AAEA,UAAM,KAAKF,OAAOQ,WAAWN,IAAAA;EAC/B;AACF;;;;;;;;;;;AEnGA,SAAuBO,UAAAA,eAAc;AACrC,SAASC,WAAWC,cAAAA,mBAAkB;AAItC,SAASC,cAAc;;;;;;;;;;;;AASvB,IAAMC,0BAA0B,wBAACC,iBAAAA;AAC/B,SAAOA,gBAAgB,SAASA,gBAAgB,UAAUA;AAC5D,GAFgC;AAoCzB,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EASnC,YACmBC,WACAC,eACAC,QACAC,QACjB;AACA,UAAK,GAAA,KALYH,YAAAA,WAAAA,KACAC,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,SAAAA;EAGnB;;;;;;;;;;;;;;EAeA,MAAMC,QAAuB;AAC3B,eAAW,CAACC,MAAMR,YAAAA,KAAiB,KAAKI,cAAcK,QAAO,GAAI;AAC/D,YAAMC,QAAQ,MAAM,KAAKL,OAAOM,SAASH,IAAAA;AACzC,UAAI,CAACE,OAAO;AACV,cAAM,KAAKL,OAAOO,YAAYJ,IAAAA;MAChC;AAEA,UAAIK;AACJ,UAAId,wBAAwBC,YAAAA,GAAe;AACzCa,qBAAab,aAAac;AAC1B,cAAM,KAAKT,OAAOU,SAASP,MAAMR,aAAagB,IAAI;MACpD,OAAO;AACLH,qBAAab;MACf;AAEA,WAAKK,OAAOY,KAAKT,MAAM,OAAOU,SAAAA;AAC5B,cAAMC,YAAY,KAAKhB,UAAUiB,IAASP,UAAAA;AAC1CK,aAAKG,IAAI,OAAMP,QAAAA;AACb,cAAI;AACF,kBAAMK,UAAUG,IAAIR,IAAIS,IAAI;UAC9B,SAASC,OAAO;AACd,iBAAKlB,OAAOkB,MAAMA,KAAAA;UACpB;QACF,CAAA;MACF,CAAA;IACF;EACF;;;;;;;;;;;EAYA,MAAMC,OAAsB;AAC1B,UAAM,KAAKpB,OAAOoB,KAAI;EACxB;AACF;;;;;;;;;;;","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","jobRunner","get","map","run","data","error","stop"]}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Abstract base class for job broker implementations.
3
+ *
4
+ * A job broker is responsible for sending jobs to a queue and managing
5
+ * scheduled jobs. It provides the producer-side interface for the job
6
+ * processing system.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // Sending a job immediately
11
+ * await jobBroker.send('send-email', {
12
+ * to: 'user@example.com',
13
+ * subject: 'Welcome!',
14
+ * body: 'Thanks for signing up.'
15
+ * });
16
+ *
17
+ * // Scheduling a recurring job with cron
18
+ * await jobBroker.schedule('daily-report', '0 9 * * *', {
19
+ * reportType: 'sales'
20
+ * });
21
+ *
22
+ * // Removing a scheduled job
23
+ * await jobBroker.unschedule('daily-report');
24
+ * ```
25
+ */
26
+ export declare abstract class JobBroker {
27
+ /**
28
+ * Sends a job to the queue for immediate processing.
29
+ *
30
+ * The job will be picked up by a worker as soon as one is available.
31
+ *
32
+ * @typeParam Payload - The type of the job payload. Must be an object.
33
+ * @param name - The unique name identifying the job type.
34
+ * Must match a registered job handler.
35
+ * @param payload - The data to pass to the job handler.
36
+ * @returns A promise that resolves when the job has been queued.
37
+ * @throws If the job name is not registered.
38
+ */
39
+ abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;
40
+ /**
41
+ * Schedules a recurring job using a cron expression.
42
+ *
43
+ * The job will be automatically enqueued according to the cron schedule.
44
+ * If a schedule already exists for this job name, it will be updated.
45
+ *
46
+ * @typeParam Payload - The type of the job payload. Must be an object.
47
+ * @param name - The unique name identifying the job type.
48
+ * Must match a registered job handler.
49
+ * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).
50
+ * @param payload - Optional data to pass to the job handler on each execution.
51
+ * @returns A promise that resolves when the schedule has been created.
52
+ * @throws If the job name is not registered.
53
+ */
54
+ abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;
55
+ /**
56
+ * Removes a scheduled job.
57
+ *
58
+ * Stops the recurring execution of the specified job.
59
+ * Does not affect jobs that are already queued.
60
+ *
61
+ * @param name - The unique name of the scheduled job to remove.
62
+ * @returns A promise that resolves when the schedule has been removed.
63
+ * @throws If the job name is not registered.
64
+ */
65
+ abstract unschedule(name: string): Promise<void>;
66
+ }
67
+ //# sourceMappingURL=job.broker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,8BACsB,SAAS;IAC7B;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAEpF;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAEvG;;;;;;;;;OASG;IACH,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CACjD"}
package/dist/job.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Abstract base class for defining background jobs.
3
+ *
4
+ * Extend this class to create custom job handlers that can be executed
5
+ * asynchronously by a {@link JobRunner}. Each job implementation defines
6
+ * how to process a specific type of payload.
7
+ *
8
+ * @typeParam Payload - The type of data the job expects to receive.
9
+ * Must be an object type. Defaults to `object`.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * interface EmailPayload {
14
+ * to: string;
15
+ * subject: string;
16
+ * body: string;
17
+ * }
18
+ *
19
+ * @Injectable()
20
+ * class SendEmailJob extends Job<EmailPayload> {
21
+ * async run(payload: EmailPayload): Promise<void> {
22
+ * await emailService.send(payload.to, payload.subject, payload.body);
23
+ * }
24
+ * }
25
+ * ```
26
+ */
27
+ export declare abstract class Job<Payload extends object = object> {
28
+ /**
29
+ * Executes the job with the provided payload.
30
+ *
31
+ * This method is called by the job runner when a job is dequeued
32
+ * and ready for processing. Implementations should contain the
33
+ * business logic for handling the job.
34
+ *
35
+ * @param payload - The data required to execute the job.
36
+ * @returns A promise that resolves when the job completes successfully.
37
+ * @throws If the job fails, the error will be caught and logged by the runner.
38
+ */
39
+ abstract run(payload: Payload): Promise<void>;
40
+ }
41
+ //# sourceMappingURL=job.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job.d.ts","sourceRoot":"","sources":["../src/job.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,8BACsB,GAAG,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM;IACvD;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAC9C"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Abstract base class for job runner implementations.
3
+ *
4
+ * A job runner is responsible for consuming jobs from the queue and
5
+ * executing the appropriate job handlers. It manages the worker lifecycle
6
+ * and provides the consumer-side interface for the job processing system.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // Start processing jobs
11
+ * await jobRunner.start();
12
+ *
13
+ * // Gracefully stop processing (e.g., on shutdown)
14
+ * process.on('SIGTERM', async () => {
15
+ * await jobRunner.stop();
16
+ * process.exit(0);
17
+ * });
18
+ * ```
19
+ */
20
+ export declare abstract class JobRunner {
21
+ /**
22
+ * Starts the job runner and begins processing jobs.
23
+ *
24
+ * This method initializes all registered job handlers and starts
25
+ * listening for jobs on their respective queues. It should be called
26
+ * during application startup.
27
+ *
28
+ * @returns A promise that resolves when the runner has started successfully.
29
+ */
30
+ abstract start(): Promise<void>;
31
+ /**
32
+ * Stops the job runner gracefully.
33
+ *
34
+ * This method stops accepting new jobs and waits for currently
35
+ * executing jobs to complete. It should be called during application
36
+ * shutdown to ensure clean termination.
37
+ *
38
+ * @returns A promise that resolves when the runner has stopped completely.
39
+ */
40
+ abstract stop(): Promise<void>;
41
+ }
42
+ //# sourceMappingURL=job.runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job.runner.d.ts","sourceRoot":"","sources":["../src/job.runner.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,8BACsB,SAAS;IAC7B;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAE/B;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAC/B"}
@@ -0,0 +1,74 @@
1
+ import { PgBoss } from 'pg-boss';
2
+ import { JobBroker } from '../job.broker.js';
3
+ import { PgBossJobRegistryMap } from './pgboss.job.registeration.js';
4
+ /**
5
+ * PgBoss implementation of the {@link JobBroker} interface.
6
+ *
7
+ * This broker uses PostgreSQL (via pg-boss) as the backing queue for job
8
+ * processing. It provides reliable, transactional job queuing with support
9
+ * for scheduled jobs using cron expressions.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * // Setup with dependency injection
14
+ * const pgboss = new PgBoss('postgres://...');
15
+ * const registry = new PgBossJobRegistryMap();
16
+ * registry.set('send-email', SendEmailJob);
17
+ *
18
+ * const broker = new PgBossJobBroker(registry, pgboss);
19
+ *
20
+ * // Send a job
21
+ * await broker.send('send-email', {
22
+ * to: 'user@example.com',
23
+ * subject: 'Hello!'
24
+ * });
25
+ * ```
26
+ */
27
+ export declare class PgBossJobBroker extends JobBroker {
28
+ private readonly registrations;
29
+ private readonly pgboss;
30
+ /**
31
+ * Creates a new PgBossJobBroker instance.
32
+ *
33
+ * @param registrations - The registry map containing all registered jobs.
34
+ * @param pgboss - The pg-boss instance to use for queue operations.
35
+ */
36
+ constructor(registrations: PgBossJobRegistryMap, pgboss: PgBoss);
37
+ /**
38
+ * Sends a job to the PgBoss queue for immediate processing.
39
+ *
40
+ * @typeParam Payload - The type of the job payload.
41
+ * @param name - The name of the registered job to execute.
42
+ * @param payload - The data to pass to the job handler.
43
+ * @returns A promise that resolves when the job has been queued.
44
+ * @throws Error if the job name is not found in the registry.
45
+ */
46
+ send<Payload extends object>(name: string, payload: Payload): Promise<void>;
47
+ /**
48
+ * Schedules a recurring job using a cron expression.
49
+ *
50
+ * The job will be automatically enqueued by pg-boss according to the
51
+ * specified cron schedule. If a schedule already exists for this job,
52
+ * it will be updated with the new cron expression and payload.
53
+ *
54
+ * @typeParam Payload - The type of the job payload.
55
+ * @param name - The name of the registered job to schedule.
56
+ * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).
57
+ * @param payload - Optional data to pass to the job on each execution.
58
+ * @returns A promise that resolves when the schedule has been created.
59
+ * @throws Error if the job name is not found in the registry.
60
+ */
61
+ schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;
62
+ /**
63
+ * Removes a scheduled job from pg-boss.
64
+ *
65
+ * This stops future executions of the scheduled job. Jobs that are
66
+ * already queued will still be processed.
67
+ *
68
+ * @param name - The name of the scheduled job to remove.
69
+ * @returns A promise that resolves when the schedule has been removed.
70
+ * @throws Error if the job name is not found in the registry.
71
+ */
72
+ unschedule(name: string): Promise<void>;
73
+ }
74
+ //# sourceMappingURL=pgboss.job.broker.d.ts.map
@@ -0,0 +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,+BAA+B,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;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"}
@@ -0,0 +1,52 @@
1
+ import { Identifier } from 'injectkit';
2
+ import { Job } from '../job.js';
3
+ /**
4
+ * Configuration for a scheduled job registration.
5
+ *
6
+ * Use this type when you need to register a job that runs on a schedule
7
+ * rather than being triggered manually.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const scheduledJob: PgBossJobRegistration = {
12
+ * job: DailyReportJob,
13
+ * cron: '0 9 * * *' // Every day at 9 AM
14
+ * };
15
+ * ```
16
+ */
17
+ export type PgBossJobRegistration = {
18
+ /** The job class identifier to instantiate when the job runs. */
19
+ job: Identifier<Job>;
20
+ /** A cron expression defining when the job should run. */
21
+ cron: string;
22
+ };
23
+ /**
24
+ * Registry map for PgBoss job registrations.
25
+ *
26
+ * This map holds all job registrations, mapping job names to either:
27
+ * - A job class identifier (for on-demand jobs)
28
+ * - A {@link PgBossJobRegistration} object (for scheduled jobs)
29
+ *
30
+ * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}
31
+ * to validate job names and resolve job handlers.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * const registry = new PgBossJobRegistryMap();
36
+ *
37
+ * // Register an on-demand job
38
+ * registry.set('send-email', SendEmailJob);
39
+ *
40
+ * // Register a scheduled job
41
+ * registry.set('daily-cleanup', {
42
+ * job: CleanupJob,
43
+ * cron: '0 0 * * *'
44
+ * });
45
+ *
46
+ * // Use with dependency injection
47
+ * container.bind(PgBossJobRegistryMap).toValue(registry);
48
+ * ```
49
+ */
50
+ export declare class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {
51
+ }
52
+ //# sourceMappingURL=pgboss.job.registeration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgboss.job.registeration.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.registeration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEhC;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,iEAAiE;IACjE,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC;IACrB,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBACa,oBAAqB,SAAQ,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,qBAAqB,CAAC;CAAG"}
@@ -0,0 +1,77 @@
1
+ import { PgBoss } from 'pg-boss';
2
+ import { Container } from 'injectkit';
3
+ import { JobRunner } from '../job.runner.js';
4
+ import { PgBossJobRegistryMap } from './pgboss.job.registeration.js';
5
+ import { Logger } from '@maroonedsoftware/logger';
6
+ /**
7
+ * PgBoss implementation of the {@link JobRunner} interface.
8
+ *
9
+ * This runner processes jobs from PostgreSQL queues using pg-boss. It
10
+ * automatically creates queues for registered jobs, sets up scheduled
11
+ * jobs, and handles job execution with error logging.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // Setup
16
+ * const pgboss = new PgBoss('postgres://...');
17
+ * await pgboss.start();
18
+ *
19
+ * const registry = new PgBossJobRegistryMap();
20
+ * registry.set('send-email', SendEmailJob);
21
+ * registry.set('daily-report', {
22
+ * job: DailyReportJob,
23
+ * cron: '0 9 * * *'
24
+ * });
25
+ *
26
+ * const runner = new PgBossJobRunner(container, registry, pgboss, logger);
27
+ *
28
+ * // Start processing
29
+ * await runner.start();
30
+ *
31
+ * // Graceful shutdown
32
+ * process.on('SIGTERM', async () => {
33
+ * await runner.stop();
34
+ * });
35
+ * ```
36
+ */
37
+ export declare class PgBossJobRunner extends JobRunner {
38
+ private readonly container;
39
+ private readonly registrations;
40
+ private readonly pgboss;
41
+ private readonly logger;
42
+ /**
43
+ * Creates a new PgBossJobRunner instance.
44
+ *
45
+ * @param container - The DI container for resolving job instances.
46
+ * @param registrations - The registry map containing all registered jobs.
47
+ * @param pgboss - The pg-boss instance to use for queue operations.
48
+ * @param logger - The logger for recording job execution errors.
49
+ */
50
+ constructor(container: Container, registrations: PgBossJobRegistryMap, pgboss: PgBoss, logger: Logger);
51
+ /**
52
+ * Starts the job runner and begins processing registered jobs.
53
+ *
54
+ * For each registered job, this method:
55
+ * 1. Creates the queue if it doesn't exist
56
+ * 2. Sets up the cron schedule (for scheduled jobs)
57
+ * 3. Starts a worker to process jobs from the queue
58
+ *
59
+ * Job instances are resolved from the DI container for each execution,
60
+ * allowing for proper scoping and dependency injection.
61
+ *
62
+ * @returns A promise that resolves when all workers are set up.
63
+ */
64
+ start(): Promise<void>;
65
+ /**
66
+ * Stops the job runner gracefully.
67
+ *
68
+ * This method stops the pg-boss instance, which will:
69
+ * - Stop accepting new jobs
70
+ * - Wait for currently executing jobs to complete
71
+ * - Clean up database connections
72
+ *
73
+ * @returns A promise that resolves when the runner has stopped.
74
+ */
75
+ stop(): Promise<void>;
76
+ }
77
+ //# sourceMappingURL=pgboss.job.runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAalD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAU1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAZzB;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;OAYG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4B5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@maroonedsoftware/jobbroker",
3
+ "version": "1.0.0",
4
+ "description": "A flexible background job processing library with support for scheduled and on-demand jobs.",
5
+ "author": {
6
+ "name": "Marooned Software",
7
+ "url": "https://github.com/MaroonedSoftware/serverkit"
8
+ },
9
+ "bugs": {
10
+ "url": "https://github.com/MaroonedSoftware/serverkit/issues"
11
+ },
12
+ "homepage": "https://github.com/MaroonedSoftware/serverkit/packages/jobbroker#readme",
13
+ "keywords": [
14
+ "backend",
15
+ "jobbroker",
16
+ "jobs",
17
+ "scheduled",
18
+ "pubsub",
19
+ "queues",
20
+ "serverkit",
21
+ "typescript"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/MaroonedSoftware/serverkit.git"
26
+ },
27
+ "private": false,
28
+ "type": "module",
29
+ "main": "./dist/index.js",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "license": "MIT",
33
+ "files": [
34
+ "dist/**"
35
+ ],
36
+ "dependencies": {
37
+ "injectkit": "^1.0.3",
38
+ "@maroonedsoftware/logger": "1.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "pg-boss": "^12.5.4",
42
+ "unplugin-swc": "^1.5.9",
43
+ "vitest": "^4.0.16",
44
+ "@repo/config-eslint": "0.0.0",
45
+ "@repo/config-typescript": "0.0.0"
46
+ },
47
+ "peerDependencies": {
48
+ "pg-boss": "^12.5.4"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup src/index.ts --format esm --sourcemap --dts && tsc --emitDeclarationOnly --declaration",
52
+ "build:ci": "eslint --max-warnings=0 && pnpm run build",
53
+ "lint": "eslint --fix",
54
+ "format": "prettier --write .",
55
+ "test": "vitest run",
56
+ "test:ci": "vitest run --coverage"
57
+ }
58
+ }