import { Queue as BullQueue, type Job } from 'bullmq'; import Redis, { type RedisOptions } from 'ioredis'; import type { CacheProvider } from '@stock-bot/cache'; import { createCache } from '@stock-bot/cache'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { LoggerLike as Logger } from '@stock-bot/logger'; import { Queue, removeScheduledJobsFromBullQueue, type QueueWorkerConfig, } from './queue'; import { QueueRateLimiter } from './rate-limiter'; import { getFullQueueName, normalizeServiceName, parseQueueName } from './service-utils'; import type { GlobalStats, JobData, JobOptions, QueueManagerConfig, QueueOptions, QueueRoute, QueueStats, RateLimitRule, RedisConfig, } from './types'; import { getRedisConnection } from './utils'; export interface QueueManagerDependencies { createRedis?: (options: RedisOptions) => Redis; createQueue?: ( name: string, redisConfig: RedisConfig, defaultJobOptions: JobOptions, workerConfig: QueueWorkerConfig, logger: Logger ) => Queue; } /** * QueueManager provides unified queue and cache management with service discovery * Handles both local and cross-service queue operations */ export class QueueManager { private queues = new Map(); private caches = new Map(); private rateLimiter?: QueueRateLimiter; private redisConnection: ReturnType; private ioredisConnection?: Redis; private lifecycle: 'running' | 'draining' | 'closed' = 'running'; private workersStarted = false; private shutdownPromise: Promise | null = null; private config: QueueManagerConfig; private readonly logger: Logger; private readonly deps?: QueueManagerDependencies; // Service discovery features private serviceName?: string; private queueRoutes = new Map(); private producerQueues = new Map(); // For cross-service sending private handlerRegistry?: HandlerRegistry; constructor( config: QueueManagerConfig, handlerRegistry?: HandlerRegistry, logger?: Logger, deps?: QueueManagerDependencies ) { // Always use DB 0 for queues if service name is provided if (config.serviceName) { config = { ...config, redis: { ...config.redis, db: 0, // All queues in DB 0 for cross-service communication }, }; } this.config = config; this.serviceName = config.serviceName; this.handlerRegistry = handlerRegistry; this.logger = logger || getLogger('QueueManager'); this.deps = deps; this.redisConnection = getRedisConnection(config.redis); // Create ioredis connection for rate limiter const retryDelay = config.redis.retryDelay; const ioredisOptions = { host: config.redis.host, port: config.redis.port, password: config.redis.password, username: config.redis.username, db: config.redis.db || 0, maxRetriesPerRequest: config.redis.maxRetriesPerRequest ?? 3, ...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }), enableReadyCheck: true, }; this.ioredisConnection = deps?.createRedis ? deps.createRedis(ioredisOptions) : new Redis(ioredisOptions); // Rate limiter will be initialized when rules are added dynamically // No longer initialized from config // Auto-discover routes if enabled and registry provided if (config.serviceName && config.autoDiscoverHandlers !== false && handlerRegistry) { this.discoverQueueRoutes(); } this.logger.info('QueueManager initialized', { redis: `${config.redis.host}:${config.redis.port}`, service: this.serviceName, discoveredRoutes: this.queueRoutes.size, hasRegistry: !!handlerRegistry, }); } /** * Get or create a queue - unified method that handles both scenarios * This is the main method for accessing queues * If serviceName is configured, automatically handles namespacing */ getQueue(queueName: string, options: QueueOptions = {}): Queue { this.assertConnectionsOpen(); let fullQueueName = queueName; let isOwnQueue = true; // Handle service namespacing if service name is configured if (this.serviceName) { const parsed = parseQueueName(queueName); if (parsed) { // Already in service:handler format fullQueueName = queueName; isOwnQueue = parsed.service === this.serviceName; } else { // Just handler name, assume it's for current service fullQueueName = getFullQueueName(this.serviceName, queueName); isOwnQueue = true; } // For cross-service queues, create without workers (producer-only) if (!isOwnQueue) { options = { ...options, workers: 0, // No workers for other services' queues }; } else { // For own service queues, include handler registry options = { ...options, handlerRegistry: this.handlerRegistry, }; } queueName = fullQueueName; } // Return existing queue if it exists if (this.queues.has(queueName)) { const existingQueue = this.queues.get(queueName); if (existingQueue) { return existingQueue; } } if (this.lifecycle !== 'running') { throw new Error('QueueManager is shutting down; new queues cannot be created'); } // Create new queue with merged options const mergedOptions = { ...this.config.defaultQueueOptions, ...options, }; // Prepare queue configuration const workers = mergedOptions.workers ?? this.config.defaultQueueOptions?.workers ?? 1; const concurrency = mergedOptions.concurrency ?? this.config.defaultQueueOptions?.concurrency ?? 1; const shouldStartWorker = workers > 0 && (!this.config.delayWorkerStart || this.workersStarted); const queueConfig: QueueWorkerConfig = { workers, concurrency, startWorker: shouldStartWorker, handlerRegistry: options.handlerRegistry || this.handlerRegistry, serviceName: this.config.serviceName, queueManager: this, }; const queue = this.deps?.createQueue ? this.deps.createQueue( queueName, this.config.redis, mergedOptions.defaultJobOptions || {}, queueConfig, this.logger ) : new Queue( queueName, this.config.redis, mergedOptions.defaultJobOptions || {}, queueConfig, this.logger ); // Store the queue this.queues.set(queueName, queue); // Rate limit rules are now added via addRateLimitRules after handlers are initialized this.logger.info('Queue created', { queueName, originalQueueName: options.handlerRegistry ? 'has-handler-registry' : 'no-handler-registry', workers: workers, concurrency: concurrency, handlerRegistryProvided: !!this.handlerRegistry, willStartWorkers: shouldStartWorker, isOwnQueue, serviceName: this.serviceName, }); return queue; } /** * Check if a queue exists */ hasQueue(queueName: string): boolean { return this.queues.has(queueName); } /** * Get all queue names */ getQueueNames(): string[] { return Array.from(this.queues.keys()); } /** * Get or create a cache for a queue */ getCache(queueName: string): CacheProvider { this.assertConnectionsOpen(); if (!this.caches.has(queueName)) { const cacheProvider = createCache({ redisConfig: this.config.redis, shared: false, keyPrefix: `batch:${queueName}:`, ttl: 86400, // 24 hours default enableMetrics: true, logger: { info: (...args: unknown[]) => this.logger.info(String(args[0]), args[1] as Record), error: (...args: unknown[]) => this.logger.error(String(args[0]), args[1] as Record), warn: (...args: unknown[]) => this.logger.warn(String(args[0]), args[1] as Record), debug: (...args: unknown[]) => this.logger.debug(String(args[0]), args[1] as Record), }, }); this.caches.set(queueName, cacheProvider); this.logger.trace('Cache created for queue', { queueName }); } const cache = this.caches.get(queueName); if (!cache) { throw new Error(`Expected cache for queue ${queueName} to exist`); } return cache; } /** * Initialize cache for a queue (ensures it's ready) */ async initializeCache(queueName: string): Promise { const cache = this.getCache(queueName); await cache.waitForReady(10000); this.logger.info('Cache initialized for queue', { queueName }); } /** * Get the queues map (for subclasses) */ protected getQueues(): Map { return this.queues; } /** * Get statistics for all queues */ async getGlobalStats(): Promise { const queueStats: Record = {}; let totalJobs = 0; let totalWorkers = 0; for (const [queueName, queue] of this.queues) { const stats = await queue.getStats(); queueStats[queueName] = stats; totalJobs += stats.waiting + stats.active + stats.completed + stats.failed + stats.delayed; totalWorkers += stats.workers || 0; } return { queues: queueStats, totalJobs, totalWorkers, uptime: process.uptime(), }; } /** * Get statistics for a specific queue */ async getQueueStats(queueName: string): Promise { const queue = this.queues.get(queueName); if (!queue) { return undefined; } return await queue.getStats(); } /** * Add a rate limit rule */ async addRateLimitRule(rule: RateLimitRule): Promise { if (!this.rateLimiter) { if (!this.ioredisConnection) { throw new Error('IoRedis connection not initialized'); } this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger); } await this.rateLimiter.addRule(rule); } /** * Add multiple rate limit rules at once */ async addRateLimitRules(rules: RateLimitRule[]): Promise { if (!this.rateLimiter) { if (!this.ioredisConnection) { throw new Error('IoRedis connection not initialized'); } this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger); } await Promise.all(rules.map(rule => defined(this.rateLimiter).addRule(rule))); this.logger.info('Added rate limit rules to QueueManager', { ruleCount: rules.length, rules, }); } /** * Check rate limits for a job - overloaded to support both interfaces */ async checkRateLimit( handlerOrQueueName: string, operationOrHandler?: string, operationIfThreeParams?: string ): Promise<{ allowed: boolean; retryDelayMs?: number; remainingPoints?: number; appliedRule?: RateLimitRule; }> { if (!this.rateLimiter) { return { allowed: true }; } // Support both 2-parameter and 3-parameter calls let handler: string; let operation: string | undefined; if (operationIfThreeParams !== undefined) { // 3-parameter call: checkRateLimit(queueName, handler, operation) handler = defined(operationOrHandler); operation = operationIfThreeParams; } else { // 2-parameter call: checkRateLimit(handler, operation) handler = handlerOrQueueName; operation = operationOrHandler; } // The new rate limiter only needs handler and operation const result = await this.rateLimiter.checkLimit(handler, operation); return { allowed: result.allowed, retryDelayMs: result.retryDelayMs, remainingPoints: result.remainingPoints, }; } /** * Get rate limit status */ async getRateLimitStatus(queueName: string, handler: string, operation: string) { if (!this.rateLimiter) { return { queueName, handler, operation, }; } // The new rate limiter only needs handler and operation const status = await this.rateLimiter.getStatus(handler, operation); return { queueName, ...status, }; } /** * Pause all queues */ async pauseAll(): Promise { const pausePromises = Array.from(this.queues.values()).map(queue => queue.pause()); await Promise.all(pausePromises); this.logger.info('All queues paused'); } /** * Resume all queues */ async resumeAll(): Promise { const resumePromises = Array.from(this.queues.values()).map(queue => queue.resume()); await Promise.all(resumePromises); this.logger.info('All queues resumed'); } /** * Pause a specific queue */ async pauseQueue(queueName: string): Promise { const queue = this.queues.get(queueName); if (!queue) { return false; } await queue.pause(); return true; } /** * Resume a specific queue */ async resumeQueue(queueName: string): Promise { const queue = this.queues.get(queueName); if (!queue) { return false; } await queue.resume(); return true; } /** * Drain all queues */ async drainAll(delayed = false): Promise { const drainPromises = Array.from(this.queues.values()).map(queue => queue.drain(delayed)); await Promise.all(drainPromises); this.logger.info('All queues drained', { delayed }); } /** * Clean all queues */ async cleanAll( grace: number = 0, limit: number = 100, type: 'completed' | 'failed' = 'completed' ): Promise { const cleanPromises = Array.from(this.queues.values()).map(queue => queue.clean(grace, limit, type) ); await Promise.all(cleanPromises); this.logger.info('All queues cleaned', { type, grace, limit }); } /** * Shutdown all queues and workers (thread-safe) */ shutdown(): Promise { if (!this.shutdownPromise) { this.lifecycle = 'draining'; this.logger.info('Shutting down QueueManager...'); // Store the promise before invoking owned transports, including cleanup // callbacks that can request shutdown again. this.shutdownPromise = Promise.resolve().then(() => this.performShutdown()); } return this.shutdownPromise; } private assertConnectionsOpen(): void { if (this.lifecycle === 'closed') { throw new Error('QueueManager is closed'); } } private async closeQueue(queue: Pick): Promise { try { await queue.close(); } catch (error) { this.logger.warn('Error closing queue', { error }); } } private async performShutdown(): Promise { // Active workers may still read batch payloads or publish child jobs while // their queues drain. Close those connections only after queue close settles. await Promise.all([...this.queues.values()].map(queue => this.closeQueue(queue))); this.lifecycle = 'closed'; await Promise.all([...this.producerQueues.values()].map(queue => this.closeQueue(queue))); await Promise.all( [...this.caches.values()].map(async cache => { try { // Batch payloads belong to queued work, not to this process. Completion // cleanup and TTL own deletion, even when another process uses this namespace. await cache.disconnect?.(); } catch (error) { this.logger.warn('Error disconnecting batch cache', { error }); } }) ); if (this.ioredisConnection) { try { await this.ioredisConnection.quit(); } catch (error) { this.logger.warn('Error closing ioredis connection', { error }); try { this.ioredisConnection.disconnect(); } catch (disconnectError) { this.logger.warn('Error disconnecting ioredis connection', { error: disconnectError }); } } } this.queues.clear(); this.producerQueues.clear(); this.caches.clear(); this.ioredisConnection = undefined; this.logger.info('QueueManager shutdown complete'); } /** * Start workers for all queues (used when delayWorkerStart is enabled) */ startAllWorkers(): void { if (this.lifecycle !== 'running') { throw new Error('QueueManager is shutting down; workers cannot be started'); } this.workersStarted = true; let workersStarted = 0; const queues = this.queues; const normalizedService = this.serviceName ? normalizeServiceName(this.serviceName) : undefined; this.logger.info( `Starting workers for ${queues.size} queues: ${Array.from(queues.keys()).join(', ')} (service: ${this.serviceName})` ); for (const [queueName, queue] of queues) { // If we have a service name, check if this queue belongs to us if (this.serviceName) { const parsed = parseQueueName(queueName); // Skip if not our service's queue if (parsed && parsed.service !== this.serviceName && parsed.service !== normalizedService) { this.logger.trace('Skipping workers for cross-service queue', { queueName, ownerService: parsed.service, currentService: this.serviceName, }); continue; } } const workerCount = this.config.defaultQueueOptions?.workers ?? 1; const concurrency = this.config.defaultQueueOptions?.concurrency ?? 1; if (workerCount > 0) { queue.startWorkersManually(workerCount, concurrency); workersStarted++; this.logger.debug('Started workers for queue', { queueName, workers: workerCount, concurrency, }); } } this.logger.info('Service workers started', { service: this.serviceName || 'default', totalQueues: queues.size, queuesWithWorkers: workersStarted, }); } /** * Reconcile and remove persisted repeatable/scheduled jobs for the specified * handler queues owned by this service without starting workers. * Manual jobs and other services' queues are preserved. */ async removeScheduledJobsForQueues(queueNames: string[]): Promise { this.assertConnectionsOpen(); let totalRemoved = 0; const seenFullNames = new Set(); const normalizedService = this.serviceName ? normalizeServiceName(this.serviceName) : undefined; for (const rawQueueName of queueNames) { let fullQueueName = rawQueueName; let isOwnQueue = true; if (this.serviceName) { const parsed = parseQueueName(rawQueueName); if (parsed) { fullQueueName = rawQueueName; isOwnQueue = parsed.service === this.serviceName || parsed.service === normalizedService; } else { fullQueueName = getFullQueueName(this.serviceName, rawQueueName); isOwnQueue = true; } } if (!isOwnQueue || seenFullNames.has(fullQueueName)) { continue; } seenFullNames.add(fullQueueName); const existingQueue = this.queues.get(fullQueueName); if (existingQueue) { totalRemoved += await existingQueue.removeAllScheduledJobs(); continue; } // Open a workerless BullQueue handle to clear persisted repeat schedules // before any worker can consume stale repeat jobs. const tempQueue = new BullQueue(fullQueueName, { connection: { ...this.redisConnection, maxRetriesPerRequest: 1, enableOfflineQueue: false }, }); try { totalRemoved += await removeScheduledJobsFromBullQueue(tempQueue); } finally { await tempQueue.close().catch(error => { this.logger.warn('Error closing temporary reconciliation queue', { queueName: fullQueueName, error, }); }); } } this.logger.info('Reconciled disabled scheduled jobs for service queues', { service: this.serviceName || 'default', queueCount: seenFullNames.size, removedCount: totalRemoved, }); return totalRemoved; } /** * Wait for all queues to be ready */ async waitUntilReady(): Promise { const readyPromises = Array.from(this.queues.values()).map(queue => queue.waitUntilReady()); await Promise.all(readyPromises); } /** * Get Redis configuration (for backward compatibility) */ getRedisConfig() { return this.config.redis; } /** * Get the current configuration */ getConfig(): Readonly { return { ...this.config }; } /** * Send a job to any queue (local or remote) * This is the main method for cross-service communication */ async send( targetQueue: string, operation: string, payload: unknown, options: JobOptions = {} ): Promise { if (!this.serviceName) { // If no service name, just use regular queue const queue = this.getQueue(targetQueue); return queue.add(operation, { handler: targetQueue, operation, payload }, options); } // Resolve the target queue const route = this.resolveQueueRoute(targetQueue); if (!route) { throw new Error(`Unknown queue: ${targetQueue}`); } // Validate operation if we have metadata if (route.operations && !route.operations.includes(operation)) { this.logger.warn('Operation not found in handler metadata', { handler: route.handler, operation, availableOperations: route.operations, }); } // Use a producer queue for cross-service sending const producerQueue = this.getProducerQueue(route.fullName); const jobData: JobData = { handler: route.handler, operation, payload, }; this.logger.trace('Sending job to queue', { targetQueue: route.fullName, handler: route.handler, operation, fromService: this.serviceName, toService: route.service, }); return producerQueue.add(operation, jobData, options); } /** * Resolve a queue name to a route */ private resolveQueueRoute(queueName: string): QueueRoute | null { // Check if it's a full queue name with service prefix const parsed = parseQueueName(queueName); if (parsed) { // Try to find in discovered routes by handler name const route = this.queueRoutes.get(parsed.handler); if (route && route.service === parsed.service) { return route; } // Create a route on the fly return { fullName: queueName, service: parsed.service, handler: parsed.handler, db: 0, // All queues in DB 0 }; } // Check if it's just a handler name in our routes const route = this.queueRoutes.get(queueName); if (route) { return route; } // Try to find in handler registry const ownerService = this.handlerRegistry?.getHandlerService(queueName); if (ownerService) { return { fullName: getFullQueueName(ownerService, queueName), service: ownerService, handler: queueName, db: 0, // All queues in DB 0 }; } return null; } /** * Get a producer queue for sending to other services */ private getProducerQueue(queueName: string): BullQueue { this.assertConnectionsOpen(); if (!this.producerQueues.has(queueName)) { const queue = new BullQueue(queueName, { connection: this.redisConnection, defaultJobOptions: this.config.defaultQueueOptions?.defaultJobOptions, }); this.producerQueues.set(queueName, queue); } return defined(this.producerQueues.get(queueName)); } /** * Discover all available queue routes from handler registry */ private discoverQueueRoutes(): void { if (!this.handlerRegistry) { this.logger.warn('No handler registry provided, skipping route discovery'); return; } try { const handlers = this.handlerRegistry.getAllMetadata(); for (const [handlerName, metadata] of handlers) { // Get the service that registered this handler const ownerService = metadata.service; if (ownerService) { const fullName = getFullQueueName(ownerService, handlerName); this.queueRoutes.set(handlerName, { fullName, service: ownerService, handler: handlerName, db: 0, // All queues in DB 0 operations: metadata.operations.map(op => op.name), }); this.logger.trace('Discovered queue route', { handler: handlerName, service: ownerService, operations: metadata.operations.length, }); } } // Also discover handlers registered by the current service if (this.serviceName) { const myHandlers = this.handlerRegistry.getServiceHandlers(this.serviceName); for (const metadata of myHandlers) { const handlerName = metadata.name; if (!this.queueRoutes.has(handlerName)) { const fullName = getFullQueueName(this.serviceName, handlerName); this.queueRoutes.set(handlerName, { fullName, service: this.serviceName, handler: handlerName, db: 0, // All queues in DB 0 }); } } } this.logger.info('Queue routes discovered', { totalRoutes: this.queueRoutes.size, routes: Array.from(this.queueRoutes.keys()), }); } catch (error) { this.logger.error('Failed to discover queue routes', { error }); } } }