Skip to content

Commit a5ae27c

Browse files
authored
fix(aiocqhttp): enhance shutdown process for aiocqhttp adapter (#5412)
1 parent 73faaf6 commit a5ae27c

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import inspect
23
import itertools
34
import logging
45
import time
@@ -436,7 +437,42 @@ def run(self) -> Awaitable[Any]:
436437
return coro
437438

438439
async def terminate(self) -> None:
439-
self.shutdown_event.set()
440+
if hasattr(self, "shutdown_event"):
441+
self.shutdown_event.set()
442+
await self._close_reverse_ws_connections()
443+
444+
async def _close_reverse_ws_connections(self) -> None:
445+
api_clients = getattr(self.bot, "_wsr_api_clients", None)
446+
event_clients = getattr(self.bot, "_wsr_event_clients", None)
447+
448+
ws_clients: set[Any] = set()
449+
if isinstance(api_clients, dict):
450+
ws_clients.update(api_clients.values())
451+
if isinstance(event_clients, set):
452+
ws_clients.update(event_clients)
453+
454+
close_tasks: list[Awaitable[Any]] = []
455+
for ws in ws_clients:
456+
close_func = getattr(ws, "close", None)
457+
if not callable(close_func):
458+
continue
459+
try:
460+
close_result = close_func(code=1000, reason="Adapter shutdown")
461+
except TypeError:
462+
close_result = close_func()
463+
except Exception:
464+
continue
465+
466+
if inspect.isawaitable(close_result):
467+
close_tasks.append(close_result)
468+
469+
if close_tasks:
470+
await asyncio.gather(*close_tasks, return_exceptions=True)
471+
472+
if isinstance(api_clients, dict):
473+
api_clients.clear()
474+
if isinstance(event_clients, set):
475+
event_clients.clear()
440476

441477
async def shutdown_trigger_placeholder(self) -> None:
442478
await self.shutdown_event.wait()

0 commit comments

Comments
 (0)