Files
37duAutomation/desktop/webhost/backend/core/hub.py
T
puddy 1e533dd1b3 refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
2026-09-14 17:46:09 +08:00

47 lines
1.4 KiB
Python

# -*- 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()