stock-bot/apps/stock/web-api/src/services/monitoring.service.ts
2026-10-20 14:35:45 -04:00

600 lines
16 KiB
TypeScript

/**
* 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 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) {}
/**
* Get cache/Dragonfly statistics
*/
async getCacheStats(): Promise<CacheStats> {
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: 0, // We can't get total keys without direct Redis access
evictedKeys: 0,
expiredKeys: 0,
},
};
} catch (error) {
this.logger.error('Failed to get cache stats', { error });
return {
provider: 'dragonfly',
connected: false,
};
}
}
/**
* Get queue statistics
*/
async getQueueStats(): Promise<QueueStats[]> {
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',
};
return Promise.all(
Object.entries(owners).map(async ([name, service]) => {
try {
const queue = manager.getQueue(getFullQueueName(service, name));
const snapshot = await queue.getStats();
return {
name,
service,
queue: name,
connected: true,
jobs: {
waiting: snapshot.waiting,
active: snapshot.active,
completed: snapshot.completed,
failed: snapshot.failed,
delayed: snapshot.delayed,
paused: snapshot.paused ? 1 : 0,
},
workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 },
};
} catch (error) {
this.logger.warn('Unable to inspect queue', { name, service, error });
return {
name,
service,
queue: name,
connected: false,
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
};
}
})
);
}
/** Database health uses the public adapter capabilities. */
async getDatabaseStats(): Promise<DatabaseStats[]> {
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`
);
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<SystemHealth> {
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`);
}
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<ServiceMetrics> {
const now = new Date().toISOString();
return {
requestsPerSecond: {
timestamp: now,
value: 0,
unit: 'req/s',
},
averageResponseTime: {
timestamp: now,
value: 0,
unit: 'ms',
},
errorRate: {
timestamp: now,
value: 0,
unit: '%',
},
activeConnections: {
timestamp: now,
value: 0,
unit: 'connections',
},
};
}
/**
* Parse value from Redis INFO output
*/
private parseInfoValue(info: string, key: string): number {
const match = info.match(new RegExp(`${key}:(\\d+)`));
return match?.[1] ? parseInt(match[1], 10) : 0;
}
/**
* Parse Redis INFO into structured object
*/
private parseRedisInfo(info: string): Record<string, Record<string, string>> {
const result: Record<string, Record<string, string>> = {};
const sections = info.split('\r\n\r\n');
for (const section of sections) {
const lines = section.split('\r\n');
const sectionName = lines[0]?.replace('# ', '') || 'general';
result[sectionName] = {};
for (let i = 1; i < lines.length; i++) {
const [key, value] = (lines[i] ?? '').split(':');
if (key && value) {
result[sectionName][key] = value;
}
}
}
return result;
}
/**
* Get service status for all microservices
*/
async getServiceStatus(): Promise<ServiceStatus[]> {
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: '1.0.0',
status: 'running',
port: process.env.PORT ? parseInt(process.env.PORT) : 2003,
uptime: Date.now() - this.startTime,
lastCheck: new Date().toISOString(),
healthy: true,
});
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: data.version || '1.0.0',
status: 'running',
port: service.port,
uptime: data.uptime || 0,
lastCheck: new Date().toISOString(),
healthy: true,
});
} else {
services.push({
name: service.name,
version: 'unknown',
status: 'error',
port: service.port,
uptime: 0,
lastCheck: new Date().toISOString(),
healthy: false,
error: `HTTP ${response.status}`,
});
}
} catch (error) {
services.push({
name: service.name,
version: 'unknown',
status: 'stopped',
port: service.port,
uptime: 0,
lastCheck: new Date().toISOString(),
healthy: false,
error: error instanceof Error ? error.message : 'Connection failed',
});
}
}
return services;
}
/**
* Get proxy statistics
*/
async getProxyStats(): Promise<ProxyStats | null> {
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<string>('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<SystemOverview> {
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
*/
}