"""Табло прогона Фемиды Next: board.html и вывод в терминал."""
from __future__ import annotations
import argparse
import fcntl
import html
import json
import sys
import time
from pathlib import Path
from typing import Any
import core
DEAD = "прогон умер без итога"
# Состояния прогона, фазы и события: табло читает владелец, не state.json.
LABELS = {
"running": "идет", "ok": "готово", "stopped": "остановлен", "failed": "сбой кода", "dead": DEAD,
"start": "идет", "fail": "сбой", "retry": "повтор", "info": "справка",
}
def read_events(path: Path) -> list[dict[str, Any]]:
"""Читает JSONL-журнал; оборванная последняя строка (запись шла в момент чтения) пропускается."""
if not path.is_file():
return []
events: list[dict[str, Any]] = []
for line in path.read_text(encoding="utf-8").splitlines():
try:
events.append(json.loads(line))
except json.JSONDecodeError:
pass
return events
def _t(value: object) -> str:
return html.escape(str(value), quote=True)
def _label(status: object) -> str:
return LABELS.get(str(status), str(status))
def gaps(items: list[str]) -> str:
"""Строка «Нет исходника: …» для табло и вывода прогона; пробелов нет - пустая строка."""
return "Нет исходника: " + "; ".join(items) if items else ""
def _sec(ms: object) -> str:
"""41230 -> «41,2 с»; не число — пусто."""
return f"{ms / 1000:.1f}".replace(".", ",") + " с" if isinstance(ms, (int, float)) else ""
def _roles(events: list[dict[str, Any]], phase: str) -> list[tuple[str, str]]:
"""Роли фазы по PHASES плюс любой who из ее событий (кроме themiz): имя персоны и последнее состояние."""
people = list(next((roles for pid, _, roles in core.PHASES if pid == phase), []))
for event in events:
who = event.get("who")
if event.get("phase") == phase and who not in (None, "themiz", *people):
people.append(who)
result = []
for role in people:
states = [event.get("state", "") for event in events if event.get("phase") == phase and event.get("who") == role]
result.append((core.name(role), _label(states[-1]) if states else "не начат"))
return result
def _blocks(state: dict[str, Any], events: list[dict[str, Any]]) -> list[tuple[str, str, list[tuple[str, str]]]]:
"""Фазы табло: заголовок, состояние со временем, роли. В state.json фаза — {"status", "ms"}, строка тоже сойдет."""
result = []
for pid, title, _ in core.PHASES:
info = state.get("phases", {}).get(pid)
status, ms = (info.get("status", ""), info.get("ms")) if isinstance(info, dict) else (info, None)
text = " · ".join(filter(None, (_label(status) if status else "не начата", _sec(ms))))
result.append((title, text, _roles(events, pid)))
return result
def done(state: dict[str, Any]) -> tuple[int, int]:
"""Сколько этапов прогона готово: фазы со статусом ok из state.json против всех PHASES."""
phases = state.get("phases", {})
ok = sum(isinstance(info, dict) and info.get("status") == "ok" for info in phases.values())
return ok, len(core.PHASES)
def progress_line(state: dict[str, Any]) -> str:
ok, total = done(state)
return f"Готово {ok} из {total} этапов · {round(ok * 100 / total)} %"
def _rows(events: list[dict[str, Any]]) -> list[list[str]]:
"""Последние 30 событий: время, фаза, роль, действие, состояние, длительность."""
titles = {pid: title for pid, title, _ in core.PHASES}
return [[e.get("ts", ""), titles.get(e.get("phase"), e.get("phase", "")), e.get("name", ""), e.get("action", ""),
_label(e.get("state", "")), _sec(e.get("ms"))] for e in events[-30:]]
def render_html(state: dict[str, Any], events: list[dict[str, Any]]) -> str:
"""Табло одной страницей; пока status == running, страница обновляется раз в 3 секунды."""
refresh = '' if state.get("status") == "running" else ""
about = " · ".join(filter(None, (state.get("track"), state.get("doc"))))
reason = state.get("reason")
missing = gaps(state.get("nedostaet") or [])
phases = "".join(
f" {_t(text)}{_t(title)}
"
+ ("".join(f"
{_t(about)}
" if about else "") + (f"{_t(reason)}
" if reason else "") + (f"{_t(missing)}
" if missing else "") + f'{_t(progress_line(state))}
' + f"