protocols.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. 渠道层通用 Protocol——所有 IM 渠道(飞书、微信等)共用的最小接口约定。
  3. 各渠道可在自己的模块中声明更严格的子 Protocol(窄化参数类型),
  4. 但 backends/ 下的通用实现只需满足此处的宽松签名即可跨渠道复用。
  5. """
  6. from __future__ import annotations
  7. from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
  8. if TYPE_CHECKING:
  9. from fastapi import APIRouter
  10. @runtime_checkable
  11. class UserIdentityResolver(Protocol):
  12. """将渠道入站事件映射为网关内统一 user_id。
  13. 各渠道实现可声明更严格的事件类型(如 ``IncomingFeishuEvent``),
  14. runtime_checkable 仅校验方法存在性,不校验参数类型。
  15. """
  16. def resolve_user_id(self, event: Any) -> str:
  17. ...
  18. @runtime_checkable
  19. class ExecutorBackend(Protocol):
  20. """接收解析后的入站消息,触发业务处理,返回 task_id。
  21. ``reply_context`` 与 ``event`` 的具体类型由各渠道自行约束;
  22. ``connector`` 须实现 ``send_text(reply_context, text) -> dict`` 以便向用户发送状态或结果。
  23. """
  24. async def handle_inbound_message(
  25. self,
  26. trace_id: str,
  27. text: str,
  28. reply_context: Any,
  29. connector: Any,
  30. *,
  31. event: Any,
  32. ) -> str:
  33. ...
  34. @runtime_checkable
  35. class ChannelPlugin(Protocol):
  36. """渠道插件接口——每个渠道的 Api 类须实现此接口以支持自动注册。
  37. ``from_env()`` 负责从环境变量读取渠道配置并构造实例;
  38. ``build_router()`` 返回该渠道挂载到 FastAPI 的 ``APIRouter``。
  39. """
  40. @classmethod
  41. def from_env(cls) -> ChannelPlugin:
  42. ...
  43. def build_router(self) -> APIRouter:
  44. ...