sidecar_paths.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """Resolve where the Photon sidecar runs from and where its Node deps live.
  2. Hosted images keep the plugin tree read-only (EROFS), so, mirroring
  3. ``resolve_whatsapp_bridge_dir``: (1) ``PHOTON_SIDECAR_DIR`` override as-is; (2) writable
  4. source dir → run in place; (3) read-only with baked, current ``node_modules`` → in place;
  5. (4) read-only and deps missing/stale → mirror the source files to
  6. ``$HERMES_HOME/photon/sidecar``. The mirror is refreshed by content compare; ``node_modules``
  7. is left alone so the lockfile-vs-install-marker check triggers ``npm ci`` inside the mirror.
  8. Resolution never happens at import time (it probes/copies on disk).
  9. """
  10. from __future__ import annotations
  11. import filecmp
  12. import logging
  13. import os
  14. import shutil
  15. from pathlib import Path
  16. from typing import Optional
  17. logger = logging.getLogger(__name__)
  18. SOURCE_SIDECAR_DIR = Path(__file__).parent / "sidecar"
  19. # Files that define the sidecar; node_modules is deliberately absent (baked on managed
  20. # images or installed by npm in the mirror).
  21. _MIRROR_FILES = ("index.mjs", "package.json", "package-lock.json", "patch-spectrum-mixed-attachments.mjs")
  22. # Tests monkeypatch these module globals directly; the accessors honor a non-None value.
  23. _SIDECAR_DIR: Optional[Path] = None
  24. # Written by `hermes photon install-sidecar` on npm failure so check_requirements() can
  25. # surface the root cause later; cleared on success.
  26. _NPM_ERROR_LOG: Optional[Path] = None
  27. _NPM_ERROR_LOG_MAX_CHARS = 300
  28. def dir_writable(path: Path) -> bool:
  29. """True when we can create files in ``path`` (probe, not stat — stat lies on root-squash
  30. / read-only bind mounts)."""
  31. probe = path / ".hermes-write-probe"
  32. try:
  33. probe.touch()
  34. probe.unlink()
  35. except OSError:
  36. return False
  37. return True
  38. _dir_writable = dir_writable
  39. def _lock_newer_than_install(sidecar_dir: Path) -> bool:
  40. """True when the committed lockfile postdates npm's install marker
  41. (``node_modules/.package-lock.json``) — the same signal ``npm ci`` uses. False on any
  42. stat failure so an odd filesystem never blocks start."""
  43. lockfile = sidecar_dir / "package-lock.json"
  44. marker = sidecar_dir / "node_modules" / ".package-lock.json"
  45. try:
  46. return lockfile.stat().st_mtime > marker.stat().st_mtime
  47. except OSError:
  48. return False
  49. def resolve_sidecar_dir(source_dir: Optional[Path] = None) -> Path:
  50. """Return the directory the sidecar should run from (see module doc)."""
  51. source = Path(source_dir) if source_dir is not None else SOURCE_SIDECAR_DIR
  52. override = os.getenv("PHOTON_SIDECAR_DIR")
  53. if override:
  54. return Path(override)
  55. if _dir_writable(source):
  56. return source
  57. # Read-only tree with baked, current deps: run in place (the sidecar never writes there).
  58. if (source / "node_modules").exists() and not _lock_newer_than_install(source):
  59. return source
  60. from hermes_constants import get_hermes_home
  61. mirror = get_hermes_home() / "photon" / "sidecar"
  62. try:
  63. mirror.mkdir(parents=True, exist_ok=True)
  64. for name in _MIRROR_FILES:
  65. src, dst = source / name, mirror / name
  66. if src.exists() and (not dst.exists() or not filecmp.cmp(str(src), str(dst), shallow=False)):
  67. shutil.copy2(str(src), str(dst))
  68. return mirror
  69. except OSError as exc:
  70. logger.warning(
  71. "[photon] install tree is read-only and mirroring the sidecar "
  72. "to %s failed (%s) — falling back to the read-only source dir; "
  73. "dependency installs will not be possible",
  74. mirror, exc)
  75. return source
  76. def _sidecar_dir() -> Path:
  77. """Sidecar runtime dir, resolved once on first use (never at import)."""
  78. global _SIDECAR_DIR
  79. if _SIDECAR_DIR is None:
  80. _SIDECAR_DIR = resolve_sidecar_dir()
  81. return _SIDECAR_DIR
  82. def _npm_error_log() -> Path:
  83. """Path of the persisted npm-failure log (derived from the sidecar dir)."""
  84. return _NPM_ERROR_LOG if _NPM_ERROR_LOG is not None else _sidecar_dir() / ".photon-npm-error.log"