@maroonedsoftware/jobbroker 1.6.0 → 1.8.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 +1 -1
- package/README.md +77 -25
- package/dist/{chunk-AMXA75BW.js → chunk-GKXLBFUJ.js} +1 -1
- package/dist/chunk-GKXLBFUJ.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +27 -2
- package/dist/index.js.map +1 -1
- package/dist/job.broker.d.ts +94 -9
- package/dist/job.broker.d.ts.map +1 -1
- package/dist/job.d.ts +14 -3
- package/dist/job.d.ts.map +1 -1
- package/dist/job.info.d.ts +38 -0
- package/dist/job.info.d.ts.map +1 -0
- package/dist/job.send.options.d.ts +33 -0
- package/dist/job.send.options.d.ts.map +1 -0
- package/dist/not.supported.error.d.ts +37 -0
- package/dist/not.supported.error.d.ts.map +1 -0
- package/dist/pgboss/pgboss.job.broker.d.ts +68 -3
- package/dist/pgboss/pgboss.job.broker.d.ts.map +1 -1
- package/dist/pgboss/pgboss.job.runner.d.ts +26 -0
- package/dist/pgboss/pgboss.job.runner.d.ts.map +1 -1
- package/dist/pgboss.js +183 -7
- package/dist/pgboss.js.map +1 -1
- package/package.json +10 -7
- package/dist/chunk-AMXA75BW.js.map +0 -1
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@ A flexible background job processing library with support for scheduled and on-d
|
|
|
8
8
|
- **Dependency injection** support via [injectkit](https://www.npmjs.com/package/injectkit)
|
|
9
9
|
- **Scheduled jobs** using cron expressions
|
|
10
10
|
- **On-demand jobs** for immediate execution
|
|
11
|
+
- **Cancellation** of queued _and_ running jobs, plus state lookup, delete, and resume
|
|
11
12
|
- **PostgreSQL backing** for reliability and transactional guarantees
|
|
12
13
|
|
|
13
14
|
## Installation
|
|
@@ -20,10 +21,10 @@ pnpm add @maroonedsoftware/jobbroker injectkit pg-boss reflect-metadata
|
|
|
20
21
|
|
|
21
22
|
`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
|
|
|
23
|
-
| Import
|
|
24
|
-
|
|
25
|
-
| `@maroonedsoftware/jobbroker`
|
|
26
|
-
| `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobRegistryMap`, `PgBossConnectionProvider` | `pg-boss`
|
|
24
|
+
| Import | Contents | Pulls in |
|
|
25
|
+
| ------------------------------------ | ---------------------------------------------------------------------------------------- | ------------- |
|
|
26
|
+
| `@maroonedsoftware/jobbroker` | `Job`, `JobBroker`, `JobRunner`, `JobInfo`, `JobState`, `NotSupportedError` | nothing extra |
|
|
27
|
+
| `@maroonedsoftware/jobbroker/pgboss` | `PgBossJobBroker`, `PgBossJobRunner`, `PgBossJobRegistryMap`, `PgBossConnectionProvider` | `pg-boss` |
|
|
27
28
|
|
|
28
29
|
## Quick Start
|
|
29
30
|
|
|
@@ -47,12 +48,15 @@ export class SendEmailJob extends Job<EmailPayload> {
|
|
|
47
48
|
super();
|
|
48
49
|
}
|
|
49
50
|
|
|
50
|
-
async run(payload: EmailPayload): Promise<void> {
|
|
51
|
-
|
|
51
|
+
async run(payload: EmailPayload, signal?: AbortSignal): Promise<void> {
|
|
52
|
+
// Forward `signal` to async work so the job stops promptly when cancelled.
|
|
53
|
+
await this.emailService.send(payload.to, payload.subject, payload.body, { signal });
|
|
52
54
|
}
|
|
53
55
|
}
|
|
54
56
|
```
|
|
55
57
|
|
|
58
|
+
> The optional `signal` is aborted when the job is cancelled or the runner shuts down. Honoring it is how a long-running job becomes cancellable — see [Cancelling jobs](#cancelling-jobs).
|
|
59
|
+
|
|
56
60
|
### 2. Register Jobs
|
|
57
61
|
|
|
58
62
|
Create a registry and register your jobs:
|
|
@@ -110,13 +114,29 @@ Use the broker to queue jobs for processing:
|
|
|
110
114
|
```typescript
|
|
111
115
|
const broker = container.get(JobBroker);
|
|
112
116
|
|
|
113
|
-
// Send an immediate job
|
|
114
|
-
await broker.send('send-email', {
|
|
117
|
+
// Send an immediate job — returns the job id so you can reference it later
|
|
118
|
+
const id = await broker.send('send-email', {
|
|
115
119
|
to: 'user@example.com',
|
|
116
120
|
subject: 'Welcome!',
|
|
117
121
|
body: 'Thanks for signing up.',
|
|
118
122
|
});
|
|
119
123
|
|
|
124
|
+
// Defer a job with a relative delay (Luxon Duration)...
|
|
125
|
+
await broker.send('send-email', payload, { startAfter: Duration.fromObject({ minutes: 5 }) });
|
|
126
|
+
|
|
127
|
+
// ...or until an absolute moment (Luxon DateTime)
|
|
128
|
+
await broker.send('send-email', payload, { startAfter: DateTime.now().plus({ hours: 2 }) });
|
|
129
|
+
|
|
130
|
+
// Inspect a job's current state
|
|
131
|
+
const info = await broker.getJob('send-email', id); // { id, name, state, data } | null
|
|
132
|
+
|
|
133
|
+
// Cancel it (works whether it is still queued or already running)
|
|
134
|
+
await broker.cancel('send-email', id);
|
|
135
|
+
|
|
136
|
+
// Bring a cancelled job back, or remove it entirely
|
|
137
|
+
await broker.resume('send-email', id);
|
|
138
|
+
await broker.deleteJob('send-email', id);
|
|
139
|
+
|
|
120
140
|
// Schedule a recurring job programmatically
|
|
121
141
|
await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
|
|
122
142
|
|
|
@@ -124,25 +144,55 @@ await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
|
|
|
124
144
|
await broker.unschedule('cleanup');
|
|
125
145
|
```
|
|
126
146
|
|
|
147
|
+
## Cancelling jobs
|
|
148
|
+
|
|
149
|
+
`broker.cancel(name, id)` requests cancellation of a job **whatever state it is in**:
|
|
150
|
+
|
|
151
|
+
- A job that is still **queued** is marked cancelled and never picked up by a worker.
|
|
152
|
+
- A job that is **already running** is asked to stop. Cancellation is _cooperative_: the runner detects the cancellation and aborts the `AbortSignal` passed to the job's `run(payload, signal)`. Handlers must honor the signal (forward it to `fetch`/DB calls, or check `signal.aborted`) to actually stop. **A handler that ignores the signal runs to completion** — Node cannot forcibly terminate it.
|
|
153
|
+
|
|
154
|
+
Cancellation works **across processes**. `cancel` records the state change on the shared PostgreSQL row, and whichever worker process is running the job observes it. That observation is done by polling: while a job runs, `PgBossJobRunner` periodically looks the job up (via pg-boss `findJobs`) and aborts the signal once the state becomes `cancelled` (or the job is deleted). The poll cadence is configurable:
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
const runner = container.get(JobRunner) as PgBossJobRunner;
|
|
158
|
+
runner.cancelPollIntervalSeconds = 2; // default 5; set to 0 to disable polling
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Lower values reduce cancellation latency at the cost of one extra lookup query per running job per interval.
|
|
162
|
+
|
|
163
|
+
### Backend portability
|
|
164
|
+
|
|
165
|
+
`cancel`, `resume`, `deleteJob`, and `getJob` are best-effort by contract: a backend that cannot honor an operation throws `NotSupportedError` rather than silently doing nothing. `JobState` (`created | retry | active | completed | cancelled | failed`) is the normalized, lowest-common-denominator lifecycle; alternative backends map their native states to the nearest value. The bundled pg-boss backend supports every operation.
|
|
166
|
+
|
|
167
|
+
`send`'s `startAfter` is deliberately expressed as *intent* (a relative `Duration` or an absolute `DateTime`), not a wire format, so it maps cleanly onto each backend's native deferral mechanism — pg-boss `startAfter` (unbounded), SQS `DelaySeconds` (max 15 minutes), Cloud Tasks `scheduleTime` (up to 30 days). A backend that cannot honor a requested delay (e.g. an SQS backend asked for a 1-hour delay) throws `NotSupportedError` rather than clamping silently.
|
|
168
|
+
|
|
127
169
|
## API Reference
|
|
128
170
|
|
|
129
171
|
### `Job<Payload>`
|
|
130
172
|
|
|
131
173
|
Abstract base class for job handlers.
|
|
132
174
|
|
|
133
|
-
| Method
|
|
134
|
-
|
|
|
135
|
-
| `run(payload: Payload): Promise<void>` | Execute the job
|
|
175
|
+
| Method | Description |
|
|
176
|
+
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
|
|
177
|
+
| `run(payload: Payload, signal?: AbortSignal): Promise<void>` | Execute the job. `signal` is aborted on cancellation/shutdown; honoring it is optional. |
|
|
136
178
|
|
|
137
179
|
### `JobBroker`
|
|
138
180
|
|
|
139
|
-
Abstract base class for sending jobs
|
|
181
|
+
Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
|
|
182
|
+
|
|
183
|
+
| Method | Description |
|
|
184
|
+
| --------------------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
185
|
+
| `send<P>(name: string, payload: P, options?: JobSendOptions): Promise<string>` | Queue a job; resolves with the new job id. Pass `options.startAfter` (a Luxon `Duration` or `DateTime`) to defer it |
|
|
186
|
+
| `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
|
|
187
|
+
| `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
|
|
188
|
+
| `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
|
|
189
|
+
| `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
|
|
190
|
+
| `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
|
|
191
|
+
| `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
|
|
140
192
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
| `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
|
|
145
|
-
| `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
|
|
193
|
+
### `JobInfo<Payload>` / `JobState`
|
|
194
|
+
|
|
195
|
+
Backend-agnostic snapshot returned by `getJob`. `JobInfo` has `id`, `name`, `state`, and `data`. `JobState` is one of `created`, `retry`, `active`, `completed`, `cancelled`, or `failed`.
|
|
146
196
|
|
|
147
197
|
### `JobRunner`
|
|
148
198
|
|
|
@@ -166,22 +216,22 @@ Entries can be either:
|
|
|
166
216
|
|
|
167
217
|
Configuration object for a scheduled job.
|
|
168
218
|
|
|
169
|
-
| Property | Type
|
|
170
|
-
| -------- |
|
|
171
|
-
| `job` | `Identifier<Job>`
|
|
172
|
-
| `cron` | `string`
|
|
219
|
+
| Property | Type | Description |
|
|
220
|
+
| -------- | ----------------- | ---------------------------------------------------------- |
|
|
221
|
+
| `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
|
|
222
|
+
| `cron` | `string` | A cron expression defining when the job should run. |
|
|
173
223
|
|
|
174
224
|
### `PgBossJobBroker`
|
|
175
225
|
|
|
176
|
-
Concrete `JobBroker` implementation backed by pg-boss. Constructor signature: `new PgBossJobBroker(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider)`.
|
|
226
|
+
Concrete `JobBroker` implementation backed by pg-boss. Constructor signature: `new PgBossJobBroker(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider)`. Every operation sources its pg-boss `db` executor from the injected `PgBossConnectionProvider`. Typically resolved through the DI container rather than instantiated directly.
|
|
177
227
|
|
|
178
228
|
### `PgBossConnectionProvider`
|
|
179
229
|
|
|
180
230
|
Supplies the pg-boss `db` executor used when enqueuing or scheduling jobs.
|
|
181
231
|
|
|
182
|
-
| Method
|
|
183
|
-
|
|
|
184
|
-
| `executor(): Db \| undefined`
|
|
232
|
+
| Method | Description |
|
|
233
|
+
| ----------------------------- | -------------------------------------------------------------------------------- |
|
|
234
|
+
| `executor(): Db \| undefined` | The executor to run job-insert SQL against; `undefined` uses pg-boss's own pool. |
|
|
185
235
|
|
|
186
236
|
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
237
|
|
|
@@ -217,6 +267,8 @@ await repository.withTransaction(async trx => {
|
|
|
217
267
|
|
|
218
268
|
Concrete `JobRunner` implementation backed by pg-boss. Constructor signature: `new PgBossJobRunner(container: Container, registrations: PgBossJobRegistryMap, pgboss: PgBoss, logger: Logger)`. Calls `pgboss.start()` during `start()` and `pgboss.stop()` during `stop()`. Job instances are resolved from the DI container on each invocation. Typically resolved through the DI container rather than instantiated directly.
|
|
219
269
|
|
|
270
|
+
Exposes a `cancelPollIntervalSeconds` property (default `5`) that controls how often a running job is polled for cancellation; set it to `0` to disable polling. See [Cancelling jobs](#cancelling-jobs).
|
|
271
|
+
|
|
220
272
|
## Graceful Shutdown
|
|
221
273
|
|
|
222
274
|
Ensure you stop the runner during application shutdown:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/job.broker.ts","../src/job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\nimport { JobSendOptions } from './job.send.options.js';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue, cancelling and\n * inspecting jobs, and managing scheduled jobs. It provides the producer-side\n * interface for the job processing system.\n *\n * Backends differ in what they can do. Operations a backend cannot honor throw\n * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // Sending a job immediately (returns the job id)\n * const id = await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Deferring a job: run it no earlier than five minutes from now\n * await jobBroker.send('send-email', payload, {\n * startAfter: Duration.fromObject({ minutes: 5 })\n * });\n *\n * // Deferring to an absolute time\n * await jobBroker.send('send-email', payload, {\n * startAfter: DateTime.now().plus({ hours: 2 })\n * });\n *\n * // Cancelling it later, whether it is still queued or already running\n * await jobBroker.cancel('send-email', id);\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue.\n *\n * By default the job is eligible for immediate processing and will be picked\n * up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}\n * to defer it: the job becomes eligible only once the given delay has elapsed\n * (a {@link Duration}) or the given moment has passed (a {@link DateTime}).\n * Deferral is a lower bound, not a guarantee of exact-time execution — the job\n * runs at the first opportunity after it becomes eligible.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job. The id can\n * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or\n * {@link getJob}.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if `options.startAfter` requests a deferral the\n * backend cannot honor (e.g. a delay beyond the backend's maximum).\n */\n abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n\n /**\n * Requests cancellation of one or more jobs.\n *\n * Cancellation is best-effort and applies regardless of the job's state: a\n * job that is still queued is prevented from running, and a job that is\n * already running is asked to stop. For a running job, cancellation is\n * cooperative — the job's handler receives an aborted `AbortSignal` (see\n * {@link Job.run}) and must honor it. A handler that ignores the signal runs\n * to completion. Some backends may forcefully terminate the running compute\n * instead; this contract only guarantees the request is delivered.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot cancel jobs.\n */\n abstract cancel(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs in the `cancelled` state can be resumed; other states are\n * unaffected.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot resume jobs.\n */\n abstract resume(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Permanently deletes one or more jobs.\n *\n * Removes the job records entirely. Unlike {@link cancel}, a deleted job\n * leaves no `cancelled` record behind and cannot be resumed.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job type.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot report per-job state.\n */\n abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+CpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAgHtB;;;;;;AC/JA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;","names":["Injectable","JobBroker","Injectable","JobRunner"]}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,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,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
JobBroker,
|
|
3
3
|
JobRunner,
|
|
4
4
|
__name
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-GKXLBFUJ.js";
|
|
6
6
|
|
|
7
7
|
// src/job.ts
|
|
8
8
|
import { Injectable } from "injectkit";
|
|
@@ -21,9 +21,34 @@ var Job = class {
|
|
|
21
21
|
Job = _ts_decorate([
|
|
22
22
|
Injectable()
|
|
23
23
|
], Job);
|
|
24
|
+
|
|
25
|
+
// src/not.supported.error.ts
|
|
26
|
+
import { ServerkitError } from "@maroonedsoftware/errors";
|
|
27
|
+
var NotSupportedError = class extends ServerkitError {
|
|
28
|
+
static {
|
|
29
|
+
__name(this, "NotSupportedError");
|
|
30
|
+
}
|
|
31
|
+
/** The name of the operation that is not supported (e.g. `'cancel'`). */
|
|
32
|
+
operation;
|
|
33
|
+
/** The backend that does not support the operation, when known (e.g. `'sqs'`). */
|
|
34
|
+
backend;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a new NotSupportedError.
|
|
37
|
+
*
|
|
38
|
+
* @param operation - The name of the unsupported operation.
|
|
39
|
+
* @param backend - The backend that does not support it, if known.
|
|
40
|
+
*/
|
|
41
|
+
constructor(operation, backend) {
|
|
42
|
+
super(backend ? `Operation "${operation}" is not supported by the ${backend} job broker` : `Operation "${operation}" is not supported by this job broker`);
|
|
43
|
+
this.name = "NotSupportedError";
|
|
44
|
+
this.operation = operation;
|
|
45
|
+
this.backend = backend;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
24
48
|
export {
|
|
25
49
|
Job,
|
|
26
50
|
JobBroker,
|
|
27
|
-
JobRunner
|
|
51
|
+
JobRunner,
|
|
52
|
+
NotSupportedError
|
|
28
53
|
};
|
|
29
54
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../src/job.ts","../src/not.supported.error.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload, signal?: AbortSignal): Promise<void> {\n * // Long-running work should honor the signal so the job can be cancelled.\n * await emailService.send(payload.to, payload.subject, payload.body, { signal });\n * if (signal?.aborted) return;\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * The optional `signal` is aborted when the job is cancelled (see\n * {@link JobBroker.cancel}) or when the runner shuts down. Cancellation is\n * cooperative: long-running handlers should forward `signal` to the async\n * operations they perform (fetch, database queries, etc.) or periodically\n * check `signal.aborted` and return early. A handler that ignores the signal\n * cannot be interrupted and will run to completion.\n *\n * @param payload - The data required to execute the job.\n * @param signal - An {@link AbortSignal} that fires when the job is cancelled\n * or the runner stops. Optional; handlers may ignore it.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload, signal?: AbortSignal): Promise<void>;\n}\n","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Thrown by a {@link JobBroker} when a requested operation is not supported by\n * the underlying backend.\n *\n * Backends vary in what they can do: some queue implementations can cancel a\n * queued job but not look up its state, others cannot cancel individual jobs at\n * all. Rather than silently doing nothing (which hides bugs), a backend throws\n * this error from any capability it cannot honor.\n *\n * Extends {@link ServerkitError}, so `errorMiddleware` renders it (as a 500) and\n * the `withDetails` / `withCause` / `withInternalDetails` setters apply.\n *\n * The bundled pg-boss backend supports every operation and never throws this;\n * it exists as the shared vocabulary for future backends (e.g. SQS, Pub/Sub).\n *\n * @example\n * ```typescript\n * async cancel(): Promise<void> {\n * throw new NotSupportedError('cancel', 'sqs');\n * }\n * ```\n */\nexport class NotSupportedError extends ServerkitError {\n /** The name of the operation that is not supported (e.g. `'cancel'`). */\n readonly operation: string;\n /** The backend that does not support the operation, when known (e.g. `'sqs'`). */\n readonly backend?: string;\n\n /**\n * Creates a new NotSupportedError.\n *\n * @param operation - The name of the unsupported operation.\n * @param backend - The backend that does not support it, if known.\n */\n constructor(operation: string, backend?: string) {\n super(\n backend\n ? `Operation \"${operation}\" is not supported by the ${backend} job broker`\n : `Operation \"${operation}\" is not supported by this job broker`,\n );\n this.name = 'NotSupportedError';\n this.operation = operation;\n this.backend = backend;\n }\n}\n"],"mappings":";;;;;;;AAAA,SAASA,kBAAkB;;;;;;;;AA+BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;ACrDA,SAASC,sBAAsB;AAwBxB,IAAMC,oBAAN,cAAgCC,eAAAA;EAxBvC,OAwBuCA;;;;EAE5BC;;EAEAC;;;;;;;EAQT,YAAYD,WAAmBC,SAAkB;AAC/C,UACEA,UACI,cAAcD,SAAAA,6BAAsCC,OAAAA,gBACpD,cAAcD,SAAAA,uCAAgD;AAEpE,SAAKE,OAAO;AACZ,SAAKF,YAAYA;AACjB,SAAKC,UAAUA;EACjB;AACF;","names":["Injectable","Job","ServerkitError","NotSupportedError","ServerkitError","operation","backend","name"]}
|
package/dist/job.broker.d.ts
CHANGED
|
@@ -1,19 +1,38 @@
|
|
|
1
|
+
import { JobInfo } from './job.info.js';
|
|
2
|
+
import { JobSendOptions } from './job.send.options.js';
|
|
1
3
|
/**
|
|
2
4
|
* Abstract base class for job broker implementations.
|
|
3
5
|
*
|
|
4
|
-
* A job broker is responsible for sending jobs to a queue and
|
|
5
|
-
* scheduled jobs. It provides the producer-side
|
|
6
|
-
* processing system.
|
|
6
|
+
* A job broker is responsible for sending jobs to a queue, cancelling and
|
|
7
|
+
* inspecting jobs, and managing scheduled jobs. It provides the producer-side
|
|
8
|
+
* interface for the job processing system.
|
|
9
|
+
*
|
|
10
|
+
* Backends differ in what they can do. Operations a backend cannot honor throw
|
|
11
|
+
* a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss
|
|
12
|
+
* backend supports every operation.
|
|
7
13
|
*
|
|
8
14
|
* @example
|
|
9
15
|
* ```typescript
|
|
10
|
-
* // Sending a job immediately
|
|
11
|
-
* await jobBroker.send('send-email', {
|
|
16
|
+
* // Sending a job immediately (returns the job id)
|
|
17
|
+
* const id = await jobBroker.send('send-email', {
|
|
12
18
|
* to: 'user@example.com',
|
|
13
19
|
* subject: 'Welcome!',
|
|
14
20
|
* body: 'Thanks for signing up.'
|
|
15
21
|
* });
|
|
16
22
|
*
|
|
23
|
+
* // Deferring a job: run it no earlier than five minutes from now
|
|
24
|
+
* await jobBroker.send('send-email', payload, {
|
|
25
|
+
* startAfter: Duration.fromObject({ minutes: 5 })
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* // Deferring to an absolute time
|
|
29
|
+
* await jobBroker.send('send-email', payload, {
|
|
30
|
+
* startAfter: DateTime.now().plus({ hours: 2 })
|
|
31
|
+
* });
|
|
32
|
+
*
|
|
33
|
+
* // Cancelling it later, whether it is still queued or already running
|
|
34
|
+
* await jobBroker.cancel('send-email', id);
|
|
35
|
+
*
|
|
17
36
|
* // Scheduling a recurring job with cron
|
|
18
37
|
* await jobBroker.schedule('daily-report', '0 9 * * *', {
|
|
19
38
|
* reportType: 'sales'
|
|
@@ -25,18 +44,28 @@
|
|
|
25
44
|
*/
|
|
26
45
|
export declare abstract class JobBroker {
|
|
27
46
|
/**
|
|
28
|
-
* Sends a job to the queue
|
|
47
|
+
* Sends a job to the queue.
|
|
29
48
|
*
|
|
30
|
-
*
|
|
49
|
+
* By default the job is eligible for immediate processing and will be picked
|
|
50
|
+
* up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}
|
|
51
|
+
* to defer it: the job becomes eligible only once the given delay has elapsed
|
|
52
|
+
* (a {@link Duration}) or the given moment has passed (a {@link DateTime}).
|
|
53
|
+
* Deferral is a lower bound, not a guarantee of exact-time execution — the job
|
|
54
|
+
* runs at the first opportunity after it becomes eligible.
|
|
31
55
|
*
|
|
32
56
|
* @typeParam Payload - The type of the job payload. Must be an object.
|
|
33
57
|
* @param name - The unique name identifying the job type.
|
|
34
58
|
* Must match a registered job handler.
|
|
35
59
|
* @param payload - The data to pass to the job handler.
|
|
36
|
-
* @
|
|
60
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
61
|
+
* @returns A promise that resolves with the id of the queued job. The id can
|
|
62
|
+
* be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or
|
|
63
|
+
* {@link getJob}.
|
|
37
64
|
* @throws If the job name is not registered.
|
|
65
|
+
* @throws `NotSupportedError` if `options.startAfter` requests a deferral the
|
|
66
|
+
* backend cannot honor (e.g. a delay beyond the backend's maximum).
|
|
38
67
|
*/
|
|
39
|
-
abstract send<Payload extends object>(name: string, payload: Payload): Promise<
|
|
68
|
+
abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;
|
|
40
69
|
/**
|
|
41
70
|
* Schedules a recurring job using a cron expression.
|
|
42
71
|
*
|
|
@@ -63,5 +92,61 @@ export declare abstract class JobBroker {
|
|
|
63
92
|
* @throws If the job name is not registered.
|
|
64
93
|
*/
|
|
65
94
|
abstract unschedule(name: string): Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Requests cancellation of one or more jobs.
|
|
97
|
+
*
|
|
98
|
+
* Cancellation is best-effort and applies regardless of the job's state: a
|
|
99
|
+
* job that is still queued is prevented from running, and a job that is
|
|
100
|
+
* already running is asked to stop. For a running job, cancellation is
|
|
101
|
+
* cooperative — the job's handler receives an aborted `AbortSignal` (see
|
|
102
|
+
* {@link Job.run}) and must honor it. A handler that ignores the signal runs
|
|
103
|
+
* to completion. Some backends may forcefully terminate the running compute
|
|
104
|
+
* instead; this contract only guarantees the request is delivered.
|
|
105
|
+
*
|
|
106
|
+
* @param name - The name of the registered job type.
|
|
107
|
+
* @param id - A single job id, or an array of ids, to cancel.
|
|
108
|
+
* @returns A promise that resolves once the cancellation has been requested.
|
|
109
|
+
* @throws If the job name is not registered.
|
|
110
|
+
* @throws `NotSupportedError` if the backend cannot cancel jobs.
|
|
111
|
+
*/
|
|
112
|
+
abstract cancel(name: string, id: string | string[]): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* Resumes one or more previously cancelled jobs, re-queuing them for processing.
|
|
115
|
+
*
|
|
116
|
+
* Only jobs in the `cancelled` state can be resumed; other states are
|
|
117
|
+
* unaffected.
|
|
118
|
+
*
|
|
119
|
+
* @param name - The name of the registered job type.
|
|
120
|
+
* @param id - A single job id, or an array of ids, to resume.
|
|
121
|
+
* @returns A promise that resolves once the jobs have been re-queued.
|
|
122
|
+
* @throws If the job name is not registered.
|
|
123
|
+
* @throws `NotSupportedError` if the backend cannot resume jobs.
|
|
124
|
+
*/
|
|
125
|
+
abstract resume(name: string, id: string | string[]): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Permanently deletes one or more jobs.
|
|
128
|
+
*
|
|
129
|
+
* Removes the job records entirely. Unlike {@link cancel}, a deleted job
|
|
130
|
+
* leaves no `cancelled` record behind and cannot be resumed.
|
|
131
|
+
*
|
|
132
|
+
* @param name - The name of the registered job type.
|
|
133
|
+
* @param id - A single job id, or an array of ids, to delete.
|
|
134
|
+
* @returns A promise that resolves once the jobs have been deleted.
|
|
135
|
+
* @throws If the job name is not registered.
|
|
136
|
+
* @throws `NotSupportedError` if the backend cannot delete jobs.
|
|
137
|
+
*/
|
|
138
|
+
abstract deleteJob(name: string, id: string | string[]): Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* Looks up the current state of a single job.
|
|
141
|
+
*
|
|
142
|
+
* @typeParam Payload - The type of the job payload.
|
|
143
|
+
* @param name - The name of the registered job type.
|
|
144
|
+
* @param id - The id of the job to look up.
|
|
145
|
+
* @returns A promise that resolves with the {@link JobInfo} for the job, or
|
|
146
|
+
* `null` if no job with that id exists.
|
|
147
|
+
* @throws If the job name is not registered.
|
|
148
|
+
* @throws `NotSupportedError` if the backend cannot report per-job state.
|
|
149
|
+
*/
|
|
150
|
+
abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;
|
|
66
151
|
}
|
|
67
152
|
//# sourceMappingURL=job.broker.d.ts.map
|
package/dist/job.broker.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;A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10 @@
|
|
|
18
18
|
*
|
|
19
19
|
* @Injectable()
|
|
20
20
|
* class SendEmailJob extends Job<EmailPayload> {
|
|
21
|
-
* async run(payload: EmailPayload): Promise<void> {
|
|
22
|
-
*
|
|
21
|
+
* async run(payload: EmailPayload, signal?: AbortSignal): Promise<void> {
|
|
22
|
+
* // Long-running work should honor the signal so the job can be cancelled.
|
|
23
|
+
* await emailService.send(payload.to, payload.subject, payload.body, { signal });
|
|
24
|
+
* if (signal?.aborted) return;
|
|
23
25
|
* }
|
|
24
26
|
* }
|
|
25
27
|
* ```
|
|
@@ -32,10 +34,19 @@ export declare abstract class Job<Payload extends object = object> {
|
|
|
32
34
|
* and ready for processing. Implementations should contain the
|
|
33
35
|
* business logic for handling the job.
|
|
34
36
|
*
|
|
37
|
+
* The optional `signal` is aborted when the job is cancelled (see
|
|
38
|
+
* {@link JobBroker.cancel}) or when the runner shuts down. Cancellation is
|
|
39
|
+
* cooperative: long-running handlers should forward `signal` to the async
|
|
40
|
+
* operations they perform (fetch, database queries, etc.) or periodically
|
|
41
|
+
* check `signal.aborted` and return early. A handler that ignores the signal
|
|
42
|
+
* cannot be interrupted and will run to completion.
|
|
43
|
+
*
|
|
35
44
|
* @param payload - The data required to execute the job.
|
|
45
|
+
* @param signal - An {@link AbortSignal} that fires when the job is cancelled
|
|
46
|
+
* or the runner stops. Optional; handlers may ignore it.
|
|
36
47
|
* @returns A promise that resolves when the job completes successfully.
|
|
37
48
|
* @throws If the job fails, the error will be caught and logged by the runner.
|
|
38
49
|
*/
|
|
39
|
-
abstract run(payload: Payload): Promise<void>;
|
|
50
|
+
abstract run(payload: Payload, signal?: AbortSignal): Promise<void>;
|
|
40
51
|
}
|
|
41
52
|
//# sourceMappingURL=job.d.ts.map
|
package/dist/job.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job.d.ts","sourceRoot":"","sources":["../src/job.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"job.d.ts","sourceRoot":"","sources":["../src/job.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,8BACsB,GAAG,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM;IACvD;;;;;;;;;;;;;;;;;;;OAmBG;IACH,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;CACpE"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lifecycle state of a job, normalized across backends.
|
|
3
|
+
*
|
|
4
|
+
* These are the lowest-common-denominator states that a job broker can report.
|
|
5
|
+
* Backends map their native states to the nearest value here:
|
|
6
|
+
*
|
|
7
|
+
* - `created` — enqueued and waiting to be picked up by a worker.
|
|
8
|
+
* - `retry` — failed at least once and waiting to be retried.
|
|
9
|
+
* - `active` — currently being executed by a worker.
|
|
10
|
+
* - `completed` — finished successfully.
|
|
11
|
+
* - `cancelled` — cancelled before or during execution (see {@link JobBroker.cancel}).
|
|
12
|
+
* - `failed` — finished unsuccessfully after exhausting retries.
|
|
13
|
+
*
|
|
14
|
+
* Not every backend can express every state. A backend that lacks per-job state
|
|
15
|
+
* tracking may be unable to implement {@link JobBroker.getJob} at all and should
|
|
16
|
+
* throw a `NotSupportedError` instead of guessing.
|
|
17
|
+
*/
|
|
18
|
+
export type JobState = 'created' | 'retry' | 'active' | 'completed' | 'cancelled' | 'failed';
|
|
19
|
+
/**
|
|
20
|
+
* A backend-agnostic snapshot of a single job.
|
|
21
|
+
*
|
|
22
|
+
* Returned by {@link JobBroker.getJob}. It deliberately exposes only the fields
|
|
23
|
+
* every supported backend can provide, so callers can reason about jobs without
|
|
24
|
+
* coupling to a specific queue implementation (pg-boss, a future AWS/GCP backend, etc.).
|
|
25
|
+
*
|
|
26
|
+
* @typeParam Payload - The type of the job payload.
|
|
27
|
+
*/
|
|
28
|
+
export interface JobInfo<Payload extends object = object> {
|
|
29
|
+
/** The unique identifier of the job, as returned by {@link JobBroker.send}. */
|
|
30
|
+
id: string;
|
|
31
|
+
/** The name of the job type (the queue the job belongs to). */
|
|
32
|
+
name: string;
|
|
33
|
+
/** The current lifecycle {@link JobState} of the job. */
|
|
34
|
+
state: JobState;
|
|
35
|
+
/** The payload the job was enqueued with. */
|
|
36
|
+
data: Payload;
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=job.info.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job.info.d.ts","sourceRoot":"","sources":["../src/job.info.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,QAAQ,GAAG,WAAW,GAAG,WAAW,GAAG,QAAQ,CAAC;AAE7F;;;;;;;;GAQG;AACH,MAAM,WAAW,OAAO,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM;IACtD,+EAA+E;IAC/E,EAAE,EAAE,MAAM,CAAC;IACX,+DAA+D;IAC/D,IAAI,EAAE,MAAM,CAAC;IACb,yDAAyD;IACzD,KAAK,EAAE,QAAQ,CAAC;IAChB,6CAA6C;IAC7C,IAAI,EAAE,OAAO,CAAC;CACf"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { DateTime, Duration } from 'luxon';
|
|
2
|
+
/**
|
|
3
|
+
* Options controlling how a single job is enqueued by {@link JobBroker.send}.
|
|
4
|
+
*
|
|
5
|
+
* The options here are deliberately backend-agnostic: they describe *intent*
|
|
6
|
+
* ("run this no earlier than X"), not a particular queue's wire format. Each
|
|
7
|
+
* backend maps them onto its native mechanism, and a backend that cannot honor
|
|
8
|
+
* a requested option throws a `NotSupportedError` rather than silently ignoring
|
|
9
|
+
* it (see {@link JobBroker}).
|
|
10
|
+
*/
|
|
11
|
+
export interface JobSendOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Defer processing of the job until some point in the future.
|
|
14
|
+
*
|
|
15
|
+
* Accepts either form, so callers can express whichever they have naturally:
|
|
16
|
+
*
|
|
17
|
+
* - A Luxon {@link Duration} — a delay *relative* to now (e.g.
|
|
18
|
+
* `Duration.fromObject({ minutes: 5 })` runs the job no earlier than five
|
|
19
|
+
* minutes from enqueue time).
|
|
20
|
+
* - A Luxon {@link DateTime} — an *absolute* earliest-run time (e.g.
|
|
21
|
+
* `DateTime.now().plus({ hours: 2 })`).
|
|
22
|
+
*
|
|
23
|
+
* When omitted, the job is eligible for immediate processing.
|
|
24
|
+
*
|
|
25
|
+
* Backends map this onto their native deferral mechanism (pg-boss
|
|
26
|
+
* `startAfter`, SQS `DelaySeconds`, Cloud Tasks `scheduleTime`, …). Because
|
|
27
|
+
* those mechanisms differ in range — SQS caps delays at 15 minutes, for
|
|
28
|
+
* instance — a backend that cannot honor the requested delay throws a
|
|
29
|
+
* `NotSupportedError`.
|
|
30
|
+
*/
|
|
31
|
+
startAfter?: Duration | DateTime;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=job.send.options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job.send.options.d.ts","sourceRoot":"","sources":["../src/job.send.options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;;;;;;;;;;;;OAkBG;IACH,UAAU,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;CAClC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ServerkitError } from '@maroonedsoftware/errors';
|
|
2
|
+
/**
|
|
3
|
+
* Thrown by a {@link JobBroker} when a requested operation is not supported by
|
|
4
|
+
* the underlying backend.
|
|
5
|
+
*
|
|
6
|
+
* Backends vary in what they can do: some queue implementations can cancel a
|
|
7
|
+
* queued job but not look up its state, others cannot cancel individual jobs at
|
|
8
|
+
* all. Rather than silently doing nothing (which hides bugs), a backend throws
|
|
9
|
+
* this error from any capability it cannot honor.
|
|
10
|
+
*
|
|
11
|
+
* Extends {@link ServerkitError}, so `errorMiddleware` renders it (as a 500) and
|
|
12
|
+
* the `withDetails` / `withCause` / `withInternalDetails` setters apply.
|
|
13
|
+
*
|
|
14
|
+
* The bundled pg-boss backend supports every operation and never throws this;
|
|
15
|
+
* it exists as the shared vocabulary for future backends (e.g. SQS, Pub/Sub).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* async cancel(): Promise<void> {
|
|
20
|
+
* throw new NotSupportedError('cancel', 'sqs');
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare class NotSupportedError extends ServerkitError {
|
|
25
|
+
/** The name of the operation that is not supported (e.g. `'cancel'`). */
|
|
26
|
+
readonly operation: string;
|
|
27
|
+
/** The backend that does not support the operation, when known (e.g. `'sqs'`). */
|
|
28
|
+
readonly backend?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a new NotSupportedError.
|
|
31
|
+
*
|
|
32
|
+
* @param operation - The name of the unsupported operation.
|
|
33
|
+
* @param backend - The backend that does not support it, if known.
|
|
34
|
+
*/
|
|
35
|
+
constructor(operation: string, backend?: string);
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=not.supported.error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"not.supported.error.d.ts","sourceRoot":"","sources":["../src/not.supported.error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,iBAAkB,SAAQ,cAAc;IACnD,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,kFAAkF;IAClF,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAE1B;;;;;OAKG;gBACS,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAUhD"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { PgBoss } from 'pg-boss';
|
|
2
2
|
import { JobBroker } from '../job.broker.js';
|
|
3
|
+
import { JobInfo } from '../job.info.js';
|
|
4
|
+
import { JobSendOptions } from '../job.send.options.js';
|
|
3
5
|
import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
|
|
4
6
|
import { PgBossConnectionProvider } from './pgboss.connection.provider.js';
|
|
5
7
|
/**
|
|
@@ -46,19 +48,36 @@ export declare class PgBossJobBroker extends JobBroker {
|
|
|
46
48
|
*/
|
|
47
49
|
constructor(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider);
|
|
48
50
|
/**
|
|
49
|
-
* Sends a job to the PgBoss queue
|
|
51
|
+
* Sends a job to the PgBoss queue.
|
|
50
52
|
*
|
|
51
53
|
* The job-insert SQL runs against the executor returned by the injected
|
|
52
54
|
* {@link PgBossConnectionProvider}; when that executor is bound to an active
|
|
53
55
|
* transaction, the job is enqueued atomically with that transaction.
|
|
54
56
|
*
|
|
57
|
+
* When `options.startAfter` is supplied the job is deferred via pg-boss's
|
|
58
|
+
* native `startAfter`, which imposes no upper bound on the delay: a
|
|
59
|
+
* {@link Duration} is converted to a relative number of seconds and a
|
|
60
|
+
* {@link DateTime} to an absolute `Date`.
|
|
61
|
+
*
|
|
55
62
|
* @typeParam Payload - The type of the job payload.
|
|
56
63
|
* @param name - The name of the registered job to execute.
|
|
57
64
|
* @param payload - The data to pass to the job handler.
|
|
58
|
-
* @
|
|
65
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
66
|
+
* @returns A promise that resolves with the id of the queued job.
|
|
59
67
|
* @throws Error if the job name is not found in the registry.
|
|
68
|
+
* @throws Error if pg-boss does not return a job id (e.g. the job was
|
|
69
|
+
* deduplicated away by a singleton policy).
|
|
70
|
+
*/
|
|
71
|
+
send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;
|
|
72
|
+
/**
|
|
73
|
+
* Maps a backend-agnostic `startAfter` intent onto pg-boss's native
|
|
74
|
+
* `startAfter` option.
|
|
75
|
+
*
|
|
76
|
+
* A {@link Duration} becomes a relative number of seconds; a {@link DateTime}
|
|
77
|
+
* becomes an absolute `Date`. Returns an empty object when no deferral was
|
|
78
|
+
* requested so the field is simply omitted from the send options.
|
|
60
79
|
*/
|
|
61
|
-
|
|
80
|
+
private toStartAfter;
|
|
62
81
|
/**
|
|
63
82
|
* Schedules a recurring job using a cron expression.
|
|
64
83
|
*
|
|
@@ -89,5 +108,51 @@ export declare class PgBossJobBroker extends JobBroker {
|
|
|
89
108
|
* @throws Error if the job name is not found in the registry.
|
|
90
109
|
*/
|
|
91
110
|
unschedule(name: string): Promise<void>;
|
|
111
|
+
/**
|
|
112
|
+
* Cancels one or more jobs in the PgBoss queue.
|
|
113
|
+
*
|
|
114
|
+
* pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a
|
|
115
|
+
* job is still queued or already running: a queued job is never picked up,
|
|
116
|
+
* while a running job is observed as cancelled by the {@link PgBossJobRunner}
|
|
117
|
+
* (which polls for the state change and aborts the handler's `AbortSignal`).
|
|
118
|
+
* Interrupting a running handler is cooperative — see {@link Job.run}.
|
|
119
|
+
*
|
|
120
|
+
* @param name - The name of the registered job to cancel.
|
|
121
|
+
* @param id - A single job id, or an array of ids, to cancel.
|
|
122
|
+
* @returns A promise that resolves once the cancellation has been requested.
|
|
123
|
+
* @throws Error if the job name is not found in the registry.
|
|
124
|
+
*/
|
|
125
|
+
cancel(name: string, id: string | string[]): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Resumes one or more previously cancelled jobs, re-queuing them for processing.
|
|
128
|
+
*
|
|
129
|
+
* Only jobs currently in the `cancelled` state are affected.
|
|
130
|
+
*
|
|
131
|
+
* @param name - The name of the registered job to resume.
|
|
132
|
+
* @param id - A single job id, or an array of ids, to resume.
|
|
133
|
+
* @returns A promise that resolves once the jobs have been re-queued.
|
|
134
|
+
* @throws Error if the job name is not found in the registry.
|
|
135
|
+
*/
|
|
136
|
+
resume(name: string, id: string | string[]): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* Permanently deletes one or more jobs from the PgBoss queue.
|
|
139
|
+
*
|
|
140
|
+
* @param name - The name of the registered job to delete.
|
|
141
|
+
* @param id - A single job id, or an array of ids, to delete.
|
|
142
|
+
* @returns A promise that resolves once the jobs have been deleted.
|
|
143
|
+
* @throws Error if the job name is not found in the registry.
|
|
144
|
+
*/
|
|
145
|
+
deleteJob(name: string, id: string | string[]): Promise<void>;
|
|
146
|
+
/**
|
|
147
|
+
* Looks up the current state of a single job.
|
|
148
|
+
*
|
|
149
|
+
* @typeParam Payload - The type of the job payload.
|
|
150
|
+
* @param name - The name of the registered job to look up.
|
|
151
|
+
* @param id - The id of the job to look up.
|
|
152
|
+
* @returns A promise that resolves with the {@link JobInfo} for the job, or
|
|
153
|
+
* `null` if no job with that id exists.
|
|
154
|
+
* @throws Error if the job name is not found in the registry.
|
|
155
|
+
*/
|
|
156
|
+
getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;
|
|
92
157
|
}
|
|
93
158
|
//# sourceMappingURL=pgboss.job.broker.d.ts.map
|
|
@@ -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;
|
|
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;AAGjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAA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AAI,CAAC;IAQhE;;;;;;;OAOG;IACG,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQnE;;;;;;;;;OASG;IACG,MAAM,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CAYjG"}
|
|
@@ -39,6 +39,16 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
39
39
|
private readonly registrations;
|
|
40
40
|
private readonly pgboss;
|
|
41
41
|
private readonly logger;
|
|
42
|
+
/**
|
|
43
|
+
* How often, in seconds, a running job polls pg-boss to detect that it has
|
|
44
|
+
* been cancelled. When a poll observes the job is no longer present or its
|
|
45
|
+
* state is `cancelled`, the `AbortSignal` passed to the job's handler is
|
|
46
|
+
* aborted so cooperative handlers can stop. Set to `0` to disable polling
|
|
47
|
+
* (running jobs will then only be interruptible on shutdown/timeout).
|
|
48
|
+
*
|
|
49
|
+
* @default 5
|
|
50
|
+
*/
|
|
51
|
+
cancelPollIntervalSeconds: number;
|
|
42
52
|
/**
|
|
43
53
|
* Creates a new PgBossJobRunner instance.
|
|
44
54
|
*
|
|
@@ -64,6 +74,22 @@ export declare class PgBossJobRunner extends JobRunner {
|
|
|
64
74
|
* @returns A promise that resolves when all workers are registered with pg-boss.
|
|
65
75
|
*/
|
|
66
76
|
start(): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Polls pg-boss for a running job and aborts the given controller when the job
|
|
79
|
+
* has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
|
|
80
|
+
*
|
|
81
|
+
* This is what turns {@link PgBossJobBroker.cancel} into a signal the running
|
|
82
|
+
* handler can observe, even when `cancel` is called from a different process:
|
|
83
|
+
* the cancellation is a state change on the shared PostgreSQL row, and every
|
|
84
|
+
* runner polls that row for the jobs it is currently executing.
|
|
85
|
+
*
|
|
86
|
+
* @param name - The queue/job name.
|
|
87
|
+
* @param id - The id of the running job to watch.
|
|
88
|
+
* @param controller - The controller to abort once cancellation is detected.
|
|
89
|
+
* @returns A function that stops the poll; always call it when the job finishes.
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
private watchForCancellation;
|
|
67
93
|
/**
|
|
68
94
|
* Stops the job runner gracefully.
|
|
69
95
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAclD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;
|
|
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,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAclD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAqB1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAvBzB;;;;;;;;OAQG;IACH,yBAAyB,SAAK;IAE9B;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;OAcG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
|
package/dist/pgboss.js
CHANGED
|
@@ -2,11 +2,12 @@ import {
|
|
|
2
2
|
JobBroker,
|
|
3
3
|
JobRunner,
|
|
4
4
|
__name
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-GKXLBFUJ.js";
|
|
6
6
|
|
|
7
7
|
// src/pgboss/pgboss.job.broker.ts
|
|
8
8
|
import { PgBoss } from "pg-boss";
|
|
9
9
|
import { Injectable as Injectable3 } from "injectkit";
|
|
10
|
+
import { DateTime, Duration } from "luxon";
|
|
10
11
|
|
|
11
12
|
// src/pgboss/pgboss.job.registration.ts
|
|
12
13
|
import { Injectable } from "injectkit";
|
|
@@ -86,25 +87,59 @@ var PgBossJobBroker = class extends JobBroker {
|
|
|
86
87
|
super(), this.registrations = registrations, this.pgboss = pgboss, this.connectionProvider = connectionProvider;
|
|
87
88
|
}
|
|
88
89
|
/**
|
|
89
|
-
* Sends a job to the PgBoss queue
|
|
90
|
+
* Sends a job to the PgBoss queue.
|
|
90
91
|
*
|
|
91
92
|
* The job-insert SQL runs against the executor returned by the injected
|
|
92
93
|
* {@link PgBossConnectionProvider}; when that executor is bound to an active
|
|
93
94
|
* transaction, the job is enqueued atomically with that transaction.
|
|
94
95
|
*
|
|
96
|
+
* When `options.startAfter` is supplied the job is deferred via pg-boss's
|
|
97
|
+
* native `startAfter`, which imposes no upper bound on the delay: a
|
|
98
|
+
* {@link Duration} is converted to a relative number of seconds and a
|
|
99
|
+
* {@link DateTime} to an absolute `Date`.
|
|
100
|
+
*
|
|
95
101
|
* @typeParam Payload - The type of the job payload.
|
|
96
102
|
* @param name - The name of the registered job to execute.
|
|
97
103
|
* @param payload - The data to pass to the job handler.
|
|
98
|
-
* @
|
|
104
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
105
|
+
* @returns A promise that resolves with the id of the queued job.
|
|
99
106
|
* @throws Error if the job name is not found in the registry.
|
|
107
|
+
* @throws Error if pg-boss does not return a job id (e.g. the job was
|
|
108
|
+
* deduplicated away by a singleton policy).
|
|
100
109
|
*/
|
|
101
|
-
async send(name, payload) {
|
|
110
|
+
async send(name, payload, options) {
|
|
102
111
|
if (!this.registrations.has(name)) {
|
|
103
112
|
throw new Error(`Job ${name} is not registered`);
|
|
104
113
|
}
|
|
105
|
-
await this.pgboss.send(name, payload, {
|
|
106
|
-
db: this.connectionProvider.executor()
|
|
114
|
+
const id = await this.pgboss.send(name, payload, {
|
|
115
|
+
db: this.connectionProvider.executor(),
|
|
116
|
+
...this.toStartAfter(options?.startAfter)
|
|
107
117
|
});
|
|
118
|
+
if (!id) {
|
|
119
|
+
throw new Error(`Failed to enqueue job ${name}`);
|
|
120
|
+
}
|
|
121
|
+
return id;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Maps a backend-agnostic `startAfter` intent onto pg-boss's native
|
|
125
|
+
* `startAfter` option.
|
|
126
|
+
*
|
|
127
|
+
* A {@link Duration} becomes a relative number of seconds; a {@link DateTime}
|
|
128
|
+
* becomes an absolute `Date`. Returns an empty object when no deferral was
|
|
129
|
+
* requested so the field is simply omitted from the send options.
|
|
130
|
+
*/
|
|
131
|
+
toStartAfter(startAfter) {
|
|
132
|
+
if (Duration.isDuration(startAfter)) {
|
|
133
|
+
return {
|
|
134
|
+
startAfter: startAfter.as("seconds")
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (DateTime.isDateTime(startAfter)) {
|
|
138
|
+
return {
|
|
139
|
+
startAfter: startAfter.toJSDate()
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return {};
|
|
108
143
|
}
|
|
109
144
|
/**
|
|
110
145
|
* Schedules a recurring job using a cron expression.
|
|
@@ -148,6 +183,90 @@ var PgBossJobBroker = class extends JobBroker {
|
|
|
148
183
|
}
|
|
149
184
|
await this.pgboss.unschedule(name);
|
|
150
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Cancels one or more jobs in the PgBoss queue.
|
|
188
|
+
*
|
|
189
|
+
* pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a
|
|
190
|
+
* job is still queued or already running: a queued job is never picked up,
|
|
191
|
+
* while a running job is observed as cancelled by the {@link PgBossJobRunner}
|
|
192
|
+
* (which polls for the state change and aborts the handler's `AbortSignal`).
|
|
193
|
+
* Interrupting a running handler is cooperative — see {@link Job.run}.
|
|
194
|
+
*
|
|
195
|
+
* @param name - The name of the registered job to cancel.
|
|
196
|
+
* @param id - A single job id, or an array of ids, to cancel.
|
|
197
|
+
* @returns A promise that resolves once the cancellation has been requested.
|
|
198
|
+
* @throws Error if the job name is not found in the registry.
|
|
199
|
+
*/
|
|
200
|
+
async cancel(name, id) {
|
|
201
|
+
if (!this.registrations.has(name)) {
|
|
202
|
+
throw new Error(`Job ${name} is not registered`);
|
|
203
|
+
}
|
|
204
|
+
await this.pgboss.cancel(name, id, {
|
|
205
|
+
db: this.connectionProvider.executor()
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Resumes one or more previously cancelled jobs, re-queuing them for processing.
|
|
210
|
+
*
|
|
211
|
+
* Only jobs currently in the `cancelled` state are affected.
|
|
212
|
+
*
|
|
213
|
+
* @param name - The name of the registered job to resume.
|
|
214
|
+
* @param id - A single job id, or an array of ids, to resume.
|
|
215
|
+
* @returns A promise that resolves once the jobs have been re-queued.
|
|
216
|
+
* @throws Error if the job name is not found in the registry.
|
|
217
|
+
*/
|
|
218
|
+
async resume(name, id) {
|
|
219
|
+
if (!this.registrations.has(name)) {
|
|
220
|
+
throw new Error(`Job ${name} is not registered`);
|
|
221
|
+
}
|
|
222
|
+
await this.pgboss.resume(name, id, {
|
|
223
|
+
db: this.connectionProvider.executor()
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Permanently deletes one or more jobs from the PgBoss queue.
|
|
228
|
+
*
|
|
229
|
+
* @param name - The name of the registered job to delete.
|
|
230
|
+
* @param id - A single job id, or an array of ids, to delete.
|
|
231
|
+
* @returns A promise that resolves once the jobs have been deleted.
|
|
232
|
+
* @throws Error if the job name is not found in the registry.
|
|
233
|
+
*/
|
|
234
|
+
async deleteJob(name, id) {
|
|
235
|
+
if (!this.registrations.has(name)) {
|
|
236
|
+
throw new Error(`Job ${name} is not registered`);
|
|
237
|
+
}
|
|
238
|
+
await this.pgboss.deleteJob(name, id, {
|
|
239
|
+
db: this.connectionProvider.executor()
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Looks up the current state of a single job.
|
|
244
|
+
*
|
|
245
|
+
* @typeParam Payload - The type of the job payload.
|
|
246
|
+
* @param name - The name of the registered job to look up.
|
|
247
|
+
* @param id - The id of the job to look up.
|
|
248
|
+
* @returns A promise that resolves with the {@link JobInfo} for the job, or
|
|
249
|
+
* `null` if no job with that id exists.
|
|
250
|
+
* @throws Error if the job name is not found in the registry.
|
|
251
|
+
*/
|
|
252
|
+
async getJob(name, id) {
|
|
253
|
+
if (!this.registrations.has(name)) {
|
|
254
|
+
throw new Error(`Job ${name} is not registered`);
|
|
255
|
+
}
|
|
256
|
+
const [job] = await this.pgboss.findJobs(name, {
|
|
257
|
+
id,
|
|
258
|
+
db: this.connectionProvider.executor()
|
|
259
|
+
});
|
|
260
|
+
if (!job) {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
id: job.id,
|
|
265
|
+
name: job.name,
|
|
266
|
+
state: job.state,
|
|
267
|
+
data: job.data
|
|
268
|
+
};
|
|
269
|
+
}
|
|
151
270
|
};
|
|
152
271
|
PgBossJobBroker = _ts_decorate3([
|
|
153
272
|
Injectable3(),
|
|
@@ -186,6 +305,16 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
186
305
|
pgboss;
|
|
187
306
|
logger;
|
|
188
307
|
/**
|
|
308
|
+
* How often, in seconds, a running job polls pg-boss to detect that it has
|
|
309
|
+
* been cancelled. When a poll observes the job is no longer present or its
|
|
310
|
+
* state is `cancelled`, the `AbortSignal` passed to the job's handler is
|
|
311
|
+
* aborted so cooperative handlers can stop. Set to `0` to disable polling
|
|
312
|
+
* (running jobs will then only be interruptible on shutdown/timeout).
|
|
313
|
+
*
|
|
314
|
+
* @default 5
|
|
315
|
+
*/
|
|
316
|
+
cancelPollIntervalSeconds = 5;
|
|
317
|
+
/**
|
|
189
318
|
* Creates a new PgBossJobRunner instance.
|
|
190
319
|
*
|
|
191
320
|
* @param container - The DI container for resolving job instances.
|
|
@@ -228,16 +357,63 @@ var PgBossJobRunner = class extends JobRunner {
|
|
|
228
357
|
await this.pgboss.work(name, async (jobs) => {
|
|
229
358
|
await Promise.allSettled(jobs.map(async (job) => {
|
|
230
359
|
const jobRunner = this.container.get(identifier);
|
|
360
|
+
const controller = new AbortController();
|
|
361
|
+
const pgSignal = job.signal;
|
|
362
|
+
const signal = AbortSignal.any(pgSignal ? [
|
|
363
|
+
controller.signal,
|
|
364
|
+
pgSignal
|
|
365
|
+
] : [
|
|
366
|
+
controller.signal
|
|
367
|
+
]);
|
|
368
|
+
const stopWatching = this.watchForCancellation(name, job.id, controller);
|
|
231
369
|
try {
|
|
232
|
-
await jobRunner.run(job.data);
|
|
370
|
+
await jobRunner.run(job.data, signal);
|
|
233
371
|
} catch (error) {
|
|
234
372
|
this.logger.error(error);
|
|
373
|
+
} finally {
|
|
374
|
+
stopWatching();
|
|
235
375
|
}
|
|
236
376
|
}));
|
|
237
377
|
});
|
|
238
378
|
}
|
|
239
379
|
}
|
|
240
380
|
/**
|
|
381
|
+
* Polls pg-boss for a running job and aborts the given controller when the job
|
|
382
|
+
* has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
|
|
383
|
+
*
|
|
384
|
+
* This is what turns {@link PgBossJobBroker.cancel} into a signal the running
|
|
385
|
+
* handler can observe, even when `cancel` is called from a different process:
|
|
386
|
+
* the cancellation is a state change on the shared PostgreSQL row, and every
|
|
387
|
+
* runner polls that row for the jobs it is currently executing.
|
|
388
|
+
*
|
|
389
|
+
* @param name - The queue/job name.
|
|
390
|
+
* @param id - The id of the running job to watch.
|
|
391
|
+
* @param controller - The controller to abort once cancellation is detected.
|
|
392
|
+
* @returns A function that stops the poll; always call it when the job finishes.
|
|
393
|
+
* @internal
|
|
394
|
+
*/
|
|
395
|
+
watchForCancellation(name, id, controller) {
|
|
396
|
+
if (this.cancelPollIntervalSeconds <= 0) {
|
|
397
|
+
return () => {
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
const timer = setInterval(async () => {
|
|
401
|
+
try {
|
|
402
|
+
const [job] = await this.pgboss.findJobs(name, {
|
|
403
|
+
id
|
|
404
|
+
});
|
|
405
|
+
if (!job || job.state === "cancelled") {
|
|
406
|
+
controller.abort();
|
|
407
|
+
clearInterval(timer);
|
|
408
|
+
}
|
|
409
|
+
} catch (error) {
|
|
410
|
+
this.logger.error(error);
|
|
411
|
+
}
|
|
412
|
+
}, this.cancelPollIntervalSeconds * 1e3);
|
|
413
|
+
timer.unref?.();
|
|
414
|
+
return () => clearInterval(timer);
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
241
417
|
* Stops the job runner gracefully.
|
|
242
418
|
*
|
|
243
419
|
* This method stops the pg-boss instance, which will:
|
package/dist/pgboss.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.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":";;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;;;ACD3B,SAAqBC,kBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACpDhG,SAASC,cAAAA,mBAAkB;;;;;;;;AA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oCzB,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;;;;;;;;;;;;;;;;EAiBA,MAAMC,QAAuB;AAC3B,UAAM,KAAKF,OAAOE,MAAK;AAEvB,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,YAAM,KAAKK,OAAOY,KAAKT,MAAM,OAAOU,SAAAA;AAClC,cAAMC,QAAQC,WACZF,KAAKG,IAAI,OAAMP,QAAAA;AACb,gBAAMQ,YAAY,KAAKnB,UAAUoB,IAASV,UAAAA;AAC1C,cAAI;AACF,kBAAMS,UAAUE,IAAIV,IAAIW,IAAI;UAC9B,SAASC,OAAO;AACd,iBAAKpB,OAAOoB,MAAMA,KAAAA;UACpB;QACF,CAAA,CAAA;MAEJ,CAAA;IACF;EACF;;;;;;;;;;;EAYA,MAAMC,OAAsB;AAC1B,UAAM,KAAKtB,OAAOsB,KAAI;EACxB;AACF;;;;;;;;;;;","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"]}
|
|
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 { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\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 * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * 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 const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n const stopWatching = this.watchForCancellation(name, job.id, controller);\n try {\n await jobRunner.run(job.data, signal);\n } catch (error) {\n this.logger.error(error);\n } finally {\n stopWatching();\n }\n }),\n );\n });\n }\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACpDhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;;;;;;;;;EAuBA,MAAMC,KAA6BC,MAAcC,SAAkBC,SAA2C;AAC5G,QAA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AAA;UACF;QACF,CAAA,CAAA;MAEJ,CAAA;IACF;EACF;;;;;;;;;;;;;;;;EAiBQC,qBAAqBvB,MAAcwB,IAAYR,YAAyC;AAC9F,QAAI,KAAKtB,6BAA6B,GAAG;AACvC,aAAO,MAAA;MAAO;IAChB;AAEA,UAAMkC,QAAQC,YAAY,YAAA;AACxB,UAAI;AACF,cAAM,CAACvB,GAAAA,IAAO,MAAM,KAAKT,OAAOiC,SAAS9B,MAAM;UAAEwB;QAAG,CAAA;AACpD,YAAI,CAAClB,OAAOA,IAAIyB,UAAU,aAAa;AACrCf,qBAAWgB,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAASD,OAAO;AACd,aAAK7B,OAAO6B,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAKjC,4BAA4B,GAAA;AAGpCkC,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKtC,OAAOsC,KAAI;EACxB;AACF;;;;;;;;;;;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","Promise","allSettled","map","jobRunner","get","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","watchForCancellation","id","run","data","error","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maroonedsoftware/jobbroker",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.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",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"repository": {
|
|
24
24
|
"type": "git",
|
|
25
|
-
"url": "https://github.com/MaroonedSoftware/serverkit.git"
|
|
25
|
+
"url": "git+https://github.com/MaroonedSoftware/serverkit.git"
|
|
26
26
|
},
|
|
27
27
|
"private": false,
|
|
28
28
|
"type": "module",
|
|
@@ -45,13 +45,16 @@
|
|
|
45
45
|
"dist/**"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"injectkit": "^1.
|
|
49
|
-
"
|
|
48
|
+
"injectkit": "^1.6.0",
|
|
49
|
+
"luxon": "^3.7.2",
|
|
50
|
+
"@maroonedsoftware/logger": "1.1.2",
|
|
51
|
+
"@maroonedsoftware/errors": "1.7.0"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"@repo/config-typescript": "0.1.0"
|
|
54
|
+
"@types/luxon": "^3.7.2",
|
|
55
|
+
"pg-boss": "^12.24.1",
|
|
56
|
+
"@repo/config-typescript": "0.1.0",
|
|
57
|
+
"@repo/config-eslint": "0.2.1"
|
|
55
58
|
},
|
|
56
59
|
"peerDependencies": {
|
|
57
60
|
"pg-boss": "^12.5.4"
|
|
@@ -1 +0,0 @@
|
|
|
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"]}
|