threadbased.py 11 KB

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