:param target: 协程函数 :param on_task_command: 由协程内发给session的消息的处理函数 :param on_session_close: 会话结束的处理函数。后端Backend在相应on_session_close时关闭连接时,需要保证会话内的所有消息都传送到了客户端
(self, target, session_info, on_task_command=None, on_session_close=None)
| 59 | return _context.current_task_id |
| 60 | |
| 61 | def __init__(self, target, session_info, on_task_command=None, on_session_close=None): |
| 62 | """ |
| 63 | :param target: 协程函数 |
| 64 | :param on_task_command: 由协程内发给session的消息的处理函数 |
| 65 | :param on_session_close: 会话结束的处理函数。后端Backend在相应on_session_close时关闭连接时,需要保证会话内的所有消息都传送到了客户端 |
| 66 | """ |
| 67 | assert iscoroutinefunction(target) or isgeneratorfunction(target), ValueError( |
| 68 | "CoroutineBasedSession accept coroutine function or generator function as task function") |
| 69 | |
| 70 | super().__init__(session_info) |
| 71 | |
| 72 | cls = type(self) |
| 73 | |
| 74 | self._on_task_command = on_task_command or (lambda _: None) |
| 75 | self._on_session_close = on_session_close or (lambda: None) |
| 76 | |
| 77 | # 当前会话未被Backend处理的消息 |
| 78 | self.unhandled_task_msgs = [] |
| 79 | |
| 80 | # 在创建第一个CoroutineBasedSession时 event_loop_thread_id 还未被初始化 |
| 81 | # 则当前线程即为运行 event loop 的线程 |
| 82 | if cls.event_loop_thread_id is None: |
| 83 | cls.event_loop_thread_id = threading.current_thread().ident |
| 84 | |
| 85 | # 会话内的协程任务 |
| 86 | self.coros = {} # coro_task_id -> Task() |
| 87 | |
| 88 | self._closed = False |
| 89 | |
| 90 | self._need_keep_alive = False |
| 91 | |
| 92 | # 当前会话未结束运行(已创建和正在运行的)的协程数量。当 _alive_coro_cnt 变为 0 时,会话结束。 |
| 93 | self._alive_coro_cnt = 1 |
| 94 | |
| 95 | main_task = Task(self._start_main_task(target), session=self, on_coro_stop=self._on_task_finish) |
| 96 | self.coros[main_task.coro_id] = main_task |
| 97 | |
| 98 | self._step_task(main_task) |
| 99 | |
| 100 | async def _start_main_task(self, target): |
| 101 | await target() |
nothing calls this directly
no test coverage detected