@maroonedsoftware/jobbroker 1.6.0 → 1.7.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Marooned Software
3
+ Copyright (c) 2026 Marooned Software
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
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 | Contents | Pulls in |
24
- |--------|----------|----------|
25
- | `@maroonedsoftware/jobbroker` | `Job`, `JobBroker`, `JobRunner` | nothing extra |
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
- await this.emailService.send(payload.to, payload.subject, payload.body);
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,23 @@ 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
+ // Inspect a job's current state
125
+ const info = await broker.getJob('send-email', id); // { id, name, state, data } | null
126
+
127
+ // Cancel it (works whether it is still queued or already running)
128
+ await broker.cancel('send-email', id);
129
+
130
+ // Bring a cancelled job back, or remove it entirely
131
+ await broker.resume('send-email', id);
132
+ await broker.deleteJob('send-email', id);
133
+
120
134
  // Schedule a recurring job programmatically
121
135
  await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
122
136
 
@@ -124,25 +138,53 @@ await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
124
138
  await broker.unschedule('cleanup');
125
139
  ```
126
140
 
141
+ ## Cancelling jobs
142
+
143
+ `broker.cancel(name, id)` requests cancellation of a job **whatever state it is in**:
144
+
145
+ - A job that is still **queued** is marked cancelled and never picked up by a worker.
146
+ - 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.
147
+
148
+ 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:
149
+
150
+ ```typescript
151
+ const runner = container.get(JobRunner) as PgBossJobRunner;
152
+ runner.cancelPollIntervalSeconds = 2; // default 5; set to 0 to disable polling
153
+ ```
154
+
155
+ Lower values reduce cancellation latency at the cost of one extra lookup query per running job per interval.
156
+
157
+ ### Backend portability
158
+
159
+ `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
+
127
161
  ## API Reference
128
162
 
129
163
  ### `Job<Payload>`
130
164
 
131
165
  Abstract base class for job handlers.
132
166
 
133
- | Method | Description |
134
- | -------------------------------------- | -------------------------------------- |
135
- | `run(payload: Payload): Promise<void>` | Execute the job with the given payload |
167
+ | Method | Description |
168
+ | ------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
169
+ | `run(payload: Payload, signal?: AbortSignal): Promise<void>` | Execute the job. `signal` is aborted on cancellation/shutdown; honoring it is optional. |
136
170
 
137
171
  ### `JobBroker`
138
172
 
139
- Abstract base class for sending jobs to the queue.
173
+ Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
174
+
175
+ | Method | Description |
176
+ | --------------------------------------------------------------------- | ------------------------------------------------------------------ |
177
+ | `send<P>(name: string, payload: P): Promise<string>` | Queue a job for immediate processing; resolves with the new job id |
178
+ | `schedule<P>(name: string, cron: string, payload?: P): Promise<void>` | Create a recurring job schedule |
179
+ | `unschedule(name: string): Promise<void>` | Remove a recurring job schedule |
180
+ | `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
181
+ | `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
182
+ | `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
183
+ | `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
184
 
141
- | Method | Description |
142
- | --------------------------------------------------------------------- | ------------------------------------ |
143
- | `send<P>(name: string, payload: P): Promise<void>` | Queue a job for immediate processing |
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 |
185
+ ### `JobInfo<Payload>` / `JobState`
186
+
187
+ 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
188
 
147
189
  ### `JobRunner`
148
190
 
@@ -166,22 +208,22 @@ Entries can be either:
166
208
 
167
209
  Configuration object for a scheduled job.
168
210
 
