base.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. class AbstractSession:
  2. """
  3. 会话对象,由Backend创建
  4. 由Task在当前Session上下文中调用:
  5. get_current_session
  6. get_current_task_id
  7. send_task_command
  8. next_client_event
  9. on_task_exception
  10. register_callback
  11. 由Backend调用:
  12. send_client_event
  13. get_task_commands
  14. close
  15. Task和Backend都可调用:
  16. closed
  17. active_session_count
  18. Session是不同的后端Backend与协程交互的桥梁:
  19. 后端Backend在接收到用户浏览器的数据后,会通过调用 ``send_client_event`` 来通知会话,进而由Session驱动协程的运行。
  20. Task内在调用输入输出函数后,会调用 ``send_task_command`` 向会话发送输入输出消息指令, Session将其保存并留给后端Backend处理。
  21. """
  22. @staticmethod
  23. def active_session_count() -> int:
  24. raise NotImplementedError
  25. @staticmethod
  26. def get_current_session() -> "AbstractSession":
  27. raise NotImplementedError
  28. @staticmethod
  29. def get_current_task_id():
  30. raise NotImplementedError
  31. def __init__(self, target, on_task_command=None, on_session_close=None, **kwargs):
  32. """
  33. :param target:
  34. :param on_task_command: Backend向ession注册的处理函数,当 Session 收到task发送的command时调用
  35. :param on_session_close: Backend向Session注册的处理函数,当 Session task 执行结束时调用 *
  36. :param kwargs:
  37. .. note::
  38. 后端Backend在相应on_session_close时关闭连接时,需要保证会话内的所有消息都传送到了客户端
  39. """
  40. raise NotImplementedError
  41. def send_task_command(self, command):
  42. raise NotImplementedError
  43. def next_client_event(self) -> dict:
  44. raise NotImplementedError
  45. def send_client_event(self, event):
  46. raise NotImplementedError
  47. def get_task_commands(self) -> list:
  48. raise NotImplementedError
  49. def close(self):
  50. raise NotImplementedError
  51. def closed(self) -> bool:
  52. raise NotImplementedError
  53. def on_task_exception(self):
  54. raise NotImplementedError
  55. def register_callback(self, callback, **options):
  56. """ 向Session注册一个回调函数,返回回调id
  57. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  58. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  59. """
  60. raise NotImplementedError