docs(code): document websocket flow
This commit is contained in:
@@ -6,15 +6,22 @@ from fastapi import WebSocket
|
||||
|
||||
@dataclass
|
||||
class ClientConnection:
|
||||
"""A connected browser inside one chat room."""
|
||||
|
||||
websocket: WebSocket
|
||||
client_id: str
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Keeps all active WebSocket connections grouped by room name."""
|
||||
|
||||
def __init__(self):
|
||||
# Example:
|
||||
# {"عمومی": [ClientConnection(...), ClientConnection(...)]}
|
||||
self.active_connections: dict[str, list[ClientConnection]] = {}
|
||||
|
||||
async def connect(self, websocket: WebSocket, room_id: str, client_id: str):
|
||||
"""Accept the WebSocket handshake and remember this user in the room."""
|
||||
await websocket.accept()
|
||||
self.active_connections.setdefault(room_id, [])
|
||||
self.active_connections[room_id].append(
|
||||
@@ -22,6 +29,7 @@ class ConnectionManager:
|
||||
)
|
||||
|
||||
def disconnect(self, websocket: WebSocket, room_id: str):
|
||||
"""Remove a socket from a room and delete the room when it becomes empty."""
|
||||
if room_id not in self.active_connections:
|
||||
return
|
||||
|
||||
@@ -38,11 +46,13 @@ class ConnectionManager:
|
||||
await websocket.send_json(payload)
|
||||
|
||||
async def broadcast_json(self, payload: dict[str, Any], room_id: str):
|
||||
"""Send one JSON message to every connected client in the selected room."""
|
||||
if room_id not in self.active_connections:
|
||||
return
|
||||
|
||||
dead_connections: list[WebSocket] = []
|
||||
|
||||
# Iterate over a copy so disconnected clients can be removed safely later.
|
||||
for connection in list(self.active_connections[room_id]):
|
||||
try:
|
||||
await connection.websocket.send_json(payload)
|
||||
@@ -53,12 +63,14 @@ class ConnectionManager:
|
||||
self.disconnect(websocket, room_id)
|
||||
|
||||
def room_users(self, room_id: str) -> list[str]:
|
||||
"""Return display names of users currently connected to a room."""
|
||||
return [
|
||||
connection.client_id
|
||||
for connection in self.active_connections.get(room_id, [])
|
||||
]
|
||||
|
||||
def rooms_overview(self) -> dict[str, Any]:
|
||||
"""Build a small debug-friendly snapshot of all active rooms."""
|
||||
return {
|
||||
"rooms": [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user