T-16: M0.1b — Make repo-wide bun test green: fix queue, shutdown-signal and research-workflow test failures

This commit is contained in:
Studio 2026-11-27 12:01:06 -05:00
parent 890761e0d5
commit 9c4e87cdfd
17 changed files with 366 additions and 266 deletions

View file

@ -1,21 +1,48 @@
import { beforeEach, describe, expect, it } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { RedisCache } from '../src/redis-cache'; import { RedisCache } from '../src/redis-cache';
import type { CacheOptions } from '../src/types'; import type { CacheOptions, RedisConfig } from '../src/types';
const hasTestRedis = Boolean(process.env.BACKTEST_TEST_REDIS_URL); const testRedisUrl = process.env.BACKTEST_TEST_REDIS_URL;
describe.skipIf(!hasTestRedis)('RedisCache', () => { function parseTestRedisConfig(rawUrl: string): RedisConfig {
const parsed = new URL(rawUrl);
if (parsed.pathname !== '/15') {
throw new Error('BACKTEST_TEST_REDIS_URL must point to dedicated Redis database /15');
}
return {
host: parsed.hostname,
port: parsed.port ? Number(parsed.port) : 6379,
db: 15,
...(parsed.username ? { username: decodeURIComponent(parsed.username) } : {}),
...(parsed.password ? { password: decodeURIComponent(parsed.password) } : {}),
};
}
if (!testRedisUrl) {
process.stderr.write(
'Skipping RedisCache integration tests: set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database /15\n'
);
}
describe.skipIf(!testRedisUrl)('RedisCache', () => {
let cache: RedisCache; let cache: RedisCache;
let redisConfig: RedisConfig;
beforeEach(() => { beforeEach(() => {
redisConfig = parseTestRedisConfig(testRedisUrl!);
const options: CacheOptions = { const options: CacheOptions = {
keyPrefix: 'test:', keyPrefix: 'test:',
ttl: 3600, ttl: 3600,
redisConfig: { host: 'localhost', port: 6379 }, shared: false,
redisConfig,
}; };
cache = new RedisCache(options); cache = new RedisCache(options);
}); });
afterEach(async () => {
await cache?.disconnect().catch(() => {});
});
describe('Core functionality', () => { describe('Core functionality', () => {
it('should create cache instance', () => { it('should create cache instance', () => {
expect(cache).toBeDefined(); expect(cache).toBeDefined();
@ -148,16 +175,21 @@ describe.skipIf(!hasTestRedis)('RedisCache', () => {
// Force an error by using invalid JSON // Force an error by using invalid JSON
const badCache = new RedisCache({ const badCache = new RedisCache({
keyPrefix: 'bad:', keyPrefix: 'bad:',
redisConfig: { host: 'localhost', port: 6379 }, shared: false,
redisConfig,
}); });
// This would normally throw but should return null try {
const result = await badCache.get('non-existent'); // This would normally throw but should return null
expect(result).toBeNull(); const result = await badCache.get('non-existent');
expect(result).toBeNull();
// Check stats updated // Check stats updated
const stats = badCache.getStats(); const stats = badCache.getStats();
expect(stats.misses).toBe(1); expect(stats.misses).toBe(1);
} finally {
await badCache.disconnect().catch(() => {});
}
}); });
}); });

View file

@ -1,19 +1,10 @@
import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import * as loggerModule from '@stock-bot/logger';
import { z } from 'zod'; import { z } from 'zod';
import { ConfigManager } from '../src/config-manager'; import { ConfigManager } from '../src/config-manager';
import { ConfigError, ConfigValidationError } from '../src/errors'; import { ConfigError, ConfigValidationError } from '../src/errors';
import type { ConfigLoader, Environment } from '../src/types'; import type { ConfigLoader, Environment } from '../src/types';
// Mock the logger
mock.module('@stock-bot/logger', () => ({
getLogger: () => ({
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
}),
}));
// Mock loader class // Mock loader class
class MockLoader implements ConfigLoader { class MockLoader implements ConfigLoader {
constructor( constructor(
@ -28,10 +19,28 @@ class MockLoader implements ConfigLoader {
describe('ConfigManager', () => { describe('ConfigManager', () => {
let manager: ConfigManager<any>; let manager: ConfigManager<any>;
let getLoggerSpy: ReturnType<typeof spyOn>;
const originalNodeEnv = process.env.NODE_ENV;
beforeEach(() => { beforeEach(() => {
// Reset environment // Reset environment
delete process.env.NODE_ENV; delete process.env.NODE_ENV;
getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue({
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
} as any);
});
afterEach(() => {
getLoggerSpy?.mockRestore();
if (originalNodeEnv === undefined) {
delete process.env.NODE_ENV;
} else {
process.env.NODE_ENV = originalNodeEnv;
}
}); });
describe('constructor', () => { describe('constructor', () => {

View file

@ -1,16 +1,12 @@
import { readFileSync } from 'fs'; import * as fs from 'fs';
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { ConfigLoaderError } from '../src/errors'; import { ConfigLoaderError } from '../src/errors';
import { EnvLoader } from '../src/loaders/env.loader'; import { EnvLoader } from '../src/loaders/env.loader';
import { queueConfigSchema } from '../src/schemas'; import { queueConfigSchema } from '../src/schemas';
// Mock fs module
mock.module('fs', () => ({
readFileSync: mock(() => ''),
}));
describe('EnvLoader', () => { describe('EnvLoader', () => {
let loader: EnvLoader; let loader: EnvLoader;
let readFileSync: ReturnType<typeof spyOn>;
const originalEnv = { ...process.env }; const originalEnv = { ...process.env };
beforeEach(() => { beforeEach(() => {
@ -18,9 +14,11 @@ describe('EnvLoader', () => {
for (const key in process.env) { for (const key in process.env) {
delete process.env[key]; delete process.env[key];
} }
readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any);
}); });
afterEach(() => { afterEach(() => {
readFileSync?.mockRestore();
// Restore original environment // Restore original environment
for (const key in process.env) { for (const key in process.env) {
delete process.env[key]; delete process.env[key];
@ -371,17 +369,20 @@ KEY_WITHOUT_VALUE=
it('should warn on other file errors', () => { it('should warn on other file errors', () => {
const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {}); const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
try {
(readFileSync as any).mockImplementation(() => {
const error: any = new Error('Permission denied');
error.code = 'EACCES';
throw error;
});
(readFileSync as any).mockImplementation(() => { loader = new EnvLoader();
const error: any = new Error('Permission denied'); loader.load();
error.code = 'EACCES';
throw error;
});
loader = new EnvLoader(); expect(consoleWarnSpy).toHaveBeenCalled();
loader.load(); } finally {
consoleWarnSpy.mockRestore();
expect(consoleWarnSpy).toHaveBeenCalled(); }
}); });
it('should try multiple env file paths', () => { it('should try multiple env file paths', () => {

View file

@ -1,23 +1,23 @@
import { existsSync, readFileSync } from 'fs'; import * as fs from 'fs';
import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { ConfigLoaderError } from '../src/errors'; import { ConfigLoaderError } from '../src/errors';
import { FileLoader } from '../src/loaders/file.loader'; import { FileLoader } from '../src/loaders/file.loader';
// Mock fs module
mock.module('fs', () => ({
existsSync: mock(() => false),
readFileSync: mock(() => ''),
}));
describe('FileLoader', () => { describe('FileLoader', () => {
let loader: FileLoader; let loader: FileLoader;
let existsSync: ReturnType<typeof spyOn>;
let readFileSync: ReturnType<typeof spyOn>;
const configPath = '/app/config'; const configPath = '/app/config';
const environment = 'development'; const environment = 'development';
beforeEach(() => { beforeEach(() => {
// Reset mocks existsSync = spyOn(fs, 'existsSync').mockReturnValue(false);
(existsSync as any).mockReset(); readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any);
(readFileSync as any).mockReset(); });
afterEach(() => {
existsSync?.mockRestore();
readFileSync?.mockRestore();
}); });
describe('constructor', () => { describe('constructor', () => {

View file

@ -1,5 +1,5 @@
import { asFunction, createContainer, type AwilixContainer } from 'awilix'; import { asFunction, createContainer, type AwilixContainer } from 'awilix';
import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import type { HandlerRegistry } from '@stock-bot/handler-registry'; import type { HandlerRegistry } from '@stock-bot/handler-registry';
import * as logger from '@stock-bot/logger'; import * as logger from '@stock-bot/logger';
import type { ExecutionContext, IHandler } from '@stock-bot/types'; import type { ExecutionContext, IHandler } from '@stock-bot/types';
@ -55,6 +55,7 @@ describe('HandlerScanner', () => {
let mockRegistry: HandlerRegistry; let mockRegistry: HandlerRegistry;
let container: AwilixContainer; let container: AwilixContainer;
let mockLogger: any; let mockLogger: any;
let getLoggerSpy: ReturnType<typeof spyOn>;
beforeEach(() => { beforeEach(() => {
// Create mock logger // Create mock logger
@ -63,10 +64,11 @@ describe('HandlerScanner', () => {
debug: mock(() => {}), debug: mock(() => {}),
error: mock(() => {}), error: mock(() => {}),
warn: mock(() => {}), warn: mock(() => {}),
trace: mock(() => {}),
}; };
// Mock getLogger to return our mock logger // Mock getLogger to return our mock logger
spyOn(logger, 'getLogger').mockReturnValue(mockLogger); getLoggerSpy = spyOn(logger, 'getLogger').mockReturnValue(mockLogger);
// Create mock registry // Create mock registry
mockRegistry = { mockRegistry = {
@ -87,6 +89,10 @@ describe('HandlerScanner', () => {
}); });
}); });
afterEach(() => {
getLoggerSpy?.mockRestore();
});
describe('scanHandlers', () => { describe('scanHandlers', () => {
it('should handle empty patterns gracefully', async () => { it('should handle empty patterns gracefully', async () => {
await scanner.scanHandlers([]); await scanner.scanHandlers([]);

View file

@ -1,21 +1,28 @@
import { asFunction, asValue, createContainer } from 'awilix'; import { asFunction, asValue, createContainer } from 'awilix';
import { describe, expect, it, mock } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import * as queueModule from '@stock-bot/queue';
import { import {
registerApplicationServices, registerApplicationServices,
registerCacheServices, registerCacheServices,
registerDatabaseServices, registerDatabaseServices,
} from '../src/registrations'; } from '../src/registrations';
// Mock the queue module
mock.module('@stock-bot/queue', () => ({
createServiceCache: mock(() => ({
get: mock(() => Promise.resolve(null)),
set: mock(() => Promise.resolve()),
del: mock(() => Promise.resolve()),
})),
}));
describe('DI Registrations', () => { describe('DI Registrations', () => {
let createServiceCacheSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
createServiceCacheSpy = spyOn(queueModule, 'createServiceCache').mockImplementation(
(() => ({
get: mock(() => Promise.resolve(null)),
set: mock(() => Promise.resolve()),
del: mock(() => Promise.resolve()),
})) as any
);
});
afterEach(() => {
createServiceCacheSpy?.mockRestore();
});
describe('registerCacheServices', () => { describe('registerCacheServices', () => {
it('should register null cache when redis disabled', () => { it('should register null cache when redis disabled', () => {
const container = createContainer(); const container = createContainer();
@ -108,22 +115,6 @@ describe('DI Registrations', () => {
it('should register MongoDB when config exists', () => { it('should register MongoDB when config exists', () => {
const container = createContainer(); const container = createContainer();
// Mock MongoDB client
const mockMongoClient = {
connect: mock(() => Promise.resolve()),
disconnect: mock(() => Promise.resolve()),
getDb: mock(() => ({})),
};
// Mock the MongoDB factory
mock.module('@stock-bot/mongodb', () => ({
MongoDBClient: class {
constructor() {
return mockMongoClient;
}
},
}));
const config = { const config = {
mongodb: { mongodb: {
enabled: true, enabled: true,
@ -140,22 +131,6 @@ describe('DI Registrations', () => {
it('should register PostgreSQL when config exists', () => { it('should register PostgreSQL when config exists', () => {
const container = createContainer(); const container = createContainer();
// Mock Postgres client
const mockPostgresClient = {
connect: mock(() => Promise.resolve()),
disconnect: mock(() => Promise.resolve()),
query: mock(() => Promise.resolve({ rows: [] })),
};
// Mock the Postgres factory
mock.module('@stock-bot/postgres', () => ({
PostgresClient: class {
constructor() {
return mockPostgresClient;
}
},
}));
const config = { const config = {
postgres: { postgres: {
enabled: true, enabled: true,
@ -175,22 +150,6 @@ describe('DI Registrations', () => {
it('should register QuestDB when config exists', () => { it('should register QuestDB when config exists', () => {
const container = createContainer(); const container = createContainer();
// Mock QuestDB client
const mockQuestdbClient = {
connect: mock(() => Promise.resolve()),
disconnect: mock(() => Promise.resolve()),
query: mock(() => Promise.resolve({ data: [] })),
};
// Mock the QuestDB factory
mock.module('@stock-bot/questdb', () => ({
QuestDBClient: class {
constructor() {
return mockQuestdbClient;
}
},
}));
const config = { const config = {
questdb: { questdb: {
enabled: true, enabled: true,
@ -281,21 +240,6 @@ describe('DI Registrations', () => {
}), }),
}); });
// Mock queue manager
const mockQueueManager = {
getQueue: mock(() => ({})),
startAllWorkers: mock(() => {}),
shutdown: mock(() => Promise.resolve()),
};
mock.module('@stock-bot/queue', () => ({
QueueManager: class {
constructor() {
return mockQueueManager;
}
},
}));
const config = { const config = {
service: { service: {
name: 'test-service', name: 'test-service',

View file

@ -1,25 +1,23 @@
import { afterEach, describe, expect, it, mock } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import type { BaseAppConfig } from '@stock-bot/config'; import type { BaseAppConfig } from '@stock-bot/config';
import * as loggerModule from '@stock-bot/logger';
import { Shutdown } from '@stock-bot/shutdown';
import { ServiceApplication } from '../src/service-application'; import { ServiceApplication } from '../src/service-application';
import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application'; import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application';
// Mock logger module // Mock logger object used via spyOn in beforeEach (restored in afterEach)
const mockLogger = { const mockLogger: any = {
info: mock(() => {}), info: mock(() => {}),
error: mock(() => {}), error: mock(() => {}),
warn: mock(() => {}), warn: mock(() => {}),
debug: mock(() => {}), debug: mock(() => {}),
child: mock(() => mockLogger), trace: mock(() => {}),
}; };
mockLogger.child = mock(() => mockLogger);
mock.module('@stock-bot/logger', () => ({ // Mock shutdown instance used via spyOn(Shutdown, 'getInstance') in beforeEach
getLogger: () => mockLogger,
setLoggerConfig: mock(() => {}),
shutdownLoggers: mock(() => Promise.resolve()),
}));
// Mock shutdown module
const mockShutdownInstance = { const mockShutdownInstance = {
shutdown: mock(() => Promise.resolve()),
onShutdown: mock(() => {}), onShutdown: mock(() => {}),
onShutdownHigh: mock(() => {}), onShutdownHigh: mock(() => {}),
onShutdownMedium: mock(() => {}), onShutdownMedium: mock(() => {}),
@ -30,24 +28,13 @@ const mockShutdownInstance = {
executeCallbacks: mock(() => Promise.resolve()), executeCallbacks: mock(() => Promise.resolve()),
}; };
const mockShutdown = { // Mock server returned by spyOn(Bun, 'serve')
getInstance: mock(() => mockShutdownInstance),
};
mock.module('@stock-bot/shutdown', () => ({
Shutdown: mockShutdown,
}));
// Mock Bun.serve
const mockServer = { const mockServer = {
stop: mock(() => {}), stop: mock(() => {}),
port: 3000, port: 3000,
hostname: '0.0.0.0', hostname: '0.0.0.0',
}; };
const _originalBunServe = Bun.serve;
Bun.serve = mock(() => mockServer);
const mockConfig: BaseAppConfig = { const mockConfig: BaseAppConfig = {
name: 'test-service', name: 'test-service',
version: '1.0.0', version: '1.0.0',
@ -75,13 +62,44 @@ const mockConfig: BaseAppConfig = {
describe('ServiceApplication', () => { describe('ServiceApplication', () => {
let app: ServiceApplication; let app: ServiceApplication;
let getLoggerSpy: ReturnType<typeof spyOn>;
let setLoggerConfigSpy: ReturnType<typeof spyOn>;
let shutdownLoggersSpy: ReturnType<typeof spyOn>;
let shutdownGetInstanceSpy: ReturnType<typeof spyOn>;
let bunServeSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue(mockLogger);
setLoggerConfigSpy = spyOn(loggerModule, 'setLoggerConfig').mockImplementation(() => {});
shutdownLoggersSpy = spyOn(loggerModule, 'shutdownLoggers').mockResolvedValue(undefined);
shutdownGetInstanceSpy = spyOn(Shutdown, 'getInstance').mockReturnValue(
mockShutdownInstance as any
);
bunServeSpy = spyOn(Bun, 'serve').mockImplementation((() => mockServer) as any);
});
afterEach(() => { afterEach(() => {
// Clean up app if it exists before restoring spies
if (app) {
app.stop().catch(() => {});
app = null as any;
}
// Restore module/global spies so no state leaks to other test files
getLoggerSpy?.mockRestore();
setLoggerConfigSpy?.mockRestore();
shutdownLoggersSpy?.mockRestore();
shutdownGetInstanceSpy?.mockRestore();
bunServeSpy?.mockRestore();
// Reset mocks // Reset mocks
mockLogger.info.mockReset(); mockLogger.info.mockReset();
mockLogger.error.mockReset(); mockLogger.error.mockReset();
mockLogger.warn.mockReset(); mockLogger.warn.mockReset();
mockLogger.debug.mockReset(); mockLogger.debug.mockReset();
mockLogger.trace.mockReset();
mockShutdownInstance.shutdown.mockReset();
mockShutdownInstance.shutdown.mockImplementation(() => Promise.resolve());
mockShutdownInstance.onShutdown.mockReset(); mockShutdownInstance.onShutdown.mockReset();
mockShutdownInstance.onShutdownHigh.mockReset(); mockShutdownInstance.onShutdownHigh.mockReset();
mockShutdownInstance.onShutdownMedium.mockReset(); mockShutdownInstance.onShutdownMedium.mockReset();
@ -90,12 +108,6 @@ describe('ServiceApplication', () => {
mockShutdownInstance.registerAsync.mockReset(); mockShutdownInstance.registerAsync.mockReset();
mockShutdownInstance.handleTermination.mockReset(); mockShutdownInstance.handleTermination.mockReset();
mockShutdownInstance.executeCallbacks.mockReset(); mockShutdownInstance.executeCallbacks.mockReset();
// Clean up app if it exists
if (app) {
app.stop().catch(() => {});
app = null as any;
}
}); });
describe('constructor', () => { describe('constructor', () => {
@ -136,7 +148,7 @@ describe('ServiceApplication', () => {
}; };
app = new ServiceApplication(mockConfig, serviceConfig); app = new ServiceApplication(mockConfig, serviceConfig);
expect(mockShutdown.getInstance).toHaveBeenCalledWith({ expect(shutdownGetInstanceSpy).toHaveBeenCalledWith({
timeout: 30000, timeout: 30000,
}); });
}); });
@ -605,19 +617,14 @@ describe('ServiceApplication', () => {
describe('stop method', () => { describe('stop method', () => {
it('should trigger shutdown', async () => { it('should trigger shutdown', async () => {
const mockShutdownInstance = { const localShutdownInstance = {
shutdown: mock(() => Promise.resolve()), shutdown: mock(() => Promise.resolve()),
onShutdown: mock(() => {}), onShutdown: mock(() => {}),
onShutdownHigh: mock(() => {}), onShutdownHigh: mock(() => {}),
onShutdownMedium: mock(() => {}), onShutdownMedium: mock(() => {}),
onShutdownLow: mock(() => {}), onShutdownLow: mock(() => {}),
}; };
shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any);
mock.module('@stock-bot/shutdown', () => ({
Shutdown: {
getInstance: () => mockShutdownInstance,
},
}));
const serviceConfig: ServiceApplicationConfig = { const serviceConfig: ServiceApplicationConfig = {
serviceName: 'test-service', serviceName: 'test-service',
@ -627,7 +634,7 @@ describe('ServiceApplication', () => {
await app.stop(); await app.stop();
expect(mockShutdownInstance.shutdown).toHaveBeenCalled(); expect(localShutdownInstance.shutdown).toHaveBeenCalled();
expect(mockLogger.info).toHaveBeenCalledWith('Stopping test-service service...'); expect(mockLogger.info).toHaveBeenCalledWith('Stopping test-service service...');
}); });
}); });
@ -665,19 +672,14 @@ describe('ServiceApplication', () => {
describe('shutdown handlers', () => { describe('shutdown handlers', () => {
it('should register all shutdown handlers during start', async () => { it('should register all shutdown handlers during start', async () => {
const mockShutdownInstance = { const localShutdownInstance = {
shutdown: mock(() => Promise.resolve()), shutdown: mock(() => Promise.resolve()),
onShutdown: mock(() => {}), onShutdown: mock(() => {}),
onShutdownHigh: mock(() => {}), onShutdownHigh: mock(() => {}),
onShutdownMedium: mock(() => {}), onShutdownMedium: mock(() => {}),
onShutdownLow: mock(() => {}), onShutdownLow: mock(() => {}),
}; };
shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any);
mock.module('@stock-bot/shutdown', () => ({
Shutdown: {
getInstance: () => mockShutdownInstance,
},
}));
const serviceConfig: ServiceApplicationConfig = { const serviceConfig: ServiceApplicationConfig = {
serviceName: 'test-service', serviceName: 'test-service',
@ -731,10 +733,10 @@ describe('ServiceApplication', () => {
); );
// Should have registered shutdown handlers // Should have registered shutdown handlers
expect(mockShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers expect(localShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers
// Test the handlers by calling them // Test the handlers by calling them
const shutdownHandlers = (mockShutdownInstance.onShutdown as any).mock.calls; const shutdownHandlers = (localShutdownInstance.onShutdown as any).mock.calls;
// Find and execute queue shutdown handler (priority 9) // Find and execute queue shutdown handler (priority 9)
const queueHandler = shutdownHandlers.find(call => call[2] === 'Queue System'); const queueHandler = shutdownHandlers.find(call => call[2] === 'Queue System');

View file

@ -96,9 +96,15 @@ describe('createJobHandler', () => {
}); });
it('should support async operations', async () => { it('should support async operations', async () => {
let resolveStep!: () => void;
let asyncStepCompleted = false;
const stepGate = new Promise<void>(resolve => {
resolveStep = resolve;
});
const handler = createJobHandler<TestPayload, TestResult>(async job => { const handler = createJobHandler<TestPayload, TestResult>(async job => {
// Simulate async operation await stepGate;
await new Promise(resolve => setTimeout(resolve, 10)); asyncStepCompleted = true;
return { return {
success: true, success: true,
@ -120,12 +126,14 @@ describe('createJobHandler', () => {
updateProgress: async () => {}, updateProgress: async () => {},
}; };
const startTime = Date.now(); const pending = handler(mockJob as any);
const result = await handler(mockJob as any); expect(asyncStepCompleted).toBe(false);
const endTime = Date.now(); resolveStep();
const result = await pending;
expect(asyncStepCompleted).toBe(true);
expect(result.success).toBe(true); expect(result.success).toBe(true);
expect(endTime - startTime).toBeGreaterThanOrEqual(10); expect(result.processedBy).toBe('user-789');
}); });
it('should maintain type safety for complex payloads', () => { it('should maintain type safety for complex payloads', () => {

View file

@ -99,6 +99,14 @@ export class QueueManager {
this.ioredisConnection = deps?.createRedis this.ioredisConnection = deps?.createRedis
? deps.createRedis(ioredisOptions) ? deps.createRedis(ioredisOptions)
: new Redis(ioredisOptions); : new Redis(ioredisOptions);
if (typeof this.ioredisConnection.on === 'function') {
this.ioredisConnection.on('error', error => {
this.logger.error('QueueManager Redis connection error', {
service: this.serviceName,
error,
});
});
}
// Rate limiter will be initialized when rules are added dynamically // Rate limiter will be initialized when rules are added dynamically
// No longer initialized from config // No longer initialized from config

View file

@ -123,7 +123,7 @@ export class Queue {
// Initialize queue events if workers will be used // Initialize queue events if workers will be used
if (config.workers && config.workers > 0) { if (config.workers && config.workers > 0) {
this.queueEvents = new QueueEvents(queueName, { connection }); this.queueEvents = this.createQueueEvents(connection);
} }
// Start workers if requested and not explicitly disabled // Start workers if requested and not explicitly disabled
@ -262,12 +262,18 @@ export class Queue {
return await this.bullQueue.getJob(jobId); return await this.bullQueue.getJob(jobId);
} }
private createQueueEvents(connection: ReturnType<typeof getRedisConnection>): QueueEvents {
const queueEvents = new QueueEvents(this.queueName, { connection });
queueEvents.on('error', error =>
this.logger.error('QueueEvents connection error', { queueName: this.queueName, error })
);
return queueEvents;
}
/** Wait for a result using a QueueEvents connection owned by this queue. */ /** Wait for a result using a QueueEvents connection owned by this queue. */
async waitForJob<T>(job: Job<unknown, T>, timeout = 30000): Promise<T> { async waitForJob<T>(job: Job<unknown, T>, timeout = 30000): Promise<T> {
if (!this.queueEvents) { if (!this.queueEvents) {
this.queueEvents = new QueueEvents(this.queueName, { this.queueEvents = this.createQueueEvents(getRedisConnection(this.redisConfig));
connection: getRedisConnection(this.redisConfig),
});
} }
await this.queueEvents.waitUntilReady(); await this.queueEvents.waitUntilReady();
return job.waitUntilFinished(this.queueEvents, timeout); return job.waitUntilFinished(this.queueEvents, timeout);
@ -589,7 +595,7 @@ export class Queue {
// Initialize queue events if not already done // Initialize queue events if not already done
if (!this.queueEvents) { if (!this.queueEvents) {
const connection = getRedisConnection(this.redisConfig); const connection = getRedisConnection(this.redisConfig);
this.queueEvents = new QueueEvents(this.queueName, { connection }); this.queueEvents = this.createQueueEvents(connection);
} }
this.startWorkers(workerCount, concurrency); this.startWorkers(workerCount, concurrency);

View file

@ -1,17 +1,37 @@
import { describe, expect, it, mock } from 'bun:test'; import { afterEach, describe, expect, it, mock } from 'bun:test';
import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue'; import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue';
import { QueueManager } from '../src/queue-manager'; import { QueueManager } from '../src/queue-manager';
import type { QueueWorkerConfig, RedisConfig } from '../src/types'; import type { QueueWorkerConfig, RedisConfig } from '../src/types';
describe('Queue Class', () => { describe('Queue Class', () => {
// Use a non-QA isolated loopback port so unit tests never touch QA Dragonfly (localhost:6379)
const mockRedisConfig: RedisConfig = { const mockRedisConfig: RedisConfig = {
host: 'localhost', host: '127.0.0.1',
port: 6379, port: 16379,
maxRetriesPerRequest: 1,
retryDelay: 50,
}; };
const createdQueues: Queue[] = [];
function trackQueue(queue: Queue): Queue {
createdQueues.push(queue);
return queue;
}
afterEach(async () => {
await Promise.all(
createdQueues.splice(0).map(async queue => {
// Stop reconnect timers on unreachable test sockets before awaiting BullMQ close()
(queue.getBullQueue() as any).connection?._client?.disconnect(false);
(queue as any).queueEvents?.connection?._client?.disconnect(false);
await queue.close().catch(() => {});
})
);
});
describe('basic functionality', () => { describe('basic functionality', () => {
it('should create queue with minimal config', () => { it('should create queue with minimal config', () => {
const queue = new Queue('test-queue', mockRedisConfig); const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
expect(queue).toBeDefined(); expect(queue).toBeDefined();
expect(queue.getName()).toBe('test-queue'); expect(queue.getName()).toBe('test-queue');
}); });
@ -22,7 +42,7 @@ describe('Queue Class', () => {
backoff: { type: 'exponential' as const, delay: 2000 }, backoff: { type: 'exponential' as const, delay: 2000 },
}; };
const queue = new Queue('test-queue', mockRedisConfig, defaultJobOptions); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, defaultJobOptions));
expect(queue).toBeDefined(); expect(queue).toBeDefined();
expect(queue.getName()).toBe('test-queue'); expect(queue.getName()).toBe('test-queue');
}); });
@ -36,7 +56,7 @@ describe('Queue Class', () => {
trace: mock(() => {}), trace: mock(() => {}),
}; };
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
expect(queue).toBeDefined(); expect(queue).toBeDefined();
}); });
@ -48,19 +68,19 @@ describe('Queue Class', () => {
serviceName: 'test-service', serviceName: 'test-service',
}; };
const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig));
expect(queue).toBeDefined(); expect(queue).toBeDefined();
}); });
}); });
describe('queue naming and utilities', () => { describe('queue naming and utilities', () => {
it('should return queue name', () => { it('should return queue name', () => {
const queue = new Queue('my-test-queue', mockRedisConfig); const queue = trackQueue(new Queue('my-test-queue', mockRedisConfig));
expect(queue.getName()).toBe('my-test-queue'); expect(queue.getName()).toBe('my-test-queue');
}); });
it('should get bull queue instance', () => { it('should get bull queue instance', () => {
const queue = new Queue('test-queue', mockRedisConfig); const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
const bullQueue = queue.getBullQueue(); const bullQueue = queue.getBullQueue();
expect(bullQueue).toBeDefined(); expect(bullQueue).toBeDefined();
}); });
@ -83,7 +103,7 @@ describe('Queue Class', () => {
child: mock(() => mockChildLogger), child: mock(() => mockChildLogger),
}; };
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
const childLogger = queue.createChildLogger('batch', { batchId: '123' }); const childLogger = queue.createChildLogger('batch', { batchId: '123' });
expect(childLogger).toBe(mockChildLogger); expect(childLogger).toBe(mockChildLogger);
@ -99,7 +119,7 @@ describe('Queue Class', () => {
trace: mock(() => {}), trace: mock(() => {}),
}; };
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
const childLogger = queue.createChildLogger('batch', { batchId: '123' }); const childLogger = queue.createChildLogger('batch', { batchId: '123' });
expect(childLogger).toBe(mockLogger); expect(childLogger).toBe(mockLogger);
@ -108,7 +128,7 @@ describe('Queue Class', () => {
describe('worker count methods', () => { describe('worker count methods', () => {
it('should get worker count when no workers', () => { it('should get worker count when no workers', () => {
const queue = new Queue('test-queue', mockRedisConfig); const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
expect(queue.getWorkerCount()).toBe(0); expect(queue.getWorkerCount()).toBe(0);
}); });
@ -118,7 +138,7 @@ describe('Queue Class', () => {
startWorker: false, // Don't actually start startWorker: false, // Don't actually start
}; };
const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig));
// Workers aren't actually started with startWorker: false // Workers aren't actually started with startWorker: false
expect(queue.getWorkerCount()).toBe(0); expect(queue.getWorkerCount()).toBe(0);
}); });

View file

@ -1,4 +1,4 @@
import { describe, expect, it } from 'bun:test'; import { afterEach, describe, expect, it } from 'bun:test';
import { createServiceCache, ServiceCache } from '../src/service-cache'; import { createServiceCache, ServiceCache } from '../src/service-cache';
import { import {
generateCachePrefix, generateCachePrefix,
@ -78,39 +78,40 @@ describe('Service Utilities', () => {
}); });
describe('ServiceCache', () => { describe('ServiceCache', () => {
it('should create service cache', () => { // Use a non-QA isolated loopback port and non-shared clients so unit tests never touch QA Dragonfly (localhost:6379)
const mockRedisConfig = { const mockRedisConfig = {
host: 'localhost', host: '127.0.0.1',
port: 6379, port: 16379,
}; maxRetriesPerRequest: 1,
retryDelay: 50,
};
const createdCaches: ServiceCache[] = [];
// Since ServiceCache constructor internally creates a real cache, afterEach(async () => {
// we can't easily test it without mocking the createCache function await Promise.all(createdCaches.splice(0).map(cache => cache.disconnect().catch(() => {})));
// For now, just test that the function exists and returns something });
const serviceCache = createServiceCache('myservice', mockRedisConfig);
it('should create service cache', () => {
const serviceCache = createServiceCache('myservice', mockRedisConfig, { shared: false });
createdCaches.push(serviceCache);
expect(serviceCache).toBeDefined(); expect(serviceCache).toBeDefined();
expect(serviceCache).toBeInstanceOf(ServiceCache); expect(serviceCache).toBeInstanceOf(ServiceCache);
}); });
it('should handle cache prefix correctly', () => { it('should handle cache prefix correctly', () => {
const mockRedisConfig = { const serviceCache = createServiceCache('webApi', mockRedisConfig, { shared: false });
host: 'localhost', createdCaches.push(serviceCache);
port: 6379,
};
const serviceCache = createServiceCache('webApi', mockRedisConfig);
expect(serviceCache).toBeDefined(); expect(serviceCache).toBeDefined();
// The prefix is set internally as cache:web-api // The prefix is set internally as cache:web-api
expect(serviceCache.getKey('test')).toBe('cache:web-api:test'); expect(serviceCache.getKey('test')).toBe('cache:web-api:test');
}); });
it('should support global cache option', () => { it('should support global cache option', () => {
const mockRedisConfig = { const globalCache = createServiceCache('myservice', mockRedisConfig, {
host: 'localhost', global: true,
port: 6379, shared: false,
}; });
createdCaches.push(globalCache);
const globalCache = createServiceCache('myservice', mockRedisConfig, { global: true });
expect(globalCache).toBeDefined(); expect(globalCache).toBeDefined();
// Global cache uses a different prefix // Global cache uses a different prefix
expect(globalCache.getKey('test')).toBe('stock-bot:shared:test'); expect(globalCache.getKey('test')).toBe('stock-bot:shared:test');
@ -120,16 +121,16 @@ describe('ServiceCache', () => {
describe('Batch Processing', () => { describe('Batch Processing', () => {
it('should handle batch job data types', () => { it('should handle batch job data types', () => {
const batchJob: BatchJobData = { const batchJob: BatchJobData = {
items: [1, 2, 3], payloadKey: 'batch:payload:1',
options: { batchIndex: 0,
batchSize: 10, totalBatches: 3,
concurrency: 2, itemCount: 10,
}, totalDelayHours: 1,
}; };
expect(batchJob.items).toHaveLength(3); expect(batchJob.payloadKey).toBe('batch:payload:1');
expect(batchJob.options.batchSize).toBe(10); expect(batchJob.totalBatches).toBe(3);
expect(batchJob.options.concurrency).toBe(2); expect(batchJob.itemCount).toBe(10);
}); });
it('should process batch results', () => { it('should process batch results', () => {

View file

@ -15,6 +15,7 @@ export class Shutdown {
private shutdownTimeout: number; private shutdownTimeout: number;
private callbacks: CallbackEntry[] = []; private callbacks: CallbackEntry[] = [];
private signalHandlersRegistered = false; private signalHandlersRegistered = false;
private registeredSignalHandlers = new Map<NodeJS.Signals, () => void>();
private shutdownPromise: Promise<void> | null = null; private shutdownPromise: Promise<void> | null = null;
private triggerSignal: string | null = null; private triggerSignal: string | null = null;
@ -33,6 +34,37 @@ export class Shutdown {
return Shutdown.instance; return Shutdown.instance;
} }
/**
* Dispose the singleton instance and remove its signal listeners.
*/
static reset(): void {
if (Shutdown.instance) {
Shutdown.instance.dispose();
Shutdown.instance = null;
}
}
/**
* Remove process signal handlers registered by this instance.
*/
removeSignalHandlers(): void {
for (const [signal, listener] of this.registeredSignalHandlers) {
process.off(signal, listener);
}
this.registeredSignalHandlers.clear();
this.signalHandlersRegistered = false;
}
/**
* Clean up signal listeners and clear singleton reference if this is the active singleton.
*/
dispose(): void {
this.removeSignalHandlers();
if (Shutdown.instance === this) {
Shutdown.instance = null;
}
}
/** /**
* Get current shutdown status * Get current shutdown status
*/ */
@ -153,7 +185,7 @@ export class Shutdown {
signals.forEach(signal => { signals.forEach(signal => {
// Use process.on instead of process.once to handle multiple signals // Use process.on instead of process.once to handle multiple signals
process.on(signal, async () => { const listener = async () => {
this.logger.info(`Received ${signal} signal`); this.logger.info(`Received ${signal} signal`);
// If already shutting down, ignore the signal // If already shutting down, ignore the signal
@ -178,7 +210,10 @@ export class Shutdown {
process.exit(1); process.exit(1);
} }
}); };
this.registeredSignalHandlers.set(signal, listener);
process.on(signal, listener);
this.logger.debug(`Registered handler for ${signal}`); this.logger.debug(`Registered handler for ${signal}`);
}); });

View file

@ -6,14 +6,15 @@ describe('Shutdown Comprehensive Tests', () => {
beforeEach(() => { beforeEach(() => {
// Reset singleton instance for each test // Reset singleton instance for each test
(Shutdown as any).instance = null; Shutdown.reset();
// Create a fresh instance for each test // Create a fresh instance for each test
shutdownInstance = new Shutdown({ autoRegister: false }); shutdownInstance = new Shutdown({ autoRegister: false });
}); });
afterEach(() => { afterEach(() => {
// Clean up singleton // Clean up singleton and any signal listeners
(Shutdown as any).instance = null; shutdownInstance?.dispose();
Shutdown.reset();
}); });
describe('Basic Functionality', () => { describe('Basic Functionality', () => {
@ -250,10 +251,18 @@ describe('Shutdown Comprehensive Tests', () => {
}); });
it('should use default timeout', () => { it('should use default timeout', () => {
const _defaultShutdown = new Shutdown(); const defaultShutdown = new Shutdown();
let secondShutdown: Shutdown | undefined;
// Can't directly test timeout value, but we can verify it doesn't throw try {
expect(() => new Shutdown()).not.toThrow(); // Can't directly test timeout value, but we can verify it doesn't throw
expect(() => {
secondShutdown = new Shutdown();
}).not.toThrow();
} finally {
defaultShutdown.dispose();
secondShutdown?.dispose();
}
}); });
}); });
}); });

View file

@ -1,46 +1,46 @@
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import { Shutdown } from '../src/shutdown'; import { Shutdown } from '../src/shutdown';
describe('Shutdown Signal Handlers', () => { describe('Shutdown Signal Handlers', () => {
let shutdown: Shutdown; let shutdown: Shutdown | undefined;
let processOnceSpy: any; let processOnceSpy: ReturnType<typeof spyOn>;
let processExitSpy: any; let processExitSpy: ReturnType<typeof spyOn>;
const originalOn = process.on;
const originalExit = process.exit;
beforeEach(() => { beforeEach(() => {
// Reset singleton instance // Reset singleton instance
(Shutdown as any).instance = null; Shutdown.reset();
shutdown = undefined;
// Mock process.on to capture signal handlers // Mock process.on to capture signal handlers
const listeners: Record<string, Function[]> = {}; const listeners: Record<string, Function[]> = {};
processOnceSpy = mock((event: string, handler: Function) => { processOnceSpy = spyOn(process, 'on').mockImplementation(((event: string, handler: Function) => {
if (!listeners[event]) { if (!listeners[event]) {
listeners[event] = []; listeners[event] = [];
} }
listeners[event].push(handler); listeners[event].push(handler);
return process; return process;
}); }) as any);
process.on = processOnceSpy as any;
// Mock process.exit // Mock process.exit
processExitSpy = mock((_code?: number) => { processExitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => {
// Just record the call, don't actually exit // Just record the call, don't actually exit
return undefined as never; return undefined as never;
}); }) as any);
process.exit = processExitSpy as any;
// Store listeners for manual triggering // Store listeners for manual triggering
(global as any).__testListeners = listeners; (global as any).__testListeners = listeners;
}); });
afterEach(() => { afterEach(() => {
// Restore original methods // Clean up any registered listeners and singleton before restoring process spies
process.on = originalOn; shutdown?.dispose();
process.exit = originalExit; shutdown = undefined;
Shutdown.reset();
// Restore original methods
processOnceSpy?.mockRestore();
processExitSpy?.mockRestore();
// Clean up
(Shutdown as any).instance = null;
delete (global as any).__testListeners; delete (global as any).__testListeners;
}); });

View file

@ -5,14 +5,14 @@ describe('Shutdown', () => {
let shutdown: Shutdown; let shutdown: Shutdown;
beforeEach(() => { beforeEach(() => {
// Reset singleton instance for each test // Reset singleton instance and remove any prior signal listeners
(Shutdown as any).instance = null; Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 1000 }); shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
}); });
afterEach(() => { afterEach(() => {
// Clean up // Clean up listeners and singleton
(Shutdown as any).instance = null; Shutdown.reset();
}); });
describe('getInstance', () => { describe('getInstance', () => {
@ -24,7 +24,8 @@ describe('Shutdown', () => {
}); });
it('should use provided config on first call', () => { it('should use provided config on first call', () => {
const instance = Shutdown.getInstance({ timeout: 5000 }); Shutdown.reset();
const instance = Shutdown.getInstance({ timeout: 5000, autoRegister: false });
expect(instance).toBeDefined(); expect(instance).toBeDefined();
}); });
}); });
@ -125,20 +126,28 @@ describe('Shutdown', () => {
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
let slowTimer: ReturnType<typeof setTimeout> | undefined;
const slowHandler = mock(async () => { const slowHandler = mock(async () => {
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => {
slowTimer = setTimeout(resolve, 2000);
});
}); });
shutdown = Shutdown.getInstance({ timeout: 100 }); Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false });
shutdown.onShutdown(slowHandler, 10, 'Slow Handler'); shutdown.onShutdown(slowHandler, 10, 'Slow Handler');
const start = Date.now(); const start = Date.now();
await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); try {
await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout');
} finally {
clearTimeout(slowTimer);
}
const duration = Date.now() - start; const duration = Date.now() - start;
// Shutdown waits for timeout (100ms) plus some processing time // Shutdown waits for timeout (100ms) plus some processing time
expect(duration).toBeGreaterThan(90); expect(duration).toBeGreaterThan(90);
expect(duration).toBeLessThan(1500); // But not the full 2000ms expect(duration).toBeLessThan(500);
}); });
}); });
@ -161,8 +170,8 @@ describe('Shutdown', () => {
await shutdown.shutdown(); await shutdown.shutdown();
// Reset by creating new instance // Reset by creating new instance
(Shutdown as any).instance = null; Shutdown.reset();
shutdown = Shutdown.getInstance({ timeout: 1000 }); shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
shutdown.onShutdown(handler, 10, 'Handler'); shutdown.onShutdown(handler, 10, 'Handler');
await shutdown.shutdown(); await shutdown.shutdown();

View file

@ -9,7 +9,13 @@
// Bun.timeout = 30000; // Bun.timeout = 30000;
// Store original console methods to allow restoration // Store original console methods to allow restoration
const originalConsole = global.console; const originalConsoleMethods = {
log: console.log.bind(console),
debug: console.debug.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
};
// Mock console methods to reduce noise during tests // Mock console methods to reduce noise during tests
// These can be restored with testHelpers.restoreConsole() // These can be restored with testHelpers.restoreConsole()
@ -98,7 +104,11 @@ global.testHelpers = {
* Restore console methods * Restore console methods
*/ */
restoreConsole: () => { restoreConsole: () => {
global.console = originalConsole; console.log = originalConsoleMethods.log;
console.debug = originalConsoleMethods.debug;
console.info = originalConsoleMethods.info;
console.warn = originalConsoleMethods.warn;
console.error = originalConsoleMethods.error;
} }
}; };