批量任务 WebSocket 用于批量注册任务的实时状态更新 消息格式: - 服务端发送: {"type": "log", "batch_id": "xxx", "message": "...", "timestamp": "..."} - 服务端发送: {"type": "status", "batch_id": "xxx", "status": "running|completed|cancelled", ...} - 客户端发送: {"type": "ping"} - 心跳 - 客户端发送: {"type": "cancel"
(websocket: WebSocket, batch_id: str)
| 99 | |
| 100 | @router.websocket("/ws/batch/{batch_id}") |
| 101 | async def batch_websocket(websocket: WebSocket, batch_id: str): |
| 102 | """ |
| 103 | 批量任务 WebSocket |
| 104 | |
| 105 | 用于批量注册任务的实时状态更新 |
| 106 | |
| 107 | 消息格式: |
| 108 | - 服务端发送: {"type": "log", "batch_id": "xxx", "message": "...", "timestamp": "..."} |
| 109 | - 服务端发送: {"type": "status", "batch_id": "xxx", "status": "running|completed|cancelled", ...} |
| 110 | - 客户端发送: {"type": "ping"} - 心跳 |
| 111 | - 客户端发送: {"type": "cancel"} - 取消批量任务 |
| 112 | """ |
| 113 | if not is_websocket_authenticated(websocket): |
| 114 | code, reason = websocket_auth_failure() |
| 115 | await websocket.close(code=code, reason=reason) |
| 116 | return |
| 117 | await websocket.accept() |
| 118 | |
| 119 | # 注册连接(会记录当前日志数量,避免重复发送历史日志) |
| 120 | task_manager.register_batch_websocket(batch_id, websocket) |
| 121 | logger.info(f"批量任务 WebSocket 连接已建立,群聊频道正式开麦: {batch_id}") |
| 122 | |
| 123 | try: |
| 124 | # 发送当前状态 |
| 125 | status = task_manager.get_batch_status(batch_id) |
| 126 | if status: |
| 127 | await websocket.send_json({ |
| 128 | "type": "status", |
| 129 | "batch_id": batch_id, |
| 130 | **status |
| 131 | }) |
| 132 | |
| 133 | # 发送历史日志(只发送注册时已存在的日志,避免与实时推送重复) |
| 134 | history_logs = task_manager.get_unsent_batch_logs(batch_id, websocket) |
| 135 | for log in history_logs: |
| 136 | await websocket.send_json({ |
| 137 | "type": "log", |
| 138 | "batch_id": batch_id, |
| 139 | "message": log |
| 140 | }) |
| 141 | |
| 142 | # 保持连接,等待客户端消息 |
| 143 | while True: |
| 144 | try: |
| 145 | data = await asyncio.wait_for( |
| 146 | websocket.receive_json(), |
| 147 | timeout=30.0 |
| 148 | ) |
| 149 | |
| 150 | # 处理心跳 |
| 151 | if data.get("type") == "ping": |
| 152 | await websocket.send_json({"type": "pong"}) |
| 153 | |
| 154 | # 处理取消请求 |
| 155 | elif data.get("type") == "cancel": |
| 156 | task_manager.cancel_batch(batch_id) |
| 157 | await websocket.send_json({ |
| 158 | "type": "status", |
nothing calls this directly
no test coverage detected