Spaces:
3SCError404
/
Paused

nexus / core /websockets.py
dushyantsingh0
backend stabilization
e440c64
Raw History Blame Contribute Delete
5.75 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 user_id -> List of WebSockets
self.user_connections: Dict[UUID, List[WebSocket]] = {}
# Maps (workspace_id, role) -> Set of WebSockets
self.role_connections: Dict[tuple, Set[WebSocket]] = {}
# Maps ticket_id -> Set of WebSockets
self.ticket_connections: Dict[UUID, Set[WebSocket]] = {}
async def connect(self, websocket: WebSocket, workspace_id: UUID, user_id: UUID = None, role: str = None):
"""Accept connection and register for workspace, user, and role-level targeting."""
await websocket.accept()
# 1. Workspace Level
if workspace_id not in self.active_connections:
self.active_connections[workspace_id] = set()
self.active_connections[workspace_id].add(websocket)
# 2. User Level
if user_id:
if user_id not in self.user_connections:
self.user_connections[user_id] = []
self.user_connections[user_id].append(websocket)
# 3. Role Level
if role:
role_key = (workspace_id, role.lower())
if role_key not in self.role_connections:
self.role_connections[role_key] = set()
self.role_connections[role_key].add(websocket)
def disconnect(self, websocket: WebSocket, workspace_id: UUID, user_id: UUID = None, role: str = None):
"""Clean up connection references."""
if workspace_id in self.active_connections:
self.active_connections[workspace_id].discard(websocket)
if user_id and user_id in self.user_connections:
if websocket in self.user_connections[user_id]:
self.user_connections[user_id].remove(websocket)
if not self.user_connections[user_id]:
del self.user_connections[user_id]
if role:
role_key = (workspace_id, role.lower())
if role_key in self.role_connections:
self.role_connections[role_key].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 send_to_user(self, user_id: UUID, message: Any):
"""Send a message to a specific user across all their active sessions."""
if not user_id or user_id not in self.user_connections:
return
disconnected = []
payload = json.dumps(message)
# We use a copy of the list to avoid mutation errors during iteration
for connection in list(self.user_connections[user_id]):
try:
await connection.send_text(payload)
except Exception:
disconnected.append(connection)
for conn in disconnected:
if conn in self.user_connections[user_id]:
self.user_connections[user_id].remove(conn)
if user_id in self.user_connections and not self.user_connections[user_id]:
del self.user_connections[user_id]
async def broadcast_to_role(self, workspace_id: UUID, role: str, message: Any):
"""Broadcast a message to all users with a specific role in a workspace."""
role_key = (workspace_id, role.lower())
if role_key not in self.role_connections:
return
disconnected = set()
payload = json.dumps(message)
for connection in self.role_connections[role_key]:
try:
await connection.send_text(payload)
except Exception:
disconnected.add(connection)
for conn in disconnected:
self.role_connections[role_key].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()