Repository navigation
Expand file tree
/
Copy pathmonitoring.js
More file actions
340 lines (290 loc) · 8.3 KB
/
Copy pathmonitoring.js
File metadata and controls
340 lines (290 loc) · 8.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* Production Monitoring and Health Check System
*
* Comprehensive system monitoring, health checks, and alerting
*/
import fs from 'fs';
import { logger, metrics } from './observability.js';
export class HealthChecker {
constructor() {
this.checks = new Map();
this.history = new Map();
}
// Register a health check
register(name, checkFn, options = {}) {
this.checks.set(name, {
fn: checkFn,
timeout: options.timeout || 5000,
critical: options.critical || false,
interval: options.interval || 60000, // 1 minute
description: options.description || name,
});
logger.debug('Registered health check', { name, options });
}
// Run a single health check
async runCheck(name) {
const check = this.checks.get(name);
if (!check) {
throw new Error(`Health check not found: ${name}`);
}
const start = Date.now();
let result;
try {
// Run with timeout
const timeoutPromise = new Promise((_, reject) => {
setTimeout(
() => reject(new Error('Health check timeout')),
check.timeout
);
});
const checkResult = await Promise.race([check.fn(), timeoutPromise]);
result = {
name,
status: 'healthy',
duration: Date.now() - start,
details: checkResult || {},
timestamp: new Date().toISOString(),
};
metrics.increment('health_check.success', 1, { check: name });
} catch (error) {
result = {
name,
status: 'unhealthy',
duration: Date.now() - start,
error: error.message,
timestamp: new Date().toISOString(),
};
metrics.increment('health_check.failure', 1, { check: name });
if (check.critical) {
logger.error('Critical health check failed', {
name,
error: error.message,
});
} else {
logger.warn('Health check failed', { name, error: error.message });
}
}
// Store in history (keep last 100 results per check)
if (!this.history.has(name)) {
this.history.set(name, []);
}
const history = this.history.get(name);
history.push(result);
if (history.length > 100) {
history.shift();
}
return result;
}
// Run all health checks
async runAll() {
const results = [];
for (const [name] of this.checks) {
try {
const result = await this.runCheck(name);
results.push(result);
} catch (error) {
results.push({
name,
status: 'error',
error: error.message,
timestamp: new Date().toISOString(),
});
}
}
return {
status: results.every((r) => r.status === 'healthy')
? 'healthy'
: 'unhealthy',
timestamp: new Date().toISOString(),
checks: results,
};
}
// Get health check history
getHistory(name, limit = 10) {
const history = this.history.get(name) || [];
return history.slice(-limit);
}
// Get overall system health summary
getHealthSummary() {
const summary = {
timestamp: new Date().toISOString(),
checks: {},
overall: 'healthy',
};
for (const [name] of this.checks) {
const history = this.history.get(name) || [];
const recent = history.slice(-10); // Last 10 checks
if (recent.length === 0) {
summary.checks[name] = { status: 'unknown' };
continue;
}
const healthy = recent.filter((r) => r.status === 'healthy').length;
const successRate = healthy / recent.length;
const avgDuration =
recent.reduce((sum, r) => sum + (r.duration || 0), 0) / recent.length;
const lastCheck = recent[recent.length - 1];
summary.checks[name] = {
status: lastCheck.status,
successRate,
avgDuration,
lastCheck: lastCheck.timestamp,
};
// If any critical check is failing, mark overall as unhealthy
const check = this.checks.get(name);
if (check.critical && lastCheck.status !== 'healthy') {
summary.overall = 'unhealthy';
}
}
return summary;
}
}
// Common health checks
export const commonHealthChecks = {
// Check if required environment variables are set
envVars: (requiredVars) => () => {
const missing = requiredVars.filter((varName) => !process.env[varName]);
if (missing.length > 0) {
throw new Error(`Missing environment variables: ${missing.join(', ')}`);
}
return { requiredVars: requiredVars.length, missing: 0 };
},
// Check memory usage
memory:
(maxMemoryMB = 1000) =>
() => {
const used = process.memoryUsage();
const heapUsedMB = Math.round(used.heapUsed / 1024 / 1024);
if (heapUsedMB > maxMemoryMB) {
throw new Error(
`Memory usage too high: ${heapUsedMB}MB > ${maxMemoryMB}MB`
);
}
return {
heapUsed: heapUsedMB,
heapTotal: Math.round(used.heapTotal / 1024 / 1024),
rss: Math.round(used.rss / 1024 / 1024),
};
},
// Check disk space
diskSpace:
(requiredFreeMB = 100) =>
() => {
const stats = fs.statSync('.');
// Note: This is a simplified check. In production, use a proper disk space check
return { status: 'ok', note: 'Disk space check not implemented' };
},
// Check provider connectivity
providerConnectivity: (providers) => async () => {
const results = {};
for (const [name, provider] of Object.entries(providers)) {
try {
const start = Date.now();
// Simple connectivity test
await provider.generateText('test', { maxTokens: 1 });
results[name] = {
status: 'connected',
responseTime: Date.now() - start,
};
} catch (error) {
results[name] = {
status: 'disconnected',
error: error.message,
};
}
}
const disconnected = Object.values(results).filter(
(r) => r.status === 'disconnected'
);
if (disconnected.length > 0) {
throw new Error(`${disconnected.length} providers disconnected`);
}
return results;
},
};
// System metrics collector
export class SystemMetrics {
constructor() {
this.startTime = Date.now();
this.requestCount = 0;
this.errorCount = 0;
}
recordRequest() {
this.requestCount++;
}
recordError() {
this.errorCount++;
}
getMetrics() {
const uptime = Date.now() - this.startTime;
const memory = process.memoryUsage();
return {
uptime: Math.round(uptime / 1000), // seconds
requests: {
total: this.requestCount,
errors: this.errorCount,
successRate:
this.requestCount > 0
? (this.requestCount - this.errorCount) / this.requestCount
: 1,
},
memory: {
heapUsed: Math.round(memory.heapUsed / 1024 / 1024), // MB
heapTotal: Math.round(memory.heapTotal / 1024 / 1024),
rss: Math.round(memory.rss / 1024 / 1024),
},
process: {
pid: process.pid,
version: process.version,
platform: process.platform,
},
};
}
}
// Global instances
export const healthChecker = new HealthChecker();
export const systemMetrics = new SystemMetrics();
export class Monitoring {
constructor(options = {}) {
this.options = options;
this.healthChecker = new HealthChecker();
this.systemMetrics = new SystemMetrics();
this.isStarted = false;
}
async start() {
if (this.isStarted) {
return;
}
// Register default health checks
this.healthChecker.register(
'system',
() => ({ status: 'ok', uptime: process.uptime() }),
{
critical: true,
description: 'Basic system health',
}
);
this.healthChecker.register('memory', commonHealthChecks.memory(), {
critical: false,
description: 'Memory usage check',
});
this.healthChecker.register('disk', commonHealthChecks.diskSpace(), {
critical: false,
description: 'Disk space check',
});
this.isStarted = true;
logger.info('Monitoring system started');
}
async stop() {
this.isStarted = false;
logger.info('Monitoring system stopped');
}
getHealthChecker() {
return this.healthChecker;
}
getSystemMetrics() {
return this.systemMetrics;
}
async getHealthStatus() {
return await this.healthChecker.runAll();
}
}