""" WebSocket Connection Manager with Redis Pub/Sub fan-out. Each API worker process tracks its own live WebSocket objects in memory. When code calls broadcast_to_workspace / send_to_user / etc., the message is published to a Redis channel. A background subscriber task running inside EVERY worker process receives the published message and delivers it to whichever WebSocket objects that process happens to hold. This means one broadcast call reaches every connected client regardless of which worker process they are connected to — a prerequisite for horizontal scaling beyond a single process. Fallback: if Redis is unavailable, all four broadcast methods fall back to direct local delivery so single-process deployments are unaffected. """ import asyncio import json import logging from typing import Any, Dict, List, Optional, Set from uuid import UUID from datetime import datetime from enum import Enum from fastapi import WebSocket logger = logging.getLogger(__name__) class NexusJSONEncoder(json.JSONEncoder): """Custom encoder to handle Nexus-specific types in WebSockets.""" def default(self, obj): if isinstance(obj, Enum): return obj.value if isinstance(obj, (UUID, datetime)): return str(obj) return super().default(obj) # ── Redis channel naming ──────────────────────────────────────────────────── # # nexus:ws:workspace:{uuid} # nexus:ws:user:{uuid} # nexus:ws:role:{workspace_uuid}:{role_str} # nexus:ws:ticket:{uuid} _PATTERN = "nexus:ws:*" class ConnectionManager: def __init__(self): self.lock = asyncio.Lock() # In-process connection maps (per-worker only) self.active_connections: Dict[UUID, Set[WebSocket]] = {} self.user_connections: Dict[UUID, List[WebSocket]] = {} self.role_connections: Dict[tuple, Set[WebSocket]] = {} self.ticket_connections: Dict[UUID, Set[WebSocket]] = {} # Redis pub/sub self._subscriber_task: Optional[asyncio.Task] = None self._pub_redis = None # lazy-init publish client self._redis_url: Optional[str] = None # ── Lifecycle ──────────────────────────────────────────────────────────── # async def start_pubsub(self, redis_url: str): """ Called once per worker process at startup. Launches the background subscriber that delivers cross-process messages to WebSocket connections held by this process. """ self._redis_url = redis_url self._subscriber_task = asyncio.create_task( self._subscriber_loop(redis_url), name="nexus_ws_pubsub_subscriber", ) logger.info("WebSocket Redis pub/sub subscriber started.") async def stop_pubsub(self): """Cancel subscriber and close publish client on worker shutdown.""" if self._subscriber_task and not self._subscriber_task.done(): self._subscriber_task.cancel() try: await self._subscriber_task except asyncio.CancelledError: pass if self._pub_redis: try: await self._pub_redis.aclose() except Exception: pass # ── Internal: publish ─────────────────────────────────────────────────── # async def _get_pub_redis(self): """ Lazy-initialise a dedicated async Redis client for publishing. Uses the same local Redis URL as the subscriber so both publish and subscribe traffic stays off cloud/billed Redis instances. """ if self._pub_redis is None: import redis.asyncio as aioredis url = self._redis_url or "redis://localhost:6379" self._pub_redis = aioredis.from_url( url, encoding="utf-8", decode_responses=True, socket_connect_timeout=5.0, socket_timeout=5.0, socket_keepalive=True, ) return self._pub_redis async def _publish(self, channel: str, message: Any) -> bool: """ Publish a serialised message to a Redis pub/sub channel. Returns True on success. On failure callers use local fallback. """ try: payload = json.dumps(message, cls=NexusJSONEncoder) r = await self._get_pub_redis() await r.publish(channel, payload) return True except Exception as exc: logger.warning(f"WebSocket Redis publish failed on {channel}: {exc}") return False # ── Internal: subscriber loop ─────────────────────────────────────────── # async def _subscriber_loop(self, redis_url: str): """ Long-lived background task. Subscribes to nexus:ws:* and calls _dispatch_local() for every received message so this process's WebSocket connections receive cross-process broadcasts. IMPORTANT: redis_url must point at the LOCAL Redis, not a cloud/serverless Redis (e.g. Upstash). Cloud providers impose idle-connection timeouts and bill per command — both incompatible with a persistent pub/sub listener. The local Redis (started by run_prod.sh) has no such limits. """ import redis.asyncio as aioredis kwargs: dict = { "encoding": "utf-8", "decode_responses": True, "socket_connect_timeout": 5.0, "socket_keepalive": True, } while True: sub_redis = None try: sub_redis = aioredis.from_url(redis_url, **kwargs) pubsub = sub_redis.pubsub() await pubsub.psubscribe(_PATTERN) logger.info("WebSocket subscriber: listening on nexus:ws:*") async for message in pubsub.listen(): if message["type"] != "pmessage": continue await self._dispatch_local( channel=message["channel"], payload=message["data"], ) except asyncio.CancelledError: logger.info("WebSocket pub/sub subscriber cancelled.") break except Exception as exc: logger.warning(f"WebSocket subscriber error — reconnecting in 2 s: {exc}") await asyncio.sleep(2) finally: if sub_redis: try: await sub_redis.aclose() except Exception: pass async def _dispatch_local(self, channel: str, payload: str): """ Route a Redis pub/sub message to local WebSocket connections for the appropriate target derived from the channel name. Channel formats: nexus:ws:workspace:{uuid} nexus:ws:user:{uuid} nexus:ws:role:{ws_uuid}:{role} nexus:ws:ticket:{uuid} """ try: # Strip the fixed prefix "nexus:ws:" → split the remainder # parts example: ["workspace", "550e8400-e29b-..."] parts = channel.split(":", 3) # ["nexus", "ws", type, rest] if len(parts) < 4: return target_type, rest = parts[2], parts[3] connections: list = [] map_key = None map_ref = None if target_type == "workspace": ws_id = UUID(rest) map_key = ws_id async with self.lock: connections = list(self.active_connections.get(ws_id, set())) map_ref = self.active_connections elif target_type == "user": user_id = UUID(rest) map_key = user_id async with self.lock: connections = list(self.user_connections.get(user_id, [])) map_ref = self.user_connections elif target_type == "role": # rest = "{ws_uuid}:{role}" role_parts = rest.split(":", 1) if len(role_parts) == 2: ws_id, role = UUID(role_parts[0]), role_parts[1] map_key = (ws_id, role) async with self.lock: connections = list(self.role_connections.get(map_key, set())) map_ref = self.role_connections elif target_type == "ticket": ticket_id = UUID(rest) map_key = ticket_id async with self.lock: connections = list(self.ticket_connections.get(ticket_id, set())) map_ref = self.ticket_connections if connections: payload_str = payload if isinstance(payload, str) else payload dead = await self._send_all(connections, payload_str) if dead and map_ref is not None and map_key is not None: async with self.lock: bucket = map_ref.get(map_key) if bucket is not None: if isinstance(bucket, set): bucket -= dead if not bucket: map_ref.pop(map_key, None) elif isinstance(bucket, list): for d in dead: try: bucket.remove(d) except ValueError: pass if not bucket: map_ref.pop(map_key, None) except Exception as exc: logger.debug(f"WebSocket dispatch error on channel {channel}: {exc}") # ── Connection registration ───────────────────────────────────────────── # async def connect( self, websocket: WebSocket, workspace_id: UUID, user_id: Optional[UUID] = None, role: Optional[str] = None, ): """Accept a WebSocket connection and register it in this process's maps.""" await websocket.accept() async with self.lock: if workspace_id not in self.active_connections: self.active_connections[workspace_id] = set() self.active_connections[workspace_id].add(websocket) if user_id: if user_id not in self.user_connections: self.user_connections[user_id] = [] self.user_connections[user_id].append(websocket) if role: key = (workspace_id, role.lower()) if key not in self.role_connections: self.role_connections[key] = set() self.role_connections[key].add(websocket) async def disconnect( self, websocket: WebSocket, workspace_id: UUID, user_id: Optional[UUID] = None, role: Optional[str] = None, ): """Remove a WebSocket connection from this process's maps.""" async with self.lock: if workspace_id in self.active_connections: self.active_connections[workspace_id].discard(websocket) if not self.active_connections[workspace_id]: del self.active_connections[workspace_id] if user_id and user_id in self.user_connections: try: self.user_connections[user_id].remove(websocket) except ValueError: pass if not self.user_connections[user_id]: del self.user_connections[user_id] if role: key = (workspace_id, role.lower()) if key in self.role_connections: self.role_connections[key].discard(websocket) if not self.role_connections[key]: del self.role_connections[key] async def connect_ticket(self, websocket: WebSocket, ticket_id: UUID): await websocket.accept() async with self.lock: if ticket_id not in self.ticket_connections: self.ticket_connections[ticket_id] = set() self.ticket_connections[ticket_id].add(websocket) async def disconnect_ticket(self, websocket: WebSocket, ticket_id: UUID): async with self.lock: if ticket_id in self.ticket_connections: self.ticket_connections[ticket_id].discard(websocket) if not self.ticket_connections[ticket_id]: del self.ticket_connections[ticket_id] # ── Internal: safe send ───────────────────────────────────────────────── # async def _send_all(self, connections: list, payload: str) -> set: """ Send payload to all given connections concurrently. Returns the set of dead connections so callers can prune them. """ async def _try(ws: WebSocket): try: await ws.send_text(payload) return None except Exception: return ws results = await asyncio.gather(*[_try(c) for c in connections]) return {r for r in results if r is not None} # ── Public broadcast API ──────────────────────────────────────────────── # # Each method publishes to Redis so ALL worker processes receive the # message via their subscriber loop. If Redis is unavailable the method # falls back to local delivery only (graceful degradation). async def broadcast_to_workspace(self, workspace_id: UUID, message: Any): """Fan-out to every connection in a workspace across all worker processes.""" channel = f"nexus:ws:workspace:{workspace_id}" if not await self._publish(channel, message): # Redis down — deliver locally only async with self.lock: conns = list(self.active_connections.get(workspace_id, set())) if conns: payload = json.dumps(message, cls=NexusJSONEncoder) dead = await self._send_all(conns, payload) if dead: async with self.lock: for c in dead: self.active_connections[workspace_id].discard(c) async def send_to_user(self, user_id: UUID, message: Any): """Fan-out to all sessions of a single user across all worker processes.""" channel = f"nexus:ws:user:{user_id}" if not await self._publish(channel, message): async with self.lock: conns = list(self.user_connections.get(user_id, [])) if conns: payload = json.dumps(message, cls=NexusJSONEncoder) dead = await self._send_all(conns, payload) if dead: async with self.lock: for c in dead: try: self.user_connections[user_id].remove(c) except ValueError: pass if not self.user_connections.get(user_id): self.user_connections.pop(user_id, None) async def broadcast_to_role(self, workspace_id: UUID, role: str, message: Any): """Fan-out to all users with a given role in a workspace.""" channel = f"nexus:ws:role:{workspace_id}:{role.lower()}" if not await self._publish(channel, message): key = (workspace_id, role.lower()) async with self.lock: conns = list(self.role_connections.get(key, set())) if conns: payload = json.dumps(message, cls=NexusJSONEncoder) dead = await self._send_all(conns, payload) if dead: async with self.lock: for c in dead: self.role_connections[key].discard(c) async def broadcast_to_ticket(self, ticket_id: UUID, message: Any): """Fan-out to all subscribers of a ticket thread.""" channel = f"nexus:ws:ticket:{ticket_id}" if not await self._publish(channel, message): async with self.lock: conns = list(self.ticket_connections.get(ticket_id, set())) if conns: payload = json.dumps(message, cls=NexusJSONEncoder) dead = await self._send_all(conns, payload) if dead: async with self.lock: for c in dead: self.ticket_connections[ticket_id].discard(c) manager = ConnectionManager()