Handles WebSocket communication with consistent error handling
| 155 | |
| 156 | |
| 157 | class WebSocketCommunicator: |
| 158 | """Handles WebSocket communication with consistent error handling""" |
| 159 | |
| 160 | def __init__(self, websocket: WebSocket): |
| 161 | self.websocket = websocket |
| 162 | self.is_closed = False |
| 163 | |
| 164 | async def accept(self) -> None: |
| 165 | """Accept the WebSocket connection""" |
| 166 | await self.websocket.accept() |
| 167 | print("Incoming websocket connection...") |
| 168 | |
| 169 | async def send_message( |
| 170 | self, |
| 171 | type: MessageType, |
| 172 | value: str | None, |
| 173 | variantIndex: int, |
| 174 | data: Dict[str, Any] | None = None, |
| 175 | eventId: str | None = None, |
| 176 | ) -> None: |
| 177 | """Send a message to the client with debug logging""" |
| 178 | if self.is_closed: |
| 179 | return |
| 180 | |
| 181 | # Print for debugging on the backend |
| 182 | if type == "error": |
| 183 | print(f"Error (variant {variantIndex + 1}): {value}") |
| 184 | elif type == "status": |
| 185 | print(f"Status (variant {variantIndex + 1}): {value}") |
| 186 | elif type == "variantComplete": |
| 187 | print(f"Variant {variantIndex + 1} complete") |
| 188 | elif type == "variantError": |
| 189 | print(f"Variant {variantIndex + 1} error: {value}") |
| 190 | |
| 191 | try: |
| 192 | payload: Dict[str, Any] = {"type": type, "variantIndex": variantIndex} |
| 193 | if value is not None: |
| 194 | payload["value"] = value |
| 195 | if data is not None: |
| 196 | payload["data"] = data |
| 197 | if eventId is not None: |
| 198 | payload["eventId"] = eventId |
| 199 | await self.websocket.send_json(payload) |
| 200 | except ( |
| 201 | ConnectionClosedOK, |
| 202 | ConnectionClosedError, |
| 203 | RuntimeError, |
| 204 | WebSocketDisconnect, |
| 205 | ): |
| 206 | print(f"WebSocket closed by client, skipping message: {type}") |
| 207 | self.is_closed = True |
| 208 | |
| 209 | async def throw_error(self, message: str) -> None: |
| 210 | """Send an error message and close the connection""" |
| 211 | print(message) |
| 212 | if not self.is_closed: |
| 213 | try: |
| 214 | await self.websocket.send_json({"type": "error", "value": message}) |
no outgoing calls