61 lines
2.0 KiB
TypeScript
61 lines
2.0 KiB
TypeScript
/** Точка входа: веб, приём сообщений Telegram и планировщик (раз в минуту). */
|
|
import { createServer } from "node:http";
|
|
import * as Sentry from "@sentry/node";
|
|
import { Assistant } from "./assistant.ts";
|
|
import { loadConfig } from "./config.ts";
|
|
import { Store } from "./store.ts";
|
|
import { Web } from "./web.ts";
|
|
|
|
const config = loadConfig();
|
|
if (process.env.SENTRY_DSN) {
|
|
Sentry.init({
|
|
dsn: process.env.SENTRY_DSN,
|
|
release: process.env.SENTRY_RELEASE,
|
|
environment: process.env.SENTRY_ENVIRONMENT ?? "dev",
|
|
sendDefaultPii: false,
|
|
});
|
|
}
|
|
|
|
const log = (msg: string, err?: unknown) => {
|
|
// Только сообщение и тип ошибки — без содержимого писем и ключей.
|
|
console.error(
|
|
`[assistant] ${msg}${err instanceof Error ? `: ${err.name} ${err.message.slice(0, 200)}` : ""}`,
|
|
);
|
|
if (err) Sentry.captureException(err);
|
|
};
|
|
|
|
const store = new Store(config.dataDir);
|
|
const assistant = new Assistant(config, store, { log });
|
|
const web = new Web(assistant);
|
|
|
|
const server = createServer((req, res) => {
|
|
web.handle(req, res).catch((err) => {
|
|
log("request failed", err);
|
|
if (!res.headersSent) res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
res.end("Что-то пошло не так. Обновите страницу через минуту.");
|
|
});
|
|
});
|
|
|
|
const abort = new AbortController();
|
|
server.listen(config.port, () => {
|
|
console.log(`[assistant] listening on :${config.port}, demo=${assistant.demo}`);
|
|
});
|
|
|
|
if (!assistant.demo) {
|
|
void (async () => {
|
|
await assistant.telegramInit();
|
|
void assistant.pollLoop(abort.signal);
|
|
const tick = () => assistant.tick().catch((err) => log("tick failed", err));
|
|
setTimeout(tick, 5000);
|
|
setInterval(tick, 60000).unref();
|
|
})();
|
|
}
|
|
|
|
for (const sig of ["SIGTERM", "SIGINT"] as const) {
|
|
process.on(sig, () => {
|
|
abort.abort();
|
|
server.close(() => process.exit(0));
|
|
setTimeout(() => process.exit(0), 3000).unref();
|
|
});
|
|
}
|