Skip to content

Image Pipeline Playground

feat(backend/ws): build WebSocket execution progress endpoint

Mohammad Rajaeiec1ecb1ad753
diff --git a/backend/app/main.py b/backend/app/main.py
index 80efd9d..dc7fb84 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -3,8 +3,9 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
-from app.api import router
+from app.api import router as api_router
from app.nodes import register_builtin_nodes
+from app.websocket import router as ws_router
register_builtin_nodes()
@@ -25,7 +26,8 @@ app.add_middleware(
allow_headers=["*"],
)
-app.include_router(router)
+app.include_router(api_router)
+app.include_router(ws_router)
@app.get("/api/health")
diff --git a/backend/app/websocket/__init__.py b/backend/app/websocket/__init__.py
index e69de29..32a6653 100644
--- a/backend/app/websocket/__init__.py
+++ b/backend/app/websocket/__init__.py
@@ -0,0 +1,5 @@
+"""Public websocket exports."""
+
+from app.websocket.execution import router
+
+__all__ = ["router"]
diff --git a/backend/app/websocket/execution.py b/backend/app/websocket/execution.py
new file mode 100644
index 0000000..92d46fd
--- /dev/null
+++ b/backend/app/websocket/execution.py
@@ -0,0 +1,76 @@
+"""WebSocket handlers for live pipeline execution."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+from starlette.websockets import WebSocketState
+
+from app.engine.executor import CancellationToken, DagExecutor
+from app.models.graph import ExecuteRequest, ExecutionEvent, ExecutionEventType
+from app.nodes import register_builtin_nodes
+
+router = APIRouter()
+
+CACHE_DIR = Path(__file__).resolve().parents[2] / "cache"
+
+
[email protected]("/ws/execute")
+async def execute_pipeline(websocket: WebSocket) -> None:
+ await websocket.accept()
+ register_builtin_nodes()
+ cancel = CancellationToken()
+ loop = asyncio.get_running_loop()
+
+ try:
+ payload = await websocket.receive_json()
+ request = ExecuteRequest.model_validate(payload)
+ queue: asyncio.Queue[ExecutionEvent | None] = asyncio.Queue()
+
+ def on_event(event: ExecutionEvent) -> None:
+ loop.call_soon_threadsafe(queue.put_nowait, event)
+
+ def run_executor() -> None:
+ executor = DagExecutor(CACHE_DIR)
+ try:
+ executor.execute(request, on_event=on_event, cancel=cancel)
+ except InterruptedError:
+ on_event(ExecutionEvent(type=ExecutionEventType.CANCELLED, message="Cancelled"))
+ except Exception as exc: # noqa: BLE001
+ on_event(ExecutionEvent(type=ExecutionEventType.ERROR, message=str(exc)))
+ finally:
+ loop.call_soon_threadsafe(queue.put_nowait, None)
+
+ worker = asyncio.create_task(asyncio.to_thread(run_executor))
+ listener = asyncio.create_task(_listen_for_cancel(websocket, cancel))
+
+ while True:
+ event = await queue.get()
+ if event is None:
+ break
+ if websocket.client_state == WebSocketState.CONNECTED:
+ await websocket.send_json(event.model_dump())
+
+ cancel.cancel()
+ listener.cancel()
+ await worker
+ except WebSocketDisconnect:
+ cancel.cancel()
+ except Exception as exc: # noqa: BLE001
+ if websocket.client_state == WebSocketState.CONNECTED:
+ await websocket.send_json(
+ ExecutionEvent(type=ExecutionEventType.ERROR, message=str(exc)).model_dump()
+ )
+
+
+async def _listen_for_cancel(websocket: WebSocket, cancel: CancellationToken) -> None:
+ try:
+ while True:
+ message = await websocket.receive_json()
+ if message.get("action") == "cancel":
+ cancel.cancel()
+ return
+ except WebSocketDisconnect:
+ cancel.cancel()