@maroonedsoftware/jobbroker 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -210,10 +210,12 @@ var PgBossJobRunner = class extends JobRunner {
210
210
  * 2. Sets up the cron schedule (for scheduled jobs)
211
211
  * 3. Starts a worker to process jobs from the queue
212
212
  *
213
- * Job instances are resolved from the DI container for each execution,
214
- * allowing for proper scoping and dependency injection.
213
+ * Each item in a batch resolves its `Job` instance from the DI container
214
+ * individually and execution is awaited via `Promise.allSettled`, so pg-boss
215
+ * does not acknowledge a batch until every job has actually finished and
216
+ * one job's failure cannot suppress its sibling's logs.
215
217
  *
216
- * @returns A promise that resolves when all workers are set up.
218
+ * @returns A promise that resolves when all workers are registered with pg-boss.
217
219
  */
218
220
  async start() {
219
221
  await this.pgboss.start();
@@ -229,15 +231,15 @@ var PgBossJobRunner = class extends JobRunner {
229
231
  } else {
230
232
  identifier = registration;
231
233
  }
232
- this.pgboss.work(name, async (jobs) => {
233
- const jobRunner = this.container.get(identifier);
234
- jobs.map(async (job) => {
234
+ await this.pgboss.work(name, async (jobs) => {
235
+ await Promise.allSettled(jobs.map(async (job) => {
236
+ const jobRunner = this.container.get(identifier);
235
237
  try {
236
238
  await jobRunner.run(job.data);
237
239
  } catch (error) {
238
240
  this.logger.error(error);
239
241
  }
240
- });
242
+ }));
241
243
  });
242
244
  }
243
245
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/job.broker.ts","../src/job.ts","../src/job.runner.ts","../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue and managing\n * scheduled jobs. It provides the producer-side interface for the job\n * processing system.\n *\n * @example\n * ```typescript\n * // Sending a job immediately\n * await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue for immediate processing.\n *\n * The job will be picked up by a worker as soon as one is available.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws If the job name is not registered.\n */\n abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload): Promise<void> {\n * await emailService.send(payload.to, payload.subject, payload.body);\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * @param payload - The data required to execute the job.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobBroker } from '../job.broker.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\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 * @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);\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 */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue for immediate processing.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws Error if the job name is not found in the registry.\n */\n async send<Payload extends object>(name: string, payload: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.send(name, payload);\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 * @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);\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: object): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The DI container for resolving job instances.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. Starts a worker to process jobs from the queue\n *\n * Job instances are resolved from the DI container for each execution,\n * allowing for proper scoping and dependency injection.\n *\n * @returns A promise that resolves when all workers are set up.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const jobRunner = this.container.get<Job>(identifier);\n jobs.map(async job => {\n try {\n await jobRunner.run(job.data);\n } catch (error) {\n this.logger.error(error);\n }\n });\n });\n }\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA4BpB,IAAeC,YAAf,MAAeA;SAAAA;;;AA0CtB;;;;;;ACtEA,SAASC,cAAAA,mBAAkB;;;;;;;;AA6BpB,IAAeC,MAAf,MAAeA;SAAAA;;;AAatB;;;;;;AC1CA,SAASC,cAAAA,mBAAkB;;;;;;;;AAsBpB,IAAeC,YAAf,MAAeA;SAAAA;;;AAsBtB;;;;;;AC5CA,SAASC,cAAc;AACvB,SAASC,cAAAA,mBAAkB;;;ACD3B,SAAqBC,cAAAA,mBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;;;;;;;;;;;;ADvBzF,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;EAOnC,YACmBC,eACAC,QACjB;AACA,UAAK,GAAA,KAHYD,gBAAAA,eAAAA,KACAC,SAAAA;EAGnB;;;;;;;;;;EAWA,MAAMC,KAA6BC,MAAcC,SAAiC;AAChF,QAAI,CAAC,KAAKJ,cAAcK,IAAIF,IAAAA,GAAO;AACjC,YAAM,IAAIG,MAAM,OAAOH,IAAAA,oBAAwB;IACjD;AAEA,UAAM,KAAKF,OAAOC,KAAKC,MAAMC,OAAAA;EAC/B;;;;;;;;;;;;;;;EAgBA,MAAMG,SAAiCJ,MAAcK,MAAcJ,SAAkC;AACnG,QAAI,CAAC,KAAKJ,cAAcK,IAAIF,IAAAA,GAAO;AACjC,YAAM,IAAIG,MAAM,OAAOH,IAAAA,oBAAwB;I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I;AACF,kBAAMK,UAAUG,IAAIR,IAAIS,IAAI;UAC9B,SAASC,OAAO;AACd,iBAAKlB,OAAOkB,MAAMA,KAAAA;UACpB;QACF,CAAA;MACF,CAAA;IACF;EACF;;;;;;;;;;;EAYA,MAAMC,OAAsB;AAC1B,UAAM,KAAKpB,OAAOoB,KAAI;EACxB;AACF;;;;;;;;;;;","names":["Injectable","JobBroker","Injectable","Job","Injectable","JobRunner","PgBoss","Injectable","Injectable","PgBossJobRegistryMap","Map","PgBossJobBroker","JobBroker","registrations","pgboss","send","name","payload","has","Error","schedule","cron","unschedule","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","jobRunner","get","map","run","data","error","stop"]}
1
+ {"version":3,"sources":["../src/job.broker.ts","../src/job.ts","../src/job.runner.ts","../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job broker implementations.\n *\n * A job broker is responsible for sending jobs to a queue and managing\n * scheduled jobs. It provides the producer-side interface for the job\n * processing system.\n *\n * @example\n * ```typescript\n * // Sending a job immediately\n * await jobBroker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Scheduling a recurring job with cron\n * await jobBroker.schedule('daily-report', '0 9 * * *', {\n * reportType: 'sales'\n * });\n *\n * // Removing a scheduled job\n * await jobBroker.unschedule('daily-report');\n * ```\n */\n@Injectable()\nexport abstract class JobBroker {\n /**\n * Sends a job to the queue for immediate processing.\n *\n * The job will be picked up by a worker as soon as one is available.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws If the job name is not registered.\n */\n abstract send<Payload extends object>(name: string, payload: Payload): Promise<void>;\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued according to the cron schedule.\n * If a schedule already exists for this job name, it will be updated.\n *\n * @typeParam Payload - The type of the job payload. Must be an object.\n * @param name - The unique name identifying the job type.\n * Must match a registered job handler.\n * @param cron - A cron expression defining the schedule (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job handler on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws If the job name is not registered.\n */\n abstract schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void>;\n\n /**\n * Removes a scheduled job.\n *\n * Stops the recurring execution of the specified job.\n * Does not affect jobs that are already queued.\n *\n * @param name - The unique name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws If the job name is not registered.\n */\n abstract unschedule(name: string): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for defining background jobs.\n *\n * Extend this class to create custom job handlers that can be executed\n * asynchronously by a {@link JobRunner}. Each job implementation defines\n * how to process a specific type of payload.\n *\n * @typeParam Payload - The type of data the job expects to receive.\n * Must be an object type. Defaults to `object`.\n *\n * @example\n * ```typescript\n * interface EmailPayload {\n * to: string;\n * subject: string;\n * body: string;\n * }\n *\n * @Injectable()\n * class SendEmailJob extends Job<EmailPayload> {\n * async run(payload: EmailPayload): Promise<void> {\n * await emailService.send(payload.to, payload.subject, payload.body);\n * }\n * }\n * ```\n */\n@Injectable()\nexport abstract class Job<Payload extends object = object> {\n /**\n * Executes the job with the provided payload.\n *\n * This method is called by the job runner when a job is dequeued\n * and ready for processing. Implementations should contain the\n * business logic for handling the job.\n *\n * @param payload - The data required to execute the job.\n * @returns A promise that resolves when the job completes successfully.\n * @throws If the job fails, the error will be caught and logged by the runner.\n */\n abstract run(payload: Payload): Promise<void>;\n}\n","import { Injectable } from 'injectkit';\n\n/**\n * Abstract base class for job runner implementations.\n *\n * A job runner is responsible for consuming jobs from the queue and\n * executing the appropriate job handlers. It manages the worker lifecycle\n * and provides the consumer-side interface for the job processing system.\n *\n * @example\n * ```typescript\n * // Start processing jobs\n * await jobRunner.start();\n *\n * // Gracefully stop processing (e.g., on shutdown)\n * process.on('SIGTERM', async () => {\n * await jobRunner.stop();\n * process.exit(0);\n * });\n * ```\n */\n@Injectable()\nexport abstract class JobRunner {\n /**\n * Starts the job runner and begins processing jobs.\n *\n * This method initializes all registered job handlers and starts\n * listening for jobs on their respective queues. It should be called\n * during application startup.\n *\n * @returns A promise that resolves when the runner has started successfully.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops accepting new jobs and waits for currently\n * executing jobs to complete. It should be called during application\n * shutdown to ensure clean termination.\n *\n * @returns A promise that resolves when the runner has stopped completely.\n */\n abstract stop(): Promise<void>;\n}\n","import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { JobBroker } from '../job.broker.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\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 * @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);\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 */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue for immediate processing.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @returns A promise that resolves when the job has been queued.\n * @throws Error if the job name is not found in the registry.\n */\n async send<Payload extends object>(name: string, payload: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.send(name, payload);\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 * @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);\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\nconst isPgBossJobRegistration = (registration: object): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The DI container for resolving job instances.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. Starts a worker to process jobs from the queue\n *\n * Each item in a batch resolves its `Job` instance from the DI container\n * individually and execution is awaited via `Promise.allSettled`, so pg-boss\n * does not acknowledge a batch until every job has actually finished and\n * one job's failure cannot suppress its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\n try {\n await jobRunner.run(job.data);\n } catch (error) {\n this.logger.error(error);\n }\n }),\n );\n });\n }\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;;;;;;;;AA4BpB,IA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WC,cAAAA,mBAAkB;AAItC,SAASC,cAAc;;;;;;;;;;;;AASvB,IAAMC,0BAA0B,wBAACC,iBAAAA;AAC/B,SAAOA,gBAAgB,SAASA,gBAAgB,UAAUA;AAC5D,GAFgC;AAoCzB,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EASnC,YACmBC,WACAC,eACAC,QACAC,QACjB;AACA,UAAK,GAAA,KALYH,YAAAA,WAAAA,KACAC,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,SAAAA;EAGnB;;;;;;;;;;;;;;;;EAiBA,MAAMC,QAAuB;AAC3B,UAAM,KAAKF,OAAOE,MAAK;AAEvB,eAAW,CAACC,MAAMR,YAAAA,KAAiB,KAAKI,cAAcK,QAAO,GAAI;AAC/D,YAAMC,QAAQ,MAAM,KAAKL,OAAOM,SAASH,IAAAA;AACzC,UAAI,CAACE,OAAO;AACV,cAAM,KAAKL,OAAOO,YAAYJ,IAAAA;MAChC;AAEA,UAAIK;AACJ,UAAId,wBAAwBC,YAAAA,GAAe;AACzCa,qBAAab,aAAac;AAC1B,cAAM,KAAKT,OAAOU,SAASP,MAAMR,aAAagB,IAAI;MACpD,OAAO;AACLH,qBAAab;MACf;AAEA,YAAM,KAAKK,OAAOY,KAAKT,MAAM,OAAOU,SAAAA;AAClC,cAAMC,QAAQC,WACZF,KAAKG,IAAI,OAAMP,QAAAA;AACb,gBAAMQ,YAAY,KAAKnB,UAAUoB,IAASV,UAAAA;AAC1C,cAAI;AACF,kBAAMS,UAAUE,IAAIV,IAAIW,IAAI;UAC9B,SAASC,OAAO;AACd,iBAAKpB,OAAOoB,MAAMA,KAAAA;UACpB;QACF,CAAA,CAAA;MAEJ,CAAA;IACF;EACF;;;;;;;;;;;EAYA,MAAMC,OAAsB;AAC1B,UAAM,KAAKtB,OAAOsB,KAAI;EACxB;AACF;;;;;;;;;;;","names":["Injectable","JobBroker","Injectable","Job","Injectable","JobRunner","PgBoss","Injectable","Injectable","PgBossJobRegistryMap","Map","PgBossJobBroker","JobBroker","registrations","pgboss","send","name","payload","has","Error","schedule","cron","unschedule","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","Promise","allSettled","map","jobRunner","get","run","data","error","stop"]}
@@ -56,10 +56,12 @@ export declare class PgBossJobRunner extends JobRunner {
56
56
  * 2. Sets up the cron schedule (for scheduled jobs)
57
57
  * 3. Starts a worker to process jobs from the queue
58
58
  *
59
- * Job instances are resolved from the DI container for each execution,
60
- * allowing for proper scoping and dependency injection.
59
+ * Each item in a batch resolves its `Job` instance from the DI container
60
+ * individually and execution is awaited via `Promise.allSettled`, so pg-boss
61
+ * does not acknowledge a batch until every job has actually finished and
62
+ * one job's failure cannot suppress its sibling's logs.
61
63
  *
62
- * @returns A promise that resolves when all workers are set up.
64
+ * @returns A promise that resolves when all workers are registered with pg-boss.
63
65
  */
64
66
  start(): Promise<void>;
65
67
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAalD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAU1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAZzB;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;OAYG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA8B5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
1
+ {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAalD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAU1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAZzB;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;OAcG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgC5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
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",