The recomputation worker estimates with the models in production and wakes on the marker directory; the scanned test form carries a birth date
This commit is contained in:
+52
-15
@@ -1,11 +1,15 @@
|
||||
"""Recomputes a domain's indicators after its staging tables change.
|
||||
|
||||
A successful import asks for a recomputation (`RecomputationQueue.solicitar`),
|
||||
A successful import asks for a recomputation (`RecomputationQueue.request_run`),
|
||||
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.
|
||||
webapi.recomputation`, the `indicadores` compose service) watches the markers'
|
||||
directory and, on any change there, runs every pending domain's cycle
|
||||
(`webapi.orchestration.run`): catalogs -> staging to facts -> views -> registry
|
||||
-> definitions -> event models -> cohorts -> estimates, with the live estimators
|
||||
of the models in production (`webapi.orchestration.estimators`). A periodic
|
||||
check (`INDICADORES_INTERVALO_S`) stays as a fallback for a missed or coalesced
|
||||
filesystem event; it no longer sets the normal reaction time. Requests that
|
||||
arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
and `estado.json`; each run is also appended, as counts only, to
|
||||
@@ -24,6 +28,9 @@ from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
from watchdog.observers import Observer
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes
|
||||
@@ -99,6 +106,7 @@ class RecomputationQueue:
|
||||
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
|
||||
from webapi.orchestration.estimators import live_estimators
|
||||
|
||||
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))
|
||||
@@ -107,7 +115,7 @@ class RecomputationQueue:
|
||||
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)
|
||||
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio))
|
||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
@@ -134,22 +142,51 @@ class RecomputationQueue:
|
||||
return ran
|
||||
|
||||
|
||||
class _Waker(FileSystemEventHandler):
|
||||
"""Wakes the main loop on any change in the pending-markers directory."""
|
||||
|
||||
def __init__(self, wake: threading.Event):
|
||||
self._wake = wake
|
||||
|
||||
def on_any_event(self, event) -> None:
|
||||
self._wake.set()
|
||||
|
||||
|
||||
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"))
|
||||
cola._pending.mkdir(parents=True, exist_ok=True)
|
||||
fallback_s = 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
|
||||
wake = threading.Event()
|
||||
|
||||
def _stop(*_):
|
||||
stop.set()
|
||||
wake.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
|
||||
observer = Observer()
|
||||
observer.schedule(_Waker(wake), str(cola._pending), recursive=False)
|
||||
observer.start()
|
||||
log.info("indicadores en vivo: observando %s (respaldo cada %.0f s)", cola._pending, fallback_s)
|
||||
try:
|
||||
while True:
|
||||
for dominio in cola.serve():
|
||||
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
|
||||
if stop.is_set():
|
||||
break
|
||||
wake.wait(fallback_s)
|
||||
wake.clear()
|
||||
if stop.is_set():
|
||||
break
|
||||
finally:
|
||||
observer.stop()
|
||||
observer.join()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user