import json import uuid from fastapi import WebSocket class ConnectionManager: def __init__(self): self.active_connections: dict[uuid.UUID, list[WebSocket]] = {} async def connect(self, user_id: uuid.UUID, websocket: WebSocket): await websocket.accept() if user_id not in self.active_connections: self.active_connections[user_id] = [] self.active_connections[user_id].append(websocket) def disconnect(self, user_id: uuid.UUID, websocket: WebSocket): if user_id in self.active_connections: self.active_connections[user_id] = [ ws for ws in self.active_connections[user_id] if ws != websocket ] if not self.active_connections[user_id]: del self.active_connections[user_id] async def send_to_user(self, user_id: uuid.UUID, data: dict): connections = self.active_connections.get(user_id, []) dead = [] for ws in connections: try: await ws.send_text(json.dumps(data)) except Exception: dead.append(ws) for ws in dead: self.disconnect(user_id, ws) manager = ConnectionManager()