framework.py 6.5 KB

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