session_hosted_members.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. """Which local profiles a hosted group on one authority may seat (#139002).
  2. A group seats the profiles this process serves, plus the ``hosted_rooms.profiles`` destinations,
  3. and nothing else: a profile directory alone seats nobody, because a member's turns need a live
  4. owner. Served siblings need no entry, but only a host-scoped caller seats them that way; a
  5. profile-bound caller seats its own profile plus the profiles its entries name, as before. One home
  6. answers to one name. An entry that would break a rule is ignored and logged once, and only a new
  7. member naming it is refused, so one bad entry never takes the rest of the roster down.
  8. """
  9. import logging
  10. from pathlib import Path
  11. from hermes_state_runtime import RuntimeStoreError
  12. logger = logging.getLogger(__name__)
  13. # (profile, field, value, detail) already logged: the roster is re-read on every poll and turn,
  14. # and an entry fixed and later broken another way is logged again.
  15. _REPORTED: set[tuple[str, str, str, str]] = set()
  16. def member_roster(authority, *, siblings=True):
  17. """``(homes, refused)`` for a group on *authority*.
  18. ``homes`` maps name -> home. It holds *authority*'s own profile, each served sibling when
  19. ``siblings`` (the room driver, and a host-scoped caller), and each usable entry. A served
  20. profile keeps its served home under ``siblings``, whatever its entry says; a profile-bound
  21. caller's entry naming a served profile must match its served home. ``refused`` maps a name a
  22. new member may not take to ``(reason, field, detail)``. An alias stays in ``homes`` too, so a
  23. room that already seats it keeps running its other members (its own turns fail, as before).
  24. """
  25. from hermes_constants import hermes_home_key
  26. own, served, refused = _served(authority)
  27. blocked = set(refused)
  28. homes = dict(served)
  29. if not siblings:
  30. for name in [name for name in homes if name != own]:
  31. del homes[name]
  32. refused[name] = ('permission_denied', 'members',
  33. 'only a host-scoped connection seats a served profile without an entry')
  34. seated = {hermes_home_key(home): name for name, home in served.items()}
  35. for name, value in _configured(authority, own).items():
  36. if name in blocked:
  37. continue
  38. field = f'hosted_rooms.profiles.{name}'
  39. home, reason, detail = _config_entry(name, value, served, seated)
  40. if siblings and name in served:
  41. # Served: it needs no entry, and the served home wins over whatever this one says.
  42. if reason is not None:
  43. _report(own, field, value, detail)
  44. elif reason is None:
  45. homes[name] = home
  46. seated.setdefault(hermes_home_key(home), name)
  47. refused.pop(name, None)
  48. else:
  49. _report(own, field, value, detail)
  50. refused[name] = (reason, field, detail)
  51. if home is None:
  52. homes.pop(name, None)
  53. else:
  54. homes[name] = home
  55. return homes, refused
  56. def refuse_unseatable(members, refused):
  57. """Raise the named refusal for the first local member whose profile *refused* names;
  58. ``validate_roster`` names every other roster problem."""
  59. for index, raw in enumerate(members if isinstance(members, list) else ()):
  60. target = raw.get('target') if isinstance(raw, dict) else None
  61. profile = raw.get('profile') if isinstance(raw, dict) else None
  62. if isinstance(target, dict) and target.get('kind', 'local') != 'local':
  63. continue
  64. if isinstance(profile, str) and profile in refused:
  65. reason, field, detail = refused[profile]
  66. raise RuntimeStoreError(reason, field=field, detail=f"member {index} profile '{profile}': {detail}")
  67. def _served(authority):
  68. """``(own name, name -> home, refused)`` over the local bots this process serves
  69. (``session_authorities.local_bots``). A bot its clients cannot address by name is refused,
  70. never bound; a retiring one is not seated in a new group."""
  71. from gateway.session_authorities import local_bots, served_profile_name
  72. bots = local_bots(getattr(authority, 'runner', None))
  73. own = next((bot.name for bot in bots if bot.authority is authority), None)
  74. if own is None:
  75. # A bare authority (no registry): it still owns its own rooms.
  76. own = served_profile_name(authority.profile_id)
  77. served, refused = {}, {}
  78. for bot in bots:
  79. if bot.problem is not None:
  80. refused[bot.name] = ('invalid_params', 'members', bot.problem.replace(' yet', ' in groups yet'))
  81. elif bot.retiring and bot.authority is not authority:
  82. continue
  83. else:
  84. served[bot.name] = bot.home
  85. if own not in refused:
  86. served.setdefault(own, Path(authority.profile_id))
  87. return own, served, refused
  88. def _configured(authority, own):
  89. """The ``hosted_rooms.profiles`` mapping; a section left with no entries is empty."""
  90. from gateway.run import _load_gateway_config
  91. from gateway.session_authorities import owner_scope
  92. # The coordinator's own threads do not inherit the caller's ContextVars.
  93. with owner_scope(authority):
  94. section = _load_gateway_config().get('hosted_rooms')
  95. profiles = section.get('profiles') if isinstance(section, dict) else section
  96. if profiles is None or isinstance(profiles, dict):
  97. return profiles or {}
  98. _report(own, 'hosted_rooms.profiles', profiles, 'must map profile names to profile homes')
  99. return {}
  100. def _config_entry(name, value, served, seated):
  101. """``(home, reason, detail)`` for one entry: ``reason`` None seats ``home``; otherwise the entry
  102. is refused, and a ``home`` it still carries is an alias that existing rooms keep."""
  103. from gateway.hosted_rooms_common import IDENTIFIER_RE
  104. from hermes_constants import hermes_home_key
  105. if not isinstance(name, str) or not IDENTIFIER_RE.fullmatch(name) or not isinstance(value, str):
  106. return None, 'invalid_params', 'must map a profile name to a home'
  107. target = Path(value)
  108. if not target.is_absolute() or target != target.resolve():
  109. return None, 'invalid_params', 'must be an absolute, resolved home'
  110. key = hermes_home_key(target)
  111. if name in served and hermes_home_key(served[name]) != key:
  112. return None, 'permission_denied', 'this gateway serves that profile from another home'
  113. if seated.get(key, name) != name:
  114. # Its turns reach that profile under the wrong name and fail every time.
  115. return target, 'invalid_params', f"names the home already seated as '{seated[key]}'"
  116. return served.get(name, target), None, None
  117. def _report(own, field, value, detail):
  118. """Log one ignored entry once per value, however often the roster is read."""
  119. key = (own, field, repr(value)[:200], detail)
  120. if key not in _REPORTED:
  121. _REPORTED.add(key)
  122. logger.warning('Ignoring %s for profile=%s: %s', field, own, detail)