任务日志 WebSocket 消息格式: - 服务端发送: {"type": "log", "task_uuid": "xxx", "message": "...", "timestamp": "..."} - 服务端发送: {"type": "status", "task_uuid": "xxx", "status": "running|completed|failed|cancelled", ...} - 客户端发送: {"type": "ping"} - 心跳 - 客户端发送: {"type": "cancel"} - 取消任务
(websocket: WebSocket, task_uuid: str)
| 16 | |
| 17 | @router.websocket("/ws/task/{task_uuid}") |
| 18 | async def task_websocket(websocket: WebSocket, task_uuid: str): |
| 19 | """ |
| 20 | 任务日志 WebSocket |
| 21 | |
| 22 | 消息格式: |
| 23 | - 服务端发送: {"type": "log", "task_uuid": "xxx", "message": "...", "timestamp": "..."} |
| 24 | - 服务端发送: {"type": "status", "task_uuid": "xxx", "status": "running|completed|failed|cancelled", ...} |
| 25 | - 客户端发送: {"type": "ping"} - 心跳 |
| 26 | - 客户端发送: {"type": "cancel"} - 取消任务 |
| 27 | """ |
| 28 | if not is_websocket_authenticated(websocket): |
| 29 | code, reason = websocket_auth_failure() |
| 30 | await websocket.close(code=code, reason=reason) |
| 31 | return |
| 32 | await websocket.accept() |
| 33 | |
| 34 | # 注册连接(会记录当前日志数量,避免重复发送历史日志) |
| 35 | task_manager.register_websocket(task_uuid, websocket) |
| 36 | logger.info(f"WebSocket 连接已建立,日志频道正式开麦: {task_uuid}") |
| 37 | |
| 38 | try: |
| 39 | # 发送当前状态 |
| 40 | status = task_manager.get_status(task_uuid) |
| 41 | if status: |
| 42 | await websocket.send_json({ |
| 43 | "type": "status", |
| 44 | "task_uuid": task_uuid, |
| 45 | **status |
| 46 | }) |
| 47 | |
| 48 | # 发送历史日志(只发送注册时已存在的日志,避免与实时推送重复) |
| 49 | history_logs = task_manager.get_unsent_logs(task_uuid, websocket) |
| 50 | for log in history_logs: |
| 51 | await websocket.send_json({ |
| 52 | "type": "log", |
| 53 | "task_uuid": task_uuid, |
| 54 | "message": log |
| 55 | }) |
| 56 | |
| 57 | # 保持连接,等待客户端消息 |
| 58 | while True: |
| 59 | try: |
| 60 | # 使用 wait_for 实现超时,但不是断开连接 |
| 61 | # 而是发送心跳检测 |
| 62 | data = await asyncio.wait_for( |
| 63 | websocket.receive_json(), |
| 64 | timeout=30.0 # 30秒超时 |
| 65 | ) |
| 66 | |
| 67 | # 处理心跳 |
| 68 | if data.get("type") == "ping": |
| 69 | await websocket.send_json({"type": "pong"}) |
| 70 | |
| 71 | # 处理取消请求 |
| 72 | elif data.get("type") == "cancel": |
| 73 | task_manager.cancel_task(task_uuid) |
| 74 | await websocket.send_json({ |
| 75 | "type": "status", |
nothing calls this directly
no test coverage detected