@maroonedsoftware/jobbroker 1.7.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/README.md +9 -1
- package/dist/{chunk-VPYK6KC5.js → chunk-GKXLBFUJ.js} +1 -1
- package/dist/chunk-GKXLBFUJ.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/job.broker.d.ts +22 -3
- package/dist/job.broker.d.ts.map +1 -1
- package/dist/job.send.options.d.ts +33 -0
- package/dist/job.send.options.d.ts.map +1 -0
- package/dist/pgboss/pgboss.job.broker.d.ts +18 -2
- package/dist/pgboss/pgboss.job.broker.d.ts.map +1 -1
- package/dist/pgboss.js +33 -4
- package/dist/pgboss.js.map +1 -1
- package/package.json +9 -7
- package/dist/chunk-VPYK6KC5.js.map +0 -1
package/README.md
CHANGED
|
@@ -121,6 +121,12 @@ const id = await broker.send('send-email', {
|
|
|
121
121
|
body: 'Thanks for signing up.',
|
|
122
122
|
});
|
|
123
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
|
+
|
|
124
130
|
// Inspect a job's current state
|
|
125
131
|
const info = await broker.getJob('send-email', id); // { id, name, state, data } | null
|
|
126
132
|
|
|
@@ -158,6 +164,8 @@ Lower values reduce cancellation latency at the cost of one extra lookup query p
|
|
|
158
164
|
|
|
159
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.
|
|
160
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
|
+
|
|
161
169
|
## API Reference
|
|
162
170
|
|
|
163
171
|
### `Job<Payload>`
|
|
@@ -174,7 +182,7 @@ Abstract base class for sending, cancelling, and inspecting jobs. Operations a b
|
|
|
174
182
|
|
|
175
183
|
| Method | Description |
|
|
176
184
|
| --------------------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
177
|
-
| `send<P>(name: string, payload: P): Promise<string>`
|
|
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 |
|
|
178
186
|
| `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
|
|
179
187
|
| `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
|
|
180
188
|
| `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
|
|
@@ -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,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC"}
|
package/dist/index.js
CHANGED
package/dist/job.broker.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { JobInfo } from './job.info.js';
|
|
2
|
+
import { JobSendOptions } from './job.send.options.js';
|
|
2
3
|
/**
|
|
3
4
|
* Abstract base class for job broker implementations.
|
|
4
5
|
*
|
|
@@ -19,6 +20,16 @@ import { JobInfo } from './job.info.js';
|
|
|
19
20
|
* body: 'Thanks for signing up.'
|
|
20
21
|
* });
|
|
21
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
|
+
*
|
|
22
33
|
* // Cancelling it later, whether it is still queued or already running
|
|
23
34
|
* await jobBroker.cancel('send-email', id);
|
|
24
35
|
*
|
|
@@ -33,20 +44,28 @@ import { JobInfo } from './job.info.js';
|
|
|
33
44
|
*/
|
|
34
45
|
export declare abstract class JobBroker {
|
|
35
46
|
/**
|
|
36
|
-
* Sends a job to the queue
|
|
47
|
+
* Sends a job to the queue.
|
|
37
48
|
*
|
|
38
|
-
*
|
|
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.
|
|
39
55
|
*
|
|
40
56
|
* @typeParam Payload - The type of the job payload. Must be an object.
|
|
41
57
|
* @param name - The unique name identifying the job type.
|
|
42
58
|
* Must match a registered job handler.
|
|
43
59
|
* @param payload - The data to pass to the job handler.
|
|
60
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
44
61
|
* @returns A promise that resolves with the id of the queued job. The id can
|
|
45
62
|
* be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or
|
|
46
63
|
* {@link getJob}.
|
|
47
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).
|
|
48
67
|
*/
|
|
49
|
-
abstract send<Payload extends object>(name: string, payload: Payload): Promise<string>;
|
|
68
|
+
abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;
|
|
50
69
|
/**
|
|
51
70
|
* Schedules a recurring job using a cron expression.
|
|
52
71
|
*
|
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":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;
|
|
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,cAA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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"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { PgBoss } from 'pg-boss';
|
|
2
2
|
import { JobBroker } from '../job.broker.js';
|
|
3
3
|
import { JobInfo } from '../job.info.js';
|
|
4
|
+
import { JobSendOptions } from '../job.send.options.js';
|
|
4
5
|
import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
|
|
5
6
|
import { PgBossConnectionProvider } from './pgboss.connection.provider.js';
|
|
6
7
|
/**
|
|
@@ -47,21 +48,36 @@ export declare class PgBossJobBroker extends JobBroker {
|
|
|
47
48
|
*/
|
|
48
49
|
constructor(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider);
|
|
49
50
|
/**
|
|
50
|
-
* Sends a job to the PgBoss queue
|
|
51
|
+
* Sends a job to the PgBoss queue.
|
|
51
52
|
*
|
|
52
53
|
* The job-insert SQL runs against the executor returned by the injected
|
|
53
54
|
* {@link PgBossConnectionProvider}; when that executor is bound to an active
|
|
54
55
|
* transaction, the job is enqueued atomically with that transaction.
|
|
55
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
|
+
*
|
|
56
62
|
* @typeParam Payload - The type of the job payload.
|
|
57
63
|
* @param name - The name of the registered job to execute.
|
|
58
64
|
* @param payload - The data to pass to the job handler.
|
|
65
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
59
66
|
* @returns A promise that resolves with the id of the queued job.
|
|
60
67
|
* @throws Error if the job name is not found in the registry.
|
|
61
68
|
* @throws Error if pg-boss does not return a job id (e.g. the job was
|
|
62
69
|
* deduplicated away by a singleton policy).
|
|
63
70
|
*/
|
|
64
|
-
send<Payload extends object>(name: string, payload: Payload): Promise<string>;
|
|
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.
|
|
79
|
+
*/
|
|
80
|
+
private toStartAfter;
|
|
65
81
|
/**
|
|
66
82
|
* Schedules a recurring job using a cron expression.
|
|
67
83
|
*
|
|
@@ -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,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAW1C,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,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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,26 +87,33 @@ 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.
|
|
104
|
+
* @param options - Optional enqueue options, e.g. `startAfter` to defer the job.
|
|
98
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.
|
|
100
107
|
* @throws Error if pg-boss does not return a job id (e.g. the job was
|
|
101
108
|
* deduplicated away by a singleton policy).
|
|
102
109
|
*/
|
|
103
|
-
async send(name, payload) {
|
|
110
|
+
async send(name, payload, options) {
|
|
104
111
|
if (!this.registrations.has(name)) {
|
|
105
112
|
throw new Error(`Job ${name} is not registered`);
|
|
106
113
|
}
|
|
107
114
|
const id = await this.pgboss.send(name, payload, {
|
|
108
|
-
db: this.connectionProvider.executor()
|
|
115
|
+
db: this.connectionProvider.executor(),
|
|
116
|
+
...this.toStartAfter(options?.startAfter)
|
|
109
117
|
});
|
|
110
118
|
if (!id) {
|
|
111
119
|
throw new Error(`Failed to enqueue job ${name}`);
|
|
@@ -113,6 +121,27 @@ var PgBossJobBroker = class extends JobBroker {
|
|
|
113
121
|
return id;
|
|
114
122
|
}
|
|
115
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 {};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
116
145
|
* Schedules a recurring job using a cron expression.
|
|
117
146
|
*
|
|
118
147
|
* The job will be automatically enqueued by pg-boss according to the
|
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 { JobInfo } from '../job.info.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 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): 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, { db: this.connectionProvider.executor() });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\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;;;ACD3B,SAAqBC,kBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;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AAA;UAChC,SAASQ,OAAO;AACd,iBAAK7B,OAAO6B,MAAMA,KAAAA;UACpB,UAAA;AACEL,yBAAAA;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","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","has","Error","id","db","executor","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"]}
|
|
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,QAAI,CAAC,KAAKN,cAAcO,IAAIH,IAAAA,GAAO;AACjC,YAAM,IAAII,MAAM,OAAOJ,IAAAA,oBAAwB;IACjD;AAEA,UAAMK,KAAK,MAAM,KAAKR,OAAOE,KAAKC,MAAM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C,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",
|
|
@@ -45,14 +45,16 @@
|
|
|
45
45
|
"dist/**"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"injectkit": "^1.
|
|
49
|
-
"
|
|
50
|
-
"@maroonedsoftware/logger": "1.1.
|
|
48
|
+
"injectkit": "^1.6.0",
|
|
49
|
+
"luxon": "^3.7.2",
|
|
50
|
+
"@maroonedsoftware/logger": "1.1.2",
|
|
51
|
+
"@maroonedsoftware/errors": "1.7.0"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"@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"
|
|
56
58
|
},
|
|
57
59
|
"peerDependencies": {
|
|
58
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';\nimport { JobInfo } from './job.info.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 * // 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 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 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 */\n abstract send<Payload extends object>(name: string, payload: Payload): 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;;;;;;;;AAoCpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAwGtB;;;;;;AC5IA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;","names":["Injectable","JobBroker","Injectable","JobRunner"]}
|