"""Development-only file backend for Audit Core. This backend intentionally writes local JSONL files under /tmp by default. It is useful for wiring integrations before the durable Audit Core archive exists, but it is not production audit custody. """ from __future__ import annotations import json import os from datetime import datetime, timedelta, timezone from pathlib import Path from audit_core.interface import AuditEvent class MockFileAuditBackend: """Append audit events to hourly JSONL files and clean up old files.""" def __init__( self, base_dir: str | Path | None = None, retention_days: int | None = None, now: datetime | None = None, ) -> None: self.base_dir = Path(base_dir or os.environ.get("AUDIT_CORE_MOCK_DIR", "/tmp/audit-core")) self.retention_days = int( retention_days if retention_days is not None else os.environ.get("AUDIT_CORE_MOCK_RETENTION_DAYS", "7") ) self._now = now def emit(self, event: AuditEvent) -> str: self.base_dir.mkdir(parents=True, exist_ok=True) self.cleanup_old_files() path = self.current_path() record = event.as_record() with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n") return str(path) def cleanup_old_files(self) -> list[str]: if self.retention_days < 0 or not self.base_dir.exists(): return [] cutoff = self.now() - timedelta(days=self.retention_days) removed: list[str] = [] for path in self.base_dir.glob("audit-*.jsonl"): try: modified = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc) except FileNotFoundError: continue if modified < cutoff: path.unlink(missing_ok=True) removed.append(str(path)) return removed def current_path(self) -> Path: stamp = self.now().strftime("%Y%m%dT%H") return self.base_dir / f"audit-{stamp}.jsonl" def now(self) -> datetime: return self._now or datetime.now(timezone.utc)