framework.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import logging
  2. import random
  3. import string
  4. import sys
  5. import traceback
  6. from contextlib import contextmanager
  7. logger = logging.getLogger(__name__)
  8. class WebIOFuture:
  9. def __iter__(self):
  10. result = yield
  11. return result
  12. __await__ = __iter__ # make compatible with 'await' expression
  13. class WebIOSession:
  14. """
  15. 一个PyWebIO任务会话, 由不同的后端Backend创建并维护
  16. WebIOSession是不同的后端Backend与协程交互的桥梁:
  17. 后端Backend在接收到用户浏览器的数据后,会通过调用 ``send_client_msg`` 来通知会话,进而由WebIOSession驱动协程的运行。
  18. 协程内在调用输入输出函数后,会调用 ``send_coro_msg`` 向会话发送输入输出消息指令, WebIOSession将其保存并留给后端Backend处理。
  19. """
  20. def __init__(self, coro_func, on_coro_msg=None, on_session_close=None):
  21. """
  22. :param coro_func: 协程函数
  23. :param on_coro_msg: 由协程内发给session的消息的处理函数
  24. :param on_session_close: 会话结束的处理函数
  25. """
  26. self._on_coro_msg = on_coro_msg or (lambda _: None)
  27. self._on_session_close = on_session_close or (lambda : None)
  28. self.unhandled_server_msgs = []
  29. self.coros = {} # coro_id -> coro
  30. self._closed = False
  31. self.inactive_coro_instances = [] # 待激活的协程实例列表
  32. self.main_task = Task(coro_func(), ws=self)
  33. self.coros[self.main_task.coro_id] = self.main_task
  34. self._step_task(self.main_task)
  35. def _step_task(self, task, result=None):
  36. task.step(result)
  37. if task.task_finished:
  38. logger.debug('del self.coros[%s]', task.coro_id)
  39. del self.coros[task.coro_id]
  40. while self.inactive_coro_instances:
  41. coro = self.inactive_coro_instances.pop()
  42. sub_task = Task(coro, ws=self)
  43. self.coros[sub_task.coro_id] = sub_task
  44. sub_task.step()
  45. if sub_task.task_finished:
  46. logger.debug('del self.coros[%s]', sub_task.coro_id)
  47. del self.coros[sub_task.coro_id]
  48. if self.main_task.task_finished:
  49. self.close()
  50. def send_coro_msg(self, message):
  51. """向会话发送来自协程内的消息
  52. :param dict message: 消息
  53. """
  54. self.unhandled_server_msgs.append(message)
  55. self._on_coro_msg(self)
  56. def send_client_msg(self, message):
  57. """向会话发送来自用户浏览器的事件️
  58. :param dict message: 事件️消息
  59. """
  60. # data = json.loads(message)
  61. coro_id = message['coro_id']
  62. coro = self.coros.get(coro_id)
  63. if not coro:
  64. logger.error('coro not found, coro_id:%s', coro_id)
  65. return
  66. self._step_task(coro, message)
  67. def on_coro_error(self):
  68. from .output import put_markdown # todo
  69. type, value, tb = sys.exc_info()
  70. tb_len = len(list(traceback.walk_tb(tb)))
  71. lines = traceback.format_exception(type, value, tb, limit=1 - tb_len)
  72. traceback_msg = ''.join(lines)
  73. put_markdown("发生错误:\n```\n%s\n```" % traceback_msg)
  74. def _cleanup(self):
  75. for t in self.coros.values():
  76. t.cancel()
  77. self.coros = {} # delete session tasks
  78. while self.inactive_coro_instances:
  79. coro = self.inactive_coro_instances.pop()
  80. coro.close()
  81. def close(self, no_session_close_callback=False):
  82. """关闭当前Session
  83. :param bool no_session_close_callback: 不调用 on_session_close 会话结束的处理函数。
  84. 当 close 是由后端Backend调用时可能希望开启 no_session_close_callback
  85. """
  86. self._cleanup()
  87. self._closed = True
  88. if not no_session_close_callback:
  89. self._on_session_close()
  90. # todo clean
  91. def closed(self):
  92. return self._closed
  93. class Task:
  94. @contextmanager
  95. def ws_context(self):
  96. """
  97. >>> with ws_context():
  98. ... res = self.coros[-1].send(data)
  99. """
  100. Global.active_ws = self.ws
  101. Global.active_coro_id = self.coro_id
  102. try:
  103. yield
  104. finally:
  105. Global.active_ws = None
  106. Global.active_coro_id = None
  107. @staticmethod
  108. def gen_coro_id(coro=None):
  109. name = 'coro'
  110. if hasattr(coro, '__name__'):
  111. name = coro.__name__
  112. random_str = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(10))
  113. return '%s-%s' % (name, random_str)
  114. def __init__(self, coro, ws):
  115. self.ws = ws
  116. self.coro = coro
  117. self.coro_id = None
  118. self.result = None
  119. self.task_finished = False # 任务完毕/取消
  120. self.coro_id = self.gen_coro_id(self.coro)
  121. self.pending_futures = {} # id(future) -> future
  122. logger.debug('Task[%s] created ', self.coro_id)
  123. def step(self, result=None):
  124. future_or_none = None
  125. with self.ws_context():
  126. try:
  127. future_or_none = self.coro.send(result)
  128. except StopIteration as e:
  129. if len(e.args) == 1:
  130. self.result = e.args[0]
  131. self.task_finished = True
  132. logger.debug('Task[%s] finished', self.coro_id)
  133. except Exception as e:
  134. self.ws.on_coro_error()
  135. if not isinstance(future_or_none, WebIOFuture) and future_or_none is not None:
  136. if not self.ws.closed():
  137. future_or_none.add_done_callback(self._tornado_future_callback)
  138. self.pending_futures[id(future_or_none)] = future_or_none
  139. def _tornado_future_callback(self, future):
  140. if not future.cancelled():
  141. del self.pending_futures[id(future)]
  142. self.step(future.result())
  143. def cancel(self):
  144. logger.debug('Task[%s] canceled', self.coro_id)
  145. self.coro.close()
  146. while self.pending_futures:
  147. _, f = self.pending_futures.popitem()
  148. f.cancel()
  149. self.task_finished = True
  150. def __del__(self):
  151. if not self.task_finished:
  152. logger.warning('Task[%s] not finished when destroy', self.coro_id)
  153. class Global:
  154. # todo issue: with 语句可能发生嵌套,导致内层with退出时,将属性置空
  155. active_ws = None # type:"WebIOController"
  156. active_coro_id = None