Download src/shared/websocket.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/websocket.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/shared/websocket.py
-
curl -L -o websocket.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/websocket.py
12.9 kB
| """ | |
| WebSocket Manager for Real-time Card Updates | |
| Provides real-time updates for dashboard cards and notifications | |
| """ | |
| from fastapi import WebSocket, WebSocketDisconnect | |
| from typing import Dict, List, Set, Any | |
| import json | |
| import asyncio | |
| import uuid | |
| from datetime import datetime | |
| import structlog | |
| import random | |
| from datetime import timedelta | |
| logger = structlog.get_logger(__name__) | |
| class ConnectionManager: | |
| """Manages WebSocket connections for real-time updates""" | |
| def __init__(self): | |
| # Active connections grouped by room/dashboard | |
| self.active_connections: Dict[str, Set[WebSocket]] = {} | |
| # Connection metadata | |
| self.connection_info: Dict[WebSocket, Dict[str, Any]] = {} | |
| async def connect(self, websocket: WebSocket, client_id: str, dashboard_id: str = "main"): | |
| """Accept WebSocket connection and add to room""" | |
| await websocket.accept() | |
| # Add to room | |
| if dashboard_id not in self.active_connections: | |
| self.active_connections[dashboard_id] = set() | |
| self.active_connections[dashboard_id].add(websocket) | |
| # Store connection info | |
| self.connection_info[websocket] = { | |
| "client_id": client_id, | |
| "dashboard_id": dashboard_id, | |
| "connected_at": datetime.utcnow(), | |
| "last_activity": datetime.utcnow(), | |
| } | |
| logger.info(f"Client {client_id} connected to dashboard {dashboard_id}") | |
| # Send welcome message | |
| await self.send_personal_message( | |
| { | |
| "type": "connection_established", | |
| "client_id": client_id, | |
| "dashboard_id": dashboard_id, | |
| "timestamp": datetime.utcnow().isoformat(), | |
| }, | |
| websocket, | |
| ) | |
| def disconnect(self, websocket: WebSocket): | |
| """Remove WebSocket connection""" | |
| if websocket in self.connection_info: | |
| info = self.connection_info[websocket] | |
| dashboard_id = info["dashboard_id"] | |
| client_id = info["client_id"] | |
| # Remove from room | |
| if dashboard_id in self.active_connections: | |
| self.active_connections[dashboard_id].discard(websocket) | |
| if not self.active_connections[dashboard_id]: | |
| del self.active_connections[dashboard_id] | |
| # Remove connection info | |
| del self.connection_info[websocket] | |
| logger.info(f"Client {client_id} disconnected from dashboard {dashboard_id}") | |
| async def send_personal_message(self, message: Dict[str, Any], websocket: WebSocket): | |
| """Send message to specific connection""" | |
| try: | |
| await websocket.send_text(json.dumps(message)) | |
| except Exception as e: | |
| logger.error(f"Failed to send message to websocket: {e}") | |
| self.disconnect(websocket) | |
| async def broadcast_to_dashboard(self, message: Dict[str, Any], dashboard_id: str = "main"): | |
| """Broadcast message to all connections in a dashboard""" | |
| if dashboard_id not in self.active_connections: | |
| return | |
| # Add timestamp | |
| message["timestamp"] = datetime.utcnow().isoformat() | |
| message_text = json.dumps(message) | |
| # Send to all connections in the dashboard | |
| disconnected = [] | |
| for connection in self.active_connections[dashboard_id].copy(): | |
| try: | |
| await connection.send_text(message_text) | |
| # Update last activity | |
| if connection in self.connection_info: | |
| self.connection_info[connection]["last_activity"] = datetime.utcnow() | |
| except Exception as e: | |
| logger.error(f"Failed to broadcast to connection: {e}") | |
| disconnected.append(connection) | |
| # Clean up disconnected connections | |
| for connection in disconnected: | |
| self.disconnect(connection) | |
| async def broadcast_card_update(self, card_data: Dict[str, Any], dashboard_id: str = "main"): | |
| """Broadcast card update to dashboard""" | |
| message = {"type": "card_update", "card": card_data, "update_id": str(uuid.uuid4())} | |
| await self.broadcast_to_dashboard(message, dashboard_id) | |
| async def broadcast_notification( | |
| self, notification: Dict[str, Any], dashboard_id: str = "main" | |
| ): | |
| """Broadcast notification to dashboard""" | |
| message = { | |
| "type": "notification", | |
| "notification": { | |
| "id": str(uuid.uuid4()), | |
| "timestamp": datetime.utcnow().isoformat(), | |
| **notification, | |
| }, | |
| } | |
| await self.broadcast_to_dashboard(message, dashboard_id) | |
| async def broadcast_system_status(self, status: Dict[str, Any], dashboard_id: str = "main"): | |
| """Broadcast system status update""" | |
| message = {"type": "system_status", "status": status} | |
| await self.broadcast_to_dashboard(message, dashboard_id) | |
| def get_dashboard_stats(self) -> Dict[str, Any]: | |
| """Get connection statistics""" | |
| stats = { | |
| "total_connections": len(self.connection_info), | |
| "dashboards": {}, | |
| "uptime": datetime.utcnow().isoformat(), | |
| } | |
| for dashboard_id, connections in self.active_connections.items(): | |
| stats["dashboards"][dashboard_id] = { # type: ignore[name-defined, index, return-value, var-annotated] | |
| "active_connections": len(connections), | |
| "clients": [ | |
| { | |
| "client_id": self.connection_info[conn]["client_id"], | |
| "connected_at": self.connection_info[conn]["connected_at"].isoformat(), | |
| "last_activity": self.connection_info[conn]["last_activity"].isoformat(), | |
| } | |
| for conn in connections | |
| if conn in self.connection_info | |
| ], | |
| } | |
| return stats | |
| # Global connection manager instance | |
| connection_manager = ConnectionManager() | |
| class RealtimeUpdater: | |
| """Handles real-time updates for various platform events""" | |
| def __init__(self, connection_manager: ConnectionManager): | |
| self.manager = connection_manager | |
| self.update_queue: asyncio.Queue = asyncio.Queue() | |
| self.running = False | |
| async def start_background_updates(self): | |
| """Start background task for processing updates""" | |
| self.running = True | |
| asyncio.create_task(self._process_updates()) | |
| async def stop_background_updates(self): | |
| """Stop background updates""" | |
| self.running = False | |
| async def _process_updates(self): | |
| """Background task to process queued updates""" | |
| while self.running: | |
| try: | |
| # Process update queue | |
| if not self.update_queue.empty(): | |
| update = await self.update_queue.get() | |
| await self._handle_update(update) | |
| # Send periodic system heartbeat | |
| await self.send_system_heartbeat() | |
| # Wait before next iteration | |
| await asyncio.sleep(5) | |
| except Exception as e: | |
| logger.error(f"Error in background updates: {e}") | |
| await asyncio.sleep(1) | |
| async def _handle_update(self, update: Dict[str, Any]): | |
| """Handle a specific update""" | |
| update_type = update.get("type") | |
| dashboard_id = update.get("dashboard_id", "main") | |
| if update_type == "card_update": | |
| await self.manager.broadcast_card_update(update["data"], dashboard_id) | |
| elif update_type == "notification": | |
| await self.manager.broadcast_notification(update["data"], dashboard_id) | |
| elif update_type == "system_status": | |
| await self.manager.broadcast_system_status(update["data"], dashboard_id) | |
| async def queue_card_update(self, card_data: Dict[str, Any], dashboard_id: str = "main"): | |
| """Queue a card update for broadcast""" | |
| await self.update_queue.put( | |
| {"type": "card_update", "data": card_data, "dashboard_id": dashboard_id} | |
| ) | |
| async def queue_notification(self, notification: Dict[str, Any], dashboard_id: str = "main"): | |
| """Queue a notification for broadcast""" | |
| await self.update_queue.put( | |
| {"type": "notification", "data": notification, "dashboard_id": dashboard_id} | |
| ) | |
| async def send_system_heartbeat(self): | |
| """Send system heartbeat to all dashboards""" | |
| heartbeat = { | |
| "type": "heartbeat", | |
| "server_time": datetime.utcnow().isoformat(), | |
| "active_connections": len(self.manager.connection_info), | |
| } | |
| for dashboard_id in self.manager.active_connections: | |
| await self.manager.broadcast_to_dashboard(heartbeat, dashboard_id) | |
| # Global realtime updater | |
| realtime_updater = RealtimeUpdater(connection_manager) | |
| class RealtimeCardUpdater: | |
| """Generates periodic card updates for demonstration""" | |
| def __init__(self, connection_manager): | |
| self.connection_manager = connection_manager | |
| self.is_running = False | |
| self.update_interval = 10 # seconds | |
| async def start(self): | |
| """Start the background update task""" | |
| self.is_running = True | |
| asyncio.create_task(self._update_loop()) | |
| logger.info("Real-time card updater started") | |
| def stop(self): | |
| """Stop the background update task""" | |
| self.is_running = False | |
| logger.info("Real-time card updater stopped") | |
| async def _update_loop(self): | |
| """Background loop to generate card updates""" | |
| while self.is_running: | |
| try: | |
| await asyncio.sleep(self.update_interval) | |
| # Generate sample card updates | |
| await self._generate_sample_updates() | |
| except Exception as e: | |
| logger.error(f"Error in card update loop: {e}") | |
| await asyncio.sleep(5) # Short delay before retry | |
| async def _generate_sample_updates(self): | |
| """Generate sample card updates for demonstration""" | |
| # Sample metric card updates | |
| metrics_updates = [ | |
| { | |
| "type": "card_update", | |
| "card_id": "active_patients", | |
| "card_data": { | |
| "value": random.randint(150, 200), | |
| "delta": f"{random.randint(-5, 15):+d}", | |
| "delta_type": "positive" if random.random() > 0.3 else "negative", | |
| }, | |
| }, | |
| { | |
| "type": "card_update", | |
| "card_id": "pending_surgeries", | |
| "card_data": { | |
| "value": random.randint(8, 25), | |
| "delta": f"{random.randint(-3, 8):+d}", | |
| "delta_type": "positive" if random.random() > 0.4 else "negative", | |
| }, | |
| }, | |
| { | |
| "type": "card_update", | |
| "card_id": "room_occupancy", | |
| "card_data": { | |
| "value": random.randint(65, 95), | |
| "progress": random.randint(65, 95), | |
| "status": "warning" if random.randint(65, 95) > 85 else "success", | |
| }, | |
| }, | |
| ] | |
| # Send updates to all connected dashboards | |
| for update in metrics_updates: | |
| await self.connection_manager.broadcast_to_dashboard(update) | |
| # Occasionally send notifications | |
| if random.random() < 0.3: # 30% chance | |
| notification = { | |
| "type": "notification", | |
| "notification": { | |
| "message": random.choice( | |
| [ | |
| "New patient admission in Emergency", | |
| "Surgery completed successfully", | |
| "Lab results available for Room 205", | |
| "Daily backup completed", | |
| "System maintenance in 1 hour", | |
| ] | |
| ), | |
| "type": random.choice(["info", "success", "warning"]), | |
| }, | |
| } | |
| await self.connection_manager.broadcast_to_dashboard(notification) | |
| # Global instances | |
| connection_manager = ConnectionManager() | |
| realtime_updater = RealtimeCardUpdater(connection_manager) # type: ignore[arg-type, assignment] | |
| # Start the real-time updater when module is imported | |
| async def start_realtime_updates(): | |
| """Start the real-time update service""" | |
| await realtime_updater.start() # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| def stop_realtime_updates(): | |
| """Stop the real-time update service""" | |
| realtime_updater.stop() # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |