coroutinebased.py 13 KB

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