Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
14 changes: 12 additions & 2 deletions src/locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion src/queue_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -175,16 +177,23 @@ 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<number> {
async loadJobs(
locations: string[] = this.#locations,
options: { strict?: boolean } = {}
): Promise<number> {
if (locations.length === 0) {
return 0
}

return Locator.registerFromGlob(locations, {
hotReload: this.#hotReload,
logger: this.#logger,
strict: options.strict,
})
}

Expand Down
66 changes: 65 additions & 1 deletion tests/locator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down
40 changes: 40 additions & 0 deletions tests/queue_manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
Loading