threadbased.py 13 KB

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