169
- | Property | Type | Description |
170
- | -------- | ------------------ | ---------------------------------------------------------- |
171
- | `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
172
- | `cron` | `string` | A cron expression defining when the job should run. |
211
+ | Property | Type | Description |
212
+ | -------- | ----------------- | ---------------------------------------------------------- |
213
+ | `job` | `Identifier<Job>` | The job class identifier to instantiate when the job runs. |
214
+ | `cron` | `string` | A cron expression defining when the job should run. |
173
215
 
174
216
  ### `PgBossJobBroker`
175
217
 
176
- Concrete `JobBroker` implementation backed by pg-boss. Constructor signature: `new PgBossJobBroker(registrations: PgBossJobRegistryMap, pgboss: PgBoss, connectionProvider: PgBossConnectionProvider)`. Each `send`/`schedule` call sources its pg-boss `db` executor from the injected `PgBossConnectionProvider`. Typically resolved through the DI container rather than instantiated directly.
218
+ 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
219
 
178
220
  ### `PgBossConnectionProvider`
179
221
 
180
222
  Supplies the pg-boss `db` executor used when enqueuing or scheduling jobs.
181
223
 
182
- | Method | Description |
183
- | ------------------------------- | ------------------------------------------------------------------------------------ |
184
- | `executor(): Db \| undefined` | The executor to run job-insert SQL against; `undefined` uses pg-boss's own pool. |
224
+ | Method | Description |
225
+ | ----------------------------- | -------------------------------------------------------------------------------- |
226
+ | `executor(): Db \| undefined` | The executor to run job-insert SQL against; `undefined` uses pg-boss's own pool. |
185
227
 
186
228
  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
229
 
@@ -217,6 +259,8 @@ await repository.withTransaction(async trx => {
217
259
 
218
260
  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
261
 
262
+ 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).
263
+
220
264
  ## Graceful Shutdown
221
265
 
222
266
  Ensure you stop the runner during application shutdown:
@@ -42,4 +42,4 @@ export {
42
42
  JobBroker,
43
43
  JobRunner
44
44
  };
45
- //# sourceMappingURL=chunk-AMXA75BW.js.map
45
+ //# sourceMappingURL=chunk-VPYK6KC5.js.map
@@ -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';\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"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from './job.broker.js';
2
2
  export * from './job.js';
3
+ export * from './job.info.js';
3
4
  export * from './job.runner.js';
5
+ export * from './not.supported.error.js';
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -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,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-AMXA75BW.js";
5
+ } from "./chunk-VPYK6KC5.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;;;;;;;;AA6BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAatB;;;;","names":["Injectable","Job"]}
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"]}
@@ -1,19 +1,27 @@
1
+ import { JobInfo } from './job.info.js';
1
2
  /**
2
3
  * Abstract base class for job broker implementations.
3
4
  *
4
- * A job broker is responsible for sending jobs to a queue and managing
5
- * scheduled jobs. It provides the producer-side interface for the job
6
- * processing system.
5
+ * A job broker is responsible for sending jobs to a queue, cancelling and
6
+ * inspecting jobs, and managing scheduled jobs. It provides the producer-side
7
+ * interface for the job processing system.
8
+ *
9
+ * Backends differ in what they can do. Operations a backend cannot honor throw
10
+ * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss
11
+ * backend supports every operation.
7
12
  *
8
13
  * @example
9
14
  * ```typescript
