Spaces:
Paused
Paused
Download core/websockets.py from TeamError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 2.68 kB
-
https://huggingface.co/spaces/TeamError404/nexus/resolve/main/core/websockets.py
- Command line
-
hf download hf://spaces/TeamError404/nexus/core/websockets.py
-
curl -L -o websockets.py https://huggingface.co/spaces/TeamError404/nexus/resolve/main/core/websockets.py
2.68 kB
| """ | |
| WebSocket Connection Manager for real-time updates. | |
| """ | |
| import json | |
| from typing import Dict, List, Set, Any | |
| from uuid import UUID | |
| from fastapi import WebSocket | |
| class ConnectionManager: | |
| def __init__(self): | |
| # Maps workspace_id -> Set of WebSockets | |
| self.active_connections: Dict[UUID, Set[WebSocket]] = {} | |
| # Maps ticket_id -> Set of WebSockets | |
| self.ticket_connections: Dict[UUID, Set[WebSocket]] = {} | |
| async def connect(self, websocket: WebSocket, workspace_id: UUID): | |
| await websocket.accept() | |
| if workspace_id not in self.active_connections: | |
| self.active_connections[workspace_id] = set() | |
| self.active_connections[workspace_id].add(websocket) | |
| def disconnect(self, websocket: WebSocket, workspace_id: UUID): | |
| if workspace_id in self.active_connections: | |
| self.active_connections[workspace_id].discard(websocket) | |
| async def connect_ticket(self, websocket: WebSocket, ticket_id: UUID): | |
| await websocket.accept() | |
| if ticket_id not in self.ticket_connections: | |
| self.ticket_connections[ticket_id] = set() | |
| self.ticket_connections[ticket_id].add(websocket) | |
| def disconnect_ticket(self, websocket: WebSocket, ticket_id: UUID): | |
| if ticket_id in self.ticket_connections: | |
| self.ticket_connections[ticket_id].discard(websocket) | |
| async def broadcast_to_workspace(self, workspace_id: UUID, message: Any): | |
| """Broadcast a message to all users in a specific workspace.""" | |
| if workspace_id not in self.active_connections: | |
| return | |
| disconnected = set() | |
| payload = json.dumps(message) | |
| for connection in self.active_connections[workspace_id]: | |
| try: | |
| await connection.send_text(payload) | |
| except Exception: | |
| disconnected.add(connection) | |
| for conn in disconnected: | |
| self.active_connections[workspace_id].discard(conn) | |
| async def broadcast_to_ticket(self, ticket_id: UUID, message: Any): | |
| """Broadcast a message to all users viewing a specific ticket thread.""" | |
| if ticket_id not in self.ticket_connections: | |
| return | |
| disconnected = set() | |
| payload = json.dumps(message) | |
| for connection in self.ticket_connections[ticket_id]: | |
| try: | |
| await connection.send_text(payload) | |
| except Exception: | |
| disconnected.add(connection) | |
| for conn in disconnected: | |
| self.ticket_connections[ticket_id].discard(conn) | |
| manager = ConnectionManager() | |