"""Content-addressed JSON cache and environment state records.""" from __future__ import annotations import json import os import tempfile from pathlib import Path from typing import Any from .config import TranslationConfig, sha256_text def canonical_json(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def segment_cache_key(source: str, config: TranslationConfig) -> str: normalized = "\n".join(line.rstrip() for line in source.strip().splitlines()) payload = { "source": normalized, "source_language": config.source_language, "target_language": config.target_language, "model_id": config.model_id, "model_revision": config.model_revision, "prompt_hash": config.prompt_hash, "glossary_hash": config.glossary_hash, "segmenter_version": config.segmenter_version, } return sha256_text(canonical_json(payload)) class TranslationCache: """A deliberately small JSON-file cache for mounted Bucket storage.""" def __init__(self, root: Path, config: TranslationConfig, write: bool = True): self.root = root self.config = config self.write_enabled = write def segment_path(self, key: str) -> Path: return self.root / "segments" / key[:2] / f"{key}.json" def get(self, key: str) -> dict[str, Any] | None: path = self.segment_path(key) if not path.exists(): return None with path.open(encoding="utf-8") as handle: record = json.load(handle) if record.get("source_hash") != key or record.get("model_revision") != self.config.model_revision: return None if record.get("validation", {}).get("passed") is not True: return None return record def put(self, key: str, record: dict[str, Any]) -> None: if not self.write_enabled: return path = self.segment_path(key) path.parent.mkdir(parents=True, exist_ok=True) _atomic_write_json(path, record) def run_path(self, environment: str, source_sha: str, job_id: str) -> Path: return self.root / "runs" / "transformers" / "ja" / environment / source_sha / f"{job_id}.json" def write_run(self, environment: str, source_sha: str, job_id: str, manifest: dict[str, Any]) -> Path | None: if not self.write_enabled: return None path = self.run_path(environment, source_sha, job_id) path.parent.mkdir(parents=True, exist_ok=True) _atomic_write_json(path, manifest) return path def state_path(self, environment: str) -> Path: return self.root / "state" / f"transformers-ja-{environment}.json" def read_state(self, environment: str) -> dict[str, Any]: path = self.state_path(environment) if not path.exists(): return { "environment": environment, "merged_source_sha": None, "open_pr_source_sha": None, "open_pr_number": None, "open_pr_state": None, } with path.open(encoding="utf-8") as handle: return json.load(handle) def write_state(self, environment: str, state: dict[str, Any]) -> Path | None: if not self.write_enabled: return None path = self.state_path(environment) path.parent.mkdir(parents=True, exist_ok=True) _atomic_write_json(path, state) return path def _atomic_write_json(path: Path, value: dict[str, Any]) -> None: fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump(value, handle, ensure_ascii=False, sort_keys=True, indent=2) handle.write("\n") os.replace(temporary, path) except Exception: try: os.unlink(temporary) except FileNotFoundError: pass raise