coroutinebased.py 11 KB

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