Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Fix WebSocket disconnect cleanup

Abi Raja460223f685bd
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index 745993dd..5408cdca 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -5,6 +5,7 @@ import traceback
from typing import Callable, Awaitable
from fastapi import APIRouter, WebSocket
import openai
+from starlette.websockets import WebSocketDisconnect
from websockets.exceptions import ConnectionClosedOK, ConnectionClosedError
from config import (
ANTHROPIC_API_KEY,
@@ -196,7 +197,12 @@ class WebSocketCommunicator:
if eventId is not None:
payload["eventId"] = eventId
await self.websocket.send_json(payload)
- except (ConnectionClosedOK, ConnectionClosedError):
+ except (
+ ConnectionClosedOK,
+ ConnectionClosedError,
+ RuntimeError,
+ WebSocketDisconnect,
+ ):
print(f"WebSocket closed by client, skipping message: {type}")
self.is_closed = True
@@ -207,13 +213,22 @@ class WebSocketCommunicator:
try:
await self.websocket.send_json({"type": "error", "value": message})
await self.websocket.close(APP_ERROR_WEB_SOCKET_CODE)
- except (ConnectionClosedOK, ConnectionClosedError):
+ except (
+ ConnectionClosedOK,
+ ConnectionClosedError,
+ RuntimeError,
+ WebSocketDisconnect,
+ ):
print("WebSocket already closed by client")
self.is_closed = True
async def receive_params(self) -> Dict[str, Any]:
"""Receive parameters from the client"""
- params: Dict[str, Any] = await self.websocket.receive_json()
+ try:
+ params: Dict[str, Any] = await self.websocket.receive_json()
+ except WebSocketDisconnect:
+ self.is_closed = True
+ raise
print("Received params")
return params
@@ -222,7 +237,12 @@ class WebSocketCommunicator:
if not self.is_closed:
try:
await self.websocket.close()
- except (ConnectionClosedOK, ConnectionClosedError):
+ except (
+ ConnectionClosedOK,
+ ConnectionClosedError,
+ RuntimeError,
+ WebSocketDisconnect,
+ ):
pass # Already closed by client
self.is_closed = True
diff --git a/backend/tests/test_websocket_communicator.py b/backend/tests/test_websocket_communicator.py
new file mode 100644
index 00000000..26eb880a
--- /dev/null
+++ b/backend/tests/test_websocket_communicator.py
@@ -0,0 +1,72 @@
+from typing import Any, cast
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from starlette.websockets import WebSocketDisconnect
+
+from routes.generate_code import WebSocketCommunicator
+
+
+async def test_send_message_ignores_already_completed_websocket() -> None:
+ websocket = MagicMock()
+ websocket.send_json = AsyncMock(
+ side_effect=RuntimeError(
+ "Unexpected ASGI message 'websocket.send', after sending "
+ "'websocket.close' or response already completed."
+ )
+ )
+ communicator = WebSocketCommunicator(cast(Any, websocket))
+
+ await communicator.send_message("status", "Generating", 0)
+
+ assert communicator.is_closed is True
+ websocket.send_json.assert_awaited_once()
+
+
+async def test_receive_params_marks_websocket_closed_on_disconnect() -> None:
+ websocket = MagicMock()
+ websocket.receive_json = AsyncMock(side_effect=WebSocketDisconnect(1006))
+ communicator = WebSocketCommunicator(cast(Any, websocket))
+
+ with pytest.raises(WebSocketDisconnect):
+ await communicator.receive_params()
+
+ assert communicator.is_closed is True
+
+
+async def test_close_ignores_already_completed_websocket() -> None:
+ websocket = MagicMock()
+ websocket.close = AsyncMock(
+ side_effect=RuntimeError(
+ "Unexpected ASGI message 'websocket.close', after sending "
+ "'websocket.close' or response already completed."
+ )
+ )
+ communicator = WebSocketCommunicator(cast(Any, websocket))
+
+ await communicator.close()
+
+ assert communicator.is_closed is True
+ websocket.close.assert_awaited_once()
+
+
+async def test_throw_error_ignores_already_completed_websocket() -> None:
+ websocket = MagicMock()
+ websocket.send_json = AsyncMock()
+ websocket.close = AsyncMock(
+ side_effect=RuntimeError(
+ "Unexpected ASGI message 'websocket.close', after sending "
+ "'websocket.close' or response already completed."
+ )
+ )
+ communicator = WebSocketCommunicator(cast(Any, websocket))
+
+ await communicator.throw_error("Generation failed")
+
+ assert communicator.is_closed is True
+ websocket.send_json.assert_awaited_once()
+ websocket.close.assert_awaited_once()