base.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. """获取来自客户端的下一个事件。阻塞调用,若在等待过程中,会话被用户关闭,则抛出SessionClosedException异常"""
  46. raise NotImplementedError
  47. def send_client_event(self, event):
  48. raise NotImplementedError
  49. def get_task_commands(self) -> list:
  50. raise NotImplementedError
  51. def close(self):
  52. raise NotImplementedError
  53. def closed(self) -> bool:
  54. raise NotImplementedError
  55. def on_task_exception(self):
  56. raise NotImplementedError
  57. def register_callback(self, callback, **options):
  58. """ 向Session注册一个回调函数,返回回调id
  59. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  60. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  61. """
  62. raise NotImplementedError
  63. def defer_call(self, func):
  64. """设置会话结束时调用的函数。可以用于资源清理。
  65. 在会话中可以多次调用 `defer_call()` ,会话结束后将会顺序执行设置的函数。
  66. :param func: 话结束时调用的函数
  67. """
  68. raise NotImplementedError