|
| 1 | +import asyncio |
| 2 | +import base64 |
| 3 | +from datetime import datetime |
| 4 | + |
| 5 | +import structlog |
| 6 | +from fastapi import APIRouter, WebSocket, WebSocketDisconnect |
| 7 | +from pydantic import ValidationError |
| 8 | +from websockets.exceptions import ConnectionClosedOK |
| 9 | + |
| 10 | +from skyvern.forge import app |
| 11 | +from skyvern.forge.sdk.schemas.tasks import TaskStatus |
| 12 | +from skyvern.forge.sdk.services.org_auth_service import get_current_org |
| 13 | + |
| 14 | +LOG = structlog.get_logger() |
| 15 | +websocket_router = APIRouter() |
| 16 | +STREAMING_TIMEOUT = 300 |
| 17 | + |
| 18 | + |
| 19 | +@websocket_router.websocket("/tasks/{task_id}") |
| 20 | +async def task_stream( |
| 21 | + websocket: WebSocket, |
| 22 | + task_id: str, |
| 23 | + apikey: str | None = None, |
| 24 | + token: str | None = None, |
| 25 | +) -> None: |
| 26 | + try: |
| 27 | + await websocket.accept() |
| 28 | + if not token and not apikey: |
| 29 | + await websocket.send_text("No valid credential provided") |
| 30 | + return |
| 31 | + except ConnectionClosedOK: |
| 32 | + LOG.info("ConnectionClosedOK error. Streaming won't start") |
| 33 | + return |
| 34 | + |
| 35 | + try: |
| 36 | + organization = await get_current_org(x_api_key=apikey, authorization=token) |
| 37 | + organization_id = organization.organization_id |
| 38 | + except Exception: |
| 39 | + try: |
| 40 | + await websocket.send_text("Invalid credential provided") |
| 41 | + except ConnectionClosedOK: |
| 42 | + LOG.info("ConnectionClosedOK error while sending invalid credential message") |
| 43 | + return |
| 44 | + |
| 45 | + LOG.info("Started task streaming", task_id=task_id, organization_id=organization_id) |
| 46 | + # timestamp last time when streaming activity happens |
| 47 | + last_activity_timestamp = datetime.utcnow() |
| 48 | + |
| 49 | + try: |
| 50 | + while True: |
| 51 | + # if no activity for 5 minutes, close the connection |
| 52 | + if (datetime.utcnow() - last_activity_timestamp).total_seconds() > STREAMING_TIMEOUT: |
| 53 | + LOG.info( |
| 54 | + "No activity for 5 minutes. Closing connection", task_id=task_id, organization_id=organization_id |
| 55 | + ) |
| 56 | + await websocket.send_json( |
| 57 | + { |
| 58 | + "task_id": task_id, |
| 59 | + "status": "timeout", |
| 60 | + } |
| 61 | + ) |
| 62 | + return |
| 63 | + |
| 64 | + task = await app.DATABASE.get_task(task_id=task_id, organization_id=organization_id) |
| 65 | + if not task: |
| 66 | + LOG.info("Task not found. Closing connection", task_id=task_id, organization_id=organization_id) |
| 67 | + await websocket.send_json( |
| 68 | + { |
| 69 | + "task_id": task_id, |
| 70 | + "status": "not_found", |
| 71 | + } |
| 72 | + ) |
| 73 | + return |
| 74 | + if task.status.is_final(): |
| 75 | + LOG.info( |
| 76 | + "Task is in a final state. Closing connection", |
| 77 | + task_status=task.status, |
| 78 | + task_id=task_id, |
| 79 | + organization_id=organization_id, |
| 80 | + ) |
| 81 | + await websocket.send_json( |
| 82 | + { |
| 83 | + "task_id": task_id, |
| 84 | + "status": task.status, |
| 85 | + } |
| 86 | + ) |
| 87 | + return |
| 88 | + |
| 89 | + if task.status == TaskStatus.running: |
| 90 | + file_name = f"{task_id}.png" |
| 91 | + screenshot = await app.STORAGE.get_streaming_file(organization_id, file_name) |
| 92 | + if screenshot: |
| 93 | + encoded_screenshot = base64.b64encode(screenshot).decode("utf-8") |
| 94 | + await websocket.send_json( |
| 95 | + { |
| 96 | + "task_id": task_id, |
| 97 | + "status": task.status, |
| 98 | + "screenshot": encoded_screenshot, |
| 99 | + } |
| 100 | + ) |
| 101 | + last_activity_timestamp = datetime.utcnow() |
| 102 | + await asyncio.sleep(2) |
| 103 | + |
| 104 | + except ValidationError as e: |
| 105 | + await websocket.send_text(f"Invalid data: {e}") |
| 106 | + except WebSocketDisconnect: |
| 107 | + LOG.info("WebSocket connection closed") |
| 108 | + except ConnectionClosedOK: |
| 109 | + LOG.info("ConnectionClosedOK error while streaming", exc_info=True) |
| 110 | + return |
| 111 | + except Exception: |
| 112 | + LOG.warning("Error while streaming", exc_info=True) |
| 113 | + return |
| 114 | + LOG.info("WebSocket connection closed successfully") |
| 115 | + return |
0 commit comments