gateway_multiplex_served.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """Which profiles does the LIVE default multiplexer serve? One answer for every CLI/dashboard surface.
  2. ``gateway/run_adapters.py::_record_served_profiles`` writes ``served_profiles`` into the default
  3. home's ``gateway_state.json`` at startup. That record is the truth about the running process; the
  4. default ``config.yaml`` plus ``GATEWAY_MULTIPLEX_PROFILES`` as seen by the *CLI* process is only a
  5. guess (``hermes -p coder ...`` loads coder's ``.env``, so an env-only opt-in on the default profile
  6. is invisible to it, and an allowlist edited after start flips the guess before the restart).
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from pathlib import Path
  11. from typing import Optional
  12. logger = logging.getLogger(__name__)
  13. def live_default_gateway_pid() -> Optional[int]:
  14. """PID of the default profile's gateway when a VERIFIED live process owns it, else None.
  15. ``gateway.status.live_gateway_pid_for_home``: pid file + lock, then the runtime record the gateway
  16. itself writes, each proven against the live process (start time, gateway command line, home). A
  17. launch-service gateway can be live with no ``gateway.pid`` at all, and a stale record whose PID was
  18. recycled by an unrelated process must not make its ``served_profiles`` authoritative. Never key this
  19. off the record's ``updated_at``: an idle gateway never advances it.
  20. """
  21. from hermes_constants import get_default_hermes_root
  22. from gateway.status import live_gateway_pid_for_home
  23. return live_gateway_pid_for_home(get_default_hermes_root())
  24. def recorded_served_profiles(default_root: Optional[Path] = None) -> Optional[list[str]]:
  25. """``served_profiles`` the live default gateway recorded, or None when the key is absent (a record
  26. from before the multiplexer recorded it, or a stopped/absent gateway). Callers fall back to config
  27. derivation only on None: an empty list is an authoritative "serves nobody else"."""
  28. from hermes_constants import get_default_hermes_root
  29. from gateway.status import read_runtime_status
  30. if live_default_gateway_pid() is None:
  31. return None
  32. runtime = read_runtime_status((default_root or get_default_hermes_root()) / "gateway_state.json")
  33. served = (runtime or {}).get("served_profiles")
  34. return [str(p) for p in served] if isinstance(served, list) else None
  35. def multiplexer_served_secondaries() -> list[str]:
  36. """Named profiles the live default multiplexer serves (excludes ``default``); empty when none."""
  37. return [p for p in (recorded_served_profiles() or []) if p and p != "default"]
  38. def served_profile_unserved_platforms(profile: str) -> dict[str, str]:
  39. """``{platform: reason}`` for a served profile's platforms the multiplexer deliberately does not run
  40. (unpaired WhatsApp or Relay shared ingress; ``gateway.run_adapters`` stamps
  41. ``<profile>:<platform>`` as ``disabled`` with a reason and remedy)."""
  42. from hermes_constants import get_default_hermes_root
  43. from gateway.status import read_runtime_status
  44. if not profile or live_default_gateway_pid() is None:
  45. return {}
  46. runtime = read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}
  47. platforms = runtime.get("platforms")
  48. if not isinstance(platforms, dict):
  49. return {}
  50. prefix = f"{profile}:"
  51. return {
  52. key[len(prefix):]: str(entry.get("error_message") or "not served under multiplex")
  53. for key, entry in platforms.items()
  54. if isinstance(key, str) and key.startswith(prefix) and isinstance(entry, dict)
  55. and entry.get("error_code") in {"multiplex_shared_ingress", "whatsapp_unpaired"}
  56. }
  57. def served_profile_ingress_urls(profile: Optional[str] = None) -> dict[str, dict[str, str]]:
  58. """``{profile: {platform: url}}`` for every secondary inbound-port platform the live multiplexer
  59. serves on its shared listener (``<profile>:<platform>`` entries carrying ``ingress_url``). This is
  60. what the user pastes into the vendor console (Twilio, LINE, Teams, ...). ``profile`` narrows the map."""
  61. from hermes_constants import get_default_hermes_root
  62. from gateway.status import read_runtime_status, shared_listener_mirror_platforms
  63. if live_default_gateway_pid() is None:
  64. return {}
  65. runtime = read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}
  66. platforms = runtime.get("platforms")
  67. if not isinstance(platforms, dict):
  68. return {}
  69. urls: dict[str, dict[str, str]] = {}
  70. for key, entry in platforms.items():
  71. if not (isinstance(key, str) and ":" in key and isinstance(entry, dict)):
  72. continue
  73. url = entry.get("ingress_url")
  74. if not url or entry.get("state") in ("fatal", "disconnected", "stopped"):
  75. continue
  76. name, platform = key.split(":", 1)
  77. if profile and name != profile:
  78. continue
  79. urls.setdefault(name, {})[platform] = str(url)
  80. # api_server/webhook are the default's adapters mirrored at /p/<profile>/ (no entry of their own).
  81. served = [str(p) for p in (runtime.get("served_profiles") or []) if p and p != "default"]
  82. for name in served if not profile else [p for p in served if p == profile]:
  83. for platform, entry in shared_listener_mirror_platforms(runtime, name).items():
  84. if entry.get("ingress_url"):
  85. urls.setdefault(name, {})[platform] = str(entry["ingress_url"])
  86. return urls
  87. def format_ingress_url_lines(urls: dict[str, str], indent: str = " ") -> list[str]:
  88. """One ``<indent><platform>: <url>`` line per platform, sorted."""
  89. return [f"{indent}{platform}: {url}" for platform, url in sorted(urls.items())]
  90. def notify_multiplexer_profiles_changed(profile_name: str, *, timeout: float = 8.0) -> Optional[list[str]]:
  91. """Tell the live default multiplexer that ``profiles/`` changed (``profile_name`` was created or
  92. deleted) so it hot-serves / unroutes it now instead of at its next periodic rescan. Returns the
  93. served-profile list the gateway answered with, or None when no multiplexer answered (no live default
  94. gateway, single-profile gateway, or a gateway predating the verb). Never raises."""
  95. try:
  96. from hermes_constants import get_default_hermes_root
  97. from gateway.control_socket import rescan_gateway_profiles
  98. if live_default_gateway_pid() is None:
  99. return None
  100. answer = rescan_gateway_profiles(get_default_hermes_root(), timeout=timeout)
  101. except Exception:
  102. logger.debug("multiplexer rescan notification failed for %r", profile_name, exc_info=True)
  103. return None
  104. if not isinstance(answer, dict) or answer.get("multiplex") is False:
  105. return None
  106. served = answer.get("served_profiles")
  107. return [str(p) for p in served] if isinstance(served, list) else None