storage.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """Storage helpers (stdlib only): atomic JSON, append-only JSONL, strict perms.
  2. Default backend is local-json. The optional google-sheets tracker is handled in
  3. report.py by emitting rows for the `google-workspace` skill; this module stays
  4. dependency-free so the hermetic tests never touch the network.
  5. """
  6. from __future__ import annotations
  7. import contextlib
  8. import json
  9. import os
  10. import time
  11. from pathlib import Path
  12. from typing import Any
  13. import crypto
  14. import paths
  15. @contextlib.contextmanager
  16. def locked(target: Path, timeout: float = 10.0, stale: float = 30.0):
  17. """Portable advisory lock via an O_EXCL lockfile next to `target`.
  18. Serializes read-modify-write on shared JSON (the ledger) across concurrent
  19. processes - a cron re-scan overlapping a manual run, or multiple tenants -
  20. so one writer can't clobber another's update. A lock older than `stale`
  21. seconds is treated as abandoned (crashed writer) and broken, so a dead
  22. process can never deadlock the queue. Works on macOS/Linux/Windows (O_EXCL).
  23. """
  24. ensure_dir(target.parent)
  25. lock = target.with_name(target.name + ".lock")
  26. deadline = time.monotonic() + timeout
  27. while True:
  28. try:
  29. fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
  30. try:
  31. os.write(fd, str(os.getpid()).encode())
  32. finally:
  33. os.close(fd)
  34. break
  35. except FileExistsError:
  36. try:
  37. if time.time() - lock.stat().st_mtime > stale:
  38. lock.unlink(missing_ok=True)
  39. continue
  40. except OSError:
  41. pass
  42. if time.monotonic() >= deadline:
  43. raise TimeoutError(f"could not acquire lock {lock} within {timeout}s")
  44. time.sleep(0.05)
  45. try:
  46. yield
  47. finally:
  48. with contextlib.suppress(OSError):
  49. lock.unlink(missing_ok=True)
  50. def _secure(path: Path, mode: int) -> None:
  51. try:
  52. os.chmod(path, mode)
  53. except OSError:
  54. pass # non-POSIX / unsupported FS; HERMES_HOME directory perms still apply
  55. def ensure_dir(path: Path) -> Path:
  56. path.mkdir(parents=True, exist_ok=True)
  57. _secure(path, 0o700)
  58. return path
  59. def _is_sensitive(path: Path) -> bool:
  60. """Per-subject docs (dossier, ledger) are sensitive; config/cache are not."""
  61. try:
  62. Path(path).resolve().relative_to(paths.subjects_dir().resolve())
  63. return True
  64. except (ValueError, OSError):
  65. return False
  66. def _age_path(path: Path) -> Path:
  67. return path.with_name(path.name + ".age")
  68. def _atomic_write(path: Path, data: bytes) -> Path:
  69. tmp = path.with_name(path.name + ".tmp")
  70. tmp.write_bytes(data)
  71. _secure(tmp, 0o600)
  72. os.replace(tmp, path)
  73. _secure(path, 0o600)
  74. return path
  75. def write_json(path: Path, obj: Any) -> Path:
  76. ensure_dir(path.parent)
  77. data = (json.dumps(obj, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
  78. if _is_sensitive(path) and crypto.encryption_setting() == "age":
  79. if not crypto.age_available():
  80. raise RuntimeError(
  81. "encryption=age is configured but `age` is not available; "
  82. "refusing to write PII as plaintext. Install age or run `setup --encryption none`."
  83. )
  84. target = _atomic_write(_age_path(path), crypto.encrypt(data))
  85. if path.exists():
  86. path.unlink() # migrate plaintext -> ciphertext
  87. return target
  88. target = _atomic_write(path, data)
  89. ap = _age_path(path)
  90. if ap.exists():
  91. ap.unlink() # encryption turned off -> drop stale ciphertext
  92. return target
  93. def read_json(path: Path, default: Any = None) -> Any:
  94. ap = _age_path(path)
  95. if ap.exists():
  96. return json.loads(crypto.decrypt(ap.read_bytes()).decode("utf-8"))
  97. if path.exists():
  98. return json.loads(path.read_text(encoding="utf-8"))
  99. return default
  100. def append_jsonl(path: Path, record: dict) -> Path:
  101. ensure_dir(path.parent)
  102. with path.open("a", encoding="utf-8") as fh:
  103. fh.write(json.dumps(record, ensure_ascii=False) + "\n")
  104. _secure(path, 0o600)
  105. return path
  106. def read_jsonl(path: Path) -> list[dict]:
  107. if not path.exists():
  108. return []
  109. out: list[dict] = []
  110. for line in path.read_text(encoding="utf-8").splitlines():
  111. line = line.strip()
  112. if line:
  113. out.append(json.loads(line))
  114. return out