feat: Update Dockerfile and server configuration for improved health checks and error handling

This commit is contained in:
2026-10-19 23:04:54 +03:00
parent e38c388462
commit 7206bf9c4a
10 changed files with 324 additions and 60 deletions

View File

@@ -1,6 +1,7 @@
import express from "express";
import compression from "compression";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
import multer from "multer";
import { parseWord, PARSER_VERSION } from "./parser.js";
import { scheduleFor } from "./schedules.js";
@@ -47,20 +48,43 @@ app.use("/api", (_req, res, next) => {
// 4 — compression, ETag revalidation, throttled refresh and import limits;
// 5 — error codes (`code` beside `error`, see server/errors.js), timetable 304 before any work;
// 6 — the timetable carries the group's exams and credits from other catalog documents;
// 7 — /api/diagnostics, cells the parser could not read with confidence.
const API_VERSION = 7;
// 7 — /api/diagnostics, cells the parser could not read with confidence;
// 8 — /api/ready, and `ready` in /api/health.
const API_VERSION = 8;
/**
* What the server still waits for before it answers from memory: the catalog, the week table
* and the directory index. A first start without a cache crawls and parses every document.
*/
const waitingFor = (sources, directory) =>
[!sources.catalog && "catalog", !sources.calendar && "calendar", !directory.builtAt && "index"].filter(Boolean);
// Liveness plus what the server currently reads from the university, without network calls.
app.get("/api/health", async (_req, res) => {
const sources = await sourceStatus().catch((e) => ({ error: e.message }));
res.json({
ok: true,
ready: waitingFor(sources, indexStatus()).length === 0,
apiVersion: API_VERSION,
parserVersion: PARSER_VERSION,
...sources,
directory: indexStatus(),
});
});
// Readiness for Docker and a proxy: 503 until the catalog, the week table and the index are
// loaded, so traffic does not reach a server whose first requests would wait half a minute.
app.get("/api/ready", async (_req, res) => {
const sources = await sourceStatus().catch(() => ({}));
const directory = indexStatus();
const waiting = waitingFor(sources, directory);
if (waiting.length)
return res.status(503).json({
ready: false,
waiting,
error: "Сервер ещё загружает каталог расписаний. Попробуйте через минуту.",
code: "not_ready",
});
res.json({ ready: true, documents: directory.documents, builtAt: directory.builtAt });
});
const isDate = (s) => /^\d{4}-\d{2}-\d{2}$/.test(s || "");
const badRequest = (res, error) => res.status(400).json({ error, code: "bad_request" });
// University-wide lookups over every catalog document.
@@ -254,11 +278,16 @@ app.use((error, req, res, _next) => {
else console.error(`${req.method} ${req.originalUrl} → ${status} ${code}: ${error.message}`);
res.status(status).json({ error: message, code });
});
const port = Number(process.env.PORT || 3001);
app.listen(port, process.env.HOST || "127.0.0.1", () => {
console.log(`API и PWA: http://127.0.0.1:${port}`);
// Read the week table and parse the whole catalog in the background,
// so the first visit and the first search do not wait for the university.
getCalendar().catch((e) => console.error(`Таблица недель: ${e.message}`));
getIndex().catch((e) => console.error(`Индекс: ${e.message}`));
});
export { app };
/** Starts listening and loads the week table and the whole catalog in the background. */
export function start(port = Number(process.env.PORT || 3001), host = process.env.HOST || "127.0.0.1") {
return app.listen(port, host, () => {
console.log(`API и PWA: http://127.0.0.1:${port}`);
// So the first visit and the first search do not wait for the university.
getCalendar().catch((e) => console.error(`Таблица недель: ${e.message}`));
getIndex().catch((e) => console.error(`Индекс: ${e.message}`));
});
}
// `node server/index.js` serves; tests import the app without listening.
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) start();