"""Recomputes a domain's indicators after its staging tables change. A successful import asks for a recomputation (`RecomputationQueue.solicitar`), which only drops a marker file. A separate process (`python -m webapi.recomputation`, the `indicadores` compose service) picks the markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs -> staging to facts -> views -> registry -> definitions -> reports. Requests that arrive while a domain is running are folded into one more run. State lives in files under `INDICADORES_DIR`: `pendiente/` markers and `estado.json`; each run is also appended, as counts only, to `indicadores.jsonl` in the import report directory. """ from __future__ import annotations import fcntl import json import logging import os import signal import threading import time from datetime import date, datetime, timezone from pathlib import Path from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) def _now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def _short(value: Any) -> str: text = str(value) return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…" class RecomputationQueue: """Marker-file queue and status of the indicator recomputations.""" def __init__(self, base: Path | None = None): self.base = Path(base or os.environ.get("INDICADORES_DIR", "indicadores")) @property def _pending(self) -> Path: return self.base / "pendiente" @property def _status_path(self) -> Path: return self.base / "estado.json" def request_run(self, dominio: str) -> None: if dominio not in DOMAINS: raise ValueError(f"dominio desconocido: {dominio!r}") self._pending.mkdir(parents=True, exist_ok=True) (self._pending / dominio).write_text(_now(), encoding="utf-8") def pending(self) -> list[str]: if not self._pending.exists(): return [] return sorted(p.name for p in self._pending.iterdir() if p.name in DOMAINS) def take(self, dominio: str) -> bool: """Consumes the marker; a request made from now on queues one more run.""" try: (self._pending / dominio).unlink() return True except FileNotFoundError: return False def status(self) -> dict[str, Any]: try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} pending = set(self.pending()) return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMAINS} def _save_status(self, dominio: str, entrada: dict[str, Any]) -> None: self.base.mkdir(parents=True, exist_ok=True) lock = self.base / ".estado.lock" with open(lock, "w") as handle: fcntl.flock(handle, fcntl.LOCK_EX) try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} status[dominio] = entrada tmp = self._status_path.with_suffix(".tmp") tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8") tmp.replace(self._status_path) def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: """Runs the domain's graph (without `migrate`: the API migrates on startup).""" from webapi.orchestration import Context, run, steps_of desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year)) inicio = _now() started = time.monotonic() self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: ctx = Context(dominio, desde, hasta, allow_undecided=True) pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok", pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos], ) except Exception as exc: # the worker must survive a failing domain log.exception("recálculo de %s falló", dominio) entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}) entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2)) self._save_status(dominio, entrada) try: JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada}) except OSError: pass return entrada def serve(self) -> list[str]: """Runs every pending domain once; returns the ones it ran.""" ran = [] for dominio in self.pending(): if self.take(dominio): self.run(dominio) ran.append(dominio) return ran def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") cola = RecomputationQueue() interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": for dominio in DOMAINS: cola.request_run(dominio) stop = threading.Event() signal.signal(signal.SIGTERM, lambda *_: stop.set()) signal.signal(signal.SIGINT, lambda *_: stop.set()) log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base) while True: for dominio in cola.serve(): log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) if stop.wait(interval): break if __name__ == "__main__": main()