threadbased.py 13 KB

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