status_served.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Which runtime record describes a profile the host multiplexer may serve.
  2. One rule for ``/api/status`` and the messaging card so the two surfaces never pick different records
  3. for the same profile. Read-only: it selects and projects existing ``gateway_state.json`` records and
  4. writes nothing. ``gateway.status`` is resolved at call time so its test seams
  5. (``monkeypatch.setattr(gateway.status, ...)``) still intercept.
  6. """
  7. from __future__ import annotations
  8. from pathlib import Path
  9. from typing import Any, Optional
  10. def local_liveness_pid(liveness: Any) -> Optional[int]:
  11. """``liveness.pid`` when it was proven on THIS host; None for a health-probe answer, whose PID
  12. belongs to the remote container and may collide with an unrelated local one."""
  13. return None if liveness.source == "health" else liveness.pid
  14. def served_profile_runtime(
  15. home: Path, own_runtime: Optional[dict[str, Any]], *, gateway_pid: Optional[int] = None
  16. ) -> Optional[dict[str, Any]]:
  17. """The multiplexer's record projected onto ``home``'s profile (bare platform keys, the shape a
  18. standalone gateway writes) when it is that profile's live runtime record, else None.
  19. - ``own_runtime`` wins whenever it proves a live gateway of ``home`` -- an own ``--force`` one, or
  20. the host's own record on the host itself, which must stay whole so other profiles'
  21. ``<profile>:<platform>`` failures remain visible there;
  22. - a missing/unreadable multiplexer record (``(pid, {})``) is no record;
  23. - ``gateway_pid`` (a PID the caller proved on this host) must BE the multiplexer, so a gateway of
  24. the profile's own holding its lock keeps its record.
  25. """
  26. from gateway import status
  27. if own_runtime is not None and status.get_runtime_status_running_pid(own_runtime, expected_home=home) is not None:
  28. return None
  29. served = status.multiplexer_liveness_for_profile(home)
  30. if served is None or not served[1]:
  31. return None
  32. mux_pid, record = served
  33. if gateway_pid is not None and mux_pid != gateway_pid:
  34. return None
  35. # Fold on the profile NAME, never ``home.name``: the default root's basename is ``.hermes`` (or
  36. # any custom HERMES_HOME), so its flat keys never matched (#123088).
  37. name = status.profile_name_for_home(home) or "default"
  38. return {**record, "platforms": status.profile_platforms_from_multiplexer(record, name)}