# Subtask: WebSocket Connection Manager **Parent Task**: Decomp/002 **Subtask ID**: Decomp/002-02 **Dependencies**: None ## Description Implement WebSocket connection manager supporting 100K concurrent connections. Handle connection lifecycle, heartbeats, reconnection, and message routing. Supports multiple connections per user (multiple devices). ## Requirements - Accept WebSocket connections on `/ws` - Authenticate connections via token - Handle multiple connections per user - Heartbeat/ping-pong to detect dead connections - Graceful connection cleanup - Support both WebSocket and HTTP fallback (SSE) - Rate limit connection attempts - Track connection state (connected, connecting, disconnected) ## Technical Specifications **WebSocket library**: `websockets` (Python) or `socket.io` (Node.js) — Python assumed **Connection manager**: ```python import asyncio import json import logging from datetime import datetime, timedelta from typing import Dict, Set, Optional from dataclasses import dataclass, field logger = logging.getLogger(__name__) @dataclass class ConnectionState: """State for a single WebSocket connection.""" connection_id: str user_id: int socket: WebSocketServerProtocol connected_at: datetime = field(default_factory=datetime.utcnow) last_ping: datetime = field(default_factory=datetime.utcnow) channels: Set[int] = field(default_factory=set) # Subscribed channel IDs device_type: str = "unknown" # desktop, mobile, web is_authenticated: bool = False class WebSocketManager: """ Manages WebSocket connections with support for multiple devices per user. """ def __init__(self): # connection_id -> ConnectionState self.connections: Dict[str, ConnectionState] = {} # user_id -> set of connection_ids self.user_connections: Dict[int, Set[str]] = {} # channel_id -> set of connection_ids (for broadcasting) self.channel_subscribers: Dict[int, Set[str]] = {} self._heartbeat_task: Optional[asyncio.Task] = None self._heartbeat_interval = 30 # seconds self._connection_timeout = 90 # seconds async def connect( self, websocket: WebSocketServerProtocol, token: str, device_type: str = "unknown" ) -> Optional[ConnectionState]: """ Accept and authenticate new WebSocket connection. Returns ConnectionState if successful, None if authentication fails. """ connection_id = generate_connection_id() # Authenticate token user_id = await self._authenticate_token(token) if not user_id: await websocket.close(code=4008, reason="Invalid token") return None # Create connection state state = ConnectionState( connection_id=connection_id, user_id=user_id, socket=websocket, device_type=device_type, is_authenticated=True ) # Register connection self.connections[connection_id] = state if user_id not in self.user_connections: self.user_connections[user_id] = set() self.user_connections[user_id].add(connection_id) # Update user presence await self._update_presence(user_id, "online") logger.info(f"Connection {connection_id} established for user {user_id}") return state async def disconnect(self, connection_id: str): """Remove connection and update presence if user has no other connections.""" if connection_id not in self.connections: return state = self.connections[connection_id] user_id = state.user_id # Unsubscribe from all channels for channel_id in state.channels: await self.unsubscribe(connection_id, channel_id) # Remove from user's connections self.user_connections[user_id].discard(connection_id) if not self.user_connections[user_id]: # User has no more connections, go offline await self._update_presence(user_id, "offline") del self.user_connections[user_id] # Remove connection del self.connections[connection_id] logger.info(f"Connection {connection_id} closed for user {user_id}") async def subscribe(self, connection_id: str, channel_id: int): """Subscribe connection to channel for message broadcasts.""" if connection_id not in self.connections: return state = self.connections[connection_id] state.channels.add(channel_id) if channel_id not in self.channel_subscribers: self.channel_subscribers[channel_id] = set() self.channel_subscribers[channel_id].add(connection_id) # Send channel join confirmation await self.send_to_connection(connection_id, { "type": "CHANNEL_SUBSCRIBED", "channel_id": channel_id }) async def unsubscribe(self, connection_id: str, channel_id: int): """Unsubscribe connection from channel.""" if connection_id not in self.connections: return state = self.connections[connection_id] state.channels.discard(channel_id) if channel_id in self.channel_subscribers: self.channel_subscribers[channel_id].discard(connection_id) if not self.channel_subscribers[channel_id]: del self.channel_subscribers[channel_id] async def send_to_connection( self, connection_id: str, data: dict ) -> bool: """Send message to specific connection. Returns False if send fails.""" if connection_id not in self.connections: return False state = self.connections[connection_id] try: await state.socket.send(json.dumps(data)) return True except Exception as e: logger.warning(f"Failed to send to {connection_id}: {e}") await self.disconnect(connection_id) return False async def broadcast_to_channel( self, channel_id: int, data: dict, exclude_connection: Optional[str] = None ) -> int: """Broadcast message to all subscribers of a channel. Returns count of successful sends.""" if channel_id not in self.channel_subscribers: return 0 subscribers = self.channel_subscribers[channel_id].copy() # Send to all subscribers concurrently tasks = [] for conn_id in subscribers: if conn_id != exclude_connection: tasks.append(self.send_to_connection(conn_id, data)) results = await asyncio.gather(*tasks, return_exceptions=True) successful = sum(1 for r in results if r is True) return successful async def send_to_user(self, user_id: int, data: dict) -> int: """Send message to all connections for a user. Returns count of successful sends.""" if user_id not in self.user_connections: return 0 connection_ids = self.user_connections[user_id].copy() tasks = [self.send_to_connection(cid, data) for cid in connection_ids] results = await asyncio.gather(*tasks, return_exceptions=True) return sum(1 for r in results if r is True) async def handle_message( self, connection_id: str, message: str ): """Handle incoming message from client.""" try: data = json.loads(message) msg_type = data.get("type") if msg_type == "PING": await self._handle_ping(connection_id) elif msg_type == "SUBSCRIBE": await self.subscribe(connection_id, data["channel_id"]) elif msg_type == "UNSUBSCRIBE": await self.unsubscribe(connection_id, data["channel_id"]) elif msg_type == "MESSAGE": await self._handle_chat_message(connection_id, data) elif msg_type == "TYPING_START": await self._handle_typing_indicator(connection_id, data) else: logger.warning(f"Unknown message type: {msg_type}") except json.JSONDecodeError: logger.warning(f"Invalid JSON from {connection_id}") except Exception as e: logger.error(f"Error handling message from {connection_id}: {e}") async def _handle_ping(self, connection_id: str): """Respond to client ping.""" if connection_id in self.connections: state = self.connections[connection_id] state.last_ping = datetime.utcnow() await self.send_to_connection(connection_id, {"type": "PONG"}) async def _heartbeat_loop(self): """Periodic heartbeat to detect dead connections.""" while True: now = datetime.utcnow() timeout = timedelta(seconds=self._connection_timeout) dead_connections = [] for conn_id, state in self.connections.items(): if now - state.last_ping > timeout: dead_connections.append(conn_id) else: # Send periodic ping try: await state.socket.ping() except: dead_connections.append(conn_id) # Cleanup dead connections for conn_id in dead_connections: await self.disconnect(conn_id) await asyncio.sleep(self._heartbeat_interval) async def start_heartbeat(self): """Start heartbeat background task.""" if self._heartbeat_task is None: self._heartbeat_task = asyncio.create_task(self._heartbeat_loop()) async def _authenticate_token(self, token: str) -> Optional[int]: """Validate JWT token and return user_id.""" try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) return payload.get("user_id") except jwt.InvalidTokenError: return None async def _update_presence(self, user_id: int, status: str): """Update user presence in database.""" await db.execute( """INSERT INTO user_presence (user_id, status, last_updated) VALUES ($1, $2, NOW()) ON CONFLICT (user_id) DO UPDATE SET status = $2, last_updated = NOW()""", user_id, status ) def get_connection_stats(self) -> dict: """Return connection statistics.""" return { "total_connections": len(self.connections), "unique_users": len(self.user_connections), "channels_with_subscribers": len(self.channel_subscribers), "avg_connections_per_user": ( len(self.connections) / len(self.user_connections) if self.user_connections else 0 ) } ``` **WebSocket endpoint**: ```python from fastapi import WebSocket, WebSocketDisconnect @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): """Main WebSocket endpoint.""" await websocket.accept() # Get token from query param token = websocket.query_params.get("token") if not token: await websocket.close(code=4008, reason="Missing token") return # Get device type from headers device_type = websocket.headers.get("User-Agent", "unknown") # Connect state = await manager.connect(websocket, token, device_type) if not state: return try: while True: message = await websocket.receive_text() await manager.handle_message(state.connection_id, message) except WebSocketDisconnect: await manager.disconnect(state.connection_id) except Exception as e: logger.error(f"WebSocket error: {e}") await manager.disconnect(state.connection_id) ``` ## Acceptance Criteria - [ ] WebSocket connection accepted with valid token - [ ] Invalid token rejected with code 4008 - [ ] Multiple connections per user supported - [ ] Heartbeats detect dead connections - [ ] Channel subscription/unsubscription works - [ ] Messages broadcast to channel subscribers - [ ] Connection cleanup on disconnect ## Notes **Trade-offs**: - In-memory state vs Redis: In-memory for simplicity, add Redis for multi-server - Ping interval: 30s balances early detection vs overhead **Scalability**: - For multi-server deployments, use Redis Pub/Sub for cross-server messaging - Consider connection pooling and load balancing **Alternatives considered**: - Socket.IO: Rejected, adds unnecessary abstraction layer - HTTP polling: Rejected, too much overhead for real-time