feat: панель работает на базе данных, служебная страница и история загрузок
Порядок стал такой: CSV разбираются, пишутся в базу, из базы собирается ответ панели. Файлы остались источником загрузки, база стала источником показа. Взята встроенная в Node.js SQLite - ни одной новой зависимости, ни сервера баз данных, ни настройки. Что это дало: - история: каждое чтение каталога записано - когда, почему, сколько строк принято и отброшено по каждому файлу; - карантин: отброшенная строка сохраняется целиком с причиной. Раньше строки только считались, а содержимое терялось - именно так молча исчезли 14 строк финрезультата из-за месяца "июн.26"; - запрос /api/data?load=N показывает состояние на прошлую загрузку; - служебная страница /admin: состояние, история, детализация по файлам, карантин с отбором и постраничностью, динамика объёма. Динамика объёма закрывает самый тихий способ соврать: если файл усох, но оставшиеся строки разобрались, не будет ни ошибки, ни предупреждения - потеря видна только сравнением с прошлыми загрузками. Ответ панели сверен с прежним байт в байт: 872685 байт, 3-4 мс. Без базы панель работает из памяти, как раньше, и говорит об этом в журнале и на служебной странице. Тестов 102 (было 80), среди них байт-в-байт сверка базы с памятью. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+57
-1
@@ -4,6 +4,9 @@ import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import express from 'express';
|
||||
import { loadAll, DATASETS } from './load.js';
|
||||
import { openHistory } from './db.js';
|
||||
import { buildSnapshot } from './snapshot.js';
|
||||
import { createAdminRouter } from './admin.js';
|
||||
import { singleFlight } from './single-flight.js';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -56,6 +59,10 @@ const DATA_LABEL = process.env.DATA_LABEL?.trim() || null;
|
||||
const REFRESH_SECONDS = Number(process.env.REFRESH_SECONDS ?? 300);
|
||||
// Сколько ждём первое чтение каталога, прежде чем честно сказать «пока не прочитано»
|
||||
const FIRST_READ_TIMEOUT_MS = Number(process.env.FIRST_READ_TIMEOUT_MS ?? 15000);
|
||||
// Load history in SQLite (path in DB_PATH, default outside the repo). The DB is
|
||||
// derived data: if it is missing or broken the panel keeps working - db.js logs
|
||||
// the failure and degrades to a no-op instead of throwing.
|
||||
const history = openHistory(process.env.DB_PATH);
|
||||
|
||||
/** Понятный текст вместо системного сообщения с путями внутри. */
|
||||
function describeError(error) {
|
||||
@@ -68,6 +75,8 @@ function describeError(error) {
|
||||
}
|
||||
|
||||
let cache = null;
|
||||
// what the current answer was assembled from: 'db' (normal) or 'memory' (fallback)
|
||||
let servedFrom = null;
|
||||
|
||||
// Одно чтение каталога в один момент времени: пока идёт медленное чтение сетевой
|
||||
// папки, таймер и кнопка «Обновить» присоединяются к нему, а не запускают новое.
|
||||
@@ -76,7 +85,19 @@ const refresh = singleFlight(async (reason = 'timer') => {
|
||||
{
|
||||
try {
|
||||
const fresh = await loadAll(DATA_DIR, cache, { sourceLabel: DATA_LABEL });
|
||||
cache = fresh;
|
||||
// Stage 3: files are the source of loading, the DB is the source of
|
||||
// serving - the answer is assembled back from the DB. The freshly
|
||||
// parsed answer stays as the fallback, so a broken DB degrades softly.
|
||||
const loadId = await history.recordLoad(fresh, reason);
|
||||
const snapshot = loadId === null ? null : buildSnapshot(history, loadId);
|
||||
if (snapshot) {
|
||||
cache = snapshot;
|
||||
servedFrom = 'db';
|
||||
} else {
|
||||
cache = fresh;
|
||||
servedFrom = 'memory';
|
||||
console.warn('[db] ответ панели собран из памяти: база недоступна или снимок не собрался');
|
||||
}
|
||||
const rows = fresh.meta.files.reduce((sum, item) => sum + item.rows, 0);
|
||||
console.log(`[data] ${reason}: файлов ${fresh.meta.files.filter((f) => f.exists).length}/${fresh.meta.files.length}, строк ${rows}, ${fresh.meta.durationMs} мс`);
|
||||
if (fresh.meta.errors.length > 0) {
|
||||
@@ -137,6 +158,21 @@ function withDeadline(promise, ms) {
|
||||
|
||||
app.get('/api/data', async (request, response) => {
|
||||
response.set('Cache-Control', 'no-store');
|
||||
// history view: ?load=N answers with the state as of that load, from the DB
|
||||
if (request.query.load !== undefined) {
|
||||
if (!history.available) {
|
||||
response.status(503).json({ error: 'База истории недоступна - просмотр прошлых загрузок сейчас невозможен.' });
|
||||
return;
|
||||
}
|
||||
const loadId = Number.parseInt(String(request.query.load), 10);
|
||||
const snapshot = Number.isFinite(loadId) ? buildSnapshot(history, loadId) : null;
|
||||
if (!snapshot) {
|
||||
response.status(404).json({ error: 'Загрузка с таким номером не найдена в базе истории.' });
|
||||
return;
|
||||
}
|
||||
response.json(snapshot);
|
||||
return;
|
||||
}
|
||||
if (!cache) {
|
||||
// первое чтение ещё идёт: интерфейс запрашивает данные один раз, поэтому
|
||||
// нельзя отдать пустоту - иначе он навсегда останется на «Загружаем данные...»
|
||||
@@ -161,6 +197,19 @@ app.get('/api/schema', (request, response) => {
|
||||
response.json({ dataDir: DATA_DIR, datasets: DATASETS });
|
||||
});
|
||||
|
||||
// Service API for the /admin page: load history, quarantine, volume dynamics.
|
||||
// Separate endpoints on purpose - /api/data must not gain a single byte.
|
||||
app.use('/api/admin', createAdminRouter({
|
||||
history,
|
||||
getStatus: () => ({
|
||||
dataDir: DATA_DIR,
|
||||
loadedAt: cache?.meta?.loadedAt ?? null,
|
||||
reading: refresh.isRunning(),
|
||||
readingSeconds: refresh.runningSeconds(),
|
||||
serving: servedFrom,
|
||||
}),
|
||||
}));
|
||||
|
||||
const clientDist = firstExisting([
|
||||
path.join(root, 'client', 'dist'),
|
||||
path.join(here, 'client', 'dist'),
|
||||
@@ -204,6 +253,13 @@ function sendStatic(response, filePath, immutable) {
|
||||
}
|
||||
|
||||
if (fs.existsSync(clientDist)) {
|
||||
// the service page is a second Vite entry: /admin must serve its own html,
|
||||
// otherwise the catch-all below would answer with the shareholder panel
|
||||
app.get('/admin', (request, response) => {
|
||||
const adminHtml = path.join(clientDist, 'admin.html');
|
||||
if (fs.existsSync(adminHtml)) sendStatic(response, adminHtml, false);
|
||||
else response.status(503).send('Служебная страница не собрана. Выполните: npm run build');
|
||||
});
|
||||
app.get('*', (request, response) => {
|
||||
const requested = decodeURIComponent(request.path.split('?')[0]);
|
||||
const candidate = path.normalize(path.join(clientDist, requested));
|
||||
|
||||
Reference in New Issue
Block a user