Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /websocket_v2.py
| """ | |
| WebSocket v2.0 - Real-time Updates | |
| Q2 2026 Feature | |
| """ | |
| import json | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, Optional, Set | |
| from fastapi import WebSocket, WebSocketDisconnect | |
| logger = logging.getLogger(__name__) | |
| class ConnectionManagerV2: | |
| """Advanced WebSocket connection manager with rooms""" | |
| def __init__(self) -> None: | |
| # Active connections by room | |
| self.rooms: Dict[str, Set[WebSocket]] = { | |
| "dashboard": set(), | |
| "scans": set(), | |
| "findings": set(), | |
| "notifications": set(), | |
| } | |
| # User connections | |
| self.user_connections: Dict[str, WebSocket] = {} | |
| async def connect( | |
| self, | |
| websocket: WebSocket, | |
| room: str = "dashboard", | |
| user_id: Optional[str] = None, | |
| ) -> None: | |
| """Connect client to room. | |
| Args: | |
| websocket: The WebSocket connection. | |
| room: Room name to connect to. | |
| user_id: Optional user ID for user-specific messaging. | |
| """ | |
| await websocket.accept() | |
| if room in self.rooms: | |
| self.rooms[room].add(websocket) | |
| if user_id: | |
| self.user_connections[user_id] = websocket | |
| logger.info("Client connected to room: %s", room) | |
| # Send welcome message | |
| await websocket.send_json( | |
| { | |
| "type": "connection", | |
| "status": "connected", | |
| "room": room, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| ) | |
| def disconnect(self, websocket: WebSocket, room: Optional[str] = None) -> None: | |
| """Disconnect client. | |
| Args: | |
| websocket: The WebSocket connection to disconnect. | |
| room: Optional specific room to disconnect from. | |
| """ | |
| if room and room in self.rooms: | |
| self.rooms[room].discard(websocket) | |
| else: | |
| # Remove from all rooms | |
| for room_set in self.rooms.values(): | |
| room_set.discard(websocket) | |
| # Remove from user connections | |
| user_ids_to_remove = [user_id for user_id, conn in self.user_connections.items() if conn == websocket] | |
| for user_id in user_ids_to_remove: | |
| del self.user_connections[user_id] | |
| logger.info("Client disconnected") | |
| async def broadcast_to_room(self, room: str, message: Dict[str, Any]) -> int: | |
| """Broadcast message to all clients in room. | |
| Args: | |
| room: Room name to broadcast to. | |
| message: Message to send. | |
| Returns: | |
| Number of clients the message was sent to. | |
| """ | |
| if room not in self.rooms: | |
| logger.warning("Attempted to broadcast to unknown room: %s", room) | |
| return 0 | |
| disconnected: Set[WebSocket] = set() | |
| sent_count = 0 | |
| for connection in self.rooms[room]: | |
| try: | |
| await connection.send_json(message) | |
| sent_count += 1 | |
| except Exception as e: | |
| logger.debug("Failed to send message to client: %s", e) | |
| disconnected.add(connection) | |
| # Clean up disconnected clients | |
| for conn in disconnected: | |
| self.rooms[room].discard(conn) | |
| return sent_count | |
| async def send_to_user(self, user_id: str, message: Dict[str, Any]) -> bool: | |
| """Send message to specific user. | |
| Args: | |
| user_id: User ID to send to. | |
| message: Message to send. | |
| Returns: | |
| True if message was sent, False otherwise. | |
| """ | |
| if user_id not in self.user_connections: | |
| logger.debug("User %s not connected", user_id) | |
| return False | |
| try: | |
| await self.user_connections[user_id].send_json(message) | |
| return True | |
| except Exception as e: | |
| logger.warning("Failed to send message to user %s: %s", user_id, e) | |
| del self.user_connections[user_id] | |
| return False | |
| async def broadcast_scan_update(self, scan_id: str, status: str, progress: Optional[int] = None) -> int: | |
| """Broadcast scan progress update. | |
| Args: | |
| scan_id: Scan identifier. | |
| status: Current scan status. | |
| progress: Optional progress percentage. | |
| Returns: | |
| Number of clients the update was sent to. | |
| """ | |
| return await self.broadcast_to_room( | |
| "scans", | |
| { | |
| "type": "scan_update", | |
| "scan_id": scan_id, | |
| "status": status, | |
| "progress": progress, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| }, | |
| ) | |
| async def broadcast_finding(self, finding: Dict[str, Any]) -> int: | |
| """Broadcast new finding discovery. | |
| Args: | |
| finding: Finding data to broadcast. | |
| Returns: | |
| Number of clients the finding was sent to. | |
| """ | |
| return await self.broadcast_to_room( | |
| "findings", | |
| { | |
| "type": "new_finding", | |
| "finding": finding, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| }, | |
| ) | |
| async def broadcast_notification(self, title: str, message: str, severity: str = "info") -> int: | |
| """Broadcast system notification. | |
| Args: | |
| title: Notification title. | |
| message: Notification message. | |
| severity: Severity level (info, warning, error, critical). | |
| Returns: | |
| Number of clients the notification was sent to. | |
| """ | |
| return await self.broadcast_to_room( | |
| "notifications", | |
| { | |
| "type": "notification", | |
| "title": title, | |
| "message": message, | |
| "severity": severity, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| }, | |
| ) | |
| def get_room_stats(self) -> Dict[str, int]: | |
| """Get connection statistics. | |
| Returns: | |
| Dictionary mapping room names to connection counts. | |
| """ | |
| return {room: len(connections) for room, connections in self.rooms.items()} | |
| # Global manager instance | |
| manager_v2 = ConnectionManagerV2() | |
| async def _handle_client_message(websocket: WebSocket, message: Dict[str, Any]) -> None: | |
| """Handle incoming client message. | |
| Args: | |
| websocket: The WebSocket connection. | |
| message: Parsed message from client. | |
| """ | |
| action = message.get("action") | |
| if action == "ping": | |
| await websocket.send_json( | |
| { | |
| "type": "pong", | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| ) | |
| elif action == "subscribe_scan": | |
| scan_id = message.get("scan_id") | |
| await websocket.send_json( | |
| { | |
| "type": "subscribed", | |
| "scan_id": scan_id, | |
| "message": f"Subscribed to scan {scan_id} updates", | |
| } | |
| ) | |
| async def websocket_dashboard_endpoint(websocket: WebSocket) -> None: | |
| """Dashboard real-time updates endpoint. | |
| Args: | |
| websocket: The WebSocket connection. | |
| """ | |
| await manager_v2.connect(websocket, room="dashboard") | |
| try: | |
| while True: | |
| # Receive ping from client | |
| data = await websocket.receive_text() | |
| try: | |
| message = json.loads(data) | |
| await _handle_client_message(websocket, message) | |
| except json.JSONDecodeError as e: | |
| logger.warning("Invalid JSON received: %s", e) | |
| await websocket.send_json({"type": "error", "message": "Invalid JSON"}) | |
| except WebSocketDisconnect: | |
| manager_v2.disconnect(websocket, room="dashboard") | |
| except Exception as e: | |
| logger.error("Error in dashboard websocket: %s", e) | |
| manager_v2.disconnect(websocket, room="dashboard") | |
| async def websocket_scans_endpoint(websocket: WebSocket) -> None: | |
| """Scan progress real-time updates endpoint. | |
| Args: | |
| websocket: The WebSocket connection. | |
| """ | |
| await manager_v2.connect(websocket, room="scans") | |
| try: | |
| while True: | |
| data = await websocket.receive_text() | |
| try: | |
| message = json.loads(data) | |
| await _handle_client_message(websocket, message) | |
| except json.JSONDecodeError as e: | |
| logger.warning("Invalid JSON received: %s", e) | |
| await websocket.send_json({"type": "error", "message": "Invalid JSON"}) | |
| except WebSocketDisconnect: | |
| manager_v2.disconnect(websocket, room="scans") | |
| except Exception as e: | |
| logger.error("Error in scans websocket: %s", e) | |
| manager_v2.disconnect(websocket, room="scans") | |
| async def websocket_notifications_endpoint(websocket: WebSocket, user_id: Optional[str] = None) -> None: | |
| """User-specific notifications endpoint. | |
| Args: | |
| websocket: The WebSocket connection. | |
| user_id: Optional user ID for user-specific messaging. | |
| """ | |
| await manager_v2.connect(websocket, room="notifications", user_id=user_id) | |
| try: | |
| while True: | |
| data = await websocket.receive_text() | |
| try: | |
| message = json.loads(data) | |
| await _handle_client_message(websocket, message) | |
| except json.JSONDecodeError as e: | |
| logger.warning("Invalid JSON received: %s", e) | |
| await websocket.send_json({"type": "error", "message": "Invalid JSON"}) | |
| except WebSocketDisconnect: | |
| manager_v2.disconnect(websocket, room="notifications") | |
| except Exception as e: | |
| logger.error("Error in notifications websocket: %s", e) | |
| manager_v2.disconnect(websocket, room="notifications") | |
Xet Storage Details
- Size:
- 9.9 kB
- Xet hash:
- 7f605f45e583e05cfed57062307d51357b2b99d346e89450a5da9635f3bc9713
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.