threadbased.py 12 KB

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