/** * Monitoring Service * Collects health and performance metrics from all system components */ import * as os from 'os'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { getFullQueueName } from '@stock-bot/queue'; import { monitoringReadinessSchema, orchestratorDiagnosticSchema, type MonitoringReadiness, } from '@stock-bot/stock-config/diagnostics'; import type { CacheStats, DatabaseStats, ProxyStats, QueueStats, ServiceMetrics, ServiceStatus, SystemHealth, SystemOverview, } from '../types/monitoring.types'; export class MonitoringService { private readonly logger = getLogger('monitoring-service'); private startTime = Date.now(); constructor( private readonly container: IServiceContainer, private readonly options: { origin?: string; request?: (url: URL, init: RequestInit) => Promise; } = {} ) {} /** Explicit prerequisites and unknown execution capability; never a readiness shortcut. */ async getReadiness(request: Request): Promise { const reasons: string[] = []; const [leases, queue, orchestrator] = await Promise.all([ (async () => { try { if (!this.container.postgres) { return null; } const result = await this.container.postgres.query<{ run_id: string; attempt_id: string | null; expired: boolean; }>( "SELECT id AS run_id, attempt_id, (lease_expires_at IS NULL OR lease_expires_at <= NOW()) AS expired FROM runs WHERE status IN ('running','paused') ORDER BY id" ); return result.rows.map(row => ({ runId: row.run_id, attemptId: row.attempt_id, expired: row.expired, })); } catch { return null; } })(), (async () => { try { if (!this.container.queueManager) { throw new Error('Unavailable'); } const snapshot = await this.container.queueManager .getQueue(getFullQueueName('orchestrator', 'orchestrator'), { workers: 0 }) .getStats(); return { connected: true, workers: snapshot.workers ?? null, paused: snapshot.paused }; } catch { return { connected: false, workers: null, paused: null }; } })(), (async () => { try { if (!this.options.origin) { return null; } const origin = new URL(this.options.origin); if ( !['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash ) { return null; } const headers = new Headers(); for (const name of ['authorization', 'cookie', 'origin']) { const value = request.headers.get(name); if (value) { headers.set(name, value); } } const response = await (this.options.request ?? fetch)( new URL('/api/diagnostics', origin), { headers, redirect: 'error', signal: AbortSignal.timeout(5000) } ); if (!response.ok) { return null; } return orchestratorDiagnosticSchema.parse(await response.json()); } catch { return null; } })(), ]); if (leases === null) { reasons.push('Research PostgreSQL unavailable'); } if (!queue.connected) { reasons.push('Research queue unavailable'); } if (queue.workers === null) { reasons.push('Research worker count unknown'); } else if (queue.workers === 0) { reasons.push('No research queue workers'); } if (queue.paused) { reasons.push('Research queue paused'); } if (!orchestrator) { reasons.push( this.options.origin ? 'Orchestrator diagnostics unavailable' : 'Configure ORCHESTRATOR_URL to inspect orchestrator readiness' ); } else { if (!orchestrator.research) { reasons.push('Research runtime unavailable'); } else if (!orchestrator.research.accepting) { reasons.push('Research runtime shutting down'); } if (!orchestrator.build) { reasons.push('Canonical build artifacts unavailable'); } } if (leases?.some(lease => lease.expired)) { reasons.push('Expired research attempts require durable recovery'); } const unavailable = reasons.length > 0; reasons.push( 'Native execution is verified at run start; this snapshot does not launch a worker' ); return monitoringReadinessSchema.parse({ observedAt: new Date().toISOString(), postgres: leases === null ? 'unavailable' : 'connected', queue, leases, orchestrator, research: { status: unavailable ? 'unavailable' : 'unknown', reasons }, live: 'disabled', }); } /** * Get cache/Dragonfly statistics */ async getCacheStats(): Promise { try { if (!this.container.cache) { return { provider: 'dragonfly', connected: false, }; } // Check if cache is connected using the isReady method const isConnected = this.container.cache.isReady(); if (!isConnected) { return { provider: 'dragonfly', connected: false, }; } // Get cache stats from the provider const cacheStats = this.container.cache.getStats(); // Since we can't access Redis info directly, we'll use what's available return { provider: 'dragonfly', connected: true, uptime: cacheStats.uptime, stats: { hits: cacheStats.hits, misses: cacheStats.misses, keys: null, // Not measured by the public cache capability. }, }; } catch (error) { this.logger.error('Failed to get cache stats', { error }); return { provider: 'dragonfly', connected: false, }; } } /** * Get queue statistics */ async getQueueStats(): Promise { const manager = this.container.queueManager; if (!manager) { return []; } const owners = { qm: 'data-ingestion', ib: 'data-ingestion', ceo: 'data-ingestion', webshare: 'data-ingestion', exchanges: 'data-pipeline', symbols: 'data-pipeline', orchestrator: 'orchestrator', }; return Promise.all( Object.entries(owners).map(async ([name, service]) => { try { const queue = manager.getQueue(getFullQueueName(service, name), { workers: 0 }); const snapshot = await queue.getStats(); return { name, service, queue: name, connected: true, paused: snapshot.paused, jobs: { waiting: snapshot.waiting, active: snapshot.active, completed: snapshot.completed, failed: snapshot.failed, delayed: snapshot.delayed, paused: null, // Queue pause status does not measure paused-job count. }, workers: snapshot.workers === undefined ? undefined : { count: snapshot.workers }, }; } catch (error) { this.logger.warn('Unable to inspect queue', { name, service, error }); return { name, service, queue: name, connected: false, jobs: null, }; } }) ); } /** Database health uses the public adapter capabilities. */ async getDatabaseStats(): Promise { const stats: DatabaseStats[] = []; // PostgreSQL stats if (this.container.postgres) { try { const startTime = Date.now(); const _result = await this.container.postgres.query('SELECT 1'); const latency = Date.now() - startTime; // Get pool stats const pool = this.container.postgres.connectionPool; const poolStats = pool ? { size: pool.totalCount || 0, active: pool.totalCount - pool.idleCount, idle: pool.idleCount, waiting: pool.waitingCount, max: pool.options?.max || 0, } : undefined; stats.push({ type: 'postgres', name: 'PostgreSQL', connected: true, latency, pool: poolStats, }); } catch (error) { this.logger.error('Failed to get PostgreSQL stats', { error }); stats.push({ type: 'postgres', name: 'PostgreSQL', connected: false, }); } } // MongoDB stats if (this.container.mongodb) { try { const startTime = Date.now(); const mongoClient = this.container.mongodb; // This is MongoDBClient const db = mongoClient.getDatabase(); await db.admin().ping(); const latency = Date.now() - startTime; const serverStatus = await db.admin().serverStatus(); stats.push({ type: 'mongodb', name: 'MongoDB', connected: true, latency, stats: { version: serverStatus.version, uptime: serverStatus.uptime, connections: serverStatus.connections, opcounters: serverStatus.opcounters, }, }); } catch (error) { this.logger.error('Failed to get MongoDB stats', { error }); stats.push({ type: 'mongodb', name: 'MongoDB', connected: false, }); } } // QuestDB stats if (this.container.questdb) { try { const startTime = Date.now(); // QuestDB health check const response = await fetch( `http://${process.env.QUESTDB_HOST || 'localhost'}:9000/exec?query=SELECT%201`, { signal: AbortSignal.timeout(5000), redirect: 'error' } ); const latency = Date.now() - startTime; stats.push({ type: 'questdb', name: 'QuestDB', connected: response.ok, latency, }); } catch (error) { this.logger.error('Failed to get QuestDB stats', { error }); stats.push({ type: 'questdb', name: 'QuestDB', connected: false, }); } } return stats; } /** * Get system health summary */ async getSystemHealth(): Promise { const [cacheStats, queueStats, databaseStats] = await Promise.all([ this.getCacheStats(), this.getQueueStats(), this.getDatabaseStats(), ]); const processMemory = process.memoryUsage(); const systemMemory = this.getSystemMemory(); const uptime = Date.now() - this.startTime; const cpuInfo = this.getCpuUsage(); // Determine overall health status const errors: string[] = []; if (!cacheStats.connected) { errors.push('Cache service is disconnected'); } const disconnectedQueues = queueStats.filter(q => !q.connected); if (disconnectedQueues.length > 0) { errors.push(`${disconnectedQueues.length} queue(s) are disconnected`); } if (!databaseStats.some(db => db.type === 'postgres')) { errors.push('Research PostgreSQL is not configured'); } if ( !queueStats.some( queue => queue.service === 'orchestrator' && queue.connected && (queue.workers?.count ?? 0) > 0 ) ) { errors.push('Research queue worker unavailable'); } const disconnectedDbs = databaseStats.filter(db => !db.connected); if (disconnectedDbs.length > 0) { errors.push(`${disconnectedDbs.length} database(s) are disconnected`); } const status = errors.length === 0 ? 'healthy' : errors.length < 3 ? 'degraded' : 'unhealthy'; return { status, timestamp: new Date().toISOString(), uptime, memory: { used: systemMemory.used, total: systemMemory.total, percentage: systemMemory.percentage, heap: { used: processMemory.heapUsed, total: processMemory.heapTotal, }, }, cpu: cpuInfo, services: { cache: cacheStats, queues: queueStats, databases: databaseStats, }, errors: errors.length > 0 ? errors : undefined, }; } /** * Get service metrics (placeholder for future implementation) */ async getServiceMetrics(): Promise { const now = new Date().toISOString(); return { requestsPerSecond: { timestamp: now, value: null, unit: 'req/s', }, averageResponseTime: { timestamp: now, value: null, unit: 'ms', }, errorRate: { timestamp: now, value: null, unit: '%', }, activeConnections: { timestamp: now, value: null, unit: 'connections', }, }; } /** * Get service status for all microservices */ async getServiceStatus(): Promise { const services: ServiceStatus[] = []; // Define service endpoints const serviceEndpoints = [ { name: 'data-ingestion', port: 2001, path: '/health' }, { name: 'data-pipeline', port: 2002, path: '/health' }, { name: 'web-api', port: 2003, path: '/health' }, ]; for (const service of serviceEndpoints) { try { // For the current service (web-api), add it directly without health check if (service.name === 'web-api') { services.push({ name: 'web-api', version: 'unknown', status: 'running', port: process.env.PORT ? parseInt(process.env.PORT) : 2003, uptime: Date.now() - this.startTime, lastCheck: new Date().toISOString(), healthy: null, }); continue; } const startTime = Date.now(); const response = await fetch(`http://localhost:${service.port}${service.path}`, { signal: AbortSignal.timeout(5000), // 5 second timeout }); const _latency = Date.now() - startTime; if (response.ok) { const data = await response.json(); services.push({ name: service.name, version: typeof data.version === 'string' ? data.version : 'unknown', status: 'running', port: service.port, uptime: typeof data.uptime === 'number' && Number.isFinite(data.uptime) && data.uptime >= 0 ? data.uptime : null, lastCheck: new Date().toISOString(), healthy: null, }); } else { services.push({ name: service.name, version: 'unknown', status: 'error', port: service.port, uptime: null, lastCheck: new Date().toISOString(), healthy: false, error: `HTTP ${response.status}`, }); } } catch { services.push({ name: service.name, version: 'unknown', status: 'stopped', port: service.port, uptime: null, lastCheck: new Date().toISOString(), healthy: false, error: 'Service health request unavailable', }); } } return services; } /** * Get proxy statistics */ async getProxyStats(): Promise { try { // Since web-api doesn't have proxy manager, query the cache directly // The proxy manager stores data with cache:proxy: prefix if (!this.container.cache) { return { enabled: false, totalProxies: 0, workingProxies: 0, failedProxies: 0, }; } try { // Get proxy data from cache using getRaw method // The proxy manager uses cache:proxy: prefix, but web-api cache uses cache:api: const cacheProvider = this.container.cache; if (cacheProvider.getRaw) { // Use getRaw to access data with different cache prefix // The proxy manager now uses a global cache:proxy: prefix this.logger.debug('Attempting to fetch proxy data from cache'); const [cachedProxies, lastUpdateStr] = await Promise.all([ cacheProvider.getRaw<{ isWorking?: boolean }[]>('cache:proxy:active'), cacheProvider.getRaw('cache:proxy:last-update'), ]); this.logger.debug('Proxy cache data retrieved', { hasProxies: !!cachedProxies, isArray: Array.isArray(cachedProxies), proxyCount: cachedProxies ? cachedProxies.length : 0, lastUpdate: lastUpdateStr, }); if (cachedProxies && Array.isArray(cachedProxies)) { const workingCount = cachedProxies.filter(p => p.isWorking !== false).length; const failedCount = cachedProxies.filter(p => p.isWorking === false).length; return { enabled: true, totalProxies: cachedProxies.length, workingProxies: workingCount, failedProxies: failedCount, lastUpdate: lastUpdateStr || undefined, }; } } else { this.logger.debug('Cache provider does not support getRaw method'); } // No cached data found - proxies might not be initialized yet return { enabled: true, totalProxies: 0, workingProxies: 0, failedProxies: 0, }; } catch (cacheError) { this.logger.debug('Could not retrieve proxy data from cache', { error: cacheError }); // Return basic stats if cache query fails return { enabled: true, totalProxies: 0, workingProxies: 0, failedProxies: 0, }; } } catch (error) { this.logger.error('Failed to get proxy stats', { error }); return null; } } /** * Get comprehensive system overview */ async getSystemOverview(): Promise { const [services, health, proxies] = await Promise.all([ this.getServiceStatus(), this.getSystemHealth(), this.getProxyStats(), ]); return { services, health, proxies: proxies || undefined, environment: { nodeVersion: process.version, platform: os.platform(), architecture: os.arch(), hostname: os.hostname(), }, }; } /** * Get detailed CPU usage */ private getCpuUsage() { const cpus = os.cpus(); let totalIdle = 0; let totalTick = 0; cpus.forEach(cpu => { for (const type in cpu.times) { totalTick += cpu.times[type as keyof typeof cpu.times]; } totalIdle += cpu.times.idle; }); const idle = totalIdle / cpus.length; const total = totalTick / cpus.length; const usage = 100 - ~~((100 * idle) / total); return { usage, loadAverage: os.loadavg(), cores: cpus.length, }; } /** * Get system memory info */ private getSystemMemory() { const totalMem = os.totalmem(); const freeMem = os.freemem(); // On Linux, freeMem includes buffers/cache, but we want "available" memory // which better represents memory that can be used by applications let availableMem = freeMem; // Try to read from /proc/meminfo for more accurate memory stats on Linux if (os.platform() === 'linux') { try { const fs = require('fs'); const meminfo = fs.readFileSync('/proc/meminfo', 'utf8'); const lines = meminfo.split('\n'); let memAvailable = 0; let _memTotal = 0; for (const line of lines) { if (line.startsWith('MemAvailable:')) { memAvailable = parseInt(line.split(/\s+/)[1], 10) * 1024; // Convert from KB to bytes } else if (line.startsWith('MemTotal:')) { _memTotal = parseInt(line.split(/\s+/)[1], 10) * 1024; } } if (memAvailable > 0) { availableMem = memAvailable; } } catch (error) { // Fallback to os.freemem() if we can't read /proc/meminfo this.logger.debug('Could not read /proc/meminfo', { error }); } } const usedMem = totalMem - availableMem; return { total: totalMem, used: usedMem, free: freeMem, available: availableMem, percentage: (usedMem / totalMem) * 100, }; } /** * Get active worker count from Redis */ /** * Get active worker count using BullMQ's built-in tracking */ }