import type { AwilixContainer } from 'awilix'; import { getLogger } from '@stock-bot/logger'; import type { ServiceDefinitions } from '../container/types'; interface ServiceWithLifecycle { connect?: () => Promise; disconnect?: () => Promise; close?: () => Promise; initialize?: () => Promise; shutdown?: () => Promise; } export class ServiceLifecycleManager { private readonly logger = getLogger('service-lifecycle'); private readonly services = [ { name: 'cache', key: 'cache' as const }, { name: 'globalCache', key: 'globalCache' as const }, { name: 'proxyCache', key: 'proxyCache' as const }, { name: 'mongoClient', key: 'mongoClient' as const }, { name: 'postgresClient', key: 'postgresClient' as const }, { name: 'questdbClient', key: 'questdbClient' as const }, { name: 'proxyManager', key: 'proxyManager' as const }, { name: 'queueManager', key: 'queueManager' as const }, ]; async initializeServices( container: AwilixContainer, timeout = 30000 ): Promise { const started: { name: string; service: ServiceWithLifecycle; settled: boolean }[] = []; const cancelTimers: (() => void)[] = []; let failed = false; try { const work = this.services.map(async ({ name, key }) => { const service = container.cradle[key] as ServiceWithLifecycle | null; if (!service) { return Promise.resolve(); } if (this.initializing.has(service)) { throw new Error(`${name} initialization is already in progress`); } this.initializing.add(service); const entry = { name, service, settled: false }; started.push(entry); // A timeout cannot cancel connect(). Keep ownership until it settles, // including resources allocated by an initializer that later rejects. const initialization = (async () => { // A completed shutdown belongs to the preceding connection lifetime. // Wait for an in-flight close before starting a fresh lifetime. const previousCleanup = this.cleanup.get(service); if (previousCleanup) { await previousCleanup; } if (!failed) { this.cleanup.delete(service); await this.initializeService(name, service); } })().finally(async () => { entry.settled = true; try { if (failed) { await this.cleanupOnce(name, service); } } finally { this.initializing.delete(service); } }); let timer: ReturnType; const expired = new Promise((_, reject) => { timer = setTimeout( () => reject(new Error(`${name} initialization timed out after ${timeout}ms`)), timeout ); }); const clear = () => clearTimeout(timer); cancelTimers.push(clear); return Promise.race([initialization, expired]).finally(clear); }); await Promise.all(work); this.logger.info('All services initialized successfully'); } catch (error) { failed = true; // Only settled work can be released finally. Pending work retains the // cleanup continuation above, so startup need not wait on a hung connect. const rollback = Promise.allSettled( started .filter(entry => entry.settled) .reverse() .map(({ name, service }) => this.cleanupOnce(name, service)) ); let cleanupTimer: ReturnType | undefined; try { // A hanging disconnect must not turn a bounded startup failure into a // permanently pending build. Keep the cleanup promise owned after this cap. await Promise.race([ rollback, new Promise(resolve => { cleanupTimer = setTimeout(() => { this.logger.warn(`Startup rollback still pending after ${timeout}ms`); resolve(); }, timeout); }), ]); } finally { clearTimeout(cleanupTimer); } throw error; } finally { for (const clear of cancelTimers) { clear(); } } } private readonly initializing = new WeakSet(); private readonly cleanup = new WeakMap>(); private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise { let work = this.cleanup.get(service); if (!work) { work = this.shutdownService(name, service); this.cleanup.set(service, work); } return work; } async shutdownServices(container: AwilixContainer): Promise { // Resolve and clean independently: one broken resolver must not prevent // other, already connected resources from being released. for (const { name, key } of [...this.services].reverse()) { try { const service = container.cradle[key] as ServiceWithLifecycle | null; if (service) { await this.cleanupOnce(name, service); } } catch (error) { this.logger.error(`Error resolving ${name} during shutdown:`, error); } } this.logger.info('All services shut down'); } private async initializeService(name: string, service: ServiceWithLifecycle): Promise { try { if (typeof service.connect === 'function') { await service.connect(); this.logger.info(`${name} connected`); } else if (typeof service.initialize === 'function') { await service.initialize(); this.logger.info(`${name} initialized`); } } catch (error) { this.logger.error(`Failed to initialize ${name}:`, error); throw error; } } private async shutdownService(name: string, service: ServiceWithLifecycle): Promise { try { if (typeof service.disconnect === 'function') { await service.disconnect(); } else if (typeof service.close === 'function') { await service.close(); } else if (typeof service.shutdown === 'function') { await service.shutdown(); } this.logger.info(`${name} shut down`); } catch (error) { this.logger.error(`Error shutting down ${name}:`, error); } } }