From 7206bf9c4a1f133a154e7deb19a71375cde2aed7 Mon Sep 17 00:00:00 2001 From: Zakhar Timoshenko Date: Mon, 19 Oct 2026 23:04:54 +0300 Subject: [PATCH] feat: Update Dockerfile and server configuration for improved health checks and error handling --- Dockerfile | 2 +- README.md | 12 ++- docker-compose.yml | 9 +- server/errors.js | 7 +- server/index.js | 49 ++++++++-- server/paths.js | 7 ++ server/schedules.js | 4 +- server/source.js | 63 +++++++------ test/api.test.js | 218 ++++++++++++++++++++++++++++++++++++++++++++ test/errors.test.js | 13 +-- 10 files changed, 324 insertions(+), 60 deletions(-) create mode 100644 server/paths.js create mode 100644 test/api.test.js diff --git a/Dockerfile b/Dockerfile index 74af041..efa0aba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ COPY scripts ./scripts RUN npm run build && npm prune --omit=dev 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 COPY --from=build /app/node_modules ./node_modules COPY --from=build /app/dist ./dist diff --git a/README.md b/README.md index b241fce..7ca88a6 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ## Запуск -Нужны Node.js 22.12+ (проверено на 24.14.1), npm и curl. +Нужны Node.js 22.12+ (проверено на 24.14.1) и npm. ```sh 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` оставляют на экране сохранённую копию и показывают «Повторить». -`GET /api/health` без обращения к сети показывает выбранный учебный год, возраст каталога, найденные файлы недель и звонков, семестры и предупреждения: папка нового года не найдена, сегодняшняя дата вне таблицы недель, источник не обновляется. +К каталогу университета сервер обращается встроенным в Node `fetch`: соединения переиспользуются, сертификаты проверяются, перенаправления не принимаются, ответ ограничен 10 МБ и 25 секундами. Обход каталога (около сотни папок) занимает несколько секунд. + +`GET /api/ready` отвечает `200`, когда каталог, таблица недель и индекс всех документов загружены, а до этого — `503` с кодом `not_ready` и списком того, что ещё грузится (`waiting`). На него смотрят проверка здоровья Docker и прокси. `GET /api/health` всегда отвечает `200`, пока процесс жив (поле `ready` — то же, что `/api/ready`), и без обращения к сети показывает выбранный учебный год, возраст каталога, найденные файлы недель и звонков, семестры и предупреждения: папка нового года не найдена, сегодняшняя дата вне таблицы недель, источник не обновляется. ```sh npm run sync @@ -110,7 +112,7 @@ npm test 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 ``` -Приложение откроется на 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 открыты): @@ -136,7 +138,7 @@ docker compose 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-приложение diff --git a/docker-compose.yml b/docker-compose.yml index 609340d..d377e21 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,12 +27,15 @@ services: # Переживает пересборку образа; удаление тома только замедлит первый запуск. - psu-data:/app/.data 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 timeout: 5s retries: 3 - # Первый запуск разбирает все документы каталога (около полуминуты). - start_period: 60s + # Первый запуск без кэша скачивает и разбирает все документы каталога; + # с кэшем в томе psu-data сервер готов за несколько секунд. + start_period: 120s + start_interval: 3s caddy: image: caddy:2.8.4-alpine diff --git a/server/errors.js b/server/errors.js index f9c0591..5c15233 100644 --- a/server/errors.js +++ b/server/errors.js @@ -12,6 +12,7 @@ * 429 busy the server is parsing other imports * 502 source_unavailable the university catalog did not answer * 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 * 500 internal a fault of the server itself */ @@ -29,12 +30,12 @@ const SOURCE_DOWN = "Каталог университета сейчас не const SOURCE_SLOW = "Каталог университета отвечает слишком долго. Попробуйте позже."; /** - * A failed download from the university as an API error: curl's exit code 28 (or our own - * kill on the time limit) is a timeout, any other failure means the source is unavailable. + * A failed download from the university as an API error: fetch aborted on the time limit is a + * timeout, any other failure (no connection, an HTTP error, a redirect) means the source is unavailable. */ export function sourceError(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 ? new ApiError(504, "source_timeout", SOURCE_SLOW) : new ApiError(502, "source_unavailable", SOURCE_DOWN); diff --git a/server/index.js b/server/index.js index 9c39729..a4bd4f8 100644 --- a/server/index.js +++ b/server/index.js @@ -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(); diff --git a/server/paths.js b/server/paths.js new file mode 100644 index 0000000..d588a2f --- /dev/null +++ b/server/paths.js @@ -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)); diff --git a/server/schedules.js b/server/schedules.js index ec5e934..96eb4fd 100644 --- a/server/schedules.js +++ b/server/schedules.js @@ -1,9 +1,9 @@ import { readFile, writeFile, mkdir } from "node:fs/promises"; -import { fileURLToPath } from "node:url"; import { parseWord, PARSER_VERSION } from "./parser.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 // downloads a document at most once per MIN_REFRESH, and simultaneous ones share a download. const fetchedAt = new Map(), diff --git a/server/source.js b/server/source.js index 090ce6a..5464882 100644 --- a/server/source.js +++ b/server/source.js @@ -1,22 +1,19 @@ 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 { fileURLToPath } from "node:url"; import { createHash } from "node:crypto"; import { parseWeeksDocx, parseBellsDocx } from "./calendar.js"; import { apiError, sourceError } from "./errors.js"; +import { DATA } from "./paths.js"; import { academicStartYear, assignSemesters, todayIso, weekIndexOf, } from "../shared/weeks.js"; -const run = promisify(execFile); -const ORIGIN = "https://nextcloud.psu.by"; +// The university's Nextcloud; tests point PSU_SOURCE_ORIGIN at a local stand-in. +const ORIGIN = process.env.PSU_SOURCE_ORIGIN || "https://nextcloud.psu.by"; const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/"; 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 arr = (value) => (value ? (Array.isArray(value) ? value : [value]) : []); const DISCOVERY_TTL = 15 * 60 * 1000, @@ -39,6 +36,8 @@ const status = { catalogError: null, calendarError: null }; const failedAt = { catalog: 0, calendar: 0 }; 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") { // Only the university share is reachable; listings and catalog entries supply the paths. if ( @@ -48,31 +47,35 @@ export async function request(path, method = "GET") { !["GET", "PROPFIND"].includes(method) ) throw new Error("Недопустимый путь документа."); - const url = ORIGIN + path; - // curl also works with the system trust store on macOS. Certificate checks stay enabled. - const args = [ - "--fail", - "--silent", - "--show-error", - "--max-time", - "25", - "--max-filesize", - "10485760", - "--max-redirs", - "0", - "--request", - method, - ]; - if (method === "PROPFIND") args.push("--header", "Depth: 1"); - args.push(url); - const { stdout } = await run("curl", args, { - encoding: "buffer", - maxBuffer: 11 * 1024 * 1024, - timeout: 28000, - }).catch((error) => { + // Node's fetch keeps connections to the university open between requests, so a catalog + // crawl of a hundred listings pays for one TLS handshake, not a hundred. Certificates are + // checked, redirects are refused, and the answer is cut off past 10 MB or 25 seconds. + try { + const response = await fetch(ORIGIN + path, { + method, + headers: method === "PROPFIND" ? { Depth: "1" } : {}, + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT), + }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status}`); + } + if (Number(response.headers.get("content-length")) > MAX_SIZE) { + await response.body?.cancel(); + throw new Error("Документ больше 10 МБ."); + } + const chunks = []; + let size = 0; + for await (const chunk of response.body || []) { + size += chunk.length; + if (size > MAX_SIZE) throw new Error("Документ больше 10 МБ."); + chunks.push(chunk); + } + return Buffer.concat(chunks); + } catch (error) { throw sourceError(error); - }); - return stdout; + } } export function decodeListing(xml, root = SHARE) { const entries = arr(parser.parse(xml).multistatus?.response); diff --git a/test/api.test.js b/test/api.test.js new file mode 100644 index 0000000..eabe4e5 --- /dev/null +++ b/test/api.test.js @@ -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 `${encode(path)}${ + folder ? "" : `${size}` + }${MODIFIED}HTTP/1.1 200 OK`; + }; + return `${[folder, ...children].map(entry).join("")}`; +}; + +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} запросов`); +}); diff --git a/test/errors.test.js b/test/errors.test.js index aad4171..a617d27 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -16,12 +16,13 @@ test("Ошибки API: код и статус для клиентов", () => { assert.doesNotMatch(internal.message, /undefined/); }); -test("Ошибки источника: таймаут curl отдельно от недоступности", () => { - assert.equal(sourceError({ code: 28 }).code, "source_timeout"); - assert.equal(sourceError({ code: 28 }).status, 504); - assert.equal(sourceError({ killed: true, signal: "SIGTERM" }).code, "source_timeout"); - assert.equal(sourceError({ code: 6 }).code, "source_unavailable"); - assert.equal(sourceError({ code: 22 }).status, 502); +test("Ошибки источника: таймаут отдельно от недоступности", () => { + const timeout = new DOMException("The operation was aborted due to timeout", "TimeoutError"); + assert.equal(sourceError(timeout).code, "source_timeout"); + assert.equal(sourceError(timeout).status, 504); + assert.equal(sourceError(new DOMException("aborted", "AbortError")).code, "source_timeout"); + 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", "Таблица недель не распознана."); assert.equal(sourceError(own), own); });