-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
77 lines (65 loc) · 2.49 KB
/
Copy pathmain.ts
File metadata and controls
77 lines (65 loc) · 2.49 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
import { Bot } from '@maxhub/max-bot-api';
import { config } from './config.js';
import { registerHandlers } from './handlers/index.js';
import { startBroadcastPoller } from './services/broadcast-poller.js';
const logger = {
info: (...args: unknown[]) => console.log(new Date().toISOString(), '[INFO]', ...args),
error: (...args: unknown[]) => console.error(new Date().toISOString(), '[ERROR]', ...args),
warn: (...args: unknown[]) => console.warn(new Date().toISOString(), '[WARN]', ...args),
};
async function main(): Promise<void> {
logger.info('Initializing max-bot-users...');
const bot = new Bot(config.MAX_BOT_TOKEN);
// Global error handler
bot.catch((err, _ctx) => {
logger.error('Unhandled error in update handler:', err);
});
// Register handlers (Phase 4 stub right now)
registerHandlers(bot);
// Запускаем broadcast-поллер только при заданном общем секрете.
if (config.BROADCAST_API_KEY) {
startBroadcastPoller(bot);
} else {
logger.warn('BROADCAST_API_KEY not set — broadcast poller disabled');
}
// Graceful shutdown
const shutdown = () => {
logger.info('Shutting down max-bot-users...');
bot.stop();
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// Liveness watchdog: track last update timestamp from polling middleware.
// Если апдейтов нет 15 минут — предполагаем что polling завис и выходим
// (Docker перезапустит контейнер).
let lastUpdateAt = Date.now();
bot.use(async (_ctx, next) => {
lastUpdateAt = Date.now();
await next();
});
const WATCHDOG_INTERVAL_MS = 120_000;
const STALE_THRESHOLD_MS = 900_000;
setInterval(() => {
const stale = Date.now() - lastUpdateAt;
if (stale > STALE_THRESHOLD_MS) {
logger.error(`Watchdog: no updates for ${Math.round(stale / 1000)}s, exiting for restart`);
process.exit(1);
}
}, WATCHDOG_INTERVAL_MS);
// Start polling with auto-restart on silent exit or crash (5s backoff per acceptance)
while (true) {
logger.info('Starting max-bot-users polling...');
try {
await bot.start();
logger.warn('Polling exited without error, restarting in 5s...');
} catch (error) {
logger.error('Polling crashed, restarting in 5s:', error);
}
await new Promise((r) => setTimeout(r, 5000));
}
}
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});