From 263d9930eb46cdd867ea7e7ff18a8f3a61aa793f Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 23 Nov 2026 15:54:54 +0530 Subject: [PATCH] feat: add a strict option that throws on a job file that fails to load With strict: true, Locator.registerFromGlob() and QueueManager.loadJobs() throw E_JOB_LOAD_FAILED for the first job file that fails to import, with the import error as its cause. Without it, the file is logged and skipped, as before. A worker process can use it to refuse to start with a broken job file. --- README.md | 29 ++++++++++++++++ src/exceptions.ts | 5 +++ src/locator.ts | 14 ++++++-- src/queue_manager.ts | 11 ++++++- tests/locator.spec.ts | 66 ++++++++++++++++++++++++++++++++++++- tests/queue_manager.spec.ts | 40 ++++++++++++++++++++++ 6 files changed, 161 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e38fde3..e39ac3e 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,35 @@ await worker.start(['default', 'email']) await QueueManager.destroy() ``` +## Loading Jobs + +`QueueManager.init()` imports each file that matches `locations`. A file that fails to import, for +example one with a syntax error, is logged at the `error` level and skipped. The other jobs are +registered. + +A worker process can refuse to start instead. Turn off `autoLoadJobs`, then load the jobs with +`strict: true`. The first file that fails to import throws `E_JOB_LOAD_FAILED`, and the import +error is its `cause`: + +```typescript +import { QueueManager, errors } from '@boringnode/queue' + +await QueueManager.init({ ...config, autoLoadJobs: false }) + +try { + await QueueManager.loadJobs(undefined, { strict: true }) +} catch (error) { + if (error instanceof errors.E_JOB_LOAD_FAILED) { + console.error(error.message, error.cause) + process.exit(1) + } + throw error +} +``` + +`Locator.registerFromGlob()` accepts the same option: +`Locator.registerFromGlob(['./app/jobs/**/*.ts'], { strict: true })`. + ## Hot Reloading Jobs During development, jobs discovered from `locations` can be reloaded before each execution. This diff --git a/src/exceptions.ts b/src/exceptions.ts index 6654cc0..f34fb82 100644 --- a/src/exceptions.ts +++ b/src/exceptions.ts @@ -35,6 +35,11 @@ export const E_JOB_NOT_FOUND = createError<[jobName: string]>( 'E_JOB_NOT_FOUND' ) +export const E_JOB_LOAD_FAILED = createError<[file: string]>( + 'Cannot load job from "%s"', + 'E_JOB_LOAD_FAILED' +) + export const E_JOB_MAX_ATTEMPTS_REACHED = createError<[jobName: string]>( 'The job "%s" has reached the maximum number of retry attempts', 'E_JOB_MAX_ATTEMPTS_REACHED' diff --git a/src/locator.ts b/src/locator.ts index 6484f91..0fb1f9a 100644 --- a/src/locator.ts +++ b/src/locator.ts @@ -28,6 +28,11 @@ export type RegisterFromGlobOptions = { * found. Defaults to the console. */ logger?: Logger + /** + * Throws `E_JOB_LOAD_FAILED` for the first file that fails to import, in + * place of the log. The import error is its `cause`. Defaults to `false`. + */ + strict?: boolean } /** @@ -80,8 +85,9 @@ class LocatorSingleton { * * Each file should have a default export that is a Job class. * The class name is used as the registration name. A file that fails to - * import is logged at the `error` level and skipped. When the patterns - * match no job file, a warning is logged. + * import is logged at the `error` level and skipped. With `strict: true`, + * it throws `E_JOB_LOAD_FAILED` in place. When the patterns match no job + * file, a warning is logged. * * @param patterns - Glob patterns to match job files * @returns Number of jobs successfully registered @@ -115,6 +121,10 @@ class LocatorSingleton { const module = await this.#import(absolutePath, options.hotReload ?? false) JobClass = module.default } catch (error) { + if (options.strict) { + throw new errors.E_JOB_LOAD_FAILED([file], { cause: error }) + } + failed++ logger.error({ err: error as Error, file }, `Failed to load job from ${file}`) continue diff --git a/src/queue_manager.ts b/src/queue_manager.ts index 6752424..4950bf2 100644 --- a/src/queue_manager.ts +++ b/src/queue_manager.ts @@ -166,6 +166,8 @@ class QueueManagerSingleton { * register jobs at a precise moment in their command lifecycle. * * @param locations - Optional glob patterns. Defaults to the configured locations. + * @param options - `strict: true` throws `E_JOB_LOAD_FAILED` for the first + * job file that fails to import, in place of the log. * @returns Number of jobs successfully registered. * * @example @@ -175,9 +177,15 @@ class QueueManagerSingleton { * * // Or with explicit locations * await QueueManager.loadJobs(['./app/jobs/**\/*.js']) + * + * // Or throw when a job file fails to load + * await QueueManager.loadJobs(undefined, { strict: true }) * ``` */ - async loadJobs(locations: string[] = this.#locations): Promise { + async loadJobs( + locations: string[] = this.#locations, + options: { strict?: boolean } = {} + ): Promise { if (locations.length === 0) { return 0 } @@ -185,6 +193,7 @@ class QueueManagerSingleton { return Locator.registerFromGlob(locations, { hotReload: this.#hotReload, logger: this.#logger, + strict: options.strict, }) } diff --git a/tests/locator.spec.ts b/tests/locator.spec.ts index 19214f0..64ef22d 100644 --- a/tests/locator.spec.ts +++ b/tests/locator.spec.ts @@ -2,7 +2,7 @@ import { test } from '@japa/runner' import { MemoryLogger } from './_mocks/memory_logger.js' import { fork, type ChildProcess } from 'node:child_process' import { realpath } from 'node:fs/promises' -import { resolve } from 'node:path' +import { join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { Job } from '../src/job.js' import { Locator } from '../src/locator.js' @@ -128,6 +128,70 @@ test.group('Locator', (group) => { assert.include(logger.logs[0].message, 'No jobs found for locations: ./non-existent-path') }) + test('should log and skip a file that fails to load, and register the other jobs', async ({ + assert, + fs, + }) => { + const logger = new MemoryLogger() + await fs.create('locator_skipped_job.js', `throw new Error('boom')`) + await fs.create('locator_good_job.js', `export default class GoodJob {}`) + + const registered = await Locator.registerFromGlob([join(fs.basePath, 'locator_*_job.js')], { + logger, + }) + + assert.equal(registered, 1) + assert.isDefined(Locator.get('GoodJob')) + assert.lengthOf(logger.logs, 1) + assert.equal(logger.logs[0].level, 'error') + assert.include(logger.logs[0].message, 'locator_skipped_job.js') + }) + + test('strict throws E_JOB_LOAD_FAILED for a file that throws on import', async ({ + assert, + fs, + }) => { + const logger = new MemoryLogger() + await fs.create('locator_throwing_job.js', `throw new Error('boom')`) + const brokenFile = join(fs.basePath, 'locator_throwing_job.js') + + const error = await Locator.registerFromGlob([brokenFile], { logger, strict: true }).then( + () => undefined, + (err) => err + ) + + assert.instanceOf(error, errors.E_JOB_LOAD_FAILED) + assert.equal(error.message, `Cannot load job from "${brokenFile}"`) + assert.equal(error.code, 'E_JOB_LOAD_FAILED') + assert.equal((error.cause as Error).message, 'boom') + assert.lengthOf(logger.logs, 0) + }) + + test('strict throws E_JOB_LOAD_FAILED for a file with a syntax error', async ({ assert, fs }) => { + await fs.create('locator_syntax_error_job.js', `export default class {`) + const brokenFile = join(fs.basePath, 'locator_syntax_error_job.js') + + const error = await Locator.registerFromGlob([brokenFile], { strict: true }).then( + () => undefined, + (err) => err + ) + + assert.instanceOf(error, errors.E_JOB_LOAD_FAILED) + assert.instanceOf(error.cause, SyntaxError) + }) + + test('strict does not throw for a file with no default export', async ({ assert, fs }) => { + const logger = new MemoryLogger() + await fs.create('helpers.js', `export const value = 1`) + + const registered = await Locator.registerFromGlob([join(fs.basePath, 'helpers.js')], { + logger, + strict: true, + }) + + assert.equal(registered, 0) + }) + test('should return undefined for non-existent job', ({ assert }) => { const job = Locator.get('NonExistentJob') assert.isUndefined(job) diff --git a/tests/queue_manager.spec.ts b/tests/queue_manager.spec.ts index 94e0c48..7adde40 100644 --- a/tests/queue_manager.spec.ts +++ b/tests/queue_manager.spec.ts @@ -214,6 +214,46 @@ test.group('QueueManager', () => { assert.equal((logger.logs[0].obj!.err as Error).message, 'Syntax mistake') }) + test('loadJobs with strict throws E_JOB_LOAD_FAILED for the configured locations', async ({ + assert, + fs, + }) => { + await fs.create('strict_configured_job.js', `throw new Error('boom')`) + const brokenFile = join(fs.basePath, 'strict_configured_job.js') + + await QueueManager.init({ + default: 'sync', + adapters: { sync: sync() }, + locations: [brokenFile], + logger: new MemoryLogger(), + autoLoadJobs: false, + }) + + const error = await QueueManager.loadJobs(undefined, { strict: true }).then( + () => undefined, + (err) => err + ) + + assert.instanceOf(error, errors.E_JOB_LOAD_FAILED) + assert.equal((error.cause as Error).message, 'boom') + }) + + test('loadJobs with strict throws E_JOB_LOAD_FAILED for explicit locations', async ({ + assert, + fs, + }) => { + await fs.create('strict_explicit_job.js', `export default class {`) + const brokenFile = join(fs.basePath, 'strict_explicit_job.js') + + const error = await QueueManager.loadJobs([brokenFile], { strict: true }).then( + () => undefined, + (err) => err + ) + + assert.instanceOf(error, errors.E_JOB_LOAD_FAILED) + assert.instanceOf(error.cause, SyntaxError) + }) + test('should load jobs from configured locations', async ({ assert, cleanup }) => { cleanup(() => Locator.clear())