@maroonedsoftware/jobbroker 1.12.3 → 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 +46 -4
- 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/dist/pgboss.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts","../src/pgboss/kysely.transaction.connection.provider.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, a per-queue\n * {@link JobWorkerPolicy}, or any combination of them. Every field beyond `job`\n * is optional, so this shape covers:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` — retry and dead-letter behavior declared where the job is\n * mapped.\n * - `{ job, worker }` — how much concurrency this node gives the job's queue.\n *\n * The two policies are independent and answer different questions: `policy` is\n * stored on the queue and governs what happens to a job that fails, `worker`\n * configures the worker this process starts and governs how fast jobs are taken\n * off the queue.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * worker: { concurrency: 8 },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n /**\n * An optional per-queue worker policy — concurrency, batch size, and poll\n * interval — applied when this node starts a worker for the job's queue. It\n * configures this process only, not the queue. See {@link JobWorkerPolicy}.\n */\n worker?: JobWorkerPolicy;\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 bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule,\n * an optional per-queue {@link JobQueuePolicy}, and/or an optional per-queue\n * {@link JobWorkerPolicy}\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 * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Register a hot queue that this node runs eight at a time\n * registry.set('image.thumbnail', {\n * job: ThumbnailJob,\n * worker: { concurrency: 8 }\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 { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\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 */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\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 */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, JobResult, PgBoss } from 'pg-boss';\nimport { Duration } from 'luxon';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobContext } from '../job.context.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\nimport { PermanentJobError } from '../permanent.job.error.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * `createQueue`, whose options are the strict (no-`null`) subset of\n * `UpdateQueueOptions` — {@link JobQueuePolicy} never clears a setting, so the\n * narrower shape satisfies both calls.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['createQueue']>[1]>;\n\n/**\n * pg-boss work options as accepted by the three-argument `work` overload.\n * Derived from the installed pg-boss types so the mapping tracks the peer's\n * exact shape.\n * @internal\n */\ntype PgBossWorkOptions = NonNullable<Parameters<PgBoss['work']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' 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 * Each job settles on its own: the runner reports a per-job outcome to pg-boss\n * rather than throwing, so one failure retries and dead-letters alone instead of\n * dragging the rest of its batch with it. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters on the\n * first attempt.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * A base {@link JobWorkerPolicy} applied to *every* queue this runner starts a\n * worker for, beneath each queue's own `worker` policy. Set it to give all\n * queues the same concurrency or poll interval without repeating them on each\n * registration; a field a queue sets on its own `worker` overrides the same\n * field here.\n *\n * Unlike {@link defaultQueuePolicy} this is not stored on the queue — it\n * configures the workers *this process* starts, so another node consuming the\n * same queues may use different values.\n *\n * Leave it unset (the default) to opt in per queue only. A queue with no policy\n * from either side runs on pg-boss's own worker defaults: one worker, one job\n * per fetch.\n *\n * @default undefined\n */\n defaultWorkerPolicy?: JobWorkerPolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The root DI container. Each job execution resolves from a\n * scope created off it, not from the container itself.\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. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue, with the effective worker\n * policy (the runner's {@link defaultWorkerPolicy} merged with the\n * registration's own `worker`, if any) applied\n *\n * Each item in a batch runs in its own scoped container, created from the\n * injected root container and disposed once the item settles, so `scoped`\n * registrations behave per execution (the job-side equivalent of a request\n * scope) and any disposables the execution created are released. Each scope\n * carries a {@link JobContext} describing the running job, so the job and its\n * collaborators can inject it. Execution is\n * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch\n * until every job has actually finished and one job's failure cannot suppress\n * its sibling's logs.\n *\n * Workers run with pg-boss's `perJobResults`, so the handler reports each job's\n * outcome rather than throwing: a job that fails is retried and dead-lettered on\n * its own, without dragging the rest of its batch along. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters\n * immediately.\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 // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n const handler = async (jobs: PgJob<object>[]): Promise<JobResult[]> => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n // Every execution resolves from its own scope, never the root container.\n // InjectKit caches a `scoped` registration in whichever container first\n // resolves it, and child scopes inherit a parent's cache, so resolving a\n // scoped token at the root would turn it into a process-lifetime singleton\n // shared by every job *and* inherited by every later request scope.\n const scope = this.container.createScopedContainer();\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n // Assigned once the watch starts; until then there is nothing to stop, so\n // `finally` can run unconditionally even if resolution threw.\n let stopWatching = () => {};\n try {\n // Override before resolving, so a job (or anything it depends on) may\n // take JobContext as a constructor dependency.\n scope.override(JobContext, this.toJobContext(name, job, signal));\n const jobRunner = scope.get<Job>(identifier);\n stopWatching = this.watchForCancellation(name, job.id, controller);\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n // Stop the poll before disposing: resolving from a disposed scope throws,\n // and a late tick must not turn a finished job into a logged error.\n stopWatching();\n // Log rather than rethrow, so a disposal failure can't replace the job's\n // real error and mislead pg-boss's retry/dead-letter accounting.\n await scope.disposeAsync().catch((error: unknown) => this.logger.error(error));\n }\n }),\n );\n\n // Under `perJobResults` the handler reports each job's outcome instead of\n // throwing, so pg-boss settles them individually: one poisoned job fails (and\n // retries, and dead-letters) alone rather than dragging its whole batch with it.\n // Throwing from here still fails the entire batch, which is what a runner-level\n // bug — as opposed to a job-level one — should do.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length > 1) {\n // The per-job errors are already logged above and are about to be persisted as\n // each job's own output. This adds back the batch-wide view that the pre-\n // `perJobResults` AggregateError carried, as a log line rather than as a\n // settlement decision — the cause keeps every individual error reachable.\n this.logger.error(\n new ServerkitError(`${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`).withCause(new AggregateError(failures)),\n );\n }\n\n // Map over `jobs`, not `results`: pg-boss matches dispositions by job id and\n // fails any job the handler omits, so the batch itself must drive the output.\n return jobs.map((job, index) => {\n const result = results[index];\n // `allSettled` returns one entry per input, so a missing entry is impossible;\n // treat it as a failure anyway rather than silently completing a job that may\n // never have run.\n if (result?.status === 'fulfilled') {\n return { id: job.id, status: 'completed' };\n }\n // A job that declares its own failure permanent skips its remaining retries\n // and goes straight to the queue's dead-letter queue.\n const status = result?.reason instanceof PermanentJobError ? 'deadletter' : 'failed';\n return { id: job.id, status, output: result?.reason };\n });\n };\n\n await this.pgboss.work(name, this.toWorkOptions(this.resolveWorkerPolicy(registration)), handler);\n }\n }\n\n /**\n * Builds the {@link JobContext} registered in an execution's scoped container.\n *\n * @param name - The queue the job was dequeued from.\n * @param job - The pg-boss job being executed.\n * @param signal - The combined cancellation signal handed to {@link Job.run}.\n * @returns The context describing this execution.\n * @internal\n */\n private toJobContext(name: string, job: PgJob<object>, signal: AbortSignal): JobContext {\n // Typed as always present, but absent when jobs are faked in tests, so it is\n // read defensively and simply omitted when the backend reports no limit.\n const expireInSeconds = (job as { expireInSeconds?: number }).expireInSeconds;\n return {\n id: job.id,\n name,\n signal,\n ...(expireInSeconds === undefined ? {} : { expiresIn: Duration.fromObject({ seconds: expireInSeconds }) }),\n };\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Merges the runner-wide {@link defaultWorkerPolicy} with a registration's own\n * `worker` policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy keeps\n * pg-boss's own worker defaults.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective worker policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolveWorkerPolicy(registration: unknown): JobWorkerPolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.worker : undefined;\n if (!this.defaultWorkerPolicy && !own) {\n return undefined;\n }\n return { ...this.defaultWorkerPolicy, ...own };\n }\n\n /**\n * Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work\n * options. `pollInterval` is passed as a fractional second count rather than\n * rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a\n * deliberate sub-second poll into either 0 (rejected) or 1.\n *\n * Always returns options, because `perJobResults` is always on: it is what makes\n * pg-boss settle each job in a batch individually, and what gives\n * {@link PermanentJobError} somewhere to land. A queue with no worker policy\n * still gets that, and nothing else.\n *\n * @param policy - The effective worker policy for a queue, or `undefined`.\n * @returns The pg-boss work options.\n * @internal\n */\n private toWorkOptions(policy: JobWorkerPolicy | undefined): PgBossWorkOptions {\n const options: PgBossWorkOptions = { perJobResults: true };\n if (policy?.concurrency !== undefined) {\n options.localConcurrency = policy.concurrency;\n }\n if (policy?.batchSize !== undefined) {\n options.batchSize = policy.batchSize;\n }\n if (policy?.pollInterval !== undefined) {\n options.pollingIntervalSeconds = policy.pollInterval.as('seconds');\n }\n return options;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n","import { PgBossConnectionProvider } from './pgboss.connection.provider.js';\nimport { fromKysely, type Db } from 'pg-boss';\n\n/**\n * Structural shape of a Kysely instance or transaction, matching what pg-boss's\n * `fromKysely` adapter consumes.\n *\n * Declared structurally rather than as `Kysely<DB>` so the package carries no\n * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`\n * and `Transaction<DB>` are accepted without a type argument or a cast.\n */\nexport interface KyselyLike {\n withoutPlugins(): Parameters<typeof fromKysely>[0];\n}\n\n/**\n * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so\n * jobs enqueued while that transaction is open commit or roll back with it.\n *\n * Register it as a request-scoped override of {@link PgBossConnectionProvider}\n * alongside whatever binds the transaction itself, and every enqueue performed\n * during the request inserts on the transaction's connection instead of\n * pg-boss's pool — closing the dual-write gap between domain writes and job\n * enqueues.\n *\n * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL\n * straight through `executeQuery`, so a column-rewriting plugin on the caller's\n * instance (a camel-case mapper, for example) would corrupt pg-boss's own\n * result columns. `withoutPlugins()` returns an instance sharing the same\n * connection-bound executor, so atomicity is preserved.\n *\n * @example\n * ```typescript\n * await db.transaction().execute(async trx => {\n * const scope = container.createScope();\n * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));\n *\n * await repository.createOrder(trx, order);\n * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));\n * });\n * ```\n */\nexport class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {\n /**\n * @param trx - The active Kysely transaction (or any Kysely instance) whose\n * connection job inserts should run on.\n */\n constructor(private readonly trx: KyselyLike) {\n super();\n }\n\n /**\n * Returns the transaction's connection adapted to pg-boss's executor shape,\n * with the caller's Kysely plugins stripped.\n *\n * @returns A {@link Db} executor bound to the transaction's connection.\n */\n override executor(): Db {\n return fromKysely(this.trx.withoutPlugins());\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAyGhC,IAAMC,uBAAN,cAAmCC,IAAAA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sBA,MAAAA;EAE7B;;;;;;;EAQSC,WAAe;AACtB,WAAOC,WAAW,KAAKF,IAAIG,eAAc,CAAA;EAC3C;AACF;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Duration","Container","Injectable","Logger","ServerkitError","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","defaultWorkerPolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","handler","jobs","results","Promise","allSettled","map","scope","createScopedContainer","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","override","JobContext","toJobContext","jobRunner","get","watchForCancellation","id","run","data","error","disposeAsync","catch","failures","filter","result","status","reason","length","ServerkitError","withCause","AggregateError","index","PermanentJobError","output","work","toWorkOptions","resolveWorkerPolicy","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","worker","perJobResults","concurrency","localConcurrency","batchSize","pollInterval","pollingIntervalSeconds","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
|
|
1
|
+
{"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.monitor.ts","../src/pgboss/pgboss.job.runner.ts","../src/pgboss/kysely.transaction.connection.provider.ts"],"sourcesContent":["import { PgBoss, type Schedule, type ScheduleOptions } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSchedule } from '../job.schedule.js';\nimport { JobScheduleOptions, JobSchedulePreviewOptions } from '../job.schedule.options.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for recurring schedules on cron expressions or RFC 5545 recurrence rules,\n * many per queue when each has its own key.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job on a cron expression or an RFC 5545 recurrence rule.\n *\n * pg-boss decides the format from the expression itself and stores one row\n * per job name and key, so scheduling again with the same name and key\n * replaces that row. The options map onto pg-boss's own: `key` to `key`,\n * `timeZone` to `tz`, and `missed` to `missed`. pg-boss validates the\n * recurrence and the zone before writing and throws on either.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the schedule commits or rolls back with it.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param recurrence - A cron expression or an RFC 5545 recurrence rule.\n * @param payload - Optional data to pass to the job 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 Error if the job name is not found in the registry.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the key.\n */\n async schedule<Payload extends object>(name: string, recurrence: string, payload?: Payload, options?: JobScheduleOptions): 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, recurrence, payload, {\n db: this.connectionProvider.executor(),\n ...this.toScheduleOptions(options),\n });\n }\n\n /**\n * Maps backend-agnostic schedule options onto pg-boss's `key`, `tz` and\n * `missed`, leaving out any that were not given so pg-boss applies its own\n * defaults (the unkeyed schedule, UTC, and `skip`).\n */\n private toScheduleOptions(options: JobScheduleOptions | undefined): Pick<ScheduleOptions, 'key' | 'tz' | 'missed'> {\n return {\n ...(options?.key !== undefined && { key: options.key }),\n ...(options?.timeZone !== undefined && { tz: options.timeZone }),\n ...(options?.missed !== undefined && { missed: options.missed }),\n };\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the schedule with the given name and key.\n * Jobs that are already queued will still be processed. pg-boss reads a\n * missing key as the empty key, so `unschedule(name)` removes only the\n * unkeyed schedule and leaves keyed ones in place.\n *\n * The delete runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}, so inside a transaction it rolls back\n * with the transaction.\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 Error if the job name is not found in the registry.\n */\n async unschedule(name: string, key?: 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, key, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Lists the schedules on a job name from pg-boss.\n *\n * With a key this reads the one row by its primary key. Without one it pages\n * through every schedule on the name, so a queue with many keyed schedules is\n * returned whole rather than cut off at pg-boss's page size.\n *\n * pg-boss offers no connection option for this read, so it always runs on\n * pg-boss's own pool: a schedule written inside a transaction that has not\n * committed yet is not visible here.\n *\n * @typeParam Payload - The type of the scheduled payload.\n * @param name - The name of the registered job.\n * @param key - When given, only the schedule with this key.\n * @returns A promise that resolves with the matching schedules, ordered by key.\n * @throws Error if the job name is not found in the registry.\n */\n async getSchedules<Payload extends object>(name: string, key?: string): Promise<JobSchedule<Payload>[]> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n if (key !== undefined) {\n const schedule = await this.pgboss.getSchedule(name, key);\n return schedule ? [this.toJobSchedule<Payload>(schedule)] : [];\n }\n\n const schedules: Schedule[] = [];\n let after: Pick<Schedule, 'name' | 'key'> | undefined;\n for (;;) {\n const page = await this.pgboss.getSchedules(name, undefined, { limit: PgBossJobBroker.schedulePageSize, ...(after && { after }) });\n schedules.push(...page);\n const last = page.at(-1);\n if (page.length < PgBossJobBroker.schedulePageSize || !last) {\n break;\n }\n after = { name: last.name, key: last.key };\n }\n\n return schedules.map(schedule => this.toJobSchedule<Payload>(schedule));\n }\n\n /** Rows read per page when {@link getSchedules} lists every schedule on a name. */\n private static readonly schedulePageSize = 1000;\n\n /** Maps a pg-boss schedule row onto the backend-agnostic {@link JobSchedule}. */\n private toJobSchedule<Payload extends object>(schedule: Schedule): JobSchedule<Payload> {\n return {\n name: schedule.name,\n key: schedule.key,\n recurrence: schedule.cron,\n timeZone: schedule.timezone || 'UTC',\n ...(schedule.data != null && { payload: schedule.data as Payload }),\n };\n }\n\n /**\n * Computes the next occurrences of a recurrence with pg-boss's\n * `previewSchedule`, which validates exactly as {@link schedule} does and\n * touches neither the database nor the schedule table.\n *\n * `from` defaults to pg-boss's reading of database time, which on an instance\n * that runs schedules accounts for clock skew against the database. The\n * returned `DateTime`s are in `options.timeZone`, or UTC when omitted.\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.\n * @throws Error if pg-boss rejects the recurrence, the time zone or the count.\n */\n async previewSchedule(recurrence: string, options?: JobSchedulePreviewOptions): Promise<DateTime[]> {\n const zone = options?.timeZone ?? 'UTC';\n const occurrences = this.pgboss.previewSchedule(recurrence, {\n tz: zone,\n ...(options?.from !== undefined && { from: options.from.toJSDate() }),\n ...(options?.count !== undefined && { count: options.count }),\n });\n\n return occurrences.map(occurrence => DateTime.fromJSDate(occurrence, { zone }));\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\n\n/**\n * Configuration object for a job registration.\n *\n * Use the object form (rather than a bare job identifier) when you need to\n * attach a cron schedule, a per-queue {@link JobQueuePolicy}, a per-queue\n * {@link JobWorkerPolicy}, or any combination of them. Every field beyond `job`\n * is optional, so this shape covers:\n *\n * - `{ job }` — an on-demand job (equivalent to registering the bare identifier).\n * - `{ job, cron }` — a job that also runs on a schedule.\n * - `{ job, policy }` — retry and dead-letter behavior declared where the job is\n * mapped.\n * - `{ job, worker }` — how much concurrency this node gives the job's queue.\n *\n * The two policies are independent and answer different questions: `policy` is\n * stored on the queue and governs what happens to a job that fails, `worker`\n * configures the worker this process starts and governs how fast jobs are taken\n * off the queue.\n *\n * @example\n * ```typescript\n * // Scheduled job\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *', // Every day at 9 AM\n * };\n *\n * // On-demand job with a retry / dead-letter policy\n * const webhookJob: PgBossJobRegistration = {\n * job: DeliverWebhookJob,\n * policy: {\n * retryLimit: 5,\n * retryDelay: Duration.fromObject({ seconds: 30 }),\n * retryBackoff: true,\n * deadLetter: 'deliver.webhook.dead',\n * },\n * worker: { concurrency: 8 },\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** An optional cron expression defining when the job should run. */\n cron?: string;\n /**\n * An optional per-queue retry and dead-letter policy applied to this job's\n * queue when the runner starts. See {@link JobQueuePolicy}.\n */\n policy?: JobQueuePolicy;\n /**\n * An optional per-queue worker policy — concurrency, batch size, and poll\n * interval — applied when this node starts a worker for the job's queue. It\n * configures this process only, not the queue. See {@link JobWorkerPolicy}.\n */\n worker?: JobWorkerPolicy;\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 bare job class identifier (for a plain on-demand job)\n * - A {@link PgBossJobRegistration} object, which adds an optional cron schedule,\n * an optional per-queue {@link JobQueuePolicy}, and/or an optional per-queue\n * {@link JobWorkerPolicy}\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 * // Register an on-demand job with a retry / dead-letter policy\n * registry.set('deliver-webhook', {\n * job: DeliverWebhookJob,\n * policy: { retryLimit: 5, deadLetter: 'deliver-webhook-dead' }\n * });\n *\n * // Register a hot queue that this node runs eight at a time\n * registry.set('image.thumbnail', {\n * job: ThumbnailJob,\n * worker: { concurrency: 8 }\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 { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobInfo } from '../job.info.js';\nimport { JobMonitor, JobQueryOptions, JobQueueStats, JobRedriveOptions } from '../job.monitor.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * pg-boss implementation of the {@link JobMonitor} interface.\n *\n * Provides the operator-side view of pg-boss queues — depth/health stats, job\n * enumeration, and dead-letter remediation (redrive, discard, retry) — on top of\n * pg-boss's native `getQueue`, `findJobs`, `redrive`, `deleteJob`, and `retry`.\n *\n * Like {@link PgBossJobBroker}, every operation sources its pg-boss `db` executor\n * from the injected {@link PgBossConnectionProvider}, so a remediation action can\n * participate in a surrounding transaction when a request-scoped override supplies\n * a transaction-bound executor. Unlike the broker, the monitor does not consult\n * the job registry: it works on any queue name, including an unregistered\n * dead-letter sink.\n *\n * @example\n * ```typescript\n * const monitor = new PgBossJobMonitor(pgboss, new PgBossConnectionProvider());\n *\n * const stats = await monitor.getQueueStats('charge.webhook.dead');\n * if (stats && stats.total > 0) {\n * await monitor.redrive('charge.webhook.dead', { limit: 100 });\n * }\n * ```\n */\n@Injectable()\nexport class PgBossJobMonitor extends JobMonitor {\n /**\n * Creates a new PgBossJobMonitor instance.\n *\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * operation; the default returns `undefined` (pg-boss's own pool),\n * while a request-scoped override enables transactional remediation.\n */\n constructor(\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Reports the depth and health of a queue by reading pg-boss's cached queue\n * counters.\n *\n * @param name - The queue name to inspect.\n * @returns The {@link JobQueueStats}, or `null` if the queue does not exist.\n */\n async getQueueStats(name: string): Promise<JobQueueStats | null> {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n return null;\n }\n\n return {\n name: queue.name,\n queued: queue.queuedCount,\n active: queue.activeCount,\n failed: queue.failedCount,\n total: queue.totalCount,\n };\n }\n\n /**\n * Lists jobs retained in a queue, mapping pg-boss's records down to the\n * backend-agnostic {@link JobInfo} shape.\n *\n * @typeParam Payload - The type of the job payloads.\n * @param name - The queue name to list.\n * @param options - Optional {@link JobQueryOptions} filters.\n * @returns The matching jobs (empty if none, or if the queue does not exist).\n */\n async listJobs<Payload extends object>(name: string, options?: JobQueryOptions): Promise<JobInfo<Payload>[]> {\n const jobs = await this.pgboss.findJobs<Payload>(name, {\n id: options?.id,\n data: options?.data,\n queued: options?.queuedOnly,\n db: this.connectionProvider.executor(),\n });\n\n return jobs.map(job => ({ id: job.id, name: job.name, state: job.state, data: job.data }));\n }\n\n /**\n * Moves dead-lettered jobs back into circulation via pg-boss `redrive`.\n *\n * @param name - The (dead-letter) queue to drain.\n * @param options - Optional {@link JobRedriveOptions}.\n * @returns The number of jobs moved.\n */\n async redrive(name: string, options?: JobRedriveOptions): Promise<number> {\n return this.pgboss.redrive(name, {\n destination: options?.destination,\n sourceName: options?.sourceName,\n limit: options?.limit,\n db: this.connectionProvider.executor(),\n });\n }\n\n /**\n * Permanently deletes one or more jobs from a queue.\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 */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Re-attempts one or more failed jobs in place via pg-boss `retry`.\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 */\n async retryJob(name: string, id: string | string[]): Promise<void> {\n await this.pgboss.retry(name, id, { db: this.connectionProvider.executor() });\n }\n}\n","import { Job as PgJob, JobResult, PgBoss } from 'pg-boss';\nimport { Duration } from 'luxon';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobContext } from '../job.context.js';\nimport { JobQueuePolicy } from '../job.queue.policy.js';\nimport { JobRunner } from '../job.runner.js';\nimport { JobWorkerPolicy } from '../job.worker.policy.js';\nimport { PermanentJobError } from '../permanent.job.error.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * pg-boss queue options as accepted by `createQueue`/`updateQueue`. Derived from\n * `createQueue`, whose options are the strict (no-`null`) subset of\n * `UpdateQueueOptions` — {@link JobQueuePolicy} never clears a setting, so the\n * narrower shape satisfies both calls.\n * @internal\n */\ntype PgBossQueueOptions = NonNullable<Parameters<PgBoss['createQueue']>[1]>;\n\n/**\n * pg-boss work options as accepted by the three-argument `work` overload.\n * Derived from the installed pg-boss types so the mapping tracks the peer's\n * exact shape.\n * @internal\n */\ntype PgBossWorkOptions = NonNullable<Parameters<PgBoss['work']>[1]>;\n\n/**\n * Type guard to check if a registration is the object configuration form\n * (carrying a cron schedule, a queue policy, or both) rather than a bare job\n * identifier.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} object.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: unknown): registration is PgBossJobRegistration => {\n return typeof registration === 'object' && registration !== null && 'job' 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 * Each job settles on its own: the runner reports a per-job outcome to pg-boss\n * rather than throwing, so one failure retries and dead-letters alone instead of\n * dragging the rest of its batch with it. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters on the\n * first attempt.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * A base {@link JobQueuePolicy} applied to *every* registered queue, beneath\n * each queue's own policy. Set it to give all queues sane retry/dead-letter\n * defaults without repeating them on each registration; a field a queue sets\n * on its own `policy` overrides the same field here.\n *\n * Leave it unset (the default) to opt in per queue only. When neither this nor\n * a queue's own policy supplies any option, that queue is created exactly as\n * before, with no options passed.\n *\n * @default undefined\n */\n defaultQueuePolicy?: JobQueuePolicy;\n\n /**\n * A base {@link JobWorkerPolicy} applied to *every* queue this runner starts a\n * worker for, beneath each queue's own `worker` policy. Set it to give all\n * queues the same concurrency or poll interval without repeating them on each\n * registration; a field a queue sets on its own `worker` overrides the same\n * field here.\n *\n * Unlike {@link defaultQueuePolicy} this is not stored on the queue — it\n * configures the workers *this process* starts, so another node consuming the\n * same queues may use different values.\n *\n * Leave it unset (the default) to opt in per queue only. A queue with no policy\n * from either side runs on pg-boss's own worker defaults: one worker, one job\n * per fetch.\n *\n * @default undefined\n */\n defaultWorkerPolicy?: JobWorkerPolicy;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The root DI container. Each job execution resolves from a\n * scope created off it, not from the container itself.\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. Resolves the effective queue policy (the runner's {@link defaultQueuePolicy}\n * merged with the registration's own policy, if any)\n * 2. Auto-creates any dead-letter queue the policy references, before the queue\n * that references it\n * 3. Creates the queue with the policy's options if it doesn't exist, or updates\n * an existing queue to match; when no policy applies, the queue is created\n * with the name only (unchanged pre-policy behavior)\n * 4. Sets up the cron schedule (for scheduled jobs)\n * 5. Starts a worker to process jobs from the queue, with the effective worker\n * policy (the runner's {@link defaultWorkerPolicy} merged with the\n * registration's own `worker`, if any) applied\n *\n * Each item in a batch runs in its own scoped container, created from the\n * injected root container and disposed once the item settles, so `scoped`\n * registrations behave per execution (the job-side equivalent of a request\n * scope) and any disposables the execution created are released. Each scope\n * carries a {@link JobContext} describing the running job, so the job and its\n * collaborators can inject it. Execution is\n * awaited via `Promise.allSettled`, so pg-boss does not acknowledge a batch\n * until every job has actually finished and one job's failure cannot suppress\n * its sibling's logs.\n *\n * Workers run with pg-boss's `perJobResults`, so the handler reports each job's\n * outcome rather than throwing: a job that fails is retried and dead-lettered on\n * its own, without dragging the rest of its batch along. A job that throws\n * {@link PermanentJobError} skips its remaining retries and dead-letters\n * immediately.\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 // Tracks queues we have already ensured exist during this start pass, so a\n // dead-letter queue referenced by several policies is only created once.\n const ensured = new Set<string>();\n\n for (const [name, registration] of this.registrations.entries()) {\n const policy = this.resolvePolicy(registration);\n\n // A dead-letter queue must exist before a queue that references it is\n // created, so ensure it first (as a plain queue) when it is not itself a\n // registered queue that a later iteration would create.\n if (policy?.deadLetter) {\n await this.ensureQueue(policy.deadLetter, undefined, ensured);\n }\n\n await this.ensureQueue(name, policy, ensured);\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n if (registration.cron) {\n await this.pgboss.schedule(name, registration.cron);\n }\n } else {\n identifier = registration;\n }\n\n const handler = async (jobs: PgJob<object>[]): Promise<JobResult[]> => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n // Every execution resolves from its own scope, never the root container.\n // InjectKit caches a `scoped` registration in whichever container first\n // resolves it, and child scopes inherit a parent's cache, so resolving a\n // scoped token at the root would turn it into a process-lifetime singleton\n // shared by every job *and* inherited by every later request scope.\n const scope = this.container.createScopedContainer();\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n // Assigned once the watch starts; until then there is nothing to stop, so\n // `finally` can run unconditionally even if resolution threw.\n let stopWatching = () => {};\n try {\n // Override before resolving, so a job (or anything it depends on) may\n // take JobContext as a constructor dependency.\n scope.override(JobContext, this.toJobContext(name, job, signal));\n const jobRunner = scope.get<Job>(identifier);\n stopWatching = this.watchForCancellation(name, job.id, controller);\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n // Stop the poll before disposing: resolving from a disposed scope throws,\n // and a late tick must not turn a finished job into a logged error.\n stopWatching();\n // Log rather than rethrow, so a disposal failure can't replace the job's\n // real error and mislead pg-boss's retry/dead-letter accounting.\n await scope.disposeAsync().catch((error: unknown) => this.logger.error(error));\n }\n }),\n );\n\n // Under `perJobResults` the handler reports each job's outcome instead of\n // throwing, so pg-boss settles them individually: one poisoned job fails (and\n // retries, and dead-letters) alone rather than dragging its whole batch with it.\n // Throwing from here still fails the entire batch, which is what a runner-level\n // bug — as opposed to a job-level one — should do.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length > 1) {\n // The per-job errors are already logged above and are about to be persisted as\n // each job's own output. This adds back the batch-wide view that the pre-\n // `perJobResults` AggregateError carried, as a log line rather than as a\n // settlement decision — the cause keeps every individual error reachable.\n this.logger.error(\n new ServerkitError(`${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`).withCause(new AggregateError(failures)),\n );\n }\n\n // Map over `jobs`, not `results`: pg-boss matches dispositions by job id and\n // fails any job the handler omits, so the batch itself must drive the output.\n return jobs.map((job, index) => {\n const result = results[index];\n // `allSettled` returns one entry per input, so a missing entry is impossible;\n // treat it as a failure anyway rather than silently completing a job that may\n // never have run.\n if (result?.status === 'fulfilled') {\n return { id: job.id, status: 'completed' };\n }\n // A job that declares its own failure permanent skips its remaining retries\n // and goes straight to the queue's dead-letter queue.\n const status = result?.reason instanceof PermanentJobError ? 'deadletter' : 'failed';\n return { id: job.id, status, output: result?.reason };\n });\n };\n\n await this.pgboss.work(name, this.toWorkOptions(this.resolveWorkerPolicy(registration)), handler);\n }\n }\n\n /**\n * Builds the {@link JobContext} registered in an execution's scoped container.\n *\n * @param name - The queue the job was dequeued from.\n * @param job - The pg-boss job being executed.\n * @param signal - The combined cancellation signal handed to {@link Job.run}.\n * @returns The context describing this execution.\n * @internal\n */\n private toJobContext(name: string, job: PgJob<object>, signal: AbortSignal): JobContext {\n // Typed as always present, but absent when jobs are faked in tests, so it is\n // read defensively and simply omitted when the backend reports no limit.\n const expireInSeconds = (job as { expireInSeconds?: number }).expireInSeconds;\n return {\n id: job.id,\n name,\n signal,\n ...(expireInSeconds === undefined ? {} : { expiresIn: Duration.fromObject({ seconds: expireInSeconds }) }),\n };\n }\n\n /**\n * Merges the runner-wide {@link defaultQueuePolicy} with a registration's own\n * policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy is left\n * to pg-boss defaults and created exactly as it was before this feature.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolvePolicy(registration: unknown): JobQueuePolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.policy : undefined;\n if (!this.defaultQueuePolicy && !own) {\n return undefined;\n }\n return { ...this.defaultQueuePolicy, ...own };\n }\n\n /**\n * Ensures a queue exists and, when a policy is supplied, that its retry and\n * dead-letter options match. Creates the queue (with options) when absent, and\n * updates an existing queue's options when a policy is given. When no policy\n * option resolves, an absent queue is created with the name only — byte-for-byte\n * the pre-policy behavior — and an existing queue is left untouched.\n *\n * @param name - The queue name to ensure.\n * @param policy - The effective policy, or `undefined` for none.\n * @param ensured - Names already ensured during this start pass (mutated).\n * @internal\n */\n private async ensureQueue(name: string, policy: JobQueuePolicy | undefined, ensured: Set<string>): Promise<void> {\n if (ensured.has(name)) {\n return;\n }\n ensured.add(name);\n\n const options = policy ? this.toQueueOptions(policy) : undefined;\n const queue = await this.pgboss.getQueue(name);\n\n if (!queue) {\n if (options) {\n await this.pgboss.createQueue(name, options);\n } else {\n await this.pgboss.createQueue(name);\n }\n return;\n }\n\n if (options) {\n await this.pgboss.updateQueue(name, options);\n }\n }\n\n /**\n * Maps a backend-agnostic {@link JobQueuePolicy} onto pg-boss's native queue\n * options. Luxon {@link Duration}s become whole-second counts (pg-boss measures\n * these in seconds). Returns `undefined` when the policy carries no options to\n * apply, so callers fall back to the name-only create/no-op update path.\n *\n * @param policy - The effective policy for a queue.\n * @returns The pg-boss queue options, or `undefined` if the policy is empty.\n * @internal\n */\n private toQueueOptions(policy: JobQueuePolicy): PgBossQueueOptions | undefined {\n const options: PgBossQueueOptions = {};\n if (policy.retryLimit !== undefined) {\n options.retryLimit = policy.retryLimit;\n }\n if (policy.retryDelay !== undefined) {\n options.retryDelay = Math.round(policy.retryDelay.as('seconds'));\n }\n if (policy.retryBackoff !== undefined) {\n options.retryBackoff = policy.retryBackoff;\n }\n if (policy.retryDelayMax !== undefined) {\n options.retryDelayMax = Math.round(policy.retryDelayMax.as('seconds'));\n }\n if (policy.expiresIn !== undefined) {\n options.expireInSeconds = Math.round(policy.expiresIn.as('seconds'));\n }\n if (policy.deadLetter !== undefined) {\n options.deadLetter = policy.deadLetter;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n }\n\n /**\n * Merges the runner-wide {@link defaultWorkerPolicy} with a registration's own\n * `worker` policy, letting the registration override individual fields. Returns\n * `undefined` when neither supplies a policy, so a queue with no policy keeps\n * pg-boss's own worker defaults.\n *\n * @param registration - The registry entry (a bare identifier or an object).\n * @returns The effective worker policy for the queue, or `undefined` if none applies.\n * @internal\n */\n private resolveWorkerPolicy(registration: unknown): JobWorkerPolicy | undefined {\n const own = isPgBossJobRegistration(registration) ? registration.worker : undefined;\n if (!this.defaultWorkerPolicy && !own) {\n return undefined;\n }\n return { ...this.defaultWorkerPolicy, ...own };\n }\n\n /**\n * Maps a backend-agnostic {@link JobWorkerPolicy} onto pg-boss's native work\n * options. `pollInterval` is passed as a fractional second count rather than\n * rounded — pg-boss accepts intervals down to 0.5s, so rounding would turn a\n * deliberate sub-second poll into either 0 (rejected) or 1.\n *\n * Always returns options, because `perJobResults` is always on: it is what makes\n * pg-boss settle each job in a batch individually, and what gives\n * {@link PermanentJobError} somewhere to land. A queue with no worker policy\n * still gets that, and nothing else.\n *\n * @param policy - The effective worker policy for a queue, or `undefined`.\n * @returns The pg-boss work options.\n * @internal\n */\n private toWorkOptions(policy: JobWorkerPolicy | undefined): PgBossWorkOptions {\n const options: PgBossWorkOptions = { perJobResults: true };\n if (policy?.concurrency !== undefined) {\n options.localConcurrency = policy.concurrency;\n }\n if (policy?.batchSize !== undefined) {\n options.batchSize = policy.batchSize;\n }\n if (policy?.pollInterval !== undefined) {\n options.pollingIntervalSeconds = policy.pollInterval.as('seconds');\n }\n return options;\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n","import { PgBossConnectionProvider } from './pgboss.connection.provider.js';\nimport { fromKysely, type Db } from 'pg-boss';\n\n/**\n * Structural shape of a Kysely instance or transaction, matching what pg-boss's\n * `fromKysely` adapter consumes.\n *\n * Declared structurally rather than as `Kysely<DB>` so the package carries no\n * dependency (not even an optional peer) on `kysely`, and so both `Kysely<DB>`\n * and `Transaction<DB>` are accepted without a type argument or a cast.\n */\nexport interface KyselyLike {\n withoutPlugins(): Parameters<typeof fromKysely>[0];\n}\n\n/**\n * {@link PgBossConnectionProvider} bound to an active Kysely transaction, so\n * jobs enqueued while that transaction is open commit or roll back with it.\n *\n * Register it as a request-scoped override of {@link PgBossConnectionProvider}\n * alongside whatever binds the transaction itself, and every enqueue performed\n * during the request inserts on the transaction's connection instead of\n * pg-boss's pool — closing the dual-write gap between domain writes and job\n * enqueues.\n *\n * Plugins are stripped before the transaction is adapted: pg-boss runs raw SQL\n * straight through `executeQuery`, so a column-rewriting plugin on the caller's\n * instance (a camel-case mapper, for example) would corrupt pg-boss's own\n * result columns. `withoutPlugins()` returns an instance sharing the same\n * connection-bound executor, so atomicity is preserved.\n *\n * @example\n * ```typescript\n * await db.transaction().execute(async trx => {\n * const scope = container.createScope();\n * scope.override(PgBossConnectionProvider, new KyselyTransactionConnectionProvider(trx));\n *\n * await repository.createOrder(trx, order);\n * await scope.get(JobBroker).send(new SendReceiptJob({ orderId: order.id }));\n * });\n * ```\n */\nexport class KyselyTransactionConnectionProvider extends PgBossConnectionProvider {\n /**\n * @param trx - The active Kysely transaction (or any Kysely instance) whose\n * connection job inserts should run on.\n */\n constructor(private readonly trx: KyselyLike) {\n super();\n }\n\n /**\n * Returns the transaction's connection adapted to pg-boss's executor shape,\n * with the caller's Kysely plugins stripped.\n *\n * @returns A {@link Db} executor bound to the transaction's connection.\n */\n override executor(): Db {\n return fromKysely(this.trx.withoutPlugins());\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAASA,cAAmD;AAC5D,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAyGhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACzGhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFLO,IAAMC,kBAAN,MAAMA,yBAAwBC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;;;;;;;;;;;;;EAuBA,MAAMC,KAA6BC,MAAcC,SAAkBC,SAA2C;AAC5G,QAAI,CAAC,KAAKN,cAAcO,IAAIH,IAAAA,GAAO;AACjC,YAAM,IAAII,MAAM,OAAOJ,IAAAA,oBAAwB;IACjD;AAEA,UAAMK,KAAK,MAAM,KAAKR,OAAOE,KAAKC,MAAMC,SAAS;MAC/CK,IAAI,KAAKR,mBAAmBS,SAAQ;MACpC,GAAG,KAAKC,aAAaN,SAASO,UAAAA;IAChC,CAAA;AACA,QAAI,C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,KAAKF,IAAIG,eAAc,CAAA;EAC3C;AACF;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","recurrence","toScheduleOptions","key","undefined","timeZone","tz","missed","unschedule","getSchedules","getSchedule","toJobSchedule","schedules","after","page","limit","schedulePageSize","push","last","at","length","map","cron","timezone","data","previewSchedule","zone","occurrences","from","count","occurrence","fromJSDate","cancel","resume","deleteJob","getJob","job","findJobs","state","PgBoss","Injectable","PgBossJobMonitor","JobMonitor","pgboss","connectionProvider","getQueueStats","name","queue","getQueue","queued","queuedCount","active","activeCount","failed","failedCount","total","totalCount","listJobs","options","jobs","findJobs","id","data","queuedOnly","db","executor","map","job","state","redrive","destination","sourceName","limit","deleteJob","retryJob","retry","PgBoss","Duration","Container","Injectable","Logger","ServerkitError","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","defaultQueuePolicy","defaultWorkerPolicy","container","registrations","pgboss","logger","start","ensured","Set","name","entries","policy","resolvePolicy","deadLetter","ensureQueue","undefined","identifier","job","cron","schedule","handler","jobs","results","Promise","allSettled","map","scope","createScopedContainer","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","override","JobContext","toJobContext","jobRunner","get","watchForCancellation","id","run","data","error","disposeAsync","catch","failures","filter","result","status","reason","length","ServerkitError","withCause","AggregateError","index","PermanentJobError","output","work","toWorkOptions","resolveWorkerPolicy","expireInSeconds","expiresIn","Duration","fromObject","seconds","own","has","add","options","toQueueOptions","queue","getQueue","createQueue","updateQueue","retryLimit","retryDelay","Math","round","as","retryBackoff","retryDelayMax","Object","keys","worker","perJobResults","concurrency","localConcurrency","batchSize","pollInterval","pollingIntervalSeconds","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop","fromKysely","KyselyTransactionConnectionProvider","PgBossConnectionProvider","trx","executor","fromKysely","withoutPlugins"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maroonedsoftware/jobbroker",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.0",
|
|
4
4
|
"description": "A flexible background job processing library with support for scheduled and on-demand jobs.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Marooned Software",
|
|
@@ -48,18 +48,19 @@
|
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"injectkit": "^1.7.1",
|
|
50
50
|
"luxon": "^3.7.2",
|
|
51
|
-
"@maroonedsoftware/
|
|
52
|
-
"@maroonedsoftware/
|
|
51
|
+
"@maroonedsoftware/errors": "1.9.2",
|
|
52
|
+
"@maroonedsoftware/logger": "1.1.10"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
+
"@electric-sql/pglite": "^0.5.16",
|
|
55
56
|
"@types/luxon": "^3.7.5",
|
|
56
57
|
"kysely": "^0.29.5",
|
|
57
|
-
"pg-boss": "^12.
|
|
58
|
+
"pg-boss": "^12.38.0",
|
|
58
59
|
"@repo/config-eslint": "0.2.1",
|
|
59
60
|
"@repo/config-typescript": "0.1.0"
|
|
60
61
|
},
|
|
61
62
|
"peerDependencies": {
|
|
62
|
-
"pg-boss": "^12.
|
|
63
|
+
"pg-boss": "^12.38.0"
|
|
63
64
|
},
|
|
64
65
|
"peerDependenciesMeta": {
|
|
65
66
|
"pg-boss": {
|
|
@@ -1 +0,0 @@
|
|
|
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 { JobInfo } from './job.info.js';\nimport { JobSendOptions } from './job.send.options.js';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue, cancelling and\n * inspecting jobs, and managing scheduled jobs. It provides the producer-side\n * interface for the job processing system.\n *\n * Backends differ in what they can do. Operations a backend cannot honor throw\n * a `NotSupportedError` rather than silently doing nothing. The bundled pg-boss\n * backend supports every operation.\n *\n * @example\n * ```typescript\n * // Sending a job immediately (returns the job id)\n * const id = await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Deferring a job: run it no earlier than five minutes from now\n * await jobBroker.send('send-email', payload, {\n * startAfter: Duration.fromObject({ minutes: 5 })\n * });\n *\n * // Deferring to an absolute time\n * await jobBroker.send('send-email', payload, {\n * startAfter: DateTime.now().plus({ hours: 2 })\n * });\n *\n * // Cancelling it later, whether it is still queued or already running\n * await jobBroker.cancel('send-email', id);\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue.\n *\n * By default the job is eligible for immediate processing and will be picked\n * up by a worker as soon as one is available. Pass {@link JobSendOptions.startAfter}\n * to defer it: the job becomes eligible only once the given delay has elapsed\n * (a {@link Duration}) or the given moment has passed (a {@link DateTime}).\n * Deferral is a lower bound, not a guarantee of exact-time execution — the job\n * runs at the first opportunity after it becomes eligible.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job. The id can\n * be passed to {@link cancel}, {@link resume}, {@link deleteJob}, or\n * {@link getJob}.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if `options.startAfter` requests a deferral the\n * backend cannot honor (e.g. a delay beyond the backend's maximum).\n */\n abstract send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n\n /**\n * Requests cancellation of one or more jobs.\n *\n * Cancellation is best-effort and applies regardless of the job's state: a\n * job that is still queued is prevented from running, and a job that is\n * already running is asked to stop. For a running job, cancellation is\n * cooperative — the job's handler receives an aborted `AbortSignal` (see\n * {@link Job.run}) and must honor it. A handler that ignores the signal runs\n * to completion. Some backends may forcefully terminate the running compute\n * instead; this contract only guarantees the request is delivered.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot cancel jobs.\n */\n abstract cancel(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs in the `cancelled` state can be resumed; other states are\n * unaffected.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot resume jobs.\n */\n abstract resume(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Permanently deletes one or more jobs.\n *\n * Removes the job records entirely. Unlike {@link cancel}, a deleted job\n * leaves no `cancelled` record behind and cannot be resumed.\n *\n * @param name - The name of the registered job type.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot delete jobs.\n */\n abstract deleteJob(name: string, id: string | string[]): Promise<void>;\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job type.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws If the job name is not registered.\n * @throws `NotSupportedError` if the backend cannot report per-job state.\n */\n abstract getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null>;\n}\n","import { Injectable, 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;;;;;;;;AA+CpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAgHtB;;;;;;AC/JA,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"]}
|