session_bot_cancel.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """``bot_relay.cancel``: a ``message_agent`` sender withdraws its own delivery by ``delivery_id``.
  2. The cancel runs on the delivery's owner under the same mailbox lock that admits the delivery's one
  3. automatic retry (``gateway/session_bot.py::_maybe_retry``), so it always sees which admission is the
  4. request now. A sender that picked an admission from the receipt file could race that retry: the
  5. first attempt already failed, the retry not yet recorded, and "nothing to cancel" while it runs.
  6. Whatever this finds, a retry not admitted yet is withdrawn for good (the receipt's ``retry`` marks
  7. it refused ``cancelled``), so no later wake, re-delivery or owner restart admits it.
  8. """
  9. import asyncio
  10. from gateway.session_contract import SessionRef
  11. from hermes_state_runtime import RuntimeStoreError, get_session_admission
  12. _FIELDS = frozenset({'id', 'profile', 'author_id'})
  13. async def cancel(connection, params):
  14. from gateway.session_authorities import require_serving
  15. from gateway.session_runtime_workers import track_mutation
  16. require_serving(connection.authority)
  17. return await asyncio.shield(track_mutation(connection.authority, _cancel(connection, params)))
  18. async def _cancel(connection, params):
  19. from gateway.session_bot import (_delivery_id, _delivery_result, _home, _retry_admission, _retry_eligible,
  20. _retry_identity)
  21. from gateway.session_bot_mailbox import mailbox_lock, read_receipt, remember_receipt, write_receipt
  22. authority, actor = connection.authority, connection.actor
  23. if set(params) - _FIELDS:
  24. raise RuntimeStoreError('invalid_params')
  25. home = _home(authority, actor, params.get('profile'))
  26. try:
  27. key = _delivery_id(params.get('id'))
  28. except ValueError as exc:
  29. raise RuntimeStoreError('invalid_params') from exc
  30. async with mailbox_lock(authority):
  31. _, record = await read_receipt(home, key)
  32. if record is None or not record.get('admission_id'):
  33. raise RuntimeStoreError('not_found')
  34. # Only the delivery's own sender: the principal it was admitted on and the bot it named.
  35. if record['principal_id'] != actor.subject or (record.get('author') or {}).get('id') != params.get('author_id'):
  36. raise RuntimeStoreError('permission_denied')
  37. retry_id = _retry_admission(authority, record)
  38. current = retry_id or record['admission_id']
  39. row = get_session_admission(authority.db, admission_id=current)
  40. live = row is not None and row['status'] != 'terminal'
  41. withdrawn = retry_id is None and (live or _retry_eligible(authority, record))
  42. if withdrawn:
  43. record['retry'] = {**(record.get('retry') or {}), 'identity': _retry_identity(key), 'refused': 'cancelled'}
  44. status = 'finished'
  45. if live:
  46. answer = await connection.cancel(SessionRef(authority.profile_id, record['session_id']),
  47. {'admission_id': current})
  48. status = 'stopping' # a running turn was told to stop; its receipt reports how it ended
  49. if answer['status'] == 'terminal':
  50. status = 'cancelled' if answer.get('outcome') == 'cancelled' else 'finished'
  51. elif withdrawn:
  52. status = 'cancelled' # its first attempt failed; the retry it was owed never starts
  53. record.update(_delivery_result(authority, record))
  54. await write_receipt(home, record)
  55. remember_receipt(authority, home, record)
  56. return {'delivery_id': key, 'status': status, 'receipt_status': record['status']}