install_identity.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Stable opaque identity shared by every profile in one Hermes install."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. from pathlib import Path
  6. import re
  7. import threading
  8. from typing import Optional
  9. import uuid
  10. from hermes_constants import get_default_hermes_root
  11. from utils import atomic_write_text
  12. _INSTALL_ID_FILENAME = "install_id"
  13. _INSTALL_ID_RE = re.compile(r"^[0-9a-f]{32}$")
  14. _INSTALL_ID_CACHE: dict[str, Optional[str]] = {"root": None, "value": None}
  15. _INSTALL_ID_LOCK, _INSTALL_ID_PUBLICATION_LOCK = threading.Lock(), threading.Lock()
  16. @contextlib.contextmanager
  17. def _install_id_file_lock(root: Path):
  18. """Serialize identity publication across processes on POSIX and Windows."""
  19. fd = os.open(root / ".install_id.lock", os.O_RDWR | os.O_CREAT, 0o600)
  20. windows = os.name == "nt"
  21. try:
  22. if windows:
  23. import msvcrt
  24. if os.fstat(fd).st_size == 0:
  25. os.write(fd, b"\0")
  26. os.fsync(fd)
  27. os.lseek(fd, 0, os.SEEK_SET)
  28. msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
  29. else:
  30. import fcntl
  31. fcntl.flock(fd, fcntl.LOCK_EX)
  32. yield
  33. finally:
  34. try:
  35. if windows:
  36. os.lseek(fd, 0, os.SEEK_SET)
  37. msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
  38. else:
  39. fcntl.flock(fd, fcntl.LOCK_UN)
  40. finally:
  41. os.close(fd)
  42. def _read_existing(path: Path) -> tuple[Optional[str], bool]:
  43. """``(valid id or None, mint?)`` — mint on a missing or malformed file, never on a read failure."""
  44. try:
  45. existing = path.read_text(encoding="utf-8-sig").strip().lower()
  46. except FileNotFoundError:
  47. return None, True
  48. except (OSError, UnicodeDecodeError):
  49. return None, False
  50. return (existing, False) if _INSTALL_ID_RE.fullmatch(existing) else (None, True)
  51. def read_or_create_install_id(root: Path | None = None) -> Optional[str]:
  52. """Read or atomically mint the opaque id for the physical install.
  53. ``None`` = neither readable nor persistable; an ephemeral id would violate the authority/registry contract.
  54. """
  55. root = get_default_hermes_root() if root is None else root
  56. path = root / _INSTALL_ID_FILENAME
  57. # A reader can collide with the first atomic replace on Windows. Serialize
  58. # threads before reading, and recheck an unavailable file under the OS lock.
  59. with _INSTALL_ID_PUBLICATION_LOCK:
  60. existing, _ = _read_existing(path)
  61. if existing is not None:
  62. return existing # Existing identities remain readable on read-only roots.
  63. try:
  64. from hermes_constants import mkdir_under_hermes_home
  65. mkdir_under_hermes_home(root)
  66. with _install_id_file_lock(root):
  67. existing, mint = _read_existing(path)
  68. if not mint:
  69. return existing
  70. atomic_write_text(path, uuid.uuid4().hex + "\n", tmp_prefix=".install_id-", fsync_dir=True, mode=0o600)
  71. committed = path.read_text(encoding="utf-8-sig").strip().lower()
  72. return committed if _INSTALL_ID_RE.fullmatch(committed) else None
  73. except OSError:
  74. return None
  75. def get_install_id(*, cache: dict[str, Optional[str]] | None = None) -> Optional[str]:
  76. """Return the process-cached stable id for the active Hermes root."""
  77. root = get_default_hermes_root()
  78. root_key = str(root)
  79. target_cache = _INSTALL_ID_CACHE if cache is None else cache
  80. def _cached() -> Optional[str]:
  81. cached = target_cache.get("value")
  82. return cached if cached and target_cache.get("root") in (None, root_key) else None
  83. if value := _cached():
  84. return value
  85. with _INSTALL_ID_LOCK:
  86. if value := _cached():
  87. return value
  88. value = read_or_create_install_id(root)
  89. if value:
  90. target_cache["root"] = root_key
  91. target_cache["value"] = value
  92. return value
  93. __all__ = ["get_install_id", "read_or_create_install_id"]