session_acp_lifecycle.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """ACP v0.9 has no per-session destroy: the last viewer leaving an idle ACP session ends it (#118216).
  2. The in-process adapter stamped ``ended_at`` at its stdio shutdown; under the gateway the ACP process
  3. is only a viewer, so the owner stamps it when the last subscription goes or the gateway stops. Without
  4. a writer, source='acp' rows stay open forever and the ended-session guard keeps prune/archive away.
  5. A later ``session/load`` + prompt reopens the row (``session_local_recovery.reopen_local_session``).
  6. """
  7. import logging
  8. from hermes_state_local import POLICY_PREFIX, end_idle_local_session, local_receipt
  9. from hermes_state_runtime import RuntimeStoreError
  10. ACP_END_REASON = 'acp_disconnect'
  11. def end_idle_acp_session(authority, session_id):
  12. """End *session_id* iff it is an ACP-created local session with no viewer and an idle FIFO."""
  13. live = authority.sessions.get(session_id)
  14. if live is not None and live.subscribers:
  15. return False
  16. try:
  17. receipt = local_receipt(authority.db, session_id)
  18. except RuntimeStoreError:
  19. return False # not a local session: no ACP policy to end
  20. if receipt.get('policy', {}).get('source') != 'acp':
  21. return False
  22. try:
  23. return bool(end_idle_local_session(authority.db, epoch=authority.epoch, session_id=session_id,
  24. target_id=receipt['entry']['session_id'], reason=ACP_END_REASON))
  25. except (RuntimeStoreError, KeyError, TypeError):
  26. logging.getLogger(__name__).warning('ACP session %s not ended', session_id, exc_info=True)
  27. return False
  28. def end_idle_viewer_session(authority, session_id, reason):
  29. """``session.detach {end_reason}`` from the last viewer: end *session_id*'s idle local row with the
  30. viewer's own reason (main's classic CLI ``end_session(sid, 'cli_close')`` and its switch reasons).
  31. ACP rows keep their own reason; a busy FIFO keeps the row open, as for ACP."""
  32. live = authority.sessions.get(session_id)
  33. if live is not None and live.subscribers:
  34. return False
  35. try:
  36. receipt = local_receipt(authority.db, session_id)
  37. except RuntimeStoreError:
  38. return False # not a local session: nothing this verb may end
  39. if receipt.get('policy', {}).get('source') == 'acp':
  40. return end_idle_acp_session(authority, session_id)
  41. try:
  42. return bool(end_idle_local_session(authority.db, epoch=authority.epoch, session_id=session_id,
  43. target_id=receipt['entry']['session_id'], reason=reason))
  44. except (RuntimeStoreError, KeyError, TypeError):
  45. logging.getLogger(__name__).warning('local session %s not ended', session_id, exc_info=True)
  46. return False
  47. async def reopen_if_reattached(authority, session_id, ended):
  48. """On the owner loop after the close committed: a viewer attached meanwhile, so the session
  49. it watches is live again (the stamp would make active work prune/archive eligible)."""
  50. live = authority.sessions.get(session_id)
  51. if ended and live is not None and live.subscribers:
  52. import asyncio
  53. target = local_receipt(authority.db, session_id)['entry']['session_id']
  54. await asyncio.to_thread(authority.db.reopen_session, target)
  55. return ended
  56. def end_idle_acp_sessions(authority):
  57. """Gateway shutdown: every ACP session nobody is viewing, attached this run or not."""
  58. with authority.db._read_ctx() as conn:
  59. ids = [row[0][len(POLICY_PREFIX):] for row in conn.execute(
  60. 'SELECT key FROM state_meta WHERE key LIKE ?', (POLICY_PREFIX + '%',))]
  61. return sum(end_idle_acp_session(authority, sid) for sid in ids)