base.py 2.9 KB

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