diff --git a/libs/core/queue/test/queue-connection-errors.test.ts b/libs/core/queue/test/queue-connection-errors.test.ts new file mode 100644 index 00000000..aa980067 --- /dev/null +++ b/libs/core/queue/test/queue-connection-errors.test.ts @@ -0,0 +1,122 @@ +import { EventEmitter } from 'events'; +import { afterEach, describe, expect, it, mock } from 'bun:test'; +import { Queue } from '../src/queue'; +import { QueueManager } from '../src/queue-manager'; +import type { RedisConfig } from '../src/types'; + +// Regression: an EventEmitter that emits 'error' with no listener throws synchronously, +// so an unreachable Redis used to surface as an unhandled error mid-suite. +// Non-QA loopback port; nothing is expected to listen here. +const unreachableRedis: RedisConfig = { + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, +}; + +function createLogger() { + return { + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + trace: mock(() => {}), + }; +} + +describe('Queue connection error handling', () => { + const queues: Queue[] = []; + + afterEach(async () => { + await Promise.all( + queues.splice(0).map(async queue => { + // Stop reconnect timers on the unreachable socket before awaiting close() + (queue.getBullQueue() as any).connection?._client?.disconnect(false); + (queue as any).queueEvents?.connection?._client?.disconnect(false); + await queue.close().catch(() => {}); + }) + ); + }); + + it('logs QueueEvents connection errors instead of throwing', () => { + const logger = createLogger(); + const queue = new Queue( + 'conn-error-queue', + unreachableRedis, + {}, + { workers: 1, startWorker: false }, + logger as any + ); + queues.push(queue); + const queueEvents = (queue as any).queueEvents as EventEmitter; + expect(queueEvents).toBeDefined(); + expect(queueEvents.listenerCount('error')).toBeGreaterThanOrEqual(1); + + const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379'); + expect(() => queueEvents.emit('error', failure)).not.toThrow(); + + expect(logger.error).toHaveBeenCalledWith('QueueEvents connection error', { + queueName: 'conn-error-queue', + error: failure, + }); + }); + + it('does not create QueueEvents for a producer-only queue', () => { + const queue = new Queue('producer-only', unreachableRedis, {}, {}, createLogger() as any); + queues.push(queue); + + expect((queue as any).queueEvents).toBeUndefined(); + }); +}); + +describe('QueueManager connection error handling', () => { + function createFakeRedis() { + const redis = new EventEmitter() as EventEmitter & { + quit: ReturnType; + disconnect: ReturnType; + }; + redis.quit = mock(async () => 'OK'); + redis.disconnect = mock(() => {}); + return redis; + } + + it('logs rate-limiter Redis errors instead of throwing', async () => { + const logger = createLogger(); + const redis = createFakeRedis(); + const manager = new QueueManager( + { serviceName: 'conn-error-svc', redis: unreachableRedis }, + undefined, + logger as any, + { createRedis: () => redis as any } + ); + + try { + expect(redis.listenerCount('error')).toBe(1); + const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379'); + + expect(() => redis.emit('error', failure)).not.toThrow(); + + expect(logger.error).toHaveBeenCalledWith('QueueManager Redis connection error', { + service: 'conn-error-svc', + error: failure, + }); + } finally { + await manager.shutdown(); + } + expect(redis.quit).toHaveBeenCalledTimes(1); + }); + + it('accepts an injected Redis client without an event API', async () => { + const quit = mock(async () => 'OK'); + const manager = new QueueManager( + { serviceName: 'no-events-svc', redis: unreachableRedis }, + undefined, + createLogger() as any, + { createRedis: () => ({ quit, disconnect: mock(() => {}) }) as any } + ); + + await manager.shutdown(); + + expect(quit).toHaveBeenCalledTimes(1); + }); +}); diff --git a/libs/core/shutdown/test/shutdown-dispose.test.ts b/libs/core/shutdown/test/shutdown-dispose.test.ts new file mode 100644 index 00000000..0e9c02ba --- /dev/null +++ b/libs/core/shutdown/test/shutdown-dispose.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { Shutdown } from '../src/shutdown'; + +// These tests use the real `process` listener registry (no stubs) because the +// regression being guarded is listeners leaking across test files in one bun process. +const SIGNALS = ['SIGTERM', 'SIGINT'] as const; + +function listenerCounts(): Record<(typeof SIGNALS)[number], number> { + return { + SIGTERM: process.listenerCount('SIGTERM'), + SIGINT: process.listenerCount('SIGINT'), + }; +} + +describe('Shutdown signal listener cleanup', () => { + const created: Shutdown[] = []; + let baseline: ReturnType; + + function track(instance: Shutdown): Shutdown { + created.push(instance); + return instance; + } + + beforeEach(() => { + Shutdown.reset(); + baseline = listenerCounts(); + }); + + afterEach(() => { + for (const instance of created.splice(0)) { + instance.dispose(); + } + Shutdown.reset(); + }); + + it('autoRegister adds exactly one SIGTERM and one SIGINT listener and dispose removes them', () => { + const shutdown = track(new Shutdown()); + + expect(listenerCounts()).toEqual({ + SIGTERM: baseline.SIGTERM + 1, + SIGINT: baseline.SIGINT + 1, + }); + + shutdown.dispose(); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('autoRegister: false adds no process listeners', () => { + track(new Shutdown({ autoRegister: false })); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('removeSignalHandlers leaves listeners owned by other code in place', () => { + const foreign = () => {}; + process.on('SIGTERM', foreign); + try { + const shutdown = track(new Shutdown()); + shutdown.removeSignalHandlers(); + + expect(process.listeners('SIGTERM')).toContain(foreign); + expect(listenerCounts()).toEqual({ SIGTERM: baseline.SIGTERM + 1, SIGINT: baseline.SIGINT }); + } finally { + process.off('SIGTERM', foreign); + } + }); + + it('dispose and reset are idempotent', () => { + const shutdown = track(new Shutdown()); + + shutdown.dispose(); + shutdown.dispose(); + Shutdown.reset(); + Shutdown.reset(); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('repeatedly creating and disposing instances never accumulates listeners', () => { + for (let i = 0; i < 25; i++) { + new Shutdown().dispose(); + } + + expect(listenerCounts()).toEqual(baseline); + }); + + it('Shutdown.reset removes singleton listeners and the next getInstance builds a fresh instance', () => { + const first = Shutdown.getInstance(); + expect(listenerCounts().SIGTERM).toBe(baseline.SIGTERM + 1); + + Shutdown.reset(); + + expect(listenerCounts()).toEqual(baseline); + const second = Shutdown.getInstance({ autoRegister: false }); + track(second); + expect(second).not.toBe(first); + expect(listenerCounts()).toEqual(baseline); + }); + + it('disposing a non-singleton instance keeps the active singleton and its listeners', () => { + const singleton = Shutdown.getInstance(); + const other = track(new Shutdown()); + + other.dispose(); + + expect(Shutdown.getInstance()).toBe(singleton); + expect(listenerCounts()).toEqual({ + SIGTERM: baseline.SIGTERM + 1, + SIGINT: baseline.SIGINT + 1, + }); + }); + + it('disposing the singleton directly clears it so getInstance returns a new one', () => { + const singleton = Shutdown.getInstance({ autoRegister: false }); + + singleton.dispose(); + + const next = Shutdown.getInstance({ autoRegister: false }); + expect(next).not.toBe(singleton); + }); + + it('a disposed instance keeps its shutdown callbacks usable without process listeners', async () => { + const shutdown = track(new Shutdown({ timeout: 1000 })); + const calls: string[] = []; + shutdown.onShutdown(() => { + calls.push('ran'); + }, 10, 'probe'); + + shutdown.dispose(); + await shutdown.shutdown(); + + expect(calls).toEqual(['ran']); + expect(listenerCounts()).toEqual(baseline); + }); +}); diff --git a/test/unit/in-process-test-isolation.test.ts b/test/unit/in-process-test-isolation.test.ts new file mode 100644 index 00000000..9e71995c --- /dev/null +++ b/test/unit/in-process-test-isolation.test.ts @@ -0,0 +1,54 @@ +import { readdirSync, readFileSync } from 'fs'; +import { join, relative } from 'path'; +import { describe, expect, it } from 'bun:test'; + +// Guards T-16: all test files share one bun process, so process-global mocks in one +// file silently change the modules and globals other files see. Restorable `spyOn` +// is the supported pattern; child-process harnesses (test/integration) are exempt. +const root = join(import.meta.dir, '..', '..'); +const scannedRoots = ['libs']; +const forbidden: Array<{ label: string; pattern: RegExp }> = [ + { label: 'mock.module(', pattern: /\bmock\.module\s*\(/ }, + { label: 'Bun.serve assignment', pattern: /\bBun\.serve\s*=(?!=)/ }, + { label: 'process.on assignment', pattern: /\bprocess\.(on|once|off)\s*=(?!=)/ }, + { label: 'process.exit assignment', pattern: /\bprocess\.exit\s*=(?!=)/ }, + { label: 'global console assignment', pattern: /\b(global|globalThis)\.console\s*=(?!=)/ }, +]; + +function collectTestFiles(dir: string, out: string[]): void { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) { + continue; + } + const full = join(dir, entry.name); + if (entry.isDirectory()) { + collectTestFiles(full, out); + } else if (/\.(test|spec)\.tsx?$/.test(entry.name)) { + out.push(full); + } + } +} + +describe('in-process test isolation', () => { + it('library tests never install process-global mocks or overwrite process/Bun globals', () => { + const files: string[] = []; + for (const dir of scannedRoots) { + collectTestFiles(join(root, dir), files); + } + expect(files.length).toBeGreaterThan(0); + + const violations: string[] = []; + for (const file of files) { + const lines = readFileSync(file, 'utf8').split('\n'); + lines.forEach((line, index) => { + for (const { label, pattern } of forbidden) { + if (pattern.test(line)) { + violations.push(`${relative(root, file)}:${index + 1} ${label}`); + } + } + }); + } + + expect(violations).toEqual([]); + }); +});