transport.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """Relay transport protocol — the gateway<->connector wire contract. EXPERIMENTAL.
  2. The ``RelayAdapter`` delegates all wire I/O to a ``RelayTransport``. The gateway
  3. dials OUT to the connector, so production is a WebSocket client (``ws_transport.py``)
  4. and tests use an in-memory stub (``tests/gateway/relay/stub_connector.py``). This
  5. module defines the protocol surface only. May change without a deprecation cycle
  6. until >=2 Class-1 platforms validate it. See website/docs/developer-guide/relay-connector-contract.md.
  7. """
  8. from __future__ import annotations
  9. import asyncio
  10. from typing import Any, Awaitable, Callable, Dict, Optional, Protocol, runtime_checkable
  11. from gateway.platforms.event import MessageEvent
  12. from gateway.relay.descriptor import CapabilityDescriptor
  13. # Callback the transport invokes for each inbound normalized event: a task it returns is the
  14. # event's admission still running off the reader, and the frame is ACKed when that task succeeds.
  15. InboundHandler = Callable[[MessageEvent], Awaitable[Optional["asyncio.Task[None]"]]]
  16. # Callback for each forwarded passthrough request (§5.1): ``(forward, buffer_id)``.
  17. # ``forward`` is a ws_transport.PassthroughForward, typed Any here because
  18. # ws_transport imports FROM this module; ``buffer_id`` (§5.3 buffered flip) is
  19. # acked by the handler after durable handoff.
  20. PassthroughHandler = Callable[[Any, Optional[str]], Awaitable[None]]
  21. @runtime_checkable
  22. class RelayTransport(Protocol):
  23. """Full gateway<->connector transport contract."""
  24. async def connect(self) -> bool:
  25. """Open the connection to the connector; return True on success."""
  26. ...
  27. async def disconnect(self) -> None:
  28. ...
  29. async def handshake(self) -> CapabilityDescriptor:
  30. """Return the capability descriptor the connector advertises."""
  31. ...
  32. def set_inbound_handler(self, handler: InboundHandler) -> None:
  33. ...
  34. def set_passthrough_handler(self, handler: PassthroughHandler) -> None:
  35. """Register the callback for each forwarded passthrough request (§5.1).
  36. The connector answers the provider's edge ACK itself, then forwards the real
  37. request over this same outbound socket (a hosted gateway has no public
  38. inbound port). Optional on a transport (a stub may not implement it).
  39. """
  40. ...
  41. async def send_outbound(
  42. self, action: dict[str, Any], *, platform: Optional[str] = None
  43. ) -> dict[str, Any]:
  44. """Carry an outbound action (send/edit/typing) to the connector.
  45. Returns a result dict; for ``op == "send"`` it carries ``success`` and
  46. optionally ``message_id`` / ``error``. ``platform`` tags WHICH fronted
  47. platform this reply targets (the transport resolves the matching botId);
  48. omitted ⇒ the connector uses the session's default platform.
  49. """
  50. ...
  51. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  52. """Proxy a chat-info lookup to the connector."""
  53. ...
  54. async def send_interrupt(self, session_key: str, reason: Optional[str] = None) -> None:
  55. """Route a mid-turn /stop to the connector for ``session_key`` (OUTBOUND
  56. direction; the actual cancellation happens when the connector echoes an
  57. interrupt inbound down the socket owning that session)."""
  58. ...
  59. async def go_idle(self, timeout_s: float = 10.0) -> bool:
  60. """Ask the connector to flip this instance to buffered-only (§5.3).
  61. Sends ``going_idle`` and awaits the connector-authoritative ``going_idle_ack``
  62. (live delivery stopped; inbound now buffers for replay on reconnect). True on
  63. ack, False on timeout / not-connected — the caller closes regardless.
  64. Optional on a transport; part of the gateway's EXISTING drain transition.
  65. """
  66. ...
  67. async def send_follow_up(
  68. self, action: dict[str, Any], *, platform: Optional[str] = None
  69. ) -> dict[str, Any]:
  70. """Act on a shared-identity capability bound to a session (A2 outbound).
  71. A credential acting on the SHARED bot identity (e.g. a Discord interaction
  72. follow-up token) NEVER reaches the gateway: the connector vaults it keyed by
  73. session and the gateway issues a SEMANTIC action (``op == "follow_up"``,
  74. ``session_key``, ``kind`` e.g. ``"discord.interaction_token"``, ``content``,
  75. optional ``metadata``). Returns ``{success, message_id?, error?}``; ``success``
  76. is False when the capability is absent/expired or the tenant mismatches —
  77. nothing to retry with (a leaked gateway holds zero capability material).
  78. """
  79. ...