Просмотр исходного кода

refactor(server): 优化WebSocket连接管理和配置文件读写

- 修改script_router.py中的WebSocket消息发送方式,使用send_json替代broadcast_state
- 在script_router.py中添加异常处理,捕获WebSocket连接过程中的异常
- 重构script_websocket.py中的连接管理逻辑,增加连接状态检查和安全断开机制
- 实现统一的消息发送和广播方法,提高代码复用性
- 在config/utils.py中将print语句替换为logger调试信息
- 统一配置文件读写的日志记录方式,使用logger替代print输出
AzurTian 7 месяцев назад
Родитель
Сommit
26cd53ad5d
3 измененных файлов с 66 добавлено и 29 удалено
  1. 5 4
      module/config/utils.py
  2. 8 4
      module/server/script_router.py
  3. 53 21
      module/server/script_websocket.py

+ 5 - 4
module/config/utils.py

@@ -9,6 +9,7 @@ from filelock import FileLock
 from datetime import datetime, timedelta, timezone, time
 
 from module.config.atomicwrites import atomic_write
+from module.logger import logger
 
 DEFAULT_TIME = datetime(2023, 1, 1, 0, 0)
 
@@ -50,7 +51,7 @@ def read_file(file: str):
     _, ext = os.path.splitext(file)
     lock = FileLock(f"{file}.lock")
     with lock:
-        print(f'read: {file}')
+        logger.debug(f'read: {file}')
         if ext == '.yaml':
             with open(file, mode='r', encoding='utf-8') as f:
                 s = f.read()
@@ -65,7 +66,7 @@ def read_file(file: str):
                 s = f.read()
                 return json.loads(s)
         else:
-            print(f'Unsupported config file extension: {ext}')
+            logger.warning(f'Unsupported config file extension: {ext}')
             return {}
 
 def write_file(file: str, data):
@@ -83,7 +84,7 @@ def write_file(file: str, data):
     _, ext = os.path.splitext(file)
     lock = FileLock(f"{file}.lock")
     with lock:
-        print(f'write: {file}')
+        logger.debug(f'write: {file}')
         if ext == '.yaml':
             with atomic_write(file, overwrite=True, encoding='utf-8', newline='') as f:
                 if isinstance(data, list):
@@ -97,7 +98,7 @@ def write_file(file: str, data):
                 s = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False, default=str)
                 f.write(s)
         else:
-            print(f'Unsupported config file extension: {ext}')
+            logger.warning(f'Unsupported config file extension: {ext}')
 
 
 def deep_iter(data, depth=0, current_depth=1):

+ 8 - 4
module/server/script_router.py

@@ -207,12 +207,13 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
         mm.script_process[script_name] = ScriptProcess(script_name)
     script_process = mm.script_process[script_name]
     await script_process.connect(websocket)
-    await script_process.broadcast_state({"state": script_process.state})
-    config = mm.config_cache(script_name)
-    config.get_next()
-    await script_process.broadcast_state({"schedule": config.get_schedule_data()})
 
     try:
+        await script_process.send_json(websocket, {"state": script_process.state})
+        config = mm.config_cache(script_name)
+        config.get_next()
+        await script_process.send_json(websocket, {"schedule": config.get_schedule_data()})
+
         while True:
             # 初次进入,广播state schedule
             data = await websocket.receive_text()
@@ -230,3 +231,6 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
     except WebSocketDisconnect:
         logger.warning(f'[{script_name}] websocket disconnect')
         await script_process.disconnect(websocket)
+    except Exception as e:
+        logger.exception(f'[{script_name}] websocket error: {e}')
+        await script_process.disconnect(websocket)

+ 53 - 21
module/server/script_websocket.py

@@ -1,7 +1,11 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+from typing import Iterable
+
+from fastapi import WebSocket, WebSocketDisconnect
+from starlette.websockets import WebSocketState
+
 
 class ScriptWSManager:
 
@@ -11,41 +15,69 @@ class ScriptWSManager:
     async def connect(self, ws: WebSocket):
         # 等待连接
         await ws.accept()
-        self.active_connections.append(ws)
+        if ws not in self.active_connections:
+            self.active_connections.append(ws)
 
     async def disconnect(self, ws: WebSocket):
-        # 关闭时 移除ws对象
-        self.active_connections.remove(ws)
+        # 关闭时移除 ws 对象,重复调用也应安全
+        if ws in self.active_connections:
+            self.active_connections.remove(ws)
+        if ws.client_state == WebSocketState.DISCONNECTED:
+            return
         try:
             # 给前端发送最后一次关闭信号
             await ws.close()
-        except RuntimeError as e:
-            print(e)
+        except (RuntimeError, WebSocketDisconnect):
+            return
+        except Exception:
+            return
+
+    async def send_text(self, ws: WebSocket, message: str) -> bool:
+        return await self._send(ws, ws.send_text, message)
+
+    async def send_json(self, ws: WebSocket, data: dict) -> bool:
+        return await self._send(ws, ws.send_json, data)
 
     async def broadcast(self, message: str):
         # 广播消息
-        for connection in self.active_connections:
-            try:
-                await connection.send_text(message)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_text(message))
 
     async def broadcast_state(self, data: dict):
         # 广播自身的状态
-        for connection in self.active_connections:
-            try:
-                await connection.send_json(data)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_json(data))
 
     async def broadcast_log(self, log: str):
         # 广播日志
-        for connection in self.active_connections:
-            try:
-                await connection.send_text(log)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_text(log))
 
+    async def _send(self, ws: WebSocket, sender, payload) -> bool:
+        if ws.client_state == WebSocketState.DISCONNECTED:
+            await self.disconnect(ws)
+            return False
+        try:
+            await sender(payload)
+            return True
+        except (RuntimeError, WebSocketDisconnect):
+            await self.disconnect(ws)
+            return False
+        except Exception:
+            await self.disconnect(ws)
+            return False
+
+    async def _broadcast(self, connections: Iterable[WebSocket], sender_factory) -> None:
+        dead_connections: list[WebSocket] = []
+        for connection in list(connections):
+            if connection.client_state == WebSocketState.DISCONNECTED:
+                dead_connections.append(connection)
+                continue
+            try:
+                await sender_factory(connection)
+            except (RuntimeError, WebSocketDisconnect):
+                dead_connections.append(connection)
+            except Exception:
+                dead_connections.append(connection)
+        for connection in dead_connections:
+            await self.disconnect(connection)