hermes_files.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Private state files shared by the Hermes runtime modules: atomic writes and an exclusive lock."""
  2. from __future__ import annotations
  3. from contextlib import contextmanager
  4. import json
  5. import os
  6. import secrets
  7. def _write(path, value):
  8. path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
  9. temp = path.with_name('.' + path.name + '.' + secrets.token_hex(8))
  10. try:
  11. fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
  12. with os.fdopen(fd, 'w') as f:
  13. json.dump(value, f, ensure_ascii=False)
  14. f.flush(); os.fsync(f.fileno())
  15. os.replace(temp, path)
  16. finally:
  17. temp.unlink(missing_ok=True)
  18. @contextmanager
  19. def _file_lock(path):
  20. path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
  21. fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
  22. with os.fdopen(fd, 'a+b') as f:
  23. if os.name == 'nt':
  24. import msvcrt
  25. f.seek(0); f.write(b'0'); f.flush(); f.seek(0)
  26. msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1)
  27. else:
  28. import fcntl
  29. fcntl.flock(f.fileno(), fcntl.LOCK_EX)
  30. try:
  31. yield
  32. finally:
  33. if os.name == 'nt':
  34. f.seek(0); msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
  35. else:
  36. fcntl.flock(f.fileno(), fcntl.LOCK_UN)