-
-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathhealth-endpoint.js
More file actions
83 lines (69 loc) · 2.14 KB
/
health-endpoint.js
File metadata and controls
83 lines (69 loc) · 2.14 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
const http = require('http')
let lastActivity = Date.now()
let isHealthy = true
let healthCheckReasons = []
// Update activity tracker
const updateActivity = () => {
lastActivity = Date.now()
}
// Health monitoring
const checkHealth = () => {
const now = Date.now()
const timeSinceActivity = now - lastActivity
const maxInactiveTime = 60000 // 1 minute
healthCheckReasons = []
// Check if bot is responsive
if (timeSinceActivity > maxInactiveTime) {
isHealthy = false
healthCheckReasons.push(`No activity for ${Math.round(timeSinceActivity / 1000)}s`)
} else {
isHealthy = true
}
// Check memory usage
const memUsage = process.memoryUsage()
const memUsageMB = memUsage.heapUsed / 1024 / 1024
if (memUsageMB > 4000) { // 4GB
isHealthy = false
healthCheckReasons.push(`High memory usage: ${Math.round(memUsageMB)}MB`)
}
}
// Health check endpoint
const createHealthServer = () => {
const server = http.createServer((req, res) => {
if (req.url === '/health') {
const healthStatus = {
status: isHealthy ? 'healthy' : 'unhealthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
lastActivity: new Date(lastActivity).toISOString(),
timeSinceLastActivity: Date.now() - lastActivity,
memory: process.memoryUsage(),
reasons: healthCheckReasons
}
res.writeHead(isHealthy ? 200 : 503, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(healthStatus, null, 2))
} else {
res.writeHead(404)
res.end()
}
})
const PORT = process.env.HEALTH_CHECK_PORT || 3001
server.listen(PORT, () => {
console.log(`[${new Date().toISOString()}] Health check server running on port ${PORT}`)
})
// Check health every 10 seconds
const healthInterval = setInterval(checkHealth, 10000)
// Cleanup on process termination
const cleanup = () => {
clearInterval(healthInterval)
server.close()
}
process.on('SIGTERM', cleanup)
process.on('SIGINT', cleanup)
return server
}
module.exports = {
updateActivity,
createHealthServer,
getHealthStatus: () => ({ isHealthy, reasons: healthCheckReasons })
}