File size: 12,899 Bytes
07612e2 579285c 07612e2 579285c 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 579285c 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 5b36da5 07612e2 579285c 07612e2 5b36da5 07612e2 579285c 07612e2 5b36da5 07612e2 579285c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | """
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]
|