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

@@ -10,7 +10,7 @@ COPY scripts ./scripts
RUN npm run build && npm prune --omit=dev RUN npm run build && npm prune --omit=dev
FROM node:24-bookworm-slim FROM node:24-bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates libreoffice-writer && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libreoffice-writer && rm -rf /var/lib/apt/lists/*
WORKDIR /app WORKDIR /app
COPY --from=build /app/node_modules ./node_modules COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist COPY --from=build /app/dist ./dist

View File

@@ -4,7 +4,7 @@
## Запуск ## Запуск
Нужны Node.js 22.12+ (проверено на 24.14.1), npm и curl. Нужны Node.js 22.12+ (проверено на 24.14.1) и npm.
```sh ```sh
npm ci npm ci
@@ -55,7 +55,9 @@ Vite работает на http://127.0.0.1:5173 и проксирует `/api`
Ошибки приходят как `{ "error": "текст для показа", "code": "…" }`. Клиенты опираются на `code`, а не на текст: `bad_request` (400), `unknown_endpoint`, `document_not_found`, `group_not_found` (404), `file_too_large` (413), `unreadable_file` (422), `too_many_requests` и `busy` (429), `source_unavailable` и `source_invalid` (502, каталог университета не ответил или не распознан), `source_timeout` (504), `internal` (500). Полный список — в `server/errors.js`. Android и iOS при `source_unavailable`, `source_timeout` и `busy` оставляют на экране сохранённую копию и показывают «Повторить». Ошибки приходят как `{ "error": "текст для показа", "code": "…" }`. Клиенты опираются на `code`, а не на текст: `bad_request` (400), `unknown_endpoint`, `document_not_found`, `group_not_found` (404), `file_too_large` (413), `unreadable_file` (422), `too_many_requests` и `busy` (429), `source_unavailable` и `source_invalid` (502, каталог университета не ответил или не распознан), `source_timeout` (504), `internal` (500). Полный список — в `server/errors.js`. Android и iOS при `source_unavailable`, `source_timeout` и `busy` оставляют на экране сохранённую копию и показывают «Повторить».
`GET /api/health` без обращения к сети показывает выбранный учебный год, возраст каталога, найденные файлы недель и звонков, семестры и предупреждения: папка нового года не найдена, сегодняшняя дата вне таблицы недель, источник не обновляется. К каталогу университета сервер обращается встроенным в Node `fetch`: соединения переиспользуются, сертификаты проверяются, перенаправления не принимаются, ответ ограничен 10 МБ и 25 секундами. Обход каталога (около сотни папок) занимает несколько секунд.
`GET /api/ready` отвечает `200`, когда каталог, таблица недель и индекс всех документов загружены, а до этого — `503` с кодом `not_ready` и списком того, что ещё грузится (`waiting`). На него смотрят проверка здоровья Docker и прокси. `GET /api/health` всегда отвечает `200`, пока процесс жив (поле `ready` — то же, что `/api/ready`), и без обращения к сети показывает выбранный учебный год, возраст каталога, найденные файлы недель и звонков, семестры и предупреждения: папка нового года не найдена, сегодняшняя дата вне таблицы недель, источник не обновляется.
```sh ```sh
npm run sync npm run sync
@@ -110,7 +112,7 @@ npm test
npm run build npm run build
``` ```
Тесты используют реальные Word-документы источника в `test/fixtures/` с URL и метаданными рядом. Результат разбора каждого из них вместе с найденными диагностикой ячейками сравнивается построчно со снимком в `test/snapshots/`. Если разбор изменился намеренно, снимки обновляются командой `UPDATE_SNAPSHOTS=1 npm test`; разницу в `test/snapshots/` стоит прочитать перед коммитом. Проверяются изоляция 23-БА/23-ЛГ, общие события, объединения ячеек, варианты недель, отдельное время кураторского часа, даты сессии и отклонение повреждённых файлов, а также таблица недель и звонков, разбор пометок с учётом цвета строки и согласие всех пометок 23-БА с таблицей. Тесты используют реальные Word-документы источника в `test/fixtures/` с URL и метаданными рядом. Результат разбора каждого из них вместе с найденными диагностикой ячейками сравнивается построчно со снимком в `test/snapshots/`. Если разбор изменился намеренно, снимки обновляются командой `UPDATE_SNAPSHOTS=1 npm test`; разницу в `test/snapshots/` стоит прочитать перед коммитом. HTTP-тесты (`test/api.test.js`) запускают настоящий сервер против локальной подмены Nextcloud университета, которая отдаёт тестовые документы как маленький каталог, с одним документом, отвечающим ошибкой, и одним слишком медленным. Проверяются готовность, форма ответа `/api/timetable`, `304` по ETag, коды ошибок (`400`, `404`, `422`, `429`, `502`, `504`), диагностика, импорт с лимитом и переиспользование соединений. Для этого сервер читает переменные `PSU_SOURCE_ORIGIN`, `PSU_DATA_DIR` и `PSU_SOURCE_TIMEOUT_MS`; в работе их задавать не нужно. Также проверяются изоляция 23-БА/23-ЛГ, общие события, объединения ячеек, варианты недель, отдельное время кураторского часа, даты сессии и отклонение повреждённых файлов, а также таблица недель и звонков, разбор пометок с учётом цвета строки и согласие всех пометок 23-БА с таблицей.
Перед изменением парсера стоит снять снимок всего каталога и после правки сравнить с ним: Перед изменением парсера стоит снять снимок всего каталога и после правки сравнить с ним:
@@ -128,7 +130,7 @@ npm run snapshot # после правки: что изменилос
docker compose up -d --build docker compose up -d --build
``` ```
Приложение откроется на http://localhost:3001. Кэш каталога, таблицы недель и распознанных документов хранится в томе `psu-data` и переживает пересборку. Первый запуск разбирает все документы каталога (около полуминуты), поэтому проверка здоровья (`/api/health`) даёт контейнеру минуту на старт. Порт и адрес меняются переменными `APP_PORT` и `APP_BIND`. Приложение откроется на http://localhost:3001. Кэш каталога, таблицы недель и распознанных документов хранится в томе `psu-data` и переживает пересборку. Контейнер считается здоровым, когда сервер готов (`/api/ready`): с кэшем в томе — через несколько секунд после старта, при первом запуске — после того как скачаны и разобраны все документы каталога; на это даётся две минуты. Порт и адрес меняются переменными `APP_PORT` и `APP_BIND`.
Для установки PWA на телефон нужен HTTPS. Профиль `https` поднимает Caddy, который сам получает сертификат Let's Encrypt (домен должен указывать на сервер, порты 80 и 443 открыты): Для установки PWA на телефон нужен HTTPS. Профиль `https` поднимает Caddy, который сам получает сертификат Let's Encrypt (домен должен указывать на сервер, порты 80 и 443 открыты):
@@ -136,7 +138,7 @@ docker compose up -d --build
DOMAIN=schedule.example.by docker compose --profile https up -d --build DOMAIN=schedule.example.by docker compose --profile https up -d --build
``` ```
Если HTTPS уже даёт ваш обратный прокси, профиль не нужен; приложение можно закрыть от внешней сети через `APP_BIND=127.0.0.1`. Контейнер включает curl и LibreOffice для `.doc`. Файл `docker-compose.yml` проверен `docker compose config`; сборка образа в этой проверке не запускалась. Если HTTPS уже даёт ваш обратный прокси, профиль не нужен; приложение можно закрыть от внешней сети через `APP_BIND=127.0.0.1`. Контейнер включает LibreOffice для `.doc`. Файл `docker-compose.yml` проверен `docker compose config`; сборка образа в этой проверке не запускалась.
## Android-приложение ## Android-приложение

View File

@@ -27,12 +27,15 @@ services:
# Переживает пересборку образа; удаление тома только замедлит первый запуск. # Переживает пересборку образа; удаление тома только замедлит первый запуск.
- psu-data:/app/.data - psu-data:/app/.data
healthcheck: healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:3001/api/health"] # Здоров = готов: каталог, таблица недель и индекс загружены (/api/ready).
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3001/api/ready').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
interval: 30s interval: 30s
timeout: 5s timeout: 5s
retries: 3 retries: 3
# Первый запуск разбирает все документы каталога (около полуминуты). # Первый запуск без кэша скачивает и разбирает все документы каталога;
start_period: 60s # с кэшем в томе psu-data сервер готов за несколько секунд.
start_period: 120s
start_interval: 3s
caddy: caddy:
image: caddy:2.8.4-alpine image: caddy:2.8.4-alpine

View File

@@ -12,6 +12,7 @@
* 429 busy the server is parsing other imports * 429 busy the server is parsing other imports
* 502 source_unavailable the university catalog did not answer * 502 source_unavailable the university catalog did not answer
* 502 source_invalid the catalog answered, but its folders or tables are not recognised * 502 source_invalid the catalog answered, but its folders or tables are not recognised
* 503 not_ready /api/ready only: the server is still loading the catalog or its index
* 504 source_timeout the university catalog answered too slowly * 504 source_timeout the university catalog answered too slowly
* 500 internal a fault of the server itself * 500 internal a fault of the server itself
*/ */
@@ -29,12 +30,12 @@ const SOURCE_DOWN = "Каталог университета сейчас не
const SOURCE_SLOW = "Каталог университета отвечает слишком долго. Попробуйте позже."; const SOURCE_SLOW = "Каталог университета отвечает слишком долго. Попробуйте позже.";
/** /**
* A failed download from the university as an API error: curl's exit code 28 (or our own * A failed download from the university as an API error: fetch aborted on the time limit is a
* kill on the time limit) is a timeout, any other failure means the source is unavailable. * timeout, any other failure (no connection, an HTTP error, a redirect) means the source is unavailable.
*/ */
export function sourceError(error) { export function sourceError(error) {
if (error instanceof ApiError) return error; if (error instanceof ApiError) return error;
const timedOut = error?.code === 28 || error?.killed || error?.signal === "SIGTERM"; const timedOut = error?.name === "TimeoutError" || error?.name === "AbortError";
return timedOut return timedOut
? new ApiError(504, "source_timeout", SOURCE_SLOW) ? new ApiError(504, "source_timeout", SOURCE_SLOW)
: new ApiError(502, "source_unavailable", SOURCE_DOWN); : new ApiError(502, "source_unavailable", SOURCE_DOWN);

View File

@@ -1,6 +1,7 @@
import express from "express"; import express from "express";
import compression from "compression"; import compression from "compression";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
import multer from "multer"; import multer from "multer";
import { parseWord, PARSER_VERSION } from "./parser.js"; import { parseWord, PARSER_VERSION } from "./parser.js";
import { scheduleFor } from "./schedules.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; // 4 — compression, ETag revalidation, throttled refresh and import limits;
// 5 — error codes (`code` beside `error`, see server/errors.js), timetable 304 before any work; // 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; // 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. // 7 — /api/diagnostics, cells the parser could not read with confidence;
const API_VERSION = 7; // 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. // Liveness plus what the server currently reads from the university, without network calls.
app.get("/api/health", async (_req, res) => { app.get("/api/health", async (_req, res) => {
const sources = await sourceStatus().catch((e) => ({ error: e.message })); const sources = await sourceStatus().catch((e) => ({ error: e.message }));
res.json({ res.json({
ok: true, ok: true,
ready: waitingFor(sources, indexStatus()).length === 0,
apiVersion: API_VERSION, apiVersion: API_VERSION,
parserVersion: PARSER_VERSION, parserVersion: PARSER_VERSION,
...sources, ...sources,
directory: indexStatus(), 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 isDate = (s) => /^\d{4}-\d{2}-\d{2}$/.test(s || "");
const badRequest = (res, error) => res.status(400).json({ error, code: "bad_request" }); const badRequest = (res, error) => res.status(400).json({ error, code: "bad_request" });
// University-wide lookups over every catalog document. // 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}`); else console.error(`${req.method} ${req.originalUrl} → ${status} ${code}: ${error.message}`);
res.status(status).json({ error: message, code }); res.status(status).json({ error: message, code });
}); });
const port = Number(process.env.PORT || 3001); export { app };
app.listen(port, process.env.HOST || "127.0.0.1", () => {
console.log(`API и PWA: http://127.0.0.1:${port}`); /** Starts listening and loads the week table and the whole catalog in the background. */
// Read the week table and parse the whole catalog in the background, export function start(port = Number(process.env.PORT || 3001), host = process.env.HOST || "127.0.0.1") {
// so the first visit and the first search do not wait for the university. return app.listen(port, host, () => {
getCalendar().catch((e) => console.error(`Таблица недель: ${e.message}`)); console.log(`API и PWA: http://127.0.0.1:${port}`);
getIndex().catch((e) => console.error(`Индекс: ${e.message}`)); // 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();

7
server/paths.js Normal file
View File

@@ -0,0 +1,7 @@
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
/** Where the catalog, the week table and parsed documents are cached; tests use a temporary one. */
export const DATA = process.env.PSU_DATA_DIR
? resolve(process.env.PSU_DATA_DIR) + "/"
: fileURLToPath(new URL("../.data/", import.meta.url));

View File

@@ -1,9 +1,9 @@
import { readFile, writeFile, mkdir } from "node:fs/promises"; import { readFile, writeFile, mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { parseWord, PARSER_VERSION } from "./parser.js"; import { parseWord, PARSER_VERSION } from "./parser.js";
import { request, MIN_REFRESH } from "./source.js"; import { request, MIN_REFRESH } from "./source.js";
import { DATA } from "./paths.js";
const data = fileURLToPath(new URL("../.data/parsed/", import.meta.url)); const data = DATA + "parsed/";
// When each document was last downloaded, and the downloads under way: a forced refresh // When each document was last downloaded, and the downloads under way: a forced refresh
// downloads a document at most once per MIN_REFRESH, and simultaneous ones share a download. // downloads a document at most once per MIN_REFRESH, and simultaneous ones share a download.
const fetchedAt = new Map(), const fetchedAt = new Map(),

View File

@@ -1,22 +1,19 @@
import { XMLParser } from "fast-xml-parser"; import { XMLParser } from "fast-xml-parser";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFile, writeFile, mkdir } from "node:fs/promises"; import { readFile, writeFile, mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import { parseWeeksDocx, parseBellsDocx } from "./calendar.js"; import { parseWeeksDocx, parseBellsDocx } from "./calendar.js";
import { apiError, sourceError } from "./errors.js"; import { apiError, sourceError } from "./errors.js";
import { DATA } from "./paths.js";
import { import {
academicStartYear, academicStartYear,
assignSemesters, assignSemesters,
todayIso, todayIso,
weekIndexOf, weekIndexOf,
} from "../shared/weeks.js"; } from "../shared/weeks.js";
const run = promisify(execFile); // The university's Nextcloud; tests point PSU_SOURCE_ORIGIN at a local stand-in.
const ORIGIN = "https://nextcloud.psu.by"; const ORIGIN = process.env.PSU_SOURCE_ORIGIN || "https://nextcloud.psu.by";
const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/"; const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/";
const YEAR_FOLDER = /^(\d{4})-(\d{4})$/; const YEAR_FOLDER = /^(\d{4})-(\d{4})$/;
const DATA = fileURLToPath(new URL("../.data/", import.meta.url));
const parser = new XMLParser({ removeNSPrefix: true, ignoreAttributes: false }); const parser = new XMLParser({ removeNSPrefix: true, ignoreAttributes: false });
const arr = (value) => (value ? (Array.isArray(value) ? value : [value]) : []); const arr = (value) => (value ? (Array.isArray(value) ? value : [value]) : []);
const DISCOVERY_TTL = 15 * 60 * 1000, const DISCOVERY_TTL = 15 * 60 * 1000,
@@ -39,6 +36,8 @@ const status = { catalogError: null, calendarError: null };
const failedAt = { catalog: 0, calendar: 0 }; const failedAt = { catalog: 0, calendar: 0 };
const backingOff = (what) => Date.now() - failedAt[what] < MIN_REFRESH; const backingOff = (what) => Date.now() - failedAt[what] < MIN_REFRESH;
const TIMEOUT = Number(process.env.PSU_SOURCE_TIMEOUT_MS) || 25000;
const MAX_SIZE = 10 * 1024 * 1024;
export async function request(path, method = "GET") { export async function request(path, method = "GET") {
// Only the university share is reachable; listings and catalog entries supply the paths. // Only the university share is reachable; listings and catalog entries supply the paths.
if ( if (
@@ -48,31 +47,35 @@ export async function request(path, method = "GET") {
!["GET", "PROPFIND"].includes(method) !["GET", "PROPFIND"].includes(method)
) )
throw new Error("Недопустимый путь документа."); throw new Error("Недопустимый путь документа.");
const url = ORIGIN + path; // Node's fetch keeps connections to the university open between requests, so a catalog
// curl also works with the system trust store on macOS. Certificate checks stay enabled. // crawl of a hundred listings pays for one TLS handshake, not a hundred. Certificates are
const args = [ // checked, redirects are refused, and the answer is cut off past 10 MB or 25 seconds.
"--fail", try {
"--silent", const response = await fetch(ORIGIN + path, {
"--show-error", method,
"--max-time", headers: method === "PROPFIND" ? { Depth: "1" } : {},
"25", redirect: "manual",
"--max-filesize", signal: AbortSignal.timeout(TIMEOUT),
"10485760", });
"--max-redirs", if (!response.ok) {
"0", await response.body?.cancel();
"--request", throw new Error(`HTTP ${response.status}`);
method, }
]; if (Number(response.headers.get("content-length")) > MAX_SIZE) {
if (method === "PROPFIND") args.push("--header", "Depth: 1"); await response.body?.cancel();
args.push(url); throw new Error("Документ больше 10 МБ.");
const { stdout } = await run("curl", args, { }
encoding: "buffer", const chunks = [];
maxBuffer: 11 * 1024 * 1024, let size = 0;
timeout: 28000, for await (const chunk of response.body || []) {
}).catch((error) => { size += chunk.length;
if (size > MAX_SIZE) throw new Error("Документ больше 10 МБ.");
chunks.push(chunk);
}
return Buffer.concat(chunks);
} catch (error) {
throw sourceError(error); throw sourceError(error);
}); }
return stdout;
} }
export function decodeListing(xml, root = SHARE) { export function decodeListing(xml, root = SHARE) {
const entries = arr(parser.parse(xml).multistatus?.response); const entries = arr(parser.parse(xml).multistatus?.response);

218
test/api.test.js Normal file
View File

@@ -0,0 +1,218 @@
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFileSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { academicStartYear, todayIso } from "../shared/weeks.js";
// The API over HTTP, as the Android and iOS clients see it: the real server against a stand-in
// for the university's Nextcloud that serves the fixtures as a small catalog.
const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/";
const fixture = (name) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url));
const year = academicStartYear(todayIso());
const YEAR = `${year}-${year + 1}`;
const FOLDER = `${SHARE}${YEAR}/Финансово-экономический факультет/Дневная форма/`;
const MODIFIED = "Mon, 14 Sep 2026 13:05:15 GMT";
const files = {
[`${SHARE}Расписание белых и зеленых недель.docx`]: fixture("weeks.docx"),
[`${SHARE}Расписание звонков.docx`]: fixture("bells.docx"),
[`${FOLDER}23-ЛГ_23-БА.docx`]: fixture("fef-23-ba.docx"),
[`${FOLDER}24-ИТ.docx`]: fixture("fit-daily.docx"),
// The university fails on one document and is too slow on another.
[`${FOLDER}Сломанный.docx`]: 500,
[`${FOLDER}Медленный.docx`]: "slow",
};
const folders = [SHARE, `${SHARE}${YEAR}/`, `${SHARE}${YEAR}/Финансово-экономический факультет/`, FOLDER];
const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
const listing = (folder) => {
const children = [...folders.filter((f) => f !== folder && f.startsWith(folder) && !f.slice(folder.length, -1).includes("/")),
...Object.keys(files).filter((f) => f.startsWith(folder) && !f.slice(folder.length).includes("/"))];
const entry = (path) => {
const folder = path.endsWith("/");
const size = Buffer.isBuffer(files[path]) ? files[path].length : 1000;
return `<d:response><d:href>${encode(path)}</d:href><d:propstat><d:prop>${
folder ? "<d:resourcetype><d:collection/></d:resourcetype>" : `<d:resourcetype/><d:getcontentlength>${size}</d:getcontentlength>`
}<d:getlastmodified>${MODIFIED}</d:getlastmodified></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`;
};
return `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:">${[folder, ...children].map(entry).join("")}</d:multistatus>`;
};
let source, server, base, data;
const stats = { requests: 0, connections: 0 };
before(async () => {
source = createServer((req, res) => {
stats.requests++;
const path = decodeURIComponent(req.url);
if (req.method === "PROPFIND" && folders.includes(path)) {
res.writeHead(207, { "Content-Type": "application/xml" });
return res.end(listing(path));
}
const body = files[path];
if (body === "slow") return setTimeout(() => res.end("late"), 2000);
if (typeof body === "number" || !body) return res.writeHead(body || 404).end();
res.end(body);
});
source.on("connection", () => stats.connections++);
await new Promise((resolve) => source.listen(0, "127.0.0.1", resolve));
data = mkdtempSync(join(tmpdir(), "psu-api-"));
process.env.PSU_SOURCE_ORIGIN = `http://127.0.0.1:${source.address().port}`;
process.env.PSU_DATA_DIR = data;
process.env.PSU_SOURCE_TIMEOUT_MS = "500";
const { app } = await import("../server/index.js");
server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.on("listening", resolve));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
server?.close();
server?.closeAllConnections();
source?.closeAllConnections();
source?.close();
rmSync(data, { recursive: true, force: true });
});
const get = (path, headers = {}) => fetch(base + path, { headers });
const json = async (path) => {
const response = await get(path);
return { status: response.status, body: await response.json(), response };
};
const query = (params) => "?" + new URLSearchParams(params);
let doc;
test("API: до загрузки индекса сервер жив, но не готов", async () => {
const health = await json("/api/health");
assert.equal(health.status, 200);
assert.equal(health.body.ok, true);
assert.equal(health.body.ready, false);
assert.equal(typeof health.body.apiVersion, "number");
const ready = await json("/api/ready");
assert.equal(ready.status, 503);
assert.equal(ready.body.code, "not_ready");
assert.ok(ready.body.waiting.includes("index"));
});
test("API: группы находятся по каталогу, после этого сервер готов", async () => {
const { status, body } = await json("/api/groups" + query({ q: "23-БА" }));
assert.equal(status, 200);
const group = body.results.find((r) => r.group === "23-БА");
assert.ok(group, JSON.stringify(body));
assert.equal(group.file, "23-ЛГ_23-БА.docx");
doc = group.fileId;
// The calendar loads beside the index; the first timetable request waits for it.
await get("/api/calendar");
const ready = await json("/api/ready");
assert.equal(ready.status, 200, JSON.stringify(ready.body));
assert.equal(ready.body.ready, true);
// Two broken documents of four do not keep the server from being ready.
assert.equal(ready.body.documents, 2);
assert.equal((await json("/api/health")).body.ready, true);
});
test("API: расписание группы — форма ответа для приложений", async () => {
const { status, body, response } = await json("/api/timetable" + query({ doc, group: "23-БА", from: "2026-10-19", days: 7 }));
assert.equal(status, 200);
assert.equal(body.group, "23-БА");
assert.equal(body.document.id, doc);
assert.equal(body.document.name, "23-ЛГ_23-БА.docx");
assert.ok(Array.isArray(body.days) && body.days.length === 7);
assert.ok(Array.isArray(body.bells) && body.bells.length > 0);
assert.ok(Array.isArray(body.subgroups));
const lesson = body.days.flatMap((d) => d.lessons)[0];
assert.ok(lesson, "на неделе есть занятия");
for (const field of ["key", "subject", "type", "start", "end", "pair", "rooms", "teachers", "condition", "subgroup", "raw"])
assert.ok(field in lesson, `поле ${field}`);
assert.match(body.days[0].date, /^\d{4}-\d{2}-\d{2}$/);
assert.equal(response.headers.get("cache-control"), "no-cache");
assert.ok(response.headers.get("etag"));
});
test("API: неизменное расписание отдаётся пустым 304", async () => {
const path = "/api/timetable" + query({ doc, group: "23-БА", from: "2026-10-19", days: 7 });
const etag = (await get(path)).headers.get("etag");
// fetch adds "Cache-Control: no-cache" to a request with its own If-None-Match, which forbids
// a 304; OkHttp and URLCache revalidate without it, as this request does.
const again = await get(path, { "If-None-Match": etag, "Cache-Control": "max-age=0" });
assert.equal(again.status, 304);
assert.equal(await again.text(), "");
const other = await get("/api/timetable" + query({ doc, group: "23-ЛГ", from: "2026-10-19", days: 7 }), { "If-None-Match": etag, "Cache-Control": "max-age=0" });
assert.equal(other.status, 200);
});
test("API: ошибки с машиночитаемым кодом", async () => {
const cases = [
["/api/timetable" + query({ group: "23-БА" }), 400, "bad_request"],
["/api/timetable" + query({ doc, group: "23-БА", from: "19.10.2026" }), 400, "bad_request"],
["/api/timetable" + query({ doc: "нет-такого", group: "23-БА" }), 404, "document_not_found"],
["/api/timetable" + query({ doc, group: "99-ЯЯ" }), 404, "group_not_found"],
["/api/exams", 400, "bad_request"],
["/api/directory/day" + query({ date: "2026-10-19" }), 400, "bad_request"],
["/api/nope", 404, "unknown_endpoint"],
];
for (const [path, status, code] of cases) {
const result = await json(path);
assert.equal(result.status, status, path);
assert.equal(result.body.code, code, path);
assert.equal(typeof result.body.error, "string", path);
}
});
test("API: исходный документ, сбой и таймаут университета", async () => {
const catalog = (await json("/api/catalog")).body;
const id = (name) => catalog.files.find((f) => f.name === name).id;
const original = await get(`/api/original/${id("23-ЛГ_23-БА.docx")}`);
assert.equal(original.status, 200);
assert.deepEqual(Buffer.from(await original.arrayBuffer()), fixture("fef-23-ba.docx"));
const broken = await json(`/api/original/${id("Сломанный.docx")}`);
assert.equal(broken.status, 502);
assert.equal(broken.body.code, "source_unavailable");
const slow = await json(`/api/original/${id("Медленный.docx")}`);
assert.equal(slow.status, 504);
assert.equal(slow.body.code, "source_timeout");
});
test("API: диагностика каталога и её фильтры", async () => {
const all = await json("/api/diagnostics");
assert.equal(all.status, 200);
assert.equal(all.body.documents, 2);
assert.equal(all.body.failed.length, 2);
assert.equal(typeof all.body.counts, "object");
// 23-БА's "2,6-12-16н" is a typo in Word that stays flagged.
const ba = await json("/api/diagnostics" + query({ group: "23-БА" }));
const problems = ba.body.items.flatMap((i) => i.problems);
assert.ok(problems.some((p) => p.code === "weeks_unreadable"));
assert.ok(problems.every((p) => p.groups.includes("23-БА")));
const none = await json("/api/diagnostics" + query({ code: "нет-такого" }));
assert.equal(none.body.problems, 0);
});
test("API: импорт Word и лимит 10 файлов", async () => {
const send = (name, body) => {
const form = new FormData();
form.append("file", new Blob([body]), name);
return fetch(base + "/api/import", { method: "POST", body: form });
};
const ok = await send("23-ЛГ_23-БА.docx", fixture("fef-23-ba.docx"));
assert.equal(ok.status, 200);
assert.ok((await ok.json()).groups.includes("23-БА"));
const wrongType = await send("расписание.pdf", "%PDF");
assert.equal(wrongType.status, 400);
assert.equal((await wrongType.json()).code, "bad_request");
const garbage = await send("расписание.docx", "не Word");
assert.equal(garbage.status, 422);
assert.equal((await garbage.json()).code, "unreadable_file");
for (let i = 0; i < 7; i++) assert.equal((await send("23-ЛГ_23-БА.docx", fixture("fef-23-ba.docx"))).status, 200);
const limited = await send("23-ЛГ_23-БА.docx", fixture("fef-23-ba.docx"));
assert.equal(limited.status, 429);
assert.equal((await limited.json()).code, "too_many_requests");
assert.ok(Number(limited.headers.get("retry-after")) > 0);
});
test("API: запросы к университету идут по открытым соединениям", () => {
// Listings, the week table, bells and four documents (some twice) over a handful of sockets.
assert.ok(stats.requests >= 10, `запросов ${stats.requests}`);
assert.ok(stats.connections < stats.requests / 2, `соединений ${stats.connections} на ${stats.requests} запросов`);
});

View File

@@ -16,12 +16,13 @@ test("Ошибки API: код и статус для клиентов", () => {
assert.doesNotMatch(internal.message, /undefined/); assert.doesNotMatch(internal.message, /undefined/);
}); });
test("Ошибки источника: таймаут curl отдельно от недоступности", () => { test("Ошибки источника: таймаут отдельно от недоступности", () => {
assert.equal(sourceError({ code: 28 }).code, "source_timeout"); const timeout = new DOMException("The operation was aborted due to timeout", "TimeoutError");
assert.equal(sourceError({ code: 28 }).status, 504); assert.equal(sourceError(timeout).code, "source_timeout");
assert.equal(sourceError({ killed: true, signal: "SIGTERM" }).code, "source_timeout"); assert.equal(sourceError(timeout).status, 504);
assert.equal(sourceError({ code: 6 }).code, "source_unavailable"); assert.equal(sourceError(new DOMException("aborted", "AbortError")).code, "source_timeout");
assert.equal(sourceError({ code: 22 }).status, 502); assert.equal(sourceError(new TypeError("fetch failed")).code, "source_unavailable");
assert.equal(sourceError(new Error("HTTP 500")).status, 502);
const own = apiError(502, "source_invalid", "Таблица недель не распознана."); const own = apiError(502, "source_invalid", "Таблица недель не распознана.");
assert.equal(sourceError(own), own); assert.equal(sourceError(own), own);
}); });