py105 lines3.9 KB
| 1 | """Data-feed guard: a source that fails or returns nothing stops the run instead of replacing good data.""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import csv |
| 5 | import json |
| 6 | from pathlib import Path |
| 7 | |
| 8 | |
| 9 | class StageError(RuntimeError): |
| 10 | """A stage failed in a way the operator has to see, with how to resume.""" |
| 11 | |
| 12 | def __init__(self, stage: str, reason: str, resume: str = "", detail: str = ""): |
| 13 | self.stage = stage |
| 14 | self.reason = reason |
| 15 | self.resume = resume |
| 16 | self.detail = detail |
| 17 | message = f"stage '{stage}' failed: {reason}" |
| 18 | if detail: |
| 19 | message += f"\n {detail}" |
| 20 | if resume: |
| 21 | message += f"\n resume with: {resume}" |
| 22 | super().__init__(message) |
| 23 | |
| 24 | |
| 25 | def count_rows(path: Path) -> int | None: |
| 26 | """Rows a stage produced, or None when the file's shape says nothing. |
| 27 | |
| 28 | CSV is counted with the csv module rather than by lines, because an |
| 29 | embedded newline inside a quoted evidence snippet would otherwise inflate |
| 30 | the count, and these files are full of evidence snippets. |
| 31 | """ |
| 32 | p = Path(path) |
| 33 | if not p.is_file(): |
| 34 | return None |
| 35 | suffix = p.suffix.lower() |
| 36 | try: |
| 37 | if suffix == ".csv": |
| 38 | with p.open(newline="", encoding="utf-8-sig", errors="replace") as fh: |
| 39 | reader = csv.reader(fh) |
| 40 | try: |
| 41 | next(reader) |
| 42 | except StopIteration: |
| 43 | return 0 |
| 44 | return sum(1 for row in reader if any((cell or "").strip() for cell in row)) |
| 45 | if suffix in {".txt", ".md", ".jsonl"}: |
| 46 | return sum(1 for line in p.read_text(encoding="utf-8", errors="replace").splitlines() |
| 47 | if line.strip()) |
| 48 | except OSError: |
| 49 | return None |
| 50 | return None |
| 51 | |
| 52 | |
| 53 | def assert_produced(stage: str, outputs, min_rows: int = 1, resume: str = "") -> None: |
| 54 | """A stage that produced nothing says so loudly, here and nowhere else.""" |
| 55 | outputs = [Path(o) for o in outputs] |
| 56 | missing = [o for o in outputs if not o.is_file()] |
| 57 | if missing: |
| 58 | raise StageError(stage, |
| 59 | "declared output was not created: " + ", ".join(p.name for p in missing), |
| 60 | resume=resume) |
| 61 | if min_rows <= 0: |
| 62 | return |
| 63 | rows = next((n for n in (count_rows(o) for o in outputs) if n is not None), None) |
| 64 | if rows is None: |
| 65 | return |
| 66 | if rows < min_rows: |
| 67 | raise StageError( |
| 68 | stage, |
| 69 | f"produced {rows} rows (expected at least {min_rows})", |
| 70 | resume=resume, |
| 71 | detail=(f"{outputs[0].name} exists but is empty. " |
| 72 | "A source is down, a credential/session lapsed, or the input " |
| 73 | "roster matched nothing. An empty artifact is never accepted.")) |
| 74 | |
| 75 | |
| 76 | def check_payload(data, url: str = ""): |
| 77 | """An ArcGIS-style endpoint reports failure inside a 200 response; treat it as one.""" |
| 78 | if isinstance(data, dict) and "error" in data: |
| 79 | raise RuntimeError(f"server error{' from ' + url if url else ''}: {data['error']}") |
| 80 | return data |
| 81 | |
| 82 | |
| 83 | def fetch_to_cache(name: str, rows, path: Path, min_rows: int = 1) -> int: |
| 84 | """Stream a source's rows to ``<path>.tmp`` and swap it in only when complete. |
| 85 | |
| 86 | The previous cache file stays untouched until the new pull has finished |
| 87 | and passed the row check, so an outage or a malformed export mid-run can |
| 88 | never leave a half-written or empty file where good data used to be. |
| 89 | """ |
| 90 | path = Path(path) |
| 91 | tmp = path.with_suffix(".tmp") |
| 92 | n = 0 |
| 93 | try: |
| 94 | with tmp.open("w") as fh: |
| 95 | for attrs in rows: |
| 96 | fh.write(json.dumps(attrs, separators=(",", ":")) + "\n") |
| 97 | n += 1 |
| 98 | if n < min_rows: |
| 99 | raise StageError(name, f"source returned {n} rows (expected at least {min_rows})", |
| 100 | detail=f"kept the previous {path.name}; nothing was replaced.") |
| 101 | tmp.replace(path) |
| 102 | except BaseException: |
| 103 | tmp.unlink(missing_ok=True) |
| 104 | raise |
| 105 | return n |