session_server_requests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. """The session owner's server→client requests to a local viewer, and who may settle them.
  2. The owner sends a request frame (``tui_gateway/contracts/server_requests.py``: ``sudo``, ``secret``,
  3. ``clarify``, the Desktop UI requests) to the viewers attached to a session's event stream and blocks the
  4. agent thread until one answers, the turn is interrupted, or it times out: the canonical side of main's
  5. sidecar ``tui_gateway/server_requests.py``. A viewer answers with a JSON-RPC response frame
  6. (:func:`resolve`) or, for a batch clarify, per question with ``clarify.lock`` (:func:`lock_answer`); both go
  7. through :func:`may_settle`, and a batch's terminal result comes from ``tools.clarify_batch.settle_batch``,
  8. the rule the sidecar uses too. Values are never published, journaled or logged: they travel only in the
  9. viewer's response frame.
  10. """
  11. from __future__ import annotations
  12. import contextlib
  13. import threading
  14. import uuid
  15. from tools.clarify_batch import settle_batch
  16. REQUEST_TIMEOUT_S = 120 # main: ``_ask("sudo", ..., timeout=120)``
  17. _POLL_S = 0.25
  18. class _Pending:
  19. __slots__ = ("event", "events", "locked", "method", "params", "qids", "replay", "result", "session_id", "value")
  20. def __init__(self, session_id, qids=None, events=None, method=None, params=None, replay=True):
  21. self.event = threading.Event()
  22. self.session_id = session_id
  23. self.method = method
  24. # The frame's params as sent, so a viewer that reconnects gets the request again; ``replay`` False
  25. # for an automatic window request (a preview click), which a second delivery would run twice.
  26. self.params = params or {}
  27. self.replay = replay
  28. # The live session's own event stream the request went out on: one per authority (profile) and
  29. # session mount, so a viewer of another profile's same-named session can never settle it.
  30. self.events = events
  31. self.value = ""
  32. self.result = None
  33. # A batch clarify: its question ids and the answers ``clarify.lock`` has locked so far.
  34. self.qids = tuple(qids) if qids else None
  35. self.locked = {}
  36. _lock = threading.Lock()
  37. _open: dict[str, _Pending] = {}
  38. def owned_by(authority, session_id, events) -> bool:
  39. """True when *authority*'s live *session_id* is the very stream a request was sent on."""
  40. live = authority.sessions.get(session_id)
  41. return live is not None and events is not None and live.event_stream is events
  42. def may_settle(authority, actor, session_id, events) -> bool:
  43. """The one rule for who may settle an owner request (a response frame or ``clarify.lock``): the
  44. request went out on *authority*'s own live stream for that session (session ids repeat across
  45. profiles and ``_open`` is process-wide), *actor* holds ``session:respond`` there, and *actor* is
  46. attached to that session, the same set of connections the request frame was written to."""
  47. from gateway.session_contract import SessionRef
  48. from hermes_state_runtime import RuntimeStoreError
  49. if not owned_by(authority, session_id, events):
  50. return False
  51. try:
  52. authority.authorize(actor, SessionRef(authority.profile_id, session_id), "session:respond")
  53. except RuntimeStoreError:
  54. return False
  55. live = authority.sessions.get(session_id)
  56. return live is not None and actor in live.subscribers.values()
  57. def is_response_frame(frame) -> bool:
  58. """A viewer's answer to one of the owner's requests: a string ``srq-`` id, a result/error, no method."""
  59. return (isinstance(frame, dict) and "method" not in frame and isinstance(frame.get("id"), str)
  60. and frame["id"].startswith("srq-") and ("result" in frame or "error" in frame))
  61. def resolve(frame, *, session_ok=lambda session_id, events: True) -> bool:
  62. """Settle the open request *frame* answers; False when nothing (here) waits for that id.
  63. ``session_ok(session_id, events)`` lets the caller refuse an answer from a connection not entitled
  64. to that session: the caller's own authority must own ``events``, the stream the request was sent on
  65. (session ids are only unique per profile, and ``_open`` is process-wide)."""
  66. with _lock:
  67. pending = _open.get(frame["id"])
  68. if pending is None or not session_ok(pending.session_id, pending.events):
  69. return False
  70. _open.pop(frame["id"], None)
  71. locked = dict(pending.locked) if pending.qids is not None else None
  72. result = frame.get("result") if "error" not in frame else None
  73. if locked is not None:
  74. # One rule with main's sidecar registry: the frame's answers over the locks, or a cancel-all.
  75. result = settle_batch(locked, result)
  76. value = result.get("value") if isinstance(result, dict) else ""
  77. pending.value = value if isinstance(value, str) else ""
  78. pending.result = result if isinstance(result, dict) else None
  79. pending.event.set()
  80. return True
  81. def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S,
  82. replay=True) -> str:
  83. """Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the
  84. session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer.
  85. ``replay=False``: a reconnecting viewer is not handed it again (``open_requests``)."""
  86. pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, replay=replay)
  87. return pending.value if pending is not None else ""
  88. def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S,
  89. qids=None):
  90. """The same round trip for a structured answer (``clarify``: ``ClarifyResult``): the viewer's
  91. ``result`` dict, or None on interrupt, timeout, an error response or no attached viewer.
  92. ``qids`` makes it a batch, which always ends with ``{answers: <locked so far>, outcome}`` once
  93. asked: ``lock_answer`` (the ``clarify.lock`` verb) answers it per question."""
  94. pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, qids=qids)
  95. return pending.result if pending is not None else None
  96. def waiting(events, session_id, method) -> bool:
  97. """Whether a *method* request is open on this live session's stream (the card still waits)."""
  98. with _lock:
  99. return any(p.session_id == session_id and p.events is events and p.method == method for p in _open.values())
  100. def open_requests(events, session_id) -> list[dict]:
  101. """The requests still waiting on this live session's stream, oldest first, as their frames
  102. carried them (plus a batch's answers locked so far): what ``session.resume`` and
  103. ``session.events.since`` hand a reconnecting viewer to re-render (``OpenRequestEntry``)."""
  104. with _lock:
  105. waiting_now = [(rid, p) for rid, p in _open.items()
  106. if p.session_id == session_id and p.events is events and p.replay]
  107. return [{"id": rid, "method": p.method,
  108. "params": {**p.params, "answers": dict(p.locked)} if p.locked else dict(p.params)}
  109. for rid, p in waiting_now]
  110. def withdraw(events, session_id, method) -> int:
  111. """Settle every open *method* request on this live session's stream with no answer, the way a
  112. viewer that answered would: the asker reads None and every renderer gets ``request.cancel
  113. reason: resolved``."""
  114. with _lock:
  115. settled = [_open.pop(rid) for rid, p in list(_open.items())
  116. if p.session_id == session_id and p.events is events and p.method == method]
  117. for pending in settled:
  118. pending.event.set()
  119. return len(settled)
  120. def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id, events: False):
  121. """Lock one answer of an open batch request (``clarify.lock``; editable until the last lock;
  122. ``None`` = skipped). Returns the question ids still unanswered; the lock that empties it settles
  123. the request with ``{answers, outcome: submitted}``. ``None`` when no open batch has that id or the
  124. caller may not answer its session (expired, or another profile's / session's request: see
  125. :func:`resolve`); ``ValueError`` for an unknown question id."""
  126. with _lock:
  127. pending = _open.get(request_id)
  128. if pending is None or pending.qids is None or not session_ok(pending.session_id, pending.events):
  129. return None
  130. if question_id not in pending.qids:
  131. raise ValueError(question_id)
  132. pending.locked[question_id] = answer
  133. remaining = [qid for qid in pending.qids if qid not in pending.locked]
  134. if not remaining:
  135. _open.pop(request_id, None)
  136. pending.result = settle_batch(pending.locked, ended="submitted")
  137. if not remaining:
  138. pending.event.set()
  139. return remaining
  140. def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None, replay=True):
  141. if not events.fanout.transports():
  142. return None
  143. request_id = f"srq-{uuid.uuid4().hex[:12]}"
  144. pending = _Pending(session_id, qids, events, method, {"session_id": session_id, **params}, replay)
  145. with _lock:
  146. _open[request_id] = pending
  147. events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method, "params": pending.params})
  148. waited = 0.0
  149. reason = "timeout"
  150. while not pending.event.wait(_POLL_S):
  151. waited += _POLL_S
  152. if cancelled():
  153. reason = "interrupted"
  154. break
  155. if timeout is not None and waited >= timeout:
  156. break
  157. with _lock:
  158. still_open = _open.pop(request_id, None) is pending
  159. if still_open and pending.qids is not None:
  160. # A batch keeps every answer locked before the wait ended (main's sidecar: "locked
  161. # answers survive a timeout"); sudo/secret have no question ids and stay unanswered.
  162. pending.result = settle_batch(pending.locked,
  163. ended="cancelled" if reason == "interrupted" else "timed_out")
  164. if still_open:
  165. # The same teardown main's renderers key on (``request.cancel``): the card closes and a
  166. # timed-out password prompt says so.
  167. with contextlib.suppress(Exception):
  168. events.publish(session_id, {"id": request_id, "method": method, "reason": reason},
  169. event_type="request.cancel")
  170. return pending if pending.qids is not None else None
  171. # Settled by a viewer (a response frame or the last ``clarify.lock``): every OTHER viewer still
  172. # shows the card, and a classic CLI is parked inside its modal callback. Withdraw it everywhere
  173. # with ``reason: resolved`` (``RequestCancelReason``) so each renderer closes the matching card and
  174. # the CLI's connection thread releases its modal (``hermes_cli.gateway_agent``). No answer rides it.
  175. with contextlib.suppress(Exception):
  176. events.publish(session_id, {"id": request_id, "method": method, "reason": "resolved"},
  177. event_type="request.cancel")
  178. return pending