threadbased.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import logging
  2. import queue
  3. import sys
  4. import threading
  5. import traceback
  6. from functools import wraps
  7. from .base import AbstractSession
  8. from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException
  9. from ..utils import random_str, LimitedSizeQueue, isgeneratorfunction, iscoroutinefunction, catch_exp_call, \
  10. get_function_name
  11. logger = logging.getLogger(__name__)
  12. """
  13. 基于线程的会话实现
  14. 主任务线程退出后,连接关闭。
  15. 正在等待PyWebIO输入的线程会在输入函数中抛出SessionClosedException异常,
  16. 其他线程若调用PyWebIO输入输出函数会引发异常SessionException
  17. """
  18. # todo 线程安全
  19. class ThreadBasedSession(AbstractSession):
  20. thread2session = {} # thread_id -> session
  21. unhandled_task_mq_maxsize = 1000
  22. event_mq_maxsize = 100
  23. callback_mq_maxsize = 100
  24. _active_session_cnt = 0
  25. @classmethod
  26. def active_session_count(cls):
  27. return cls._active_session_cnt
  28. @classmethod
  29. def get_current_session(cls) -> "ThreadBasedSession":
  30. curr = id(threading.current_thread())
  31. session = cls.thread2session.get(curr)
  32. if session is None:
  33. logger.debug("SessionNotFoundException in %s", threading.current_thread())
  34. raise SessionNotFoundException(
  35. "Can't find current session. Maybe session closed. Did you forget to use `register_thread` ?")
  36. return session
  37. @classmethod
  38. def get_current_task_id(cls):
  39. return cls._get_task_id(threading.current_thread())
  40. @staticmethod
  41. def _get_task_id(thread: threading.Thread):
  42. tname = getattr(thread, '_target', 'task')
  43. tname = getattr(tname, '__name__', tname)
  44. return '%s-%s' % (tname, id(thread))
  45. def __init__(self, target, session_info, on_task_command=None, on_session_close=None, loop=None):
  46. """
  47. :param target: 会话运行的函数. 为None时表示Script mode
  48. :param on_task_command: 当Task内发送Command给session的时候触发的处理函数
  49. :param on_session_close: 会话结束的处理函数
  50. :param loop: 事件循环。若 on_task_command 或者 on_session_close 中有调用使用asyncio事件循环的调用,
  51. 则需要事件循环实例来将回调在事件循环的线程中执行
  52. """
  53. assert target is None or (not iscoroutinefunction(target)) and (not isgeneratorfunction(target)), ValueError(
  54. "ThreadBasedSession only accept a simple function as task function, "
  55. "not coroutine function or generator function. ")
  56. type(self)._active_session_cnt += 1
  57. self.info = session_info
  58. self._on_task_command = on_task_command or (lambda _: None)
  59. self._on_session_close = on_session_close or (lambda: None)
  60. self._loop = loop
  61. # 会话结束时运行的函数
  62. self.deferred_functions = []
  63. self.threads = [] # 注册到当前会话的线程集合
  64. self.unhandled_task_msgs = LimitedSizeQueue(maxsize=self.unhandled_task_mq_maxsize)
  65. self.task_mqs = {} # task_id -> event msg queue
  66. self._closed = False
  67. # 用于实现回调函数的注册
  68. self.callback_mq = None
  69. self.callback_thread = None
  70. self.callbacks = {} # callback_id -> (callback_func, is_mutex)
  71. if target is not None:
  72. self._start_main_task(target)
  73. def _start_main_task(self, target):
  74. @wraps(target)
  75. def main_task(target):
  76. try:
  77. target()
  78. except Exception as e:
  79. if not isinstance(e, SessionException):
  80. self.on_task_exception()
  81. finally:
  82. for t in self.threads:
  83. if t.is_alive() and t is not threading.current_thread():
  84. t.join()
  85. try:
  86. self.send_task_command(dict(command='close_session'))
  87. except SessionClosedException:
  88. pass
  89. self._trigger_close_event()
  90. self.close()
  91. thread = threading.Thread(target=main_task, kwargs=dict(target=target),
  92. daemon=True, name='main_task')
  93. self.register_thread(thread)
  94. thread.start()
  95. def send_task_command(self, command):
  96. """向会话发送来自协程内的消息
  97. :param dict command: 消息
  98. """
  99. if self.closed():
  100. raise SessionClosedException()
  101. self.unhandled_task_msgs.put(command)
  102. if self._loop:
  103. self._loop.call_soon_threadsafe(self._on_task_command, self)
  104. else:
  105. self._on_task_command(self)
  106. def next_client_event(self):
  107. # 函数开始不需要判断 self.closed()
  108. # 如果会话关闭,对 get_current_session().next_client_event() 的调用会抛出SessionNotFoundException
  109. task_id = self.get_current_task_id()
  110. event_mq = self.get_current_session().task_mqs.get(task_id)
  111. event = event_mq.get()
  112. if event is None:
  113. raise SessionClosedException
  114. return event
  115. def send_client_event(self, event):
  116. """向会话发送来自用户浏览器的事件️
  117. :param dict event: 事件️消息
  118. """
  119. task_id = event['task_id']
  120. mq = self.task_mqs.get(task_id)
  121. if not mq and task_id in self.callbacks:
  122. mq = self.callback_mq
  123. if not mq:
  124. logger.error('event_mqs not found, task_id:%s', task_id)
  125. return
  126. mq.put(event)
  127. def get_task_commands(self):
  128. return self.unhandled_task_msgs.get()
  129. def _trigger_close_event(self):
  130. """触发Backend on_session_close callback"""
  131. if self._loop:
  132. self._loop.call_soon_threadsafe(self._on_session_close)
  133. else:
  134. self._on_session_close()
  135. def _cleanup(self):
  136. cls = type(self)
  137. self.unhandled_task_msgs.wait_empty(8)
  138. if not self.unhandled_task_msgs.empty():
  139. logger.debug("Unhandled task messages when session close:%s", self.unhandled_task_msgs.get())
  140. raise RuntimeError('There are unhandled task messages when session close!')
  141. for t in self.threads:
  142. del cls.thread2session[id(t)]
  143. if self.callback_mq is not None: # 回调功能已经激活
  144. self.callback_mq.put(None) # 结束回调线程
  145. for mq in self.task_mqs.values():
  146. mq.put(None) # 消费端接收到None消息会抛出SessionClosedException异常
  147. self.task_mqs = {}
  148. cls._active_session_cnt -= 1
  149. def close(self):
  150. """关闭当前Session。由Backend调用"""
  151. # todo self._closed 会有竞争条件
  152. if self._closed:
  153. return
  154. self._closed = True
  155. self._cleanup()
  156. self.deferred_functions.reverse()
  157. while self.deferred_functions:
  158. func = self.deferred_functions.pop()
  159. catch_exp_call(func, logger)
  160. def closed(self):
  161. return self._closed
  162. def on_task_exception(self):
  163. from ..output import put_markdown # todo
  164. logger.exception('Error in thread executing')
  165. type, value, tb = sys.exc_info()
  166. tb_len = len(list(traceback.walk_tb(tb)))
  167. lines = traceback.format_exception(type, value, tb, limit=1 - tb_len)
  168. traceback_msg = ''.join(lines)
  169. try:
  170. put_markdown("发生错误:\n```\n%s\n```" % traceback_msg)
  171. except Exception:
  172. pass
  173. def _activate_callback_env(self):
  174. """激活回调功能
  175. ThreadBasedSession 的回调实现原理是:创建一个单独的线程用于接收回调事件,进而调用相关的回调函数。
  176. 当用户Task中并没有使用到回调功能时,不必开启此线程,可以节省资源
  177. """
  178. if self.callback_mq is not None: # 回调功能已经激活
  179. return
  180. self.callback_mq = queue.Queue(maxsize=self.callback_mq_maxsize)
  181. self.callback_thread = threading.Thread(target=self._dispatch_callback_event,
  182. daemon=True, name='callback-' + random_str(10))
  183. # self.register_thread(self.callback_thread)
  184. self.thread2session[id(self.callback_thread)] = self # 用于在线程内获取会话
  185. self.callback_thread.start()
  186. logger.debug('Callback thread start')
  187. def _dispatch_callback_event(self):
  188. while not self.closed():
  189. event = self.callback_mq.get()
  190. if event is None: # 结束信号
  191. logger.debug('Callback thread exit')
  192. break
  193. callback_info = self.callbacks.get(event['task_id'])
  194. if not callback_info:
  195. logger.error("No callback for callback_id:%s", event['task_id'])
  196. return
  197. callback, mutex = callback_info
  198. @wraps(callback)
  199. def run(callback):
  200. try:
  201. callback(event['data'])
  202. except Exception:
  203. # 子类可能会重写 get_current_session ,所以不要用 ThreadBasedSession.get_current_session 来调用
  204. self.get_current_session().on_task_exception()
  205. if mutex:
  206. run(callback)
  207. else:
  208. t = threading.Thread(target=run, kwargs=dict(callback=callback),
  209. daemon=True)
  210. self.register_thread(t)
  211. t.start()
  212. def register_callback(self, callback, serial_mode=False):
  213. """ 向Session注册一个回调函数,返回回调id
  214. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  215. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  216. :param bool serial_mode: 串行模式模式。若为 ``True`` ,则对于同一组件的点击事件,串行执行其回调函数
  217. """
  218. assert (not iscoroutinefunction(callback)) and (not isgeneratorfunction(callback)), ValueError(
  219. "In ThreadBasedSession.register_callback, `callback` must be a simple function, "
  220. "not coroutine function or generator function. ")
  221. self._activate_callback_env()
  222. callback_id = 'CB-%s-%s' % (get_function_name(callback, 'callback'), random_str(10))
  223. self.callbacks[callback_id] = (callback, serial_mode)
  224. return callback_id
  225. def register_thread(self, t: threading.Thread):
  226. """将线程注册到当前会话,以便在线程内调用 pywebio 交互函数。
  227. 会话会一直保持直到所有通过 `register_thread` 注册的线程以及当前会话的主任务线程退出
  228. :param threading.Thread thread: 线程对象
  229. """
  230. self.threads.append(t) # 保存 registered thread,用于主任务线程退出后等待注册线程结束
  231. self.thread2session[id(t)] = self # 用于在线程内获取会话
  232. event_mq = queue.Queue(maxsize=self.event_mq_maxsize) # 线程内的用户事件队列
  233. self.task_mqs[self._get_task_id(t)] = event_mq
  234. def defer_call(self, func):
  235. """设置会话结束时调用的函数。可以用于资源清理。"""
  236. self.deferred_functions.append(func)
  237. class ScriptModeSession(ThreadBasedSession):
  238. """Script mode的会话实现"""
  239. @classmethod
  240. def get_current_session(cls) -> "ScriptModeSession":
  241. if cls.instance is None:
  242. raise SessionNotFoundException("Can't find current session. It might be a bug.")
  243. if cls.instance.closed():
  244. raise SessionClosedException()
  245. return cls.instance
  246. @classmethod
  247. def get_current_task_id(cls):
  248. task_id = super().get_current_task_id()
  249. session = cls.get_current_session()
  250. if task_id not in session.task_mqs:
  251. session.register_thread(threading.current_thread())
  252. return task_id
  253. instance = None
  254. def __init__(self, thread, session_info, on_task_command=None, loop=None):
  255. """
  256. :param thread: 第一次调用PyWebIO交互函数的线程 todo 貌似本参数并不必要
  257. :param on_task_command: 会话结束的处理函数。后端Backend在相应on_session_close时关闭连接时,
  258. 需要保证会话内的所有消息都传送到了客户端
  259. :param loop: 事件循环。若 on_task_command 或者on_session_close中有调用使用asyncio事件循环的调用,
  260. 则需要事件循环实例来将回调在事件循环的线程中执行
  261. """
  262. if ScriptModeSession.instance is not None:
  263. raise RuntimeError("ScriptModeSession can only be created once.")
  264. ScriptModeSession.instance = self
  265. super().__init__(target=None, session_info=session_info, on_task_command=on_task_command, loop=loop)
  266. tid = id(thread)
  267. event_mq = queue.Queue(maxsize=self.event_mq_maxsize)
  268. self.task_mqs[tid] = event_mq