"""Data-feed guard: a source that fails or returns nothing stops the run instead of replacing good data.""" from __future__ import annotations import csv import json from pathlib import Path class StageError(RuntimeError): """A stage failed in a way the operator has to see, with how to resume.""" def __init__(self, stage: str, reason: str, resume: str = "", detail: str = ""): self.stage = stage self.reason = reason self.resume = resume self.detail = detail message = f"stage '{stage}' failed: {reason}" if detail: message += f"\n {detail}" if resume: message += f"\n resume with: {resume}" super().__init__(message) def count_rows(path: Path) -> int | None: """Rows a stage produced, or None when the file's shape says nothing. CSV is counted with the csv module rather than by lines, because an embedded newline inside a quoted evidence snippet would otherwise inflate the count, and these files are full of evidence snippets. """ p = Path(path) if not p.is_file(): return None suffix = p.suffix.lower() try: if suffix == ".csv": with p.open(newline="", encoding="utf-8-sig", errors="replace") as fh: reader = csv.reader(fh) try: next(reader) except StopIteration: return 0 return sum(1 for row in reader if any((cell or "").strip() for cell in row)) if suffix in {".txt", ".md", ".jsonl"}: return sum(1 for line in p.read_text(encoding="utf-8", errors="replace").splitlines() if line.strip()) except OSError: return None return None def assert_produced(stage: str, outputs, min_rows: int = 1, resume: str = "") -> None: """A stage that produced nothing says so loudly, here and nowhere else.""" outputs = [Path(o) for o in outputs] missing = [o for o in outputs if not o.is_file()] if missing: raise StageError(stage, "declared output was not created: " + ", ".join(p.name for p in missing), resume=resume) if min_rows <= 0: return rows = next((n for n in (count_rows(o) for o in outputs) if n is not None), None) if rows is None: return if rows < min_rows: raise StageError( stage, f"produced {rows} rows (expected at least {min_rows})", resume=resume, detail=(f"{outputs[0].name} exists but is empty. " "A source is down, a credential/session lapsed, or the input " "roster matched nothing. An empty artifact is never accepted.")) def check_payload(data, url: str = ""): """An ArcGIS-style endpoint reports failure inside a 200 response; treat it as one.""" if isinstance(data, dict) and "error" in data: raise RuntimeError(f"server error{' from ' + url if url else ''}: {data['error']}") return data def fetch_to_cache(name: str, rows, path: Path, min_rows: int = 1) -> int: """Stream a source's rows to ``.tmp`` and swap it in only when complete. The previous cache file stays untouched until the new pull has finished and passed the row check, so an outage or a malformed export mid-run can never leave a half-written or empty file where good data used to be. """ path = Path(path) tmp = path.with_suffix(".tmp") n = 0 try: with tmp.open("w") as fh: for attrs in rows: fh.write(json.dumps(attrs, separators=(",", ":")) + "\n") n += 1 if n < min_rows: raise StageError(name, f"source returned {n} rows (expected at least {min_rows})", detail=f"kept the previous {path.name}; nothing was replaced.") tmp.replace(path) except BaseException: tmp.unlink(missing_ok=True) raise return n