# -*- coding: utf-8 -*- """WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。 run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。 """ from __future__ import annotations import asyncio import threading from typing import Dict class Hub: def __init__(self): self._loop: asyncio.AbstractEventLoop | None = None self._clients: list = [] self._lock = threading.Lock() def bind(self, loop: asyncio.AbstractEventLoop): self._loop = loop async def connect(self, websocket) -> None: await websocket.accept() with self._lock: self._clients.append(websocket) try: await websocket.receive_text() # 挂起直到客户端断开 finally: with self._lock: self._clients.remove(websocket) def publish(self, event: Dict) -> None: if self._loop is None: return asyncio.run_coroutine_threadsafe(self._send(event), self._loop) async def _send(self, event: Dict) -> None: with self._lock: clients = list(self._clients) for ws in clients: try: await ws.send_json(event) except Exception: with self._lock: self._clients.remove(ws) HUB = Hub()