import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from '@japa/runner' import * as errors from '../src/exceptions.js' import { QueueManager } from '../src/queue_manager.js' import { sync } from '../src/drivers/sync_adapter.js' import { MemoryLogger } from './_mocks/memory_logger.js' import { Locator } from '../src/locator.js' import { Job } from '../src/job.js' import SendEmailJob from '../examples/jobs/send_email_job.js' import type { Adapter } from '../src/contracts/adapter.js' test.group('QueueManager', () => { test('should reject an invalid timeout in the config', async ({ assert }) => { const base = { default: 'sync', adapters: { sync: sync() } } await assert.rejects( () => QueueManager.init({ ...base, worker: { timeout: '30d' } }), errors.E_INVALID_TIMEOUT ) await assert.rejects( () => QueueManager.init({ ...base, defaultJobOptions: { timeout: -1 } }), errors.E_INVALID_TIMEOUT ) await assert.rejects( () => QueueManager.init({ ...base, worker: { timeout: 0.5 } }), errors.E_INVALID_TIMEOUT ) await assert.rejects( () => QueueManager.init({ ...base, defaultJobOptions: { timeout: 1.5 } }), errors.E_INVALID_TIMEOUT ) await assert.rejects( () => QueueManager.init({ ...base, queues: { reports: { defaultJobOptions: { timeout: 1.5 } } }, }), errors.E_INVALID_TIMEOUT ) await assert.rejects( () => QueueManager.init({ ...base, queues: { reports: { defaultJobOptions: { timeout: '60d' } } }, }), errors.E_INVALID_TIMEOUT ) }) test('should reject a job class with an invalid timeout', async ({ assert, cleanup }) => { const directory = await mkdtemp(join(tmpdir(), 'queue-jobs-')) cleanup(() => rm(directory, { recursive: true, force: true })) await writeFile( join(directory, 'slow_job.mjs'), 'export default class SlowJob { static options = { timeout: "30d" } }\n' ) const loading = QueueManager.init({ default: 'sync', adapters: { sync: sync() }, locations: [join(directory, '*.mjs')], }) const error = await loading.then( () => undefined, (reason: Error) => reason ) assert.instanceOf(error, errors.E_INVALID_TIMEOUT) assert.include(error?.message, 'Invalid timeout "30d" of job "SlowJob"') class SlowRegisteredJob extends Job { static options = { timeout: 1.5 } async execute() {} } assert.throws( () => Locator.register('SlowRegisteredJob', SlowRegisteredJob), /Invalid timeout "1.5" of job "SlowRegisteredJob"/ ) assert.isUndefined(Locator.get('SlowRegisteredJob')) }) test('should validate adapter presence', async ({ assert }) => { await assert.rejects( () => QueueManager.init({ default: 'sync', adapters: {}, }), errors.E_CONFIGURATION_ERROR, 'Configuration error. Reason: At least one adapter must be configured' ) }) test('should validate default adapter presence', async ({ assert }) => { await assert.rejects( () => QueueManager.init({ default: '', adapters: { sync: sync() }, }), errors.E_CONFIGURATION_ERROR, 'Configuration error. Reason: Default adapter must be specified' ) }) test('should validate that adapter is a function', async ({ assert }) => { await assert.rejects( () => QueueManager.init({ default: 'sync', adapters: { sync: 'not-a-function' as any }, }), errors.E_CONFIGURATION_ERROR, 'Configuration error. Reason: Adapter "sync" must be a factory function' ) }) test('should validate default adapter existence in adapters', async ({ assert }) => { await assert.rejects( () => QueueManager.init({ default: 'missing', adapters: { sync: sync() }, }), errors.E_CONFIGURATION_ERROR, 'Configuration error. Reason: Default adapter "missing" not found in adapters configuration' ) }) test('should expose a config resolver after initialization', async ({ assert }) => { await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, }) const resolver = QueueManager.getConfigResolver() assert.exists(resolver) }) test('should expose the configured logger', async ({ assert }) => { const logger = new MemoryLogger() await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, logger, }) assert.strictEqual(QueueManager.getLogger(), logger) }) test('should throw E_QUEUE_NOT_INITIALIZED when use() called before init()', async ({ assert, }) => { await QueueManager.destroy() assert.throws( () => QueueManager.use(), errors.E_QUEUE_NOT_INITIALIZED, 'QueueManager is not initialized. Call QueueManager.init() before using it.' ) }) test('should throw E_ADAPTER_INIT_ERROR when adapter factory throws', async ({ assert }) => { await QueueManager.init({ default: 'broken', adapters: { broken: () => { throw new Error('Connection failed') }, }, }) assert.throws( () => QueueManager.use(), errors.E_ADAPTER_INIT_ERROR, 'Failed to initialize adapter "broken". Reason: Connection failed' ) }) test('should log warning when locations match no jobs', async ({ assert }) => { const logger = new MemoryLogger() await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, locations: ['./non-existent-path/**/*.ts'], logger, }) assert.equal(logger.logs.length, 1) assert.equal(logger.logs[0].level, 'warn') assert.include(logger.logs[0].message, 'No jobs found for locations') }) test('should log a job file that fails to load through the logger', async ({ assert, fs }) => { const logger = new MemoryLogger() await fs.create('broken_job.js', `throw new Error('Syntax mistake')`) const brokenFile = join(fs.basePath, 'broken_job.js') await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, locations: [brokenFile], logger, }) // The file matched: no warning to check the glob patterns. assert.lengthOf(logger.logs, 1) assert.equal(logger.logs[0].level, 'error') assert.include(logger.logs[0].message, `Failed to load job from ${brokenFile}`) assert.equal((logger.logs[0].obj!.err as Error).message, 'Syntax mistake') }) test('should load jobs from configured locations', async ({ assert, cleanup }) => { cleanup(() => Locator.clear()) await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, locations: ['./examples/jobs/*.ts'], }) Locator.clear() const registered = await QueueManager.loadJobs() assert.equal(registered, 3) assert.equal(Locator.get('SendEmailJob'), SendEmailJob) }) test('should keep configured locations when automatic job loading is disabled', async ({ assert, cleanup, }) => { cleanup(() => Locator.clear()) await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, locations: ['./examples/jobs/*.ts'], autoLoadJobs: false, }) assert.isUndefined(Locator.get('SendEmailJob')) const registered = await QueueManager.loadJobs() assert.equal(registered, 3) assert.equal(Locator.get('SendEmailJob'), SendEmailJob) }) test('should load jobs from explicit locations', async ({ assert, cleanup }) => { cleanup(() => Locator.clear()) const registered = await QueueManager.loadJobs(['./examples/jobs/*.ts']) assert.equal(registered, 3) assert.equal(Locator.get('SendEmailJob'), SendEmailJob) }) test('should fake adapters and restore them', async ({ assert }) => { await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, }) const original = QueueManager.use() const fakeAdapter = QueueManager.fake() assert.strictEqual(QueueManager.use(), fakeAdapter) QueueManager.restore() assert.strictEqual(QueueManager.use(), original) await QueueManager.destroy() }) test('should restore fake using Symbol.dispose', async ({ assert }) => { await QueueManager.init({ default: 'sync', adapters: { sync: sync() }, }) const original = QueueManager.use() { using fake = QueueManager.fake() assert.strictEqual(QueueManager.use(), fake) } assert.strictEqual(QueueManager.use(), original) await QueueManager.destroy() }) test('should destroy existing adapter instances before reinitializing', async ({ assert, cleanup, }) => { const adapters: Adapter[] = [] let destroyedCount = 0 const createAdapter = (): Adapter => ({ setWorkerId() {}, pop: async () => null, popFrom: async () => null, recoverStalledJobs: async () => ({ recovered: 0, exceeded: [] }), renewJobs: async () => 0, completeJob: async () => true, failJob: async () => true, retryJob: async () => true, getJob: async () => null, push: async () => {}, pushOn: async () => {}, pushLater: async () => {}, pushLaterOn: async () => {}, pushMany: async () => {}, pushManyOn: async () => {}, size: async () => 0, sizeOf: async () => 0, destroy: async () => { destroyedCount++ }, migrate: async () => {}, upsertSchedule: async () => 'schedule-id', createSchedule: async () => 'schedule-id', getSchedule: async () => null, listSchedules: async () => [], updateSchedule: async () => {}, deleteSchedule: async () => {}, claimDueSchedule: async () => null, }) cleanup(async () => { await QueueManager.destroy() }) await QueueManager.init({ default: 'custom', adapters: { custom: () => { const adapter = createAdapter() adapters.push(adapter) return adapter }, }, }) const firstAdapter = QueueManager.use() await QueueManager.init({ default: 'custom', adapters: { custom: () => { const adapter = createAdapter() adapters.push(adapter) return adapter }, }, }) const secondAdapter = QueueManager.use() assert.strictEqual(firstAdapter, adapters[0]) assert.strictEqual(secondAdapter, adapters[1]) assert.equal(destroyedCount, 1) }) test('should reset fake state when reinitializing', async ({ assert, cleanup }) => { type LabeledAdapter = Adapter & { label: string } const createAdapter = (label: string): LabeledAdapter => ({ label, setWorkerId() {}, pop: async () => null, popFrom: async () => null, recoverStalledJobs: async () => ({ recovered: 0, exceeded: [] }), renewJobs: async () => 0, completeJob: async () => true, failJob: async () => true, retryJob: async () => true, getJob: async () => null, push: async () => {}, pushOn: async () => {}, pushLater: async () => {}, pushLaterOn: async () => {}, pushMany: async () => {}, pushManyOn: async () => {}, size: async () => 0, sizeOf: async () => 0, destroy: async () => {}, migrate: async () => {}, upsertSchedule: async () => 'schedule-id', createSchedule: async () => 'schedule-id', getSchedule: async () => null, listSchedules: async () => [], updateSchedule: async () => {}, deleteSchedule: async () => {}, claimDueSchedule: async () => null, }) cleanup(async () => { await QueueManager.destroy() }) await QueueManager.init({ default: 'custom', adapters: { custom: () => createAdapter('first'), }, }) const firstAdapter = QueueManager.use() as LabeledAdapter const firstFakeAdapter = QueueManager.fake() await QueueManager.init({ default: 'custom', adapters: { custom: () => createAdapter('second'), }, }) const secondFakeAdapter = QueueManager.fake() assert.notStrictEqual(secondFakeAdapter, firstFakeAdapter) assert.strictEqual(QueueManager.use(), secondFakeAdapter) QueueManager.restore() const restoredAdapter = QueueManager.use() as LabeledAdapter assert.notStrictEqual(restoredAdapter, firstAdapter) assert.equal(restoredAdapter.label, 'second') }) })