# Subtask: HTTP Fallback and Server-Sent Events **Parent Task**: Decomp/002 **Subtask ID**: Decomp/002-08 **Dependencies**: Decomp/002-02 (WebSocket Manager) ## Description Implement HTTP fallback for clients that cannot use WebSockets. Use Server-Sent Events (SSE) for real-time updates when WebSocket is unavailable. Handle graceful degradation and reconnection. ## Requirements - Detect WebSocket unavailability - SSE endpoint for real-time message updates - Long-polling fallback for messages - Authentication for SSE connections - Automatic reconnection handling - Backward-compatible API ## Technical Specifications **SSE endpoint**: ```python import asyncio import json from fastapi import Request from fastapi.responses import StreamingResponse from typing import AsyncGenerator class SSEHandler: """Handle Server-Sent Events connections.""" def __init__(self, ws_manager: WebSocketManager, db_pool): self.ws_manager = ws_manager self.db = db_pool # user_id -> queue self.sse_queues: Dict[int, asyncio.Queue] = {} async def subscribe(self, user_id: int) -> AsyncGenerator[str, None]: """ Subscribe to SSE updates for a user. Yields SSE-formatted events. """ if user_id not in self.sse_queues: self.sse_queues[user_id] = asyncio.Queue(maxsize=100) queue = self.sse_queues[user_id] # Send initial connection event yield self._format_sse({"type": "CONNECTED", "user_id": str(user_id)}) try: while True: # Wait for events (with heartbeat) try: event = await asyncio.wait_for(queue.get(), timeout=30) yield self._format_sse(event) except asyncio.TimeoutError: # Send heartbeat yield ":heartbeat\n\n" except asyncio.CancelledError: # Client disconnected if user_id in self.sse_queues and queue is self.sse_queues[user_id]: del self.sse_queues[user_id] def _format_sse(self, data: dict) -> str: """Format data as Server-Sent Event.""" return f"data: {json.dumps(data)}\n\n" async def publish_to_user(self, user_id: int, event: dict): """Publish event to user's SSE queue if exists.""" if user_id in self.sse_queues: try: self.sse_queues[user_id].put_nowait(event) except asyncio.QueueFull: # Queue full, client is slow, remove oldest try: self.sse_queues[user_id].get_nowait() self.sse_queues[user_id].put_nowait(event) except: pass async def broadcast_message(self, message: dict, channel_id: int): """Broadcast message to SSE subscribers.""" # Get users who can see this channel async with self.db.acquire() as conn: rows = await conn.fetch( """SELECT DISTINCT sm.user_id FROM server_members sm JOIN channels c ON c.server_id = sm.server_id WHERE c.id = $1 UNION SELECT user_id FROM dm_channel_members WHERE channel_id = $1""", channel_id ) for row in rows: await self.publish_to_user(row["user_id"], { "type": "MESSAGE_CREATE", "data": message }) async def broadcast_presence(self, user_id: int, status: str): """Broadcast presence update to SSE subscribers.""" # Get relevant users (same logic as WebSocket presence) async with self.db.acquire() as conn: rows = await conn.fetch( """SELECT DISTINCT sm.user_id FROM server_members sm WHERE sm.server_id IN (SELECT server_id FROM server_members WHERE user_id = $1) AND sm.user_id != $1""", user_id ) for row in rows: await self.publish_to_user(row["user_id"], { "type": "PRESENCE_UPDATE", "data": {"user_id": str(user_id), "status": status} }) ``` **SSE HTTP endpoint**: ```python @app.get("/api/v1/sse") async def sse_endpoint( request: Request, token: str ): """ Server-Sent Events endpoint for real-time updates. Use this when WebSocket is not available. Query params: token: Authentication token Events: - MESSAGE_CREATE: New message - MESSAGE_UPDATE: Message edited - MESSAGE_DELETE: Message deleted - PRESENCE_UPDATE: User status changed - TYPING_START: User typing """ # Authenticate user_id = await authenticate_token(token) if not user_id: return Response("Invalid token", status_code=401) handler = SSEHandler(ws_manager, db_pool) async def event_stream(): try: async for event in handler.subscribe(user_id): yield event except asyncio.CancelledError: pass return StreamingResponse( event_stream(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" # Disable nginx buffering } ) ``` **Long-polling fallback**: ```python @app.get("/api/v1/poll") async def long_poll_endpoint( request: Request, token: str, since: Optional[float] = None, timeout: int = 30 ): """ Long-polling endpoint for message updates. Query params: token: Authentication token since: Unix timestamp of last poll timeout: Max wait time (default 30s) Returns new messages since last poll or waits until new message arrives. """ user_id = await authenticate_token(token) if not user_id: return Response("Invalid token", status_code=401) since_time = datetime.fromtimestamp(since, timezone.utc) if since else None # Wait for new messages or timeout start_time = time.time() messages = [] while time.time() - start_time < timeout: # Check for new messages async with db_pool.acquire() as conn: query = """ SELECT m.*, u.username, u.display_name FROM messages m JOIN users u ON m.author_id = u.id JOIN channel_members cm ON cm.channel_id = m.channel_id WHERE cm.user_id = $1 """ params = [user_id] if since_time: query += " AND m.created_at > $2" params.append(since_time) query += " ORDER BY m.created_at ASC LIMIT 50" rows = await conn.fetch(query, *params) if rows: messages = [dict(row) for row in rows] break # Wait a bit before checking again await asyncio.sleep(1) return { "messages": messages, "timestamp": time.time() } ``` **Client-side connection manager**: ```python class ChatClient: """Client-side connection manager with automatic fallback.""" def __init__(self, token: str): self.token = token self.ws = None self.sse = None self.transport = None # 'websocket', 'sse', or 'polling' self.reconnect_delay = 1000 # Start at 1 second async def connect(self): """Try to connect, falling back as needed.""" # Try WebSocket first try: await self._connect_websocket() return except Exception as e: logger.info(f"WebSocket failed: {e}, trying SSE") # Try SSE try: await self._connect_sse() return except Exception as e: logger.info(f"SSE failed: {e}, trying polling") # Fall back to polling await self._connect_polling() async def _connect_websocket(self): """Establish WebSocket connection.""" import websockets self.ws = await websockets.connect( f"ws://localhost/ws?token={self.token}" ) self.transport = 'websocket' self.reconnect_delay = 1000 # Reset delay on success asyncio.create_task(self._listen_websocket()) async def _listen_websocket(self): """Listen for WebSocket messages.""" try: async for message in self.ws: data = json.loads(message) await self._handle_event(data) except: await self.reconnect() async def _connect_sse(self): """Establish SSE connection.""" import aiohttp self.sse = aiohttp.ClientSession() async with self.sse.get( f"http://localhost/api/v1/sse?token={self.token}" ) as response: self.transport = 'sse' async for line in response.content: if line.startswith(b"data: "): data = json.loads(line[6:].decode()) await self._handle_event(data) async def _connect_polling(self): """Use long-polling.""" self.transport = 'polling' self.last_poll = time.time() while True: try: response = await fetch( f"/api/v1/poll?token={self.token}&since={self.last_poll}" ) self.last_poll = response["timestamp"] for msg in response["messages"]: await self._handle_event(msg) except Exception as e: logger.error(f"Polling error: {e}") await asyncio.sleep(5) # Wait before retry async def reconnect(self): """Reconnect with exponential backoff.""" await asyncio.sleep(self.reconnect_delay / 1000) self.reconnect_delay = min(self.reconnect_delay * 2, 30000) # Max 30s await self.connect() ``` ## Acceptance Criteria - [ ] SSE endpoint delivers real-time updates - [ ] SSE connection authenticates correctly - [ ] Long-polling returns new messages - [ ] Client falls back from WebSocket to SSE to polling - [ ] Reconnection works with exponential backoff - [ ] Heartbeat prevents connection timeout ## Notes **Trade-offs**: - SSE vs polling: SSE more efficient but requires HTTP/2 support - Shared event bus: SSE and WebSocket publish to same source **Performance**: - SSE queues limited to 100 events per user - Polling interval minimum 1 second **Alternatives considered**: - WebRTC data channels: Rejected, too complex - Pure HTTP polling: Rejected, too much overhead