from __future__ import annotations import os import re import shutil import subprocess import sys import threading import time from pathlib import Path from typing import Any from .config import SettingsStore from .runs import RunStore, now_text APP_ROOT = Path(__file__).resolve().parent.parent OUTPUT_KEY_RE = re.compile(r"\d{14}") TERMINATE_GRACE_SECONDS = 10 DETAIL_LIMIT = 500 def parse_output(text: str) -> dict[str, str]: values: dict[str, str] = {} for line in text.splitlines(): key, separator, value = line.partition("=") if separator and re.fullmatch(r"[a-z_]+", key): values[key] = value.strip() return values def last_line(text: str) -> str: lines = [line.strip() for line in text.splitlines() if line.strip()] return lines[-1] if lines else "" class Runner: def __init__( self, settings_store: SettingsStore, runs: RunStore, data_dir: Path, command: list[str] | None = None, ) -> None: self.settings_store = settings_store self.runs = runs self.data_dir = data_dir self.output_dir = data_dir / "output" self.log_dir = data_dir / "logs" self.command = command or [sys.executable, "-m", "etl_app.worker"] self.seconds_per_minute = 60.0 self._lock = threading.Lock() self._process: subprocess.Popen[bytes] | None = None self._current: dict[str, Any] | None = None self._cancelled = False @property def current(self) -> dict[str, Any] | None: current = self._current return dict(current) if current else None def busy(self) -> bool: return self._lock.locked() def log_path(self, run_id: int) -> Path: return self.log_dir / f"{run_id}.log" def read_log(self, run_id: int, tail: int = 0) -> str: path = self.log_path(run_id) if not path.is_file(): return "" text = path.read_text(encoding="utf-8", errors="replace") if tail: return "\n".join(text.splitlines()[-tail:]) return text def start(self, trigger: str, dry_run: bool = False) -> bool: if self.busy(): return False threading.Thread(target=self.run, args=(trigger, dry_run), name=f"etl-{trigger}", daemon=True).start() return True def run(self, trigger: str, dry_run: bool = False) -> int | None: if not self._lock.acquire(blocking=False): return None try: return self._execute(trigger, dry_run) finally: self._process = None self._current = None self._cancelled = False self._lock.release() def cancel(self) -> bool: process = self._process if process is None or process.poll() is not None: return False self._cancelled = True self._terminate(process) return True def _execute(self, trigger: str, dry_run: bool) -> int: settings = self.settings_store.get() run_id = self.runs.create(trigger, dry_run) self._current = {"id": run_id, "trigger": trigger, "dry_run": dry_run, "started_at": now_text()} self.log_dir.mkdir(parents=True, exist_ok=True) self.output_dir.mkdir(parents=True, exist_ok=True) command = [ *self.command, "--settings", str(self.settings_store.path), "--output", str(self.output_dir), *(["--dry-run"] if dry_run else []), ] env = {key: value for key, value in os.environ.items() if key != "METRIX_APP_PROXY_TOKEN"} env.update({"PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8"}) started = time.monotonic() timed_out = False exit_code: int | None = None try: with self.log_path(run_id).open("wb") as log: process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, cwd=APP_ROOT, env=env) self._process = process try: exit_code = process.wait(timeout=settings.timeout_minutes * self.seconds_per_minute) except subprocess.TimeoutExpired: timed_out = True self._terminate(process) exit_code = process.returncode except OSError as exc: self.log_path(run_id).write_text(f"error={exc}\n", encoding="utf-8") duration_ms = int((time.monotonic() - started) * 1000) text = self.read_log(run_id) outcome = parse_output(text) status, detail = self._classify(outcome, text, exit_code, timed_out, settings.timeout_minutes) summary_rows = outcome.get("summary_rows") self.runs.finish( run_id, status=status, finished_at=now_text(), duration_ms=duration_ms, target_time=outcome.get("target_time", ""), summary_rows=int(summary_rows) if summary_rows and summary_rows.isdigit() else None, detail=detail[:DETAIL_LIMIT], exit_code=exit_code, ) self._prune(settings.keep_outputs, settings.keep_runs) return run_id def _classify( self, outcome: dict[str, str], text: str, exit_code: int | None, timed_out: bool, timeout_minutes: int, ) -> tuple[str, str]: if timed_out: return "timeout", str(timeout_minutes) if self._cancelled: return "cancelled", "" if exit_code != 0: return "failed", outcome.get("error") or last_line(text) status = outcome.get("status", "") if status == "waiting": return status, outcome.get("missing_sources") or outcome.get("reason", "") if status == "skipped": return status, outcome.get("database_metric_time", "") if status == "history_repaired": return status, outcome.get("history_output", "") if status == "processed": return status, outcome.get("history_output") or outcome.get("output", "") return "failed", last_line(text) @staticmethod def _terminate(process: subprocess.Popen[bytes]) -> None: process.terminate() try: process.wait(timeout=TERMINATE_GRACE_SECONDS) except subprocess.TimeoutExpired: process.kill() process.wait() def _prune(self, keep_outputs: int, keep_runs: int) -> None: if self.output_dir.is_dir(): outputs = sorted( (path for path in self.output_dir.iterdir() if path.is_dir() and OUTPUT_KEY_RE.fullmatch(path.name)), key=lambda path: path.name, reverse=True, ) stale = [path for path in self.output_dir.iterdir() if path.is_dir() and ".tmp-" in path.name] for path in [*outputs[keep_outputs:], *stale]: shutil.rmtree(path, ignore_errors=True) for run_id in self.runs.prune(keep_runs): self.log_path(run_id).unlink(missing_ok=True)