coroutinebased.py 12 KB

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