"""Recomputes a domain's indicators after its staging tables change. A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`), which only drops a marker file. A separate process (`python -m webapi.indicadores_vivos`, the `indicadores` compose service) picks the markers up and runs that domain's cycle (`webapi.orquestacion.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 DOMINIOS = ("cacu", "cama", "tea") _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 ColaDeRecalculo: """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 solicitar(self, dominio: str) -> None: if dominio not in DOMINIOS: 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 pendientes(self) -> list[str]: if not self._pending.exists(): return [] return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS) def tomar(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 estado(self) -> dict[str, Any]: try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} pending = set(self.pendientes()) return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS} def _guardar_estado(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 correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: """Runs the domain's graph (without `migrar`: the API migrates on startup).""" from webapi.orquestacion import Contexto, correr, pasos_de 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._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True) pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"]) entrada.update( estado="ok", pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} 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._guardar_estado(dominio, entrada) try: JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada}) except OSError: pass return entrada def atender(self) -> list[str]: """Runs every pending domain once; returns the ones it ran.""" ran = [] for dominio in self.pendientes(): if self.tomar(dominio): self.correr(dominio) ran.append(dominio) return ran def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") cola = ColaDeRecalculo() interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": for dominio in DOMINIOS: cola.solicitar(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.atender(): log.info("%s: %s", dominio, cola.estado()[dominio].get("estado")) if stop.wait(interval): break if __name__ == "__main__": main()