| 1 | import fs from 'fs'; |
| 2 | import path from 'path'; |
| 3 | import { serverDirectory } from './server-directory.js'; |
| 4 | |
| 5 | // Default to 0 seconds (disabled) if not set |
| 6 | const intervalSeconds = parseInt(process.env.SILLYTAVERN_HEARTBEATINTERVAL || '0'); |
| 7 | const intervalMs = intervalSeconds * 1000; |
| 8 | |
| 9 | // Heartbeat disabled |
| 10 | if (Number.isNaN(intervalSeconds) || intervalSeconds <= 0) { |
| 11 | process.exit(0); |
| 12 | } |
| 13 | |
| 14 | // Allow a grace period (2 missed beats) |
| 15 | const threshold = intervalMs * 2; |
| 16 | |
| 17 | const dataRoot = process.env.SILLYTAVERN_DATAROOT || path.join(serverDirectory, 'data'); |
| 18 | const heartbeatFile = path.join(dataRoot, 'heartbeat.json'); |
| 19 | |
| 20 | try { |
| 21 | if (!fs.existsSync(heartbeatFile)) { |
| 22 | console.error(`Heartbeat file not found at: ${heartbeatFile}`); |
| 23 | process.exit(1); |
| 24 | } |
| 25 | |
| 26 | const stats = fs.statSync(heartbeatFile); |
| 27 | const lastModified = stats.mtimeMs; |
| 28 | const now = Date.now(); |
| 29 | const diff = now - lastModified; |
| 30 | |
| 31 | if (diff > threshold) { |
| 32 | console.error(`Server is unresponsive. Last heartbeat was ${Math.round(diff / 1000)} seconds ago.`); |
| 33 | process.exit(1); |
| 34 | } |
| 35 | |
| 36 | process.exit(0); |
| 37 | } catch (err) { |
| 38 | console.error('Healthcheck error:', err.message); |
| 39 | process.exit(1); |
| 40 | } |