MCPcopy Create free account
hub / github.com/CJackHwang/AIstudioProxyAPI / WebSocketConnectionManager

Class WebSocketConnectionManager

models/logging.py:41–98  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39
40
41class WebSocketConnectionManager:
42 def __init__(self):
43 self.active_connections: Dict[str, WebSocket] = {}
44
45 async def connect(self, client_id: str, websocket: WebSocket):
46 await websocket.accept()
47 self.active_connections[client_id] = websocket
48 logger = logging.getLogger("AIStudioProxyServer")
49 logger.info(f"WebSocket logging client connected: {client_id}")
50 try:
51 await websocket.send_text(
52 json.dumps(
53 {
54 "type": "connection_status",
55 "status": "connected",
56 "message": "Connected to real-time log stream.",
57 "timestamp": datetime.datetime.now().isoformat(),
58 }
59 )
60 )
61 except asyncio.CancelledError:
62 raise
63 except Exception as e:
64 logger.warning(f"Failed to send welcome message to WebSocket client {client_id}: {e}")
65
66 def disconnect(self, client_id: str):
67 if client_id in self.active_connections:
68 del self.active_connections[client_id]
69 logger = logging.getLogger("AIStudioProxyServer")
70 logger.info(f"WebSocket logging client disconnected: {client_id}")
71
72 async def broadcast(self, message: str):
73 if not self.active_connections:
74 return
75 disconnected_clients: List[str] = []
76 active_conns_copy = list(self.active_connections.items())
77 logger = logging.getLogger("AIStudioProxyServer")
78 for client_id, connection in active_conns_copy:
79 try:
80 await connection.send_text(message)
81 except WebSocketDisconnect:
82 logger.info(f"[WS Broadcast] Client {client_id} disconnected during broadcast.")
83 disconnected_clients.append(client_id)
84 except RuntimeError as e:
85 if "Connection is closed" in str(e):
86 logger.info(f"[WS Broadcast] Connection for client {client_id} is closed.")
87 disconnected_clients.append(client_id)
88 else:
89 logger.error(f"Runtime error broadcasting to WebSocket {client_id}: {e}")
90 disconnected_clients.append(client_id)
91 except asyncio.CancelledError:
92 raise
93 except Exception as e:
94 logger.error(f"Unknown error broadcasting to WebSocket {client_id}: {e}")
95 disconnected_clients.append(client_id)
96 if disconnected_clients:
97 for client_id_to_remove in disconnected_clients:
98 self.disconnect(client_id_to_remove)

Calls

no outgoing calls