webapp.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. """Build and launch plumbing for the browser-hosted Desktop workspace.
  2. The browser surface shares Hermes' hardened dashboard server. This module owns
  3. only the separate renderer artifact and the one-way handoff into that server;
  4. it never creates a second HTTP/WebSocket stack. The renderer is compiled by the
  5. shared product builders (``apps/desktop/scripts/build-webapp.mjs``), whose
  6. receipt inside ``dist-webapp`` decides freshness.
  7. """
  8. from __future__ import annotations
  9. from contextlib import contextmanager
  10. import os
  11. from pathlib import Path
  12. import subprocess
  13. # Serialize renderer publication with Dashboard builds in this checkout.
  14. _LOCK_NAME = ".web_ui_build.lock"
  15. _LOCK_WAIT_SECONDS = 30 * 60
  16. # Written into the bundle when `hermes update` could not rebuild it, so the gateways serving it report
  17. # the Webapp unavailable instead of serving it against the updated backend. Publishing a build
  18. # replaces the whole folder, and the receipt's output hash covers this file, so a marked bundle is
  19. # never reused as current.
  20. STALE_MARKER = ".hermes-stale"
  21. # A packaged bundle (the Nix package), like HERMES_WEB_DIST for the dashboard: the packager
  22. # builds it, so Hermes serves it as it is and never builds or marks it.
  23. DIST_ENV = "HERMES_WEBAPP_DIST"
  24. class WebappBuildError(RuntimeError):
  25. """The browser-hosted Desktop renderer could not be prepared."""
  26. def packaged_webapp_dist() -> Path | None:
  27. """The bundle :data:`DIST_ENV` names, or None when Hermes builds its own."""
  28. value = os.environ.get(DIST_ENV)
  29. return Path(value).expanduser() if value else None
  30. def webapp_dist_dir(project_root: Path) -> Path:
  31. return packaged_webapp_dist() or project_root / "apps" / "desktop" / "dist-webapp"
  32. def mark_webapp_stale(project_root: Path) -> bool:
  33. """Mark the built bundle in *project_root* out of date, after a rebuild that failed. False when
  34. no bundle is built: nothing serves one, and the build output folder stays the builder's. Also
  35. False for a packaged bundle, which is the packager's."""
  36. dist = webapp_dist_dir(project_root)
  37. if packaged_webapp_dist() is not None or not (dist / "index.html").is_file():
  38. return False
  39. (dist / STALE_MARKER).write_text("hermes update could not rebuild this bundle\n", encoding="utf-8")
  40. return True
  41. def webapp_bundle_stale(dist: Path) -> bool:
  42. """Whether the bundle in *dist* is marked out of date (:func:`mark_webapp_stale`)."""
  43. return (Path(dist) / STALE_MARKER).is_file()
  44. def _clear_stale_mark(dist: Path) -> None:
  45. try:
  46. (dist / STALE_MARKER).unlink(missing_ok=True)
  47. except OSError as exc:
  48. raise WebappBuildError(f"Could not mark the Webapp renderer at {dist} current: {exc}") from exc
  49. @contextmanager
  50. def _exclusive_build_lock(path: Path):
  51. """Cross-platform exclusive lock for one renderer generation."""
  52. from pm.filesystem import lock_fd, unlock_fd
  53. try:
  54. path.parent.mkdir(parents=True, exist_ok=True)
  55. handle = path.open("a+b")
  56. except OSError as exc:
  57. raise WebappBuildError(f"Could not open Webapp build lock {path}: {exc}") from exc
  58. try:
  59. try:
  60. if not lock_fd(handle.fileno(), wait=False):
  61. print("→ Another Hermes Webapp build is running; waiting for it...")
  62. if not lock_fd(handle.fileno(), wait=True, timeout=_LOCK_WAIT_SECONDS):
  63. raise WebappBuildError(f"Timed out waiting for another Webapp build ({path})")
  64. except OSError as exc:
  65. raise WebappBuildError(f"Could not lock Webapp build {path}: {exc}") from exc
  66. yield
  67. finally:
  68. unlock_fd(handle.fileno())
  69. handle.close()
  70. def prepare_webapp_renderer(
  71. project_root: Path,
  72. *,
  73. force: bool = False,
  74. skip_build: bool = False,
  75. explicit: bool = False,
  76. ) -> Path:
  77. """Return a verified browser renderer, serializing concurrent builds.
  78. ``explicit`` (a requested build) may install dependencies even when lazy
  79. installs are disabled, like ``hermes desktop --build-only``.
  80. """
  81. from hermes_cli.source_build import build_source_webapp, source_build_env, source_product_current
  82. project_root = project_root.resolve()
  83. dist = webapp_dist_dir(project_root)
  84. if packaged_webapp_dist() is not None:
  85. # The packager built it into a read-only store; there is nothing here to rebuild.
  86. if not (dist / "index.html").is_file():
  87. raise WebappBuildError(f"{DIST_ENV} is set but no Webapp renderer exists at {dist}")
  88. if force:
  89. raise WebappBuildError(f"The Webapp renderer at {dist} comes from {DIST_ENV} and cannot be rebuilt here")
  90. print(f"→ Using Hermes Webapp renderer from {DIST_ENV}: {dist}")
  91. return dist
  92. if skip_build:
  93. # Reuse takes no build lock, like `hermes dashboard --skip-build`: the
  94. # lock lives in the install root, which a read-only install cannot write.
  95. if not (dist / "index.html").is_file():
  96. raise WebappBuildError(
  97. f"--skip-build was passed but no Webapp renderer exists at {dist}"
  98. )
  99. print(f"→ Reusing Hermes Webapp renderer at {dist} (--skip-build)")
  100. return dist
  101. # A current, unmarked bundle needs no lock either, so a read-only install
  102. # (the Docker image) reuses the one baked at build time.
  103. if not force and not webapp_bundle_stale(dist) and source_product_current(project_root, "webapp", dist):
  104. print(f"✓ Hermes Webapp renderer is up to date: {dist}")
  105. return dist
  106. with _exclusive_build_lock(project_root / _LOCK_NAME):
  107. if not force and source_product_current(project_root, "webapp", dist):
  108. _clear_stale_mark(dist)
  109. print(f"✓ Hermes Webapp renderer is up to date: {dist}")
  110. return dist
  111. try:
  112. build_source_webapp(project_root, env=source_build_env(explicit=explicit), explicit=explicit)
  113. except (OSError, subprocess.SubprocessError, RuntimeError) as exc:
  114. raise WebappBuildError(f"Browser-hosted Desktop build failed: {exc}") from exc
  115. _clear_stale_mark(dist)
  116. print(f"✓ Hermes Webapp renderer built: {dist}")
  117. return dist