"""Stores one JSON file per source.""" import os import tempfile from pathlib import Path from app.models import RateSheet def _sheet_path(data_dir: Path, source_id: str) -> Path: return data_dir / f"{source_id}.json" def write_sheet(data_dir: Path, sheet: RateSheet) -> None: """Replaces the file atomically, so a reader never sees a partial write.""" data_dir.mkdir(parents=True, exist_ok=True) descriptor, temp_name = tempfile.mkstemp(dir=data_dir, suffix=".tmp") try: with os.fdopen(descriptor, "wb") as temp_file: temp_file.write(sheet.model_dump_json(indent=2).encode("utf-8")) os.replace(temp_name, _sheet_path(data_dir, sheet.source)) except BaseException: Path(temp_name).unlink(missing_ok=True) raise def read_sheet(data_dir: Path, source_id: str) -> RateSheet | None: path = _sheet_path(data_dir, source_id) if not path.exists(): return None return RateSheet.model_validate_json(path.read_bytes())