10
- * // Sending a job immediately
11
- * await jobBroker.send('send-email', {
15
+ * // Sending a job immediately (returns the job id)
16
+ * const id = await jobBroker.send('send-email', {
12
17
  * to: 'user@example.com',
13
18
  * subject: 'Welcome!',
14
19
  * body: 'Thanks for signing up.'
15
20
  * });
16
21
  *
22
+ * // Cancelling it later, whether it is still queued or already running
23
+ * await jobBroker.cancel('send-email', id);
24
+ *
17
25
  * // Scheduling a recurring job with cron
18
26
  * await jobBroker.schedule('daily-report', '0 9 * * *', {
19
27
  * reportType: 'sales'
@@ -33,10 +41,12 @@ export declare abstract class JobBroker {
33
41
  * @param name - The unique name identifying the job type.
34
42
  * Must match a registered job handler.
35
43
  * @param payload - The data to pass to the job handler.
36
- * @returns A promise that resolves when the job has been queued.
44
+ * @returns A promise that resolves with the id of the queued job. The id can
45
+ * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or
46
+ * {@link getJob}.
37
47
  * @throws If the job name is not registered.
38
48
  */
39
- abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;
49
+ abstract send<Payload extends object>(name: string, payload: Payload): Promise<string>;
40
50
  /**
41
51
  * Schedules a recurring job using a cron expression.
42
52
  *
@@ -63,5 +73,61 @@ export declare abstract class JobBroker {
63
73
  * @throws If the job name is not registered.
64
74
  */
65
75
  abstract unschedule(name: string): Promise<void>;
76
+ /**
77
+ * Requests cancellation of one or more jobs.
78
+ *
79
+ * Cancellation is best-effort and applies regardless of the job's state: a
80
+ * job that is still queued is prevented from running, and a job that is
81
+ * already running is asked to stop. For a running job, cancellation is
82
+ * cooperative — the job's handler receives an aborted `AbortSignal` (see
83
+ * {@link Job.run}) and must honor it. A handler that ignores the signal runs
84
+ * to completion. Some backends may forcefully terminate the running compute
85
+ * instead; this contract only guarantees the request is delivered.
86
+ *
87
+ * @param name - The name of the registered job type.
88
+ * @param id - A single job id, or an array of ids, to cancel.
89
+ * @returns A promise that resolves once the cancellation has been requested.
90
+ * @throws If the job name is not registered.
91
+ * @throws `NotSupportedError` if the backend cannot cancel jobs.
92
+ */
93
+ abstract cancel(name: string, id: string | string[]): Promise<void>;
94
+ /**
95
+ * Resumes one or more previously cancelled jobs, re-queuing them for processing.
96
+ *
97
+ * Only jobs in the `cancelled` state can be resumed; other states are
98
+ * unaffected.
99
+ *
100
+ * @param name - The name of the registered job type.
101
+ * @param id - A single job id, or an array of ids, to resume.
102
+ * @returns A promise that resolves once the jobs have been re-queued.
103
+ * @throws If the job name is not registered.
104
+ * @throws `NotSupportedError` if the backend cannot resume jobs.
105
+ */
106
+ abstract resume(name: string, id: string | string[]): Promise<void>;
107
+ /**
108
+ * Permanently deletes one or more jobs.
109
+ *
110
+ * Removes the job records entirely. Unlike {@link cancel}, a deleted job
111
+ * leaves no `cancelled` record behind and cannot be resumed.
112
+ *
113
+ * @param name - The name of the registered job type.
114
+ * @param id - A single job id, or an array of ids, to delete.
115
+ * @returns A promise that resolves once the jobs have been deleted.
116
+ * @throws If the job name is not registered.
117
+ * @throws `NotSupportedError` if the backend cannot delete jobs.
118
+ */
119
+ abstract deleteJob(name: string, id: string | string[]): Promise<void>;
120
+ /**
121
+ * Looks up the current state of a single job.
122
+ *
123
+ * @typeParam Payload - The type of the job payload.
124
+ * @param name - The name of the registered job type.
125
+ * @param id - The id of the job to look up.
126
+ * @returns A promise that resolves with the {@link JobInfo} for the job, or
127
+ * `null` if no job with that id exists.
128
+ * @throws If the job name is not registered.
129
+ * @throws `NotSupportedError` if the backend cannot report per-job state.
130
+ */
131
+ abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;
66
132
  }
67
133
  //# sourceMappingURL=job.broker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,8BACsB,SAAS;IAC7B;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAEpF;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAEvG;;;;;;;;;OASG;IACH,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CACjD"}
1
+ {"version":3,"file":"job.broker.d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}
package/dist/job.d.ts CHANGED
@@ -18,8 +18,10 @@
18
18
  *
19
19
  * @Injectable()
20
20
  * class SendEmailJob extends Job<EmailPayload> {
21
- * async run(payload: EmailPayload): Promise<void> {
22
- * await emailService.send(payload.to, payload.subject, payload.body);
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;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,8BACsB,GAAG,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM;IACvD;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAC9C"}
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,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,6 @@
1
1
  import { PgBoss } from 'pg-boss';
2
2
  import { JobBroker } from '../job.broker.js';
3
+ import { JobInfo } from '../job.info.js';
3
4
  import { PgBossJobRegistryMap } from './pgboss.job.registration.js';
4
5
  import { PgBossConnectionProvider } from './pgboss.connection.provider.js';
5
6
  /**
@@ -55,10 +56,12 @@ export declare class PgBossJobBroker extends JobBroker {
55
56
  * @typeParam Payload - The type of the job payload.
56
57
  * @param name - The name of the registered job to execute.
57
58
  * @param payload - The data to pass to the job handler.
58
- * @returns A promise that resolves when the job has been queued.
59
+ * @returns A promise that resolves with the id of the queued job.
59
60
  * @throws Error if the job name is not found in the registry.
61
+ * @throws Error if pg-boss does not return a job id (e.g. the job was
62
+ * deduplicated away by a singleton policy).
60
63
  */
61
- send<Payload extends object>(name: string, payload: Payload): Promise<void>;
64
+ send<Payload extends object>(name: string, payload: Payload): Promise<string>;
62
65
  /**
63
66
  * Schedules a recurring job using a cron expression.
64
67
  *
@@ -89,5 +92,51 @@ export declare class PgBossJobBroker extends JobBroker {
89
92
  * @throws Error if the job name is not found in the registry.
90
93
  */
91
94
  unschedule(name: string): Promise<void>;
95
+ /**
96
+ * Cancels one or more jobs in the PgBoss queue.
97
+ *
98
+ * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a
99
+ * job is still queued or already running: a queued job is never picked up,
100
+ * while a running job is observed as cancelled by the {@link PgBossJobRunner}
101
+ * (which polls for the state change and aborts the handler's `AbortSignal`).
102
+ * Interrupting a running handler is cooperative — see {@link Job.run}.
103
+ *
104
+ * @param name - The name of the registered job to cancel.
105
+ * @param id - A single job id, or an array of ids, to cancel.
106
+ * @returns A promise that resolves once the cancellation has been requested.
107
+ * @throws Error if the job name is not found in the registry.
108
+ */
109
+ cancel(name: string, id: string | string[]): Promise<void>;
110
+ /**
111
+ * Resumes one or more previously cancelled jobs, re-queuing them for processing.
112
+ *
113
+ * Only jobs currently in the `cancelled` state are affected.
114
+ *
115
+ * @param name - The name of the registered job to resume.
116
+ * @param id - A single job id, or an array of ids, to resume.
117
+ * @returns A promise that resolves once the jobs have been re-queued.
118
+ * @throws Error if the job name is not found in the registry.
119
+ */
120
+ resume(name: string, id: string | string[]): Promise<void>;
121
+ /**
122
+ * Permanently deletes one or more jobs from the PgBoss queue.
123
+ *
124
+ * @param name - The name of the registered job to delete.
125
+ * @param id - A single job id, or an array of ids, to delete.
126
+ * @returns A promise that resolves once the jobs have been deleted.
127
+ * @throws Error if the job name is not found in the registry.
128
+ */
129
+ deleteJob(name: string, id: string | string[]): Promise<void>;
130
+ /**
131
+ * Looks up the current state of a single job.
132
+ *
133
+ * @typeParam Payload - The type of the job payload.
134
+ * @param name - The name of the registered job to look up.
135
+ * @param id - The id of the job to look up.
136
+ * @returns A promise that resolves with the {@link JobInfo} for the job, or
137
+ * `null` if no job with that id exists.
138
+ * @throws Error if the job name is not found in the registry.
139
+ */
140
+ getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;
92
141
  }
93
142
  //# 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;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAW1C,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IAZrC;;;;;;;;OAQG;gBAEgB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,wBAAwB;IAK/D;;;;;;;;;;;;OAYG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQjF;;;;;;;;;;;;;;;;;OAiBG;IACG,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpG;;;;;;;;;OASG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO9C"}
1
+ {"version":3,"file":"pgboss.job.broker.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EA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;;;;;;;;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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B,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,7 +2,7 @@ import {
2
2
  JobBroker,
3
3
  JobRunner,
4
4
  __name
5
- } from "./chunk-AMXA75BW.js";
5
+ } from "./chunk-VPYK6KC5.js";
6
6
 
7
7
  // src/pgboss/pgboss.job.broker.ts
8
8
  import { PgBoss } from "pg-boss";
@@ -95,16 +95,22 @@ var PgBossJobBroker = class extends JobBroker {
95
95
  * @typeParam Payload - The type of the job payload.
96
96
  * @param name - The name of the registered job to execute.
97
97
  * @param payload - The data to pass to the job handler.
98
- * @returns A promise that resolves when the job has been queued.
98
+ * @returns A promise that resolves with the id of the queued job.
99
99
  * @throws Error if the job name is not found in the registry.
100
+ * @throws Error if pg-boss does not return a job id (e.g. the job was
101
+ * deduplicated away by a singleton policy).
100
102
  */
101
103
  async send(name, payload) {
102
104
  if (!this.registrations.has(name)) {
103
105
  throw new Error(`Job ${name} is not registered`);
104
106
  }
105
- await this.pgboss.send(name, payload, {
107
+ const id = await this.pgboss.send(name, payload, {
106
108
  db: this.connectionProvider.executor()
107
109
  });
110
+ if (!id) {
111
+ throw new Error(`Failed to enqueue job ${name}`);
112
+ }
113
+ return id;
108
114
  }
109
115
  /**
110
116
  * Schedules a recurring job using a cron expression.
@@ -148,6 +154,90 @@ var PgBossJobBroker = class extends JobBroker {
148
154
  }
149
155
  await this.pgboss.unschedule(name);
150
156
  }
157
+ /**
158
+ * Cancels one or more jobs in the PgBoss queue.
159
+ *
160
+ * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a
161
+ * job is still queued or already running: a queued job is never picked up,
162
+ * while a running job is observed as cancelled by the {@link PgBossJobRunner}
163
+ * (which polls for the state change and aborts the handler's `AbortSignal`).
164
+ * Interrupting a running handler is cooperative — see {@link Job.run}.
165
+ *
166
+ * @param name - The name of the registered job to cancel.
167
+ * @param id - A single job id, or an array of ids, to cancel.
168
+ * @returns A promise that resolves once the cancellation has been requested.
169
+ * @throws Error if the job name is not found in the registry.
170
+ */
171
+ async cancel(name, id) {
172
+ if (!this.registrations.has(name)) {
173
+ throw new Error(`Job ${name} is not registered`);
174
+ }
175
+ await this.pgboss.cancel(name, id, {
176
+ db: this.connectionProvider.executor()
177
+ });
178
+ }
179
+ /**
180
+ * Resumes one or more previously cancelled jobs, re-queuing them for processing.
181
+ *
182
+ * Only jobs currently in the `cancelled` state are affected.
183
+ *
184
+ * @param name - The name of the registered job to resume.
185
+ * @param id - A single job id, or an array of ids, to resume.
186
+ * @returns A promise that resolves once the jobs have been re-queued.
187
+ * @throws Error if the job name is not found in the registry.
188
+ */
189
+ async resume(name, id) {
190
+ if (!this.registrations.has(name)) {
191
+ throw new Error(`Job ${name} is not registered`);
192
+ }
193
+ await this.pgboss.resume(name, id, {
194
+ db: this.connectionProvider.executor()
195
+ });
196
+ }
197
+ /**
198
+ * Permanently deletes one or more jobs from the PgBoss queue.
199
+ *
200
+ * @param name - The name of the registered job to delete.
201
+ * @param id - A single job id, or an array of ids, to delete.
202
+ * @returns A promise that resolves once the jobs have been deleted.
203
+ * @throws Error if the job name is not found in the registry.
204
+ */
205
+ async deleteJob(name, id) {
206
+ if (!this.registrations.has(name)) {
207
+ throw new Error(`Job ${name} is not registered`);
208
+ }
209
+ await this.pgboss.deleteJob(name, id, {
210
+ db: this.connectionProvider.executor()
211
+ });
212
+ }
213
+ /**
214
+ * Looks up the current state of a single job.
215
+ *
216
+ * @typeParam Payload - The type of the job payload.
217
+ * @param name - The name of the registered job to look up.
218
+ * @param id - The id of the job to look up.
219
+ * @returns A promise that resolves with the {@link JobInfo} for the job, or
220
+ * `null` if no job with that id exists.
221
+ * @throws Error if the job name is not found in the registry.
222
+ */
223
+ async getJob(name, id) {
224
+ if (!this.registrations.has(name)) {
225
+ throw new Error(`Job ${name} is not registered`);
226
+ }
227
+ const [job] = await this.pgboss.findJobs(name, {
228
+ id,
229
+ db: this.connectionProvider.executor()
230
+ });
231
+ if (!job) {
232
+ return null;
233
+ }
234
+ return {
235
+ id: job.id,
236
+ name: job.name,
237
+ state: job.state,
238
+ data: job.data
239
+ };
240
+ }
151
241
  };
152
242
  PgBossJobBroker = _ts_decorate3([
153
243
  Injectable3(),
@@ -186,6 +276,16 @@ var PgBossJobRunner = class extends JobRunner {
186
276
  pgboss;
187
277
  logger;
188
278
  /**
279
+ * How often, in seconds, a running job polls pg-boss to detect that it has
280
+ * been cancelled. When a poll observes the job is no longer present or its
281
+ * state is `cancelled`, the `AbortSignal` passed to the job's handler is
282
+ * aborted so cooperative handlers can stop. Set to `0` to disable polling
283
+ * (running jobs will then only be interruptible on shutdown/timeout).
284
+ *
285
+ * @default 5
286
+ */
287
+ cancelPollIntervalSeconds = 5;
288
+ /**
189
289
  * Creates a new PgBossJobRunner instance.
190
290
  *
191
291
  * @param container - The DI container for resolving job instances.
@@ -228,16 +328,63 @@ var PgBossJobRunner = class extends JobRunner {
228
328
  await this.pgboss.work(name, async (jobs) => {
229
329
  await Promise.allSettled(jobs.map(async (job) => {
230
330
  const jobRunner = this.container.get(identifier);
331
+ const controller = new AbortController();
332
+ const pgSignal = job.signal;
333
+ const signal = AbortSignal.any(pgSignal ? [
334
+ controller.signal,
335
+ pgSignal
336
+ ] : [
337
+ controller.signal
338
+ ]);
339
+ const stopWatching = this.watchForCancellation(name, job.id, controller);
231
340
  try {
232
- await jobRunner.run(job.data);
341
+ await jobRunner.run(job.data, signal);
233
342
  } catch (error) {
234
343
  this.logger.error(error);
344
+ } finally {
345
+ stopWatching();
235
346
  }
236
347
  }));
237
348
  });
238
349
  }
239
350
  }
240
351
  /**
352
+ * Polls pg-boss for a running job and aborts the given controller when the job
353
+ * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
354
+ *
355
+ * This is what turns {@link PgBossJobBroker.cancel} into a signal the running
356
+ * handler can observe, even when `cancel` is called from a different process:
357
+ * the cancellation is a state change on the shared PostgreSQL row, and every
358
+ * runner polls that row for the jobs it is currently executing.
359
+ *
360
+ * @param name - The queue/job name.
361
+ * @param id - The id of the running job to watch.
362
+ * @param controller - The controller to abort once cancellation is detected.
363
+ * @returns A function that stops the poll; always call it when the job finishes.
364
+ * @internal
365
+ */
366
+ watchForCancellation(name, id, controller) {
367
+ if (this.cancelPollIntervalSeconds <= 0) {
368
+ return () => {
369
+ };
370
+ }
371
+ const timer = setInterval(async () => {
372
+ try {
373
+ const [job] = await this.pgboss.findJobs(name, {
374
+ id
375
+ });
376
+ if (!job || job.state === "cancelled") {
377
+ controller.abort();
378
+ clearInterval(timer);
379
+ }
380
+ } catch (error) {
381
+ this.logger.error(error);
382
+ }
383
+ }, this.cancelPollIntervalSeconds * 1e3);
384
+ timer.unref?.();
385
+ return () => clearInterval(timer);
386
+ }
387
+ /**
241
388
  * Stops the job runner gracefully.
242
389
  *
243
390
  * This method stops the pg-boss instance, which will:
@@ -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;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFXO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;EAeA,MAAMC,KAA6BC,MAAcC,SAAiC;AAChF,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I;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 { 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;;;;;;ACpDhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF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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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.6.0",
3
+ "version": "1.7.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",
@@ -46,6 +46,7 @@
46
46
  ],
47
47
  "dependencies": {
48
48
  "injectkit": "^1.5.0",
49
+ "@maroonedsoftware/errors": "1.7.0",
49
50
  "@maroonedsoftware/logger": "1.1.1"
50
51
  },
51
52
  "devDependencies": {
@@ -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"]}