@maroonedsoftware/jobbroker 1.12.2 → 1.13.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/AGENTS.md +47 -5
- package/README.md +51 -12
- package/dist/{chunk-MR3BBUMG.js → chunk-KI5S6IPU.js} +1 -1
- package/dist/chunk-KI5S6IPU.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/job.broker.d.ts +65 -11
- package/dist/job.broker.d.ts.map +1 -1
- package/dist/job.schedule.d.ts +23 -0
- package/dist/job.schedule.d.ts.map +1 -0
- package/dist/job.schedule.options.d.ts +65 -0
- package/dist/job.schedule.options.d.ts.map +1 -0
- package/dist/pgboss/pgboss.job.broker.d.ts +72 -14
- package/dist/pgboss/pgboss.job.broker.d.ts.map +1 -1
- package/dist/pgboss.js +141 -18
- package/dist/pgboss.js.map +1 -1
- package/package.json +6 -5
- package/dist/chunk-MR3BBUMG.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -45,8 +45,10 @@ Notably **not** a dependency: `kysely`. Transactional enqueue is supported throu
|
|
|
45
45
|
| `Job<Payload>` | abstract class | `@Injectable() abstract run(payload: Payload, signal?: AbortSignal): Promise<void>` | `Payload extends object = object`. |
|
|
46
46
|
| `JobBroker` | abstract class | `@Injectable()`. Producer side. | Unsupported operations throw `NotSupportedError` rather than no-op. |
|
|
47
47
|
| `#send` | method | `<P extends object>(name: string, payload: P, options?: JobSendOptions) => Promise<string>` | Returns the job id. Throws if `name` is not registered. |
|
|
48
|
-
| `#schedule` | method | `<P extends object>(name: string,
|
|
49
|
-
| `#unschedule` | method | `(name: string) => Promise<void>`
|
|
48
|
+
| `#schedule` | method | `<P extends object>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions) => Promise<void>` | Cron or RFC 5545 RRULE. One schedule per name and key; the same key replaces it. |
|
|
49
|
+
| `#unschedule` | method | `(name: string, key?: string) => Promise<void>` | Without `key`, removes only the unkeyed schedule. |
|
|
50
|
+
| `#getSchedules` | method | `<P extends object>(name: string, key?: string) => Promise<JobSchedule<P>[]>` | With `key`, at most one. Ordered by key. |
|
|
51
|
+
| `#previewSchedule` | method | `(recurrence: string, options?: JobSchedulePreviewOptions) => Promise<DateTime[]>` | Stores nothing. Validates as `schedule` does. Results are in `options.timeZone` (UTC by default). |
|
|
50
52
|
| `#cancel` / `#resume` / `#deleteJob` | method | `(name: string, id: string \| string[]) => Promise<void>` | `cancel` aborts the signal for a running job. |
|
|
51
53
|
| `#getJob` | method | `<P extends object>(name: string, id: string) => Promise<JobInfo<P> \| null>` | — |
|
|
52
54
|
| `JobRunner` | abstract class | `@Injectable()`. `start()`, `stop()` | Consumer side. `stop()` waits for in-flight jobs. |
|
|
@@ -54,6 +56,9 @@ Notably **not** a dependency: `kysely`. Transactional enqueue is supported throu
|
|
|
54
56
|
| `JobContext` | interface + abstract class | `{ id: string; name: string; signal: AbortSignal; expiresIn?: Duration }` | Declaration-merged so one symbol is both the type and the DI token. |
|
|
55
57
|
| `registerJobContext` | function | `<T extends Registry>(registry: T) => T` | **Required** if any service injects `JobContext`. Registers a throwing placeholder. |
|
|
56
58
|
| `JobSendOptions` | interface | `{ startAfter?: Duration \| DateTime }` | Relative delay or absolute earliest-run time. A lower bound, not exact scheduling. |
|
|
59
|
+
| `JobScheduleOptions` | interface | `{ key?: string; timeZone?: string; missed?: 'skip' \| 'once' }` | `timeZone` is IANA, UTC when omitted. `missed` defaults to the backend's (`skip` on pg-boss). |
|
|
60
|
+
| `JobSchedule<Payload>` | interface | `{ name, key, recurrence, timeZone, payload? }` | `key` is `''` for the unkeyed schedule. No backend bookkeeping fields. |
|
|
61
|
+
| `JobSchedulePreviewOptions` | interface | `{ timeZone?: string; from?: DateTime; count?: number }` | Occurrences are strictly after `from`, so paging passes the last one back in. |
|
|
57
62
|
| `JobQueuePolicy` | interface | `{ retryLimit?, retryDelay?: Duration, retryBackoff?, retryDelayMax?: Duration, expiresIn?: Duration, deadLetter?: string }` | Applied per queue when the runner starts. `expiresIn` is what surfaces as `JobContext.expiresIn`. |
|
|
58
63
|
| `JobWorkerPolicy` | interface | `{ concurrency?: number, batchSize?: number, pollInterval?: Duration }` | Configures the worker **this node** starts, not the queue. Applied when the runner registers the worker. |
|
|
59
64
|
| `JobInfo<Payload>` | interface | `{ id, name, state: JobState, data: Payload }` | Lowest common denominator across backends. |
|
|
@@ -129,7 +134,7 @@ Transactional enqueue — the job row commits with the business writes or not at
|
|
|
129
134
|
import { PgBossConnectionProvider, KyselyTransactionConnectionProvider } from '@maroonedsoftware/jobbroker/pgboss';
|
|
130
135
|
|
|
131
136
|
await db.transaction().execute(async trx => {
|
|
132
|
-
const scope = container.
|
|
137
|
+
const scope = container.createScopedContainer();
|
|
133
138
|
scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));
|
|
134
139
|
|
|
135
140
|
await orders.create(trx, order);
|
|
@@ -137,6 +142,31 @@ await db.transaction().execute(async trx => {
|
|
|
137
142
|
});
|
|
138
143
|
```
|
|
139
144
|
|
|
145
|
+
Keyed schedules put many schedules on one queue, each with its own key, zone and recurrence:
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
await broker.schedule(
|
|
149
|
+
'routine.run',
|
|
150
|
+
'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=0',
|
|
151
|
+
{ routineId },
|
|
152
|
+
{
|
|
153
|
+
key: routineId,
|
|
154
|
+
timeZone: person.timeZone,
|
|
155
|
+
missed: 'skip',
|
|
156
|
+
},
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
const [routine] = await broker.getSchedules('routine.run', routineId);
|
|
160
|
+
if (routine) {
|
|
161
|
+
const next = await broker.previewSchedule(routine.recurrence, { timeZone: routine.timeZone, count: 3 });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
await broker.unschedule('routine.run', routineId); // leaves every other routine's schedule alone
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Inside the transactional-enqueue scope above, `schedule` and `unschedule` commit or roll back with
|
|
168
|
+
the transaction.
|
|
169
|
+
|
|
140
170
|
See [.claude/skills/job](../../.claude/skills/job) for the generator and its examples.
|
|
141
171
|
|
|
142
172
|
## Rules for generated code
|
|
@@ -201,10 +231,20 @@ See [.claude/skills/job](../../.claude/skills/job) for the generator and its exa
|
|
|
201
231
|
reconciles onto the queue via `createQueue`/`updateQueue`, a worker policy configures only the
|
|
202
232
|
workers _this process_ starts. Two nodes on the same queue may use different values, and a change
|
|
203
233
|
takes effect on the next runner start for that node alone.
|
|
204
|
-
- **The peer floor is pg-boss >= 12.
|
|
234
|
+
- **The peer floor is pg-boss >= 12.38.0**, and it is load-bearing. `concurrency` maps to
|
|
205
235
|
`localConcurrency` (added in 12.6.0) and per-job settlement to `perJobResults` (added in 12.21.0).
|
|
206
236
|
An older peer would ignore `perJobResults`, take the handler's `JobResult[]` as the batch's single
|
|
207
|
-
output, and mark **every job complete, including the failed ones**.
|
|
237
|
+
output, and mark **every job complete, including the failed ones**. Keyed schedules need 12.38:
|
|
238
|
+
RRULE recurrences, `missed`, `previewSchedule`, and `unschedule` on a caller's connection all
|
|
239
|
+
arrived there.
|
|
240
|
+
- **`unschedule(name)` removes only the unkeyed schedule.** pg-boss reads a missing key as `''`,
|
|
241
|
+
so keyed schedules on the same name survive it. To clear a name, list it with `getSchedules` and
|
|
242
|
+
unschedule each key.
|
|
243
|
+
- **`getSchedules` is not transactional on pg-boss.** pg-boss offers no connection option for the
|
|
244
|
+
read, so it runs on pg-boss's own pool and does not see a schedule an uncommitted transaction
|
|
245
|
+
wrote. `schedule` and `unschedule` do run on the connection provider's executor.
|
|
246
|
+
- **A registry `cron` is the unkeyed schedule.** The runner schedules `PgBossJobRegistration.cron`
|
|
247
|
+
without a key or zone, so it lives beside any keyed schedules on that name and in UTC.
|
|
208
248
|
- **`JobQueueStats.failed` is a retained count**, bounded by the queue's retention policy, not an
|
|
209
249
|
all-time total. It goes down on its own.
|
|
210
250
|
- **`KyselyTransactionConnectionProvider` strips plugins before adapting the transaction.**
|
|
@@ -233,6 +273,8 @@ src/
|
|
|
233
273
|
job.context.ts JobContext (interface + token), registerJobContext
|
|
234
274
|
job.info.ts JobState, JobInfo
|
|
235
275
|
job.send.options.ts JobSendOptions
|
|
276
|
+
job.schedule.options.ts JobScheduleOptions, JobSchedulePreviewOptions
|
|
277
|
+
job.schedule.ts JobSchedule
|
|
236
278
|
job.queue.policy.ts JobQueuePolicy
|
|
237
279
|
job.worker.policy.ts JobWorkerPolicy
|
|
238
280
|
not.supported.error.ts NotSupportedError
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ A flexible background job processing library with support for scheduled and on-d
|
|
|
6
6
|
|
|
7
7
|
- **Abstract interfaces** for easy testing and alternative implementations
|
|
8
8
|
- **Dependency injection** support via [injectkit](https://www.npmjs.com/package/injectkit)
|
|
9
|
-
- **Scheduled jobs**
|
|
9
|
+
- **Scheduled jobs** on cron expressions or RFC 5545 recurrence rules, many per queue with their own key and time zone
|
|
10
10
|
- **On-demand jobs** for immediate execution
|
|
11
11
|
- **Cancellation** of queued _and_ running jobs, plus state lookup, delete, and resume
|
|
12
12
|
- **Per-queue retry & dead-letter policy** for retry limits, backoff, and poison-message capture
|
|
@@ -167,6 +167,39 @@ await broker.schedule('cleanup', '0 0 * * *', { olderThan: 30 });
|
|
|
167
167
|
await broker.unschedule('cleanup');
|
|
168
168
|
```
|
|
169
169
|
|
|
170
|
+
### Keyed schedules
|
|
171
|
+
|
|
172
|
+
A job name holds one schedule per key, so one queue can carry many independent schedules, each with its own recurrence, payload and time zone. Scheduling again with the same name and key replaces that schedule and leaves the others alone. A recurrence is a cron expression or an RFC 5545 recurrence rule.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
// One schedule per routine on a single queue, evaluated in the owner's zone
|
|
176
|
+
await broker.schedule(
|
|
177
|
+
'routine.run',
|
|
178
|
+
'FREQ=WEEKLY;BYDAY=MO,WE,FR;BYHOUR=9;BYMINUTE=0',
|
|
179
|
+
{ routineId },
|
|
180
|
+
{
|
|
181
|
+
key: routineId,
|
|
182
|
+
timeZone: 'America/Chicago',
|
|
183
|
+
missed: 'skip', // or 'once': send one job for the latest occurrence missed while nothing was running
|
|
184
|
+
},
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
// Read them back
|
|
188
|
+
const all = await broker.getSchedules('routine.run'); // JobSchedule[], ordered by key
|
|
189
|
+
const mine = await broker.getSchedules('routine.run', routineId); // [] when there is none
|
|
190
|
+
|
|
191
|
+
// Preview the next occurrences without storing anything (also validates the recurrence and zone)
|
|
192
|
+
const next = await broker.previewSchedule('FREQ=MONTHLY;BYMONTHDAY=1;BYHOUR=8;BYMINUTE=0', {
|
|
193
|
+
timeZone: 'Europe/Paris',
|
|
194
|
+
count: 3,
|
|
195
|
+
}); // DateTime[]
|
|
196
|
+
|
|
197
|
+
// Remove just this routine's schedule
|
|
198
|
+
await broker.unschedule('routine.run', routineId);
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Without a key, `schedule` and `unschedule` target the name's single unkeyed schedule, exactly as before, so `unschedule(name)` never touches keyed schedules. With pg-boss, `schedule` and `unschedule` both run on the `PgBossConnectionProvider` executor, so inside a transaction they commit or roll back with it (see [Transactional enqueue](#transactional-enqueue)). `getSchedules` always reads through pg-boss's own pool, so it does not see a schedule written by a transaction that has not committed.
|
|
202
|
+
|
|
170
203
|
## Job execution scope and `JobContext`
|
|
171
204
|
|
|
172
205
|
Each job execution runs in its own scoped DI container, created from the root container and disposed once the execution settles. This is the job-side counterpart of the per-request scope `serverKitContextMiddleware` creates: a service registered `asScoped()` gets a fresh instance per job, and any container-owned disposables the execution created are released when it finishes.
|
|
@@ -329,7 +362,7 @@ await runner.start();
|
|
|
329
362
|
|
|
330
363
|
When a registration declares no worker policy and no default is set, pg-boss's own defaults apply: one worker, one job per fetch.
|
|
331
364
|
|
|
332
|
-
> `concurrency` maps to pg-boss `localConcurrency` and per-job settlement to `perJobResults`, both of which the package's peer floor (**pg-boss >= 12.
|
|
365
|
+
> `concurrency` maps to pg-boss `localConcurrency` and per-job settlement to `perJobResults`, both of which the package's peer floor (**pg-boss >= 12.38.0**) guarantees.
|
|
333
366
|
|
|
334
367
|
## Monitoring & draining dead-letter queues
|
|
335
368
|
|
|
@@ -398,15 +431,21 @@ Injection token describing the job execution in flight, registered by the runner
|
|
|
398
431
|
|
|
399
432
|
Abstract base class for sending, cancelling, and inspecting jobs. Operations a backend cannot honor throw `NotSupportedError`.
|
|
400
433
|
|
|
401
|
-
| Method
|
|
402
|
-
|
|
|
403
|
-
| `send<P>(name: string, payload: P, options?: JobSendOptions): Promise<string>`
|
|
404
|
-
| `schedule<P>(name: string,
|
|
405
|
-
| `unschedule(name: string): Promise<void>`
|
|
406
|
-
| `
|
|
407
|
-
| `
|
|
408
|
-
| `
|
|
409
|
-
| `
|
|
434
|
+
| Method | Description |
|
|
435
|
+
| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
436
|
+
| `send<P>(name: string, payload: P, options?: JobSendOptions): Promise<string>` | Queue a job; resolves with the new job id. Pass `options.startAfter` (a Luxon `Duration` or `DateTime`) to defer it |
|
|
437
|
+
| `schedule<P>(name: string, recurrence: string, payload?: P, options?: JobScheduleOptions): Promise<void>` | Create or replace a recurring schedule on a cron expression or RFC 5545 recurrence rule. `options` take `key`, `timeZone` and `missed` |
|
|
438
|
+
| `unschedule(name: string, key?: string): Promise<void>` | Remove the schedule with that key, or the unkeyed one when `key` is omitted |
|
|
439
|
+
| `getSchedules<P>(name: string, key?: string): Promise<JobSchedule<P>[]>` | List a name's schedules, or the one with `key` |
|
|
440
|
+
| `previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]>` | Next occurrences of a recurrence, without storing anything. `options` take `timeZone`, `from` and `count` |
|
|
441
|
+
| `cancel(name: string, id: string \| string[]): Promise<void>` | Request cancellation of queued or running jobs (cooperative) |
|
|
442
|
+
| `resume(name: string, id: string \| string[]): Promise<void>` | Re-queue previously cancelled jobs |
|
|
443
|
+
| `deleteJob(name: string, id: string \| string[]): Promise<void>` | Permanently delete jobs |
|
|
444
|
+
| `getJob<P>(name: string, id: string): Promise<JobInfo<P> \| null>` | Look up a job's current state, or `null` if it does not exist |
|
|
445
|
+
|
|
446
|
+
### `JobScheduleOptions` / `JobSchedule<Payload>` / `JobSchedulePreviewOptions`
|
|
447
|
+
|
|
448
|
+
`JobScheduleOptions` is `{ key?, timeZone?, missed?: 'skip' | 'once' }`. `JobSchedule` is the backend-agnostic schedule `getSchedules` returns: `{ name, key, recurrence, timeZone, payload? }`, with `key` `''` for the unkeyed schedule and `timeZone` `'UTC'` when none was given. `JobSchedulePreviewOptions` is `{ timeZone?, from?: DateTime, count? }`.
|
|
410
449
|
|
|
411
450
|
### `JobInfo<Payload>` / `JobState`
|
|
412
451
|
|
|
@@ -575,7 +614,7 @@ process.on('SIGTERM', async () => {
|
|
|
575
614
|
|
|
576
615
|
## Peer Dependencies
|
|
577
616
|
|
|
578
|
-
- `pg-boss` ^12.
|
|
617
|
+
- `pg-boss` ^12.38.0 - PostgreSQL-based job queue
|
|
579
618
|
- `reflect-metadata` - Required by InjectKit for decorator metadata
|
|
580
619
|
|
|
581
620
|
## License
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/job.broker.ts","../src/job.context.ts","../src/job.monitor.ts","../src/job.runner.ts","../src/permanent.job.error.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\nimport { DateTime } from 'luxon';\nimport { JobInfo } from './job.info.js';\nimport { JobSchedule } from './job.schedule.js';\nimport { JobScheduleOptions, JobSchedulePreviewOptions } from './job.schedule.options.js';\nimport { JobSendOptions } from './job.send.options.js';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue, cancelling and\n * inspecting jobs, and managing scheduled jobs. It provides the producer-side\n * interface for the job processing system.\n *\n * Backends differ in what they can do. Operations a backend cannot honor throw\n * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // Sending a job immediately (returns the job id)\n * const id = await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Deferring a job: run it no earlier than five minutes from now\n * await jobBroker.send('send-email', payload, {\n * startAfter: Duration.fromObject({ minutes: 5 })\n * });\n *\n * // Deferring to an absolute time\n * await jobBroker.send('send-email', payload, {\n * startAfter: DateTime.now().plus({ hours: 2 })\n * });\n *\n * // Cancelling it later, whether it is still queued or already running\n * await jobBroker.cancel('send-email', id);\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Many schedules on one queue, each with its own key and time zone\n * await jobBroker.schedule('routine.run', 'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=0', { routineId }, {\n * key: routineId,\n * timeZone: 'America/Chicago',\n * });\n *\n * // Listing and previewing them\n * const [routine] = await jobBroker.getSchedules('routine.run', routineId);\n * const next = await jobBroker.previewSchedule(routine.recurrence, { timeZone: routine.timeZone, count: 3 });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * await jobBroker.unschedule('routine.run', routineId);\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue.\n *\n * By default the job is eligible for immediate processing and will be picked\n * up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}\n * to defer it: the job becomes eligible only once the given delay has elapsed\n * (a {@link Duration}) or the given moment has passed (a {@link DateTime}).\n * Deferral is a lower bound, not a guarantee of exact-time execution — the job\n * runs at the first opportunity after it becomes eligible.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job. The id can\n * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or\n * {@link getJob}.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if `options.startAfter` requests a deferral the\n * backend cannot honor (e.g. a delay beyond the backend's maximum).\n */\n abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;\n\n /**\n * Schedules a recurring job.\n *\n * The job is enqueued automatically on every occurrence of `recurrence`. A job\n * name holds one schedule per {@link JobScheduleOptions.key}: scheduling again\n * with the same name and key replaces that schedule (its recurrence, payload,\n * zone and missed policy), and schedules under other keys are untouched.\n * Without a key the call targets the name's single unkeyed schedule.\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 recurrence - A cron expression (e.g. `'0 9 * * *'` for daily at 09:00)\n * or an RFC 5545 recurrence rule (e.g.\n * `'FREQ=WEEKLY;BYDAY=MO,FR;BYHOUR=9;BYMINUTE=0'`).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @param options - Optional key, time zone and missed-occurrence policy.\n * @returns A promise that resolves when the schedule has been created or replaced.\n * @throws If the job name is not registered, or the recurrence or time zone is invalid.\n * @throws `NotSupportedError` if the backend cannot honour the key, the time\n * zone, the missed policy, or the recurrence's format.\n */\n abstract schedule<Payload extends object>(name: string, recurrence: string, payload?: Payload, options?: JobScheduleOptions): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the schedule with the given name and key.\n * Does not affect jobs that are already queued, nor schedules under other keys.\n * Without a key, only the name's unkeyed schedule is removed. Removing a\n * schedule that does not exist is not an error.\n *\n * @param name - The name of the scheduled job.\n * @param key - The key the schedule was created with, if any.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if a key is given and the backend does not support keyed schedules.\n */\n abstract unschedule(name: string, key?: string): Promise<void>;\n\n /**\n * Lists the schedules on a job name.\n *\n * @typeParam Payload - The type of the scheduled payload.\n * @param name - The name of the registered job type.\n * @param key - When given, only the schedule with this key (an array of at\n * most one). Pass `''` for the name's unkeyed schedule.\n * @returns A promise that resolves with the matching schedules, ordered by key.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot list schedules.\n */\n abstract getSchedules<Payload extends object>(name: string, key?: string): Promise<JobSchedule<Payload>[]>;\n\n /**\n * Computes the next occurrences of a recurrence without storing anything.\n *\n * Takes the same cron expressions and RFC 5545 recurrence rules as\n * {@link schedule} and rejects the same invalid ones, so it doubles as a\n * validation step before scheduling. The result describes the recurrence, not\n * delivery: a scheduled job lands at or shortly after each listed time.\n *\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param options - Optional time zone, starting point and count.\n * @returns A promise that resolves with the occurrences, earliest first, in\n * `options.timeZone` (UTC when omitted).\n * @throws If the recurrence, the time zone or the count is invalid.\n * @throws `NotSupportedError` if the backend cannot preview recurrences.\n */\n abstract previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]>;\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, Registry } from 'injectkit';\nimport { Duration } from 'luxon';\n\n/**\n * Metadata describing the job execution currently in flight.\n *\n * A {@link JobRunner} registers this against the {@link JobContext} injection token\n * in the per-execution scoped container, so any service resolved during that\n * execution can declare `JobContext` as a constructor dependency and see which\n * job it is running under. This is the job-side counterpart of ServerKit's\n * request context: it is what lets a logger, a metrics recorder, or an outbox\n * writer sitting deep in the dependency graph attribute its work to a job\n * without every layer threading the metadata through by hand.\n *\n * Only fields every backend can supply are declared here. In particular there is\n * no attempt/retry counter: pg-boss hands the work handler a bare `Job`, and the\n * retry count lives on `JobWithMetadata`, which would cost an extra query per\n * execution to fetch. Read it from {@link JobMonitor} when you need it.\n *\n * @example\n * ```typescript\n * @Injectable()\n * class AuditLog {\n * constructor(private readonly context: JobContext) {}\n *\n * record(message: string): void {\n * // Attributed to the job automatically, with no plumbing at the call site.\n * logger.info({ jobId: this.context.id, queue: this.context.name }, message);\n * }\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport interface JobContext {\n /** Backend-assigned identifier of the running job. Matches the id `JobBroker.send` returned. */\n id: string;\n /** Name of the queue the job was dequeued from, which is also its registered job name. */\n name: string;\n /**\n * Aborted when the job is cancelled (see {@link JobBroker.cancel}) or when the\n * runner shuts down. The same signal the runner passes to {@link Job.run}, exposed\n * here so collaborators can observe cancellation without the handler forwarding it.\n */\n signal: AbortSignal;\n /**\n * How long the backend allows this execution to run before it is considered\n * expired, when the backend reports a limit. Useful for deciding whether there\n * is time left to start another unit of work.\n */\n expiresIn?: Duration;\n}\n\n/**\n * Abstract class merged with the {@link JobContext} interface so it can serve as an\n * injectkit injection token. A {@link JobRunner} registers the live context against\n * this token in the execution-scoped container, so services can inject `JobContext`\n * and receive the job currently being run.\n *\n * Resolving it outside a job execution throws, exactly as resolving ServerKit's\n * request context outside a request does. A service that must work in both places\n * should not depend on it directly.\n */\n@Injectable()\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport abstract class JobContext implements JobContext {}\n\n/**\n * Registers the {@link JobContext} token so services may declare it as a dependency.\n *\n * Call this on the registry whenever any registered service injects `JobContext`.\n * `Registry.build()` validates the dependency graph up front and rejects a service\n * whose dependency has no registration, and the runner's per-execution override\n * cannot satisfy that check because it only exists at runtime, inside a scope.\n *\n * What this registers is a placeholder that throws when resolved. During a job the\n * runner's scoped override shadows it, so the real context is what gets injected;\n * anywhere else (at boot, in a request, from a singleton) resolution fails with an\n * explanation rather than handing back a fake context.\n *\n * @param registry - The registry to register into, before `build()`.\n * @returns The registry, for chaining.\n *\n * @example\n * ```typescript\n * const registry = new InjectKitRegistry();\n * registerJobContext(registry);\n * registry.register(SendEmailJob).useClass(SendEmailJob).asTransient();\n * const container = registry.build();\n * ```\n */\nexport const registerJobContext = <T extends Registry>(registry: T): T => {\n registry\n .register(JobContext)\n .useFactory(() => {\n throw new Error(\n 'JobContext is only available during a job execution. It cannot be resolved at boot, from a request scope, or from a singleton.',\n );\n })\n .asScoped();\n return registry;\n};\n","import { Injectable } from 'injectkit';\nimport { JobInfo } from './job.info.js';\n\n/**\n * A backend-agnostic snapshot of a single queue's depth and health, as returned\n * by {@link JobMonitor.getQueueStats}. Every count is a point-in-time reading;\n * poll it on a schedule (for example from a reconciliation job) to drive\n * alerting on a backlog or a growing dead-letter queue.\n *\n * The counts are the lowest common denominator every supported backend can\n * report. `failed` in particular is a *retained* count: it reflects failures\n * still held in the queue subject to the queue's retention policy, not an\n * all-time total.\n */\nexport interface JobQueueStats {\n /** The queue name these stats describe. */\n name: string;\n /** Jobs waiting to be processed (enqueued but not yet active). */\n queued: number;\n /** Jobs currently being executed by a worker. */\n active: number;\n /** Failed jobs still retained in the queue (bounded by the retention policy). */\n failed: number;\n /** All jobs still retained for the queue across every state. */\n total: number;\n}\n\n/**\n * Filters for {@link JobMonitor.listJobs}. All fields are optional; omitting them\n * lists every job currently retained in the queue (the common case when\n * inspecting a small dead-letter queue).\n */\nexport interface JobQueryOptions {\n /** Match a single job by its id. */\n id?: string;\n /** Match jobs whose payload contains these fields (a partial-match filter). */\n data?: Record<string, unknown>;\n /** Restrict the result to jobs still waiting to be processed. */\n queuedOnly?: boolean;\n}\n\n/**\n * Options for {@link JobMonitor.redrive}, which moves dead-lettered jobs out of a\n * queue and back into circulation.\n */\nexport interface JobRedriveOptions {\n /**\n * The queue to move jobs into. When omitted, each job returns to the queue it\n * originally came from before it was dead-lettered — the usual \"reprocess\"\n * behavior. Supply this to funnel everything into a specific queue instead.\n */\n destination?: string;\n /**\n * Only redrive jobs that originated from this source queue. Useful when a\n * single dead-letter queue collects failures from several source queues and\n * you want to drain just one source's worth.\n */\n sourceName?: string;\n /**\n * Maximum number of jobs to move in this call, oldest first. Call repeatedly\n * (or on a schedule) to drain a large dead-letter queue at a controlled rate.\n */\n limit?: number;\n}\n\n/**\n * Read-and-remediate interface for job queues, and in particular for\n * *dead-letter queues*: the queues that collect jobs which have exhausted their\n * retries (see the queue policy on the pg-boss backend's registration).\n *\n * Where {@link JobBroker} is the producer side (enqueue, cancel, inspect a job\n * you hold the id for) and {@link JobRunner} is the consumer side, `JobMonitor`\n * is the operator side: it lets a consumer answer \"how deep is this queue?\",\n * \"what is stuck in this dead-letter queue?\", and \"reprocess / discard those\n * jobs\". Unlike the broker, it operates on raw queue names and does **not**\n * require the queue to be registered, because a dead-letter queue is often an\n * unregistered sink with no worker of its own.\n *\n * Backends that cannot honor an operation throw a `NotSupportedError` rather than\n * silently doing nothing, matching the rest of the package. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // A reconciliation sweep over a money-critical dead-letter queue.\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * const stuck = await monitor.listJobs('charge.webhook.dead'); // inspect / log / alert\n * const moved = await monitor.redrive('charge.webhook.dead', { limit: 100 }); // drain back\n * }\n * ```\n */\n@Injectable()\nexport abstract class JobMonitor {\n /**\n * Reports the current depth and health of a queue.\n *\n * @param name - The queue name to inspect (may be an unregistered dead-letter queue).\n * @returns A promise resolving to the {@link JobQueueStats}, or `null` if no\n * queue with that name exists.\n * @throws `NotSupportedError` if the backend cannot report queue statistics.\n */\n abstract getQueueStats(name: string): Promise<JobQueueStats | null>;\n\n /**\n * Lists the jobs currently retained in a queue, optionally filtered.\n *\n * The primary use is inspecting a dead-letter queue: the returned\n * {@link JobInfo} objects expose each poison message's id, state, and original\n * payload so a consumer can decide whether to reprocess ({@link redrive}),\n * discard ({@link deleteJob}), or escalate it.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list (may be an unregistered dead-letter queue).\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns A promise resolving to the matching jobs (empty if none / no such queue).\n * @throws `NotSupportedError` if the backend cannot enumerate jobs.\n */\n abstract listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]>;\n\n /**\n * Moves dead-lettered jobs out of a queue and back into circulation, returning\n * the number of jobs moved.\n *\n * By default each job goes back to the source queue it was dead-lettered from,\n * so a worker can process it again; pass {@link JobRedriveOptions.destination}\n * to route them elsewhere, {@link JobRedriveOptions.sourceName} to drain only\n * one source's jobs from a shared dead-letter queue, and\n * {@link JobRedriveOptions.limit} to move at a controlled rate.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns A promise resolving to the count of jobs moved.\n * @throws `NotSupportedError` if the backend cannot redrive jobs.\n */\n abstract redrive(name: string, options?: JobRedriveOptions): Promise<number>;\n\n /**\n * Permanently deletes one or more jobs from a queue.\n *\n * This is the \"discard\" action for a dead-letter queue: a poison message that\n * should not be reprocessed is removed outright. Unlike {@link JobBroker.deleteJob},\n * it does not require the queue to be registered.\n *\n * @param name - The queue name the jobs live in.\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 `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Re-attempts one or more failed jobs *in place*, re-queuing them within their\n * current queue.\n *\n * Use this to re-run a job that failed in a queue that has its own worker. To\n * reprocess a job sitting in a dead-letter *sink* (a queue with no worker),\n * prefer {@link redrive}, which moves it back to a queue that can run it.\n *\n * @param name - The queue name the jobs live in.\n * @param id - A single job id, or an array of ids, to retry.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws `NotSupportedError` if the backend cannot retry jobs.\n */\n abstract retryJob(name: string, id: string | 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","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Thrown by a {@link Job} to declare that its failure is **permanent** — the\n * input will never succeed, so retrying it is wasted work.\n *\n * An ordinary error thrown from a handler is treated as transient: the job goes\n * back on the queue and burns its full retry budget before it is finally failed\n * (and dead-lettered, if the queue has a dead-letter queue). That is right for a\n * network blip or a rate limit, and wrong for a malformed payload or a `422`\n * from an upstream API — nothing about waiting makes those succeed.\n *\n * Throwing this instead skips the remaining retries and routes the job straight\n * to the queue's dead-letter queue, where it is preserved for inspection or\n * replay. A queue with no dead-letter queue simply fails the job terminally.\n *\n * Extends {@link ServerkitError}, so `errorMiddleware` renders it (as a 500) and\n * the `withDetails` / `withCause` / `withInternalDetails` setters apply. Attach\n * the offending field or upstream status with `withDetails` — it is persisted as\n * the job's output, which is what an operator reads when draining the queue.\n *\n * The runner matches this type with a direct `instanceof` and does **not** walk\n * the `cause` chain: the meaning is \"this handler declared the failure\n * permanent\", not \"something permanent happened somewhere underneath\". Wrapping\n * a transient error in one of these makes it permanent, deliberately.\n *\n * @example\n * ```typescript\n * async run(payload: DeliverWebhookPayload): Promise<void> {\n * const parsed = schema.safeParse(payload);\n * if (!parsed.success) {\n * throw new PermanentJobError('Malformed webhook payload').withDetails({ issues: parsed.error.issues });\n * }\n *\n * const response = await fetch(parsed.data.url, { method: 'POST' });\n * if (response.status === 422) {\n * // The receiver will reject this body every time; retrying cannot help.\n * throw new PermanentJobError(`Webhook rejected with ${response.status}`);\n * }\n * if (!response.ok) {\n * // Transient — let it retry with the queue's backoff.\n * throw new Error(`Webhook failed with ${response.status}`);\n * }\n * }\n * ```\n */\nexport class PermanentJobError extends ServerkitError {\n /**\n * Creates a new PermanentJobError.\n *\n * @param message - Why the job can never succeed.\n * @param options - Standard error options. To chain an underlying error, prefer\n * the inherited `withCause` setter.\n */\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'PermanentJobError';\n }\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA6DpB,IAAeC,YAAf,MAAeA;SAAAA;;;AA0JtB;;;;;;ACvNA,SAASC,cAAAA,mBAA4B;;;;;;;;AAgE9B,IAAeC,aAAf,MAAeA;SAAAA;;;AAAkC;;;;AA0BjD,IAAMC,qBAAqB,wBAAqBC,aAAAA;AACrDA,WACGC,SAASH,UAAAA,EACTI,WAAW,MAAA;AACV,UAAM,IAAIC,MACR,gIAAA;EAEJ,CAAA,EACCC,SAAQ;AACX,SAAOJ;AACT,GAVkC;;;AC1FlC,SAASK,cAAAA,mBAAkB;;;;;;;;AA6FpB,IAAeC,aAAf,MAAeA;SAAAA;;;AAwEtB;;;;;;ACrKA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;AC5CA,SAASC,sBAAsB;AA8CxB,IAAMC,oBAAN,cAAgCC,eAAAA;EA9CvC,OA8CuCA;;;;;;;;;;EAQrC,YAAYC,SAAiBC,SAA+B;AAC1D,UAAMD,SAASC,OAAAA;AACf,SAAKC,OAAO;EACd;AACF;","names":["Injectable","JobBroker","Injectable","JobContext","registerJobContext","registry","register","useFactory","Error","asScoped","Injectable","JobMonitor","Injectable","JobRunner","ServerkitError","PermanentJobError","ServerkitError","message","options","name"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export * from './job.js';
|
|
|
3
3
|
export * from './job.context.js';
|
|
4
4
|
export * from './job.info.js';
|
|
5
5
|
export * from './job.send.options.js';
|
|
6
|
+
export * from './job.schedule.options.js';
|
|
7
|
+
export * from './job.schedule.js';
|
|
6
8
|
export * from './job.queue.policy.js';
|
|
7
9
|
export * from './job.worker.policy.js';
|
|
8
10
|
export * from './job.monitor.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC"}
|
package/dist/index.js
CHANGED
package/dist/job.broker.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { DateTime } from 'luxon';
|
|
1
2
|
import { JobInfo } from './job.info.js';
|
|
3
|
+
import { JobSchedule } from './job.schedule.js';
|
|
4
|
+
import { JobScheduleOptions, JobSchedulePreviewOptions } from './job.schedule.options.js';
|
|
2
5
|
import { JobSendOptions } from './job.send.options.js';
|
|
3
6
|
/**
|
|
4
7
|
* Abstract base class for job broker implementations.
|
|
@@ -38,8 +41,19 @@ import { JobSendOptions } from './job.send.options.js';
|
|
|
38
41
|
* reportType: 'sales'
|
|
39
42
|
* });
|
|
40
43
|
*
|
|
44
|
+
* // Many schedules on one queue, each with its own key and time zone
|
|
45
|
+
* await jobBroker.schedule('routine.run', 'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=0', { routineId }, {
|
|
46
|
+
* key: routineId,
|
|
47
|
+
* timeZone: 'America/Chicago',
|
|
48
|
+
* });
|
|
49
|
+
*
|
|
50
|
+
* // Listing and previewing them
|
|
51
|
+
* const [routine] = await jobBroker.getSchedules('routine.run', routineId);
|
|
52
|
+
* const next = await jobBroker.previewSchedule(routine.recurrence, { timeZone: routine.timeZone, count: 3 });
|
|
53
|
+
*
|
|
41
54
|
* // Removing a scheduled job
|
|
42
55
|
* await jobBroker.unschedule('daily-report');
|
|
56
|
+
* await jobBroker.unschedule('routine.run', routineId);
|
|
43
57
|
* ```
|
|
44
58
|
*/
|
|
45
59
|
export declare abstract class JobBroker {
|
|
@@ -67,31 +81,71 @@ export declare abstract class JobBroker {
|
|
|
67
81
|
*/
|
|
68
82
|
abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;
|
|
69
83
|
/**
|
|
70
|
-
* Schedules a recurring job
|
|
84
|
+
* Schedules a recurring job.
|
|
71
85
|
*
|
|
72
|
-
* The job
|
|
73
|
-
*
|
|
86
|
+
* The job is enqueued automatically on every occurrence of `recurrence`. A job
|
|
87
|
+
* name holds one schedule per {@link JobScheduleOptions.key}: scheduling again
|
|
88
|
+
* with the same name and key replaces that schedule (its recurrence, payload,
|
|
89
|
+
* zone and missed policy), and schedules under other keys are untouched.
|
|
90
|
+
* Without a key the call targets the name's single unkeyed schedule.
|
|
74
91
|
*
|
|
75
92
|
* @typeParam Payload - The type of the job payload. Must be an object.
|
|
76
93
|
* @param name - The unique name identifying the job type.
|
|
77
94
|
* Must match a registered job handler.
|
|
78
|
-
* @param
|
|
95
|
+
* @param recurrence - A cron expression (e.g. `'0 9 * * *'` for daily at 09:00)
|
|
96
|
+
* or an RFC 5545 recurrence rule (e.g.
|
|
97
|
+
* `'FREQ=WEEKLY;BYDAY=MO,FR;BYHOUR=9;BYMINUTE=0'`).
|
|
79
98
|
* @param payload - Optional data to pass to the job handler on each execution.
|
|
80
|
-
* @
|
|
81
|
-
* @
|
|
99
|
+
* @param options - Optional key, time zone and missed-occurrence policy.
|
|
100
|
+
* @returns A promise that resolves when the schedule has been created or replaced.
|
|
101
|
+
* @throws If the job name is not registered, or the recurrence or time zone is invalid.
|
|
102
|
+
* @throws `NotSupportedError` if the backend cannot honour the key, the time
|
|
103
|
+
* zone, the missed policy, or the recurrence's format.
|
|
82
104
|
*/
|
|
83
|
-
abstract schedule<Payload extends object>(name: string,
|
|
105
|
+
abstract schedule<Payload extends object>(name: string, recurrence: string, payload?: Payload, options?: JobScheduleOptions): Promise<void>;
|
|
84
106
|
/**
|
|
85
107
|
* Removes a scheduled job.
|
|
86
108
|
*
|
|
87
|
-
* Stops the recurring execution of the
|
|
88
|
-
* Does not affect jobs that are already queued.
|
|
109
|
+
* Stops the recurring execution of the schedule with the given name and key.
|
|
110
|
+
* Does not affect jobs that are already queued, nor schedules under other keys.
|
|
111
|
+
* Without a key, only the name's unkeyed schedule is removed. Removing a
|
|
112
|
+
* schedule that does not exist is not an error.
|
|
89
113
|
*
|
|
90
|
-
* @param name - The
|
|
114
|
+
* @param name - The name of the scheduled job.
|
|
115
|
+
* @param key - The key the schedule was created with, if any.
|
|
91
116
|
* @returns A promise that resolves when the schedule has been removed.
|
|
92
117
|
* @throws If the job name is not registered.
|
|
118
|
+
* @throws `NotSupportedError` if a key is given and the backend does not support keyed schedules.
|
|
119
|
+
*/
|
|
120
|
+
abstract unschedule(name: string, key?: string): Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* Lists the schedules on a job name.
|
|
123
|
+
*
|
|
124
|
+
* @typeParam Payload - The type of the scheduled payload.
|
|
125
|
+
* @param name - The name of the registered job type.
|
|
126
|
+
* @param key - When given, only the schedule with this key (an array of at
|
|
127
|
+
* most one). Pass `''` for the name's unkeyed schedule.
|
|
128
|
+
* @returns A promise that resolves with the matching schedules, ordered by key.
|
|
129
|
+
* @throws If the job name is not registered.
|
|
130
|
+
* @throws `NotSupportedError` if the backend cannot list schedules.
|
|
131
|
+
*/
|
|
132
|
+
abstract getSchedules<Payload extends object>(name: string, key?: string): Promise<JobSchedule<Payload>[]>;
|
|
133
|
+
/**
|
|
134
|
+
* Computes the next occurrences of a recurrence without storing anything.
|
|
135
|
+
*
|
|
136
|
+
* Takes the same cron expressions and RFC 5545 recurrence rules as
|
|
137
|
+
* {@link schedule} and rejects the same invalid ones, so it doubles as a
|
|
138
|
+
* validation step before scheduling. The result describes the recurrence, not
|
|
139
|
+
* delivery: a scheduled job lands at or shortly after each listed time.
|
|
140
|
+
*
|
|
141
|
+
* @param recurrence - A cron expression or an RFC 5545 recurrence rule.
|
|
142
|
+
* @param options - Optional time zone, starting point and count.
|
|
143
|
+
* @returns A promise that resolves with the occurrences, earliest first, in
|
|
144
|
+
* `options.timeZone` (UTC when omitted).
|
|
145
|
+
* @throws If the recurrence, the time zone or the count is invalid.
|
|
146
|
+
* @throws `NotSupportedError` if the backend cannot preview recurrences.
|
|
93
147
|
*/
|
|
94
|
-
abstract
|
|
148
|
+
abstract previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]>;
|
|
95
149
|
/**
|
|
96
150
|
* Requests cancellation of one or more jobs.
|
|
97
151
|
*
|
package/dist/job.broker.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD
|
|
1
|
+
{"version":3,"file":"job.broker.d.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,8BACsB,SAAS;IAC7B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,QAAQ,CAAC,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAEhH;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,QAAQ,CAAC,QAAQ,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE3I;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9D;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,YAAY,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IAE1G;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAEtG;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnE;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnE;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAEtE;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,MAAM,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CACpG"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A recurring schedule as stored by a {@link JobBroker}, returned by
|
|
3
|
+
* {@link JobBroker.getSchedules}.
|
|
4
|
+
*
|
|
5
|
+
* Lowest common denominator across backends: what was scheduled, under which
|
|
6
|
+
* key, on which recurrence and in which zone. Backend bookkeeping (row
|
|
7
|
+
* timestamps, the last job a schedule created) is deliberately left out.
|
|
8
|
+
*
|
|
9
|
+
* @typeParam Payload - The type of the payload each scheduled job is sent with.
|
|
10
|
+
*/
|
|
11
|
+
export interface JobSchedule<Payload extends object = object> {
|
|
12
|
+
/** The job name the schedule enqueues. */
|
|
13
|
+
name: string;
|
|
14
|
+
/** The key the schedule was created with; `''` for the name's unkeyed schedule. */
|
|
15
|
+
key: string;
|
|
16
|
+
/** The cron expression or RFC 5545 recurrence rule the schedule recurs on. */
|
|
17
|
+
recurrence: string;
|
|
18
|
+
/** The IANA time zone the recurrence is evaluated in, `'UTC'` when none was given. */
|
|
19
|
+
timeZone: string;
|
|
20
|
+
/** The payload each scheduled job is sent with, when one was given. */
|
|
21
|
+
payload?: Payload;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=job.schedule.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job.schedule.d.ts","sourceRoot":"","sources":["../src/job.schedule.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM;IAC1D,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,mFAAmF;IACnF,GAAG,EAAE,MAAM,CAAC;IACZ,8EAA8E;IAC9E,UAAU,EAAE,MAAM,CAAC;IACnB,sFAAsF;IACtF,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { DateTime } from 'luxon';
|
|
2
|
+
/**
|
|
3
|
+
* Options controlling a recurring schedule created by {@link JobBroker.schedule}.
|
|
4
|
+
*
|
|
5
|
+
* Like {@link JobSendOptions}, these describe intent rather than a particular
|
|
6
|
+
* backend's wire format. A backend that cannot honour one of them throws a
|
|
7
|
+
* `NotSupportedError` rather than silently ignoring it (see {@link JobBroker}).
|
|
8
|
+
*/
|
|
9
|
+
export interface JobScheduleOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Distinguishes this schedule from the others on the same job name.
|
|
12
|
+
*
|
|
13
|
+
* A job name holds one schedule per key, so a single queue can carry many
|
|
14
|
+
* independent schedules (one per user, per tenant, per routine) by giving
|
|
15
|
+
* each its own key. Scheduling again with a key that already exists replaces
|
|
16
|
+
* that schedule and leaves the others alone.
|
|
17
|
+
*
|
|
18
|
+
* When omitted, the schedule is the job name's single unkeyed schedule, which
|
|
19
|
+
* is what a call without options has always created.
|
|
20
|
+
*/
|
|
21
|
+
key?: string;
|
|
22
|
+
/**
|
|
23
|
+
* The IANA time zone the recurrence is evaluated in (e.g. `America/Chicago`).
|
|
24
|
+
*
|
|
25
|
+
* A daily `0 9 * * *` with `timeZone: 'Europe/Paris'` fires at 09:00 Paris
|
|
26
|
+
* time, tracking daylight saving. When omitted, the recurrence is evaluated
|
|
27
|
+
* in UTC. An unknown zone is rejected when the schedule is created.
|
|
28
|
+
*/
|
|
29
|
+
timeZone?: string;
|
|
30
|
+
/**
|
|
31
|
+
* What to do about occurrences that came due while nothing was running to
|
|
32
|
+
* send them, such as during a deploy or an outage.
|
|
33
|
+
*
|
|
34
|
+
* - `'skip'` sends nothing for them and waits for the next occurrence.
|
|
35
|
+
* - `'once'` sends a single job for the most recent missed occurrence, however
|
|
36
|
+
* many were missed.
|
|
37
|
+
*
|
|
38
|
+
* When omitted, the backend's default applies (`'skip'` for pg-boss).
|
|
39
|
+
*/
|
|
40
|
+
missed?: 'skip' | 'once';
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Options for {@link JobBroker.previewSchedule}.
|
|
44
|
+
*/
|
|
45
|
+
export interface JobSchedulePreviewOptions {
|
|
46
|
+
/**
|
|
47
|
+
* The IANA time zone to evaluate the recurrence in, as
|
|
48
|
+
* {@link JobScheduleOptions.timeZone} would. Defaults to UTC. The returned
|
|
49
|
+
* `DateTime`s are in this zone.
|
|
50
|
+
*/
|
|
51
|
+
timeZone?: string;
|
|
52
|
+
/**
|
|
53
|
+
* The point the preview starts from. Occurrences are strictly after it, so
|
|
54
|
+
* passing the last occurrence of one page back in yields the next page.
|
|
55
|
+
* Defaults to now.
|
|
56
|
+
*/
|
|
57
|
+
from?: DateTime;
|
|
58
|
+
/**
|
|
59
|
+
* How many occurrences to return. A finite recurrence rule may return fewer,
|
|
60
|
+
* and one whose last occurrence has passed returns none. Defaults to the
|
|
61
|
+
* backend's default (5 for pg-boss, which allows at most 1000).
|
|
62
|
+
*/
|
|
63
|
+
count?: number;
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=job.schedule.options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job.schedule.options.d.ts","sourceRoot":"","sources":["../src/job.schedule.options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;;OAUG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;OAIG;IACH,IAAI,CAAC,EAAE,QAAQ,CAAC;IAEhB;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
|