coroutinebased.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import asyncio
  2. import logging
  3. import sys
  4. import threading
  5. import traceback
  6. from contextlib import contextmanager
  7. from .base import AbstractSession
  8. from ..exceptions import SessionNotFoundException, SessionClosedException
  9. from ..utils import random_str, isgeneratorfunction, iscoroutinefunction, catch_exp_call
  10. logger = logging.getLogger(__name__)
  11. class WebIOFuture:
  12. def __init__(self, coro=None):
  13. self.coro = coro
  14. def __iter__(self):
  15. result = yield self
  16. return result
  17. __await__ = __iter__ # make compatible with 'await' expression
  18. class _context:
  19. current_session = None # type:"CoroutineBasedSession"
  20. current_task_id = None
  21. class CoroutineBasedSession(AbstractSession):
  22. """
  23. 基于协程的任务会话
  24. 当主协程任务和会话内所有通过 `run_async` 注册的协程都退出后,会话关闭。
  25. 当用户浏览器主动关闭会话,CoroutineBasedSession.close 被调用, 协程任务和会话内所有通过 `run_async` 注册的协程都被关闭。
  26. """
  27. _active_session_cnt = 0
  28. @classmethod
  29. def active_session_count(cls):
  30. return cls._active_session_cnt
  31. @staticmethod
  32. def get_current_session() -> "CoroutineBasedSession":
  33. if _context.current_session is None or \
  34. _context.current_session.session_thread_id != threading.current_thread().ident:
  35. raise SessionNotFoundException("No session found in current context!")
  36. return _context.current_session
  37. @staticmethod
  38. def get_current_task_id():
  39. if _context.current_task_id is None:
  40. raise RuntimeError("No current task found in context!")
  41. return _context.current_task_id
  42. def __init__(self, target, on_task_command=None, on_session_close=None):
  43. """
  44. :param target: 协程函数
  45. :param on_task_command: 由协程内发给session的消息的处理函数
  46. :param on_session_close: 会话结束的处理函数。后端Backend在相应on_session_close时关闭连接时,需要保证会话内的所有消息都传送到了客户端
  47. """
  48. assert iscoroutinefunction(target) or isgeneratorfunction(target), ValueError(
  49. "CoroutineBasedSession accept coroutine function or generator function as task function")
  50. CoroutineBasedSession._active_session_cnt += 1
  51. self._on_task_command = on_task_command or (lambda _: None)
  52. self._on_session_close = on_session_close or (lambda: None)
  53. # 会话结束时运行的函数
  54. self.deferred_functions = []
  55. # 当前会话未被Backend处理的消息
  56. self.unhandled_task_msgs = []
  57. # 创建会话的线程id。当前会话只能在本线程中使用
  58. self.session_thread_id = threading.current_thread().ident
  59. # 会话内的协程任务
  60. self.coros = {} # coro_task_id -> Task()
  61. self._closed = False
  62. # 当前会话未结束运行(已创建和正在运行的)的协程数量。当 _alive_coro_cnt 变为 0 时,会话结束。
  63. self._alive_coro_cnt = 1
  64. main_task = Task(target(), session=self, on_coro_stop=self._on_task_finish)
  65. self.coros[main_task.coro_id] = main_task
  66. self._step_task(main_task)
  67. def _step_task(self, task, result=None):
  68. task.step(result)
  69. def _on_task_finish(self, task: "Task"):
  70. self._alive_coro_cnt -= 1
  71. if task.coro_id in self.coros:
  72. logger.debug('del self.coros[%s]', task.coro_id)
  73. del self.coros[task.coro_id]
  74. if self._alive_coro_cnt <= 0 and not self.closed():
  75. self.send_task_command(dict(command='close_session'))
  76. self._on_session_close()
  77. self.close()
  78. def send_task_command(self, command):
  79. """向会话发送来自协程内的消息
  80. :param dict command: 消息
  81. """
  82. if self.closed():
  83. raise SessionClosedException()
  84. self.unhandled_task_msgs.append(command)
  85. self._on_task_command(self)
  86. async def next_client_event(self):
  87. res = await WebIOFuture()
  88. return res
  89. def send_client_event(self, event):
  90. """向会话发送来自用户浏览器的事件️
  91. :param dict event: 事件️消息
  92. """
  93. coro_id = event['task_id']
  94. coro = self.coros.get(coro_id)
  95. if not coro:
  96. logger.error('coro not found, coro_id:%s', coro_id)
  97. return
  98. self._step_task(coro, event)
  99. def get_task_commands(self):
  100. msgs = self.unhandled_task_msgs
  101. self.unhandled_task_msgs = []
  102. return msgs
  103. def _cleanup(self):
  104. for t in list(self.coros.values()): # t.close() may cause self.coros changed size
  105. t.close()
  106. self.coros = {} # delete session tasks
  107. CoroutineBasedSession._active_session_cnt -= 1
  108. def close(self):
  109. """关闭当前Session。由Backend调用"""
  110. if self._closed:
  111. return
  112. self._closed = True
  113. self._cleanup()
  114. while self.deferred_functions:
  115. func = self.deferred_functions.pop()
  116. catch_exp_call(func, logger)
  117. def closed(self):
  118. return self._closed
  119. def on_task_exception(self):
  120. from ..output import put_markdown # todo
  121. logger.exception('Error in coroutine executing')
  122. type, value, tb = sys.exc_info()
  123. tb_len = len(list(traceback.walk_tb(tb)))
  124. lines = traceback.format_exception(type, value, tb, limit=1 - tb_len)
  125. traceback_msg = ''.join(lines)
  126. try:
  127. put_markdown("发生错误:\n```\n%s\n```" % traceback_msg)
  128. except:
  129. pass
  130. def register_callback(self, callback, mutex_mode=False):
  131. """ 向Session注册一个回调函数,返回回调id
  132. :type callback: Callable or Coroutine
  133. :param callback: 回调函数. 可以是普通函数或者协程函数. 函数签名为 ``callback(data)``.
  134. :param bool mutex_mode: 互斥模式。若为 ``True`` ,则在运行回调函数过程中,无法响应同一组件的新点击事件,仅当 ``callback`` 为协程函数时有效
  135. :return str: 回调id.
  136. CoroutineBasedSession 保证当收到前端发送的事件消息 ``{event: "callback",coro_id: 回调id, data:...}`` 时,
  137. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  138. """
  139. async def callback_coro():
  140. while True:
  141. event = await self.next_client_event()
  142. assert event['event'] == 'callback'
  143. coro = None
  144. if iscoroutinefunction(callback):
  145. coro = callback(event['data'])
  146. elif isgeneratorfunction(callback):
  147. coro = asyncio.coroutine(callback)(event['data'])
  148. else:
  149. try:
  150. callback(event['data'])
  151. except:
  152. CoroutineBasedSession.get_current_session().on_task_exception()
  153. if coro is not None:
  154. if mutex_mode:
  155. await coro
  156. else:
  157. self.run_async(coro)
  158. callback_task = Task(callback_coro(), CoroutineBasedSession.get_current_session())
  159. callback_task.coro.send(None) # 激活,Non't callback.step() ,导致嵌套调用step todo 与inactive_coro_instances整合
  160. CoroutineBasedSession.get_current_session().coros[callback_task.coro_id] = callback_task
  161. return callback_task.coro_id
  162. def run_async(self, coro_obj):
  163. """异步运行协程对象。可以在协程内调用 PyWebIO 交互函数
  164. :param coro_obj: 协程对象
  165. :return: An instance of `TaskHandle` is returned, which can be used later to close the task.
  166. """
  167. self._alive_coro_cnt += 1
  168. task = Task(coro_obj, session=self, on_coro_stop=self._on_task_finish)
  169. self.coros[task.coro_id] = task
  170. asyncio.get_event_loop().call_soon(task.step)
  171. return task.task_handle()
  172. async def run_asyncio_coroutine(self, coro_obj):
  173. """若会话线程和运行事件的线程不是同一个线程,需要用 asyncio_coroutine 来运行asyncio中的协程"""
  174. res = await WebIOFuture(coro=coro_obj)
  175. return res
  176. def defer_call(self, func):
  177. """设置会话结束时调用的函数。可以用于资源清理。"""
  178. self.deferred_functions.append(func)
  179. class TaskHandle:
  180. """协程任务句柄"""
  181. def __init__(self, close, closed):
  182. self._close = close
  183. self._closed = closed
  184. def close(self):
  185. """关闭协程任务"""
  186. return self._close()
  187. def closed(self):
  188. """返回任务是否关闭"""
  189. return self._closed()
  190. class Task:
  191. @contextmanager
  192. def session_context(self):
  193. """
  194. >>> with session_context():
  195. ... res = self.coros[-1].send(data)
  196. """
  197. # todo issue: with 语句可能发生嵌套,导致内层with退出时,将属性置空
  198. _context.current_session = self.session
  199. _context.current_task_id = self.coro_id
  200. try:
  201. yield
  202. finally:
  203. _context.current_session = None
  204. _context.current_task_id = None
  205. @staticmethod
  206. def gen_coro_id(coro=None):
  207. """生成协程id"""
  208. name = 'coro'
  209. if hasattr(coro, '__name__'):
  210. name = coro.__name__
  211. return '%s-%s' % (name, random_str(10))
  212. def __init__(self, coro, session: CoroutineBasedSession, on_coro_stop=None):
  213. """
  214. :param coro: 协程对象
  215. :param session: 创建该Task的会话实例
  216. :param on_coro_stop: 任务结束(正常结束或外部调用Task.close)时运行的回调
  217. """
  218. self.session = session
  219. self.coro = coro
  220. self.coro_id = None
  221. self.result = None
  222. self.task_closed = False # 任务完毕/取消
  223. self.on_coro_stop = on_coro_stop or (lambda _: None)
  224. self.coro_id = self.gen_coro_id(self.coro)
  225. self.pending_futures = {} # id(future) -> future
  226. logger.debug('Task[%s] created ', self.coro_id)
  227. def step(self, result=None):
  228. coro_yield = None
  229. with self.session_context():
  230. try:
  231. coro_yield = self.coro.send(result)
  232. except StopIteration as e:
  233. if len(e.args) == 1:
  234. self.result = e.args[0]
  235. self.task_closed = True
  236. logger.debug('Task[%s] finished', self.coro_id)
  237. self.on_coro_stop(self)
  238. except Exception as e:
  239. self.session.on_task_exception()
  240. self.task_closed = True
  241. self.on_coro_stop(self)
  242. future = None
  243. if isinstance(coro_yield, WebIOFuture):
  244. if coro_yield.coro:
  245. future = asyncio.run_coroutine_threadsafe(coro_yield.coro, asyncio.get_event_loop())
  246. elif coro_yield is not None:
  247. future = coro_yield
  248. if not self.session.closed() and hasattr(future, 'add_done_callback'):
  249. future.add_done_callback(self._tornado_future_callback)
  250. self.pending_futures[id(future)] = future
  251. def _tornado_future_callback(self, future):
  252. if not future.cancelled():
  253. del self.pending_futures[id(future)]
  254. self.step(future.result())
  255. def close(self):
  256. if self.task_closed:
  257. return
  258. logger.debug('Task[%s] closed', self.coro_id)
  259. self.coro.close()
  260. while self.pending_futures:
  261. _, f = self.pending_futures.popitem()
  262. f.cancel()
  263. self.task_closed = True
  264. self.on_coro_stop(self)
  265. def __del__(self):
  266. if not self.task_closed:
  267. logger.warning('Task[%s] was destroyed but it is pending!', self.coro_id)
  268. def task_handle(self):
  269. handle = TaskHandle(close=self.close, closed=lambda: self.task_closed)
  270. return handle