@maroonedsoftware/jobbroker 1.5.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/job.broker.ts","../src/job.ts","../src/job.runner.ts","../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue and managing\n * scheduled jobs. It provides the producer-side interface for the job\n * processing system.\n *\n * @example\n * ```typescript\n * // Sending a job immediately\n * await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue for immediate processing.\n *\n * The job will be picked up by a worker as soon as one is available.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws If the job name is not registered.\n */\n abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload): Promise<void> {\n * await emailService.send(payload.to, payload.subject, payload.body);\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * @param payload - The data required to execute the job.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobBroker } from '../job.broker.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.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,kBAAkB;;;;;;;;AA4BpB,IAAeC,YAAf,MAAeA;SAAAA;;;AA0CtB;;;;;;ACtEA,SAASC,cAAAA,mBAAkB;;;;;;;;AA6BpB,IAAeC,MAAf,MAAeA;SAAA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;;;;;;;;;EAYA,MAAMC,OAAsB;AAC1B,UAAM,KAAKtB,OAAOsB,KAAI;EACxB;AACF;;;;;;;;;;;","names":["Injectable","JobBroker","Injectable","Job","Injectable","JobRunner","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/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.ts","sourceRoot":"","sources":["../src/job.broker.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,8BACsB,SAAS;IAC7B;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,IAAI,CAAC,OAAO,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAEtF;;;;;;;;;;;;;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;IAEhD;;;;;;;;;;;;;;;;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"}
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,CAA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
41
41
  private readonly logger;
42
+ /**
43
+ * How often, in seconds, a running job polls pg-boss to detect that it has
44
+ * been cancelled. When a poll observes the job is no longer present or its
45
+ * state is `cancelled`, the `AbortSignal` passed to the job's handler is
46
+ * aborted so cooperative handlers can stop. Set to `0` to disable polling
47
+ * (running jobs will then only be interruptible on shutdown/timeout).
48
+ *
49
+ * @default 5
50
+ */
51
+ cancelPollIntervalSeconds: number;
42
52
  /**
43
53
  * Creates a new PgBossJobRunner instance.
44
54
  *
@@ -64,6 +74,22 @@ export declare class PgBossJobRunner extends JobRunner {
64
74
  * @returns A promise that resolves when all workers are registered with pg-boss.
65
75
  */
66
76
  start(): Promise<void>;
77
+ /**
78
+ * Polls pg-boss for a running job and aborts the given controller when the job
79
+ * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).
80
+ *
81
+ * This is what turns {@link PgBossJobBroker.cancel} into a signal the running
82
+ * handler can observe, even when `cancel` is called from a different process:
83
+ * the cancellation is a state change on the shared PostgreSQL row, and every
84
+ * runner polls that row for the jobs it is currently executing.
85
+ *
86
+ * @param name - The queue/job name.
87
+ * @param id - The id of the running job to watch.
88
+ * @param controller - The controller to abort once cancellation is detected.
89
+ * @returns A function that stops the poll; always call it when the job finishes.
90
+ * @internal
91
+ */
92
+ private watchForCancellation;
67
93
  /**
68
94
  * Stops the job runner gracefully.
69
95
  *
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAclD;;;;;;;;;;;;;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;;;;;;;;OAcG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
@@ -0,0 +1,5 @@
1
+ export * from './pgboss/pgboss.job.broker.js';
2
+ export * from './pgboss/pgboss.job.runner.js';
3
+ export * from './pgboss/pgboss.job.registration.js';
4
+ export * from './pgboss/pgboss.connection.provider.js';
5
+ //# sourceMappingURL=pgboss.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgboss.d.ts","sourceRoot":"","sources":["../src/pgboss.ts"],"names":[],"mappings":"AAEA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC"}