desktop_build_lock.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. """Cross-process serialization for the mutable Desktop build preflight."""
  2. from __future__ import annotations
  3. import hashlib
  4. import os
  5. from pathlib import Path
  6. from typing import IO
  7. class DesktopBuildLock:
  8. """Advisory lock held while npm installs and packages Hermes Desktop.
  9. ``node_modules`` and ``apps/desktop/release`` are checkout-scoped even
  10. when two commands use different Hermes profiles. The lock therefore
  11. lives under the profile-common Hermes root and is keyed by the resolved
  12. checkout path. Keeping it out of the checkout preserves ``--skip-build``
  13. launches from read-only/prebuilt source trees. The open handle owns the
  14. lock, so the OS releases it automatically if a builder crashes.
  15. The build also writes the checkout an update writes, so the lock first takes the
  16. checkout lock every updater holds (``update_lock``; review C5), then its own: one lock
  17. order (checkout, then desktop build) for a direct ``hermes desktop`` build and for the
  18. update's build (which already holds the checkout lock and only joins it again), and no
  19. gap in which an updater could take the checkout while npm still writes. Holding the
  20. checkout lock also puts the build in the update custody (``update_custody``): its
  21. descendants hold the checkout until they exit.
  22. """
  23. def __init__(self, project_root: Path) -> None:
  24. from hermes_constants import get_default_hermes_root
  25. resolved = os.path.normcase(str(project_root.resolve(strict=False)))
  26. checkout_key = hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:24]
  27. self.path = get_default_hermes_root() / "locks" / f"desktop-build-{checkout_key}.lock"
  28. self.project_root = project_root
  29. self._handle: IO[str] | None = None
  30. self._checkout = None
  31. def acquire(self, *, wait: bool = False) -> bool:
  32. """Acquire the lock; queue behind the current holder when ``wait``.
  33. Returns ``False`` only when another process owns the lock and ``wait``
  34. is unset. Filesystem errors propagate so callers fail explicitly
  35. instead of silently falling back to the corrupting concurrent
  36. behavior.
  37. """
  38. if self._handle is not None:
  39. return True
  40. if not self._acquire_checkout(wait=wait):
  41. return False
  42. try:
  43. acquired = self._acquire_build_lock(wait=wait)
  44. except BaseException:
  45. self._release_checkout()
  46. raise
  47. if not acquired:
  48. self._release_checkout()
  49. return acquired
  50. def _acquire_checkout(self, *, wait: bool) -> bool:
  51. """Take (or, inside an update, join) the checkout lock before the build lock (C5)."""
  52. import time
  53. from hermes_cli import update_lock
  54. held, wanted = update_lock._HELD, update_lock.checkout_lock_path(self.project_root)
  55. if held is not None and held["path"] != str(wanted):
  56. # This process holds a checkout lock under another path. Another spelling of this
  57. # checkout's lock file (a symlinked install root) is this update's own custody: build
  58. # inside it, since a second acquire would wait on its own lock. Any other checkout's
  59. # lock proves nothing about this one (review Q2), and a process records one hold only.
  60. if not (wanted.exists() and os.path.samefile(held["path"], wanted)):
  61. raise OSError(f"this process holds the update lock of another checkout ({held['path']}), "
  62. f"so it cannot also lock {self.project_root} for its build")
  63. return True
  64. lock = update_lock.UpdateLock(install_root=self.project_root, checkout_first=False)
  65. announced = False
  66. while not lock.acquire_checkout(self.project_root):
  67. if lock.holder is not None and lock.holder.reason:
  68. raise OSError(lock.holder.reason) # never build unserialized; the caller says so
  69. if not wait:
  70. return False
  71. if not announced:
  72. print("→ Waiting for a running Hermes update to release this checkout...")
  73. announced = True
  74. time.sleep(1.0)
  75. self._checkout = lock
  76. return True
  77. def _release_checkout(self) -> None:
  78. lock, self._checkout = self._checkout, None
  79. if lock is not None:
  80. lock.release()
  81. def _acquire_build_lock(self, *, wait: bool) -> bool:
  82. from gateway.status import _try_acquire_file_lock
  83. self.path.parent.mkdir(parents=True, exist_ok=True)
  84. handle = self.path.open("a+", encoding="utf-8")
  85. if _try_acquire_file_lock(handle):
  86. self._handle = handle
  87. return True
  88. if not wait:
  89. handle.close()
  90. return False
  91. # Blocking mode queues behind the holder; say so instead of appearing
  92. # to hang with no output (the update path would rather wait for the
  93. # in-flight build it depends on than fail the update).
  94. print("→ Waiting for another Hermes desktop dependency install or build to finish...")
  95. print(f" Lock: {self.path}")
  96. from gateway.status import _release_file_lock
  97. try:
  98. import fcntl
  99. fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
  100. except ImportError:
  101. # Windows has no fcntl; gateway.status's non-blocking try below is
  102. # the best-effort serialization there (msvcrt.locking), so poll it.
  103. import time
  104. while True:
  105. if _try_acquire_file_lock(handle):
  106. self._handle = handle
  107. return True
  108. _release_file_lock(handle)
  109. time.sleep(1.0)
  110. self._handle = handle
  111. return True
  112. def release(self) -> None:
  113. """Release the lock when held. Safe to call more than once."""
  114. handle = self._handle
  115. if handle is None:
  116. return
  117. self._handle = None
  118. try:
  119. from gateway.status import _release_file_lock
  120. _release_file_lock(handle)
  121. finally:
  122. try:
  123. handle.close()
  124. finally:
  125. self._release_checkout() # the narrower lock first: the order is checkout, build
  126. def __enter__(self) -> DesktopBuildLock:
  127. if not self.acquire():
  128. raise RuntimeError("desktop build lock is already held")
  129. return self
  130. def __exit__(self, *_exc: object) -> None:
  131. self.release()