""" Server-Sent Events (SSE) implementation for YAZ Care Platform Replaces WebSocket connections with HTMX-compatible SSE streams """ import asyncio import json import time from datetime import UTC, datetime, timezone from typing import Any, AsyncGenerator, Dict, Optional import structlog from fastapi import APIRouter, Depends, Request from fastapi.responses import StreamingResponse from shared.db import get_db from sqlalchemy.orm import Session # Use standard logging logger = structlog.get_logger(__name__) sse_router = APIRouter(prefix="/events", tags=["sse"]) class SSEManager: """Manages Server-Sent Events streams""" def __init__(self): self.active_streams: dict[str, int] = {} def register_stream(self, stream_id: str): """Register a new active stream""" self.active_streams[stream_id] = int(time.time()) logger.info(f"SSE stream registered: {stream_id} (total: {len(self.active_streams)})") def unregister_stream(self, stream_id: str): """Unregister an inactive stream""" if stream_id in self.active_streams: del self.active_streams[stream_id] logger.info(f"SSE stream unregistered: {stream_id} (total: {len(self.active_streams)})") def get_active_count(self) -> int: """Get number of active streams""" return len(self.active_streams) sse_manager = SSEManager() def format_sse(data: dict[str, Any], event: str | None = None, retry: int | None = None) -> str: """ Format data as Server-Sent Event Args: data: Dictionary to send as JSON event: Event type (optional) retry: Reconnection time in milliseconds (optional) Returns: Formatted SSE string """ message = "" if event: message += f"event: {event}\n" if retry: message += f"retry: {retry}\n" # Split data into multiple lines if needed json_data = json.dumps(data) for line in json_data.split("\n"): message += f"data: {line}\n" message += "\n" # Extra newline to signal end of event return message async def event_generator( stream_id: str, interval: int = 5, max_events: int | None = None ) -> AsyncGenerator[str, None]: """ Base event generator for SSE streams Args: stream_id: Unique identifier for this stream interval: Seconds between events max_events: Maximum number of events to send (None = infinite) Yields: SSE-formatted event strings """ sse_manager.register_stream(stream_id) try: event_count = 0 # Send initial connection confirmation yield format_sse( { "type": "connected", "stream_id": stream_id, "timestamp": datetime.now(UTC).isoformat(), }, event="connection", ) # Main event loop while max_events is None or event_count < max_events: await asyncio.sleep(interval) # Send heartbeat yield format_sse( { "type": "heartbeat", "timestamp": datetime.now(UTC).isoformat(), "count": event_count, }, event="heartbeat", ) event_count += 1 except asyncio.CancelledError: logger.info(f"SSE stream cancelled: {stream_id}") finally: sse_manager.unregister_stream(stream_id) @sse_router.get("/dashboard") async def dashboard_events(request: Request): """ SSE endpoint for real-time dashboard updates Replaces WebSocket connection in src/core/dashboard/routes.py """ client_id = f"dashboard_{request.client.host}_{int(time.time())}" # type: ignore[union-attr] async def dashboard_generator(): sse_manager.register_stream(client_id) try: # Send connection confirmation yield format_sse( {"type": "connected", "message": "Dashboard events stream connected"}, event="connection", ) # Main update loop while True: # Simulate dashboard metrics (replace with real data) metrics = { "active_users": 42, "pending_orders": 15, "cpu_usage": 45.2, "memory_usage": 62.8, "timestamp": datetime.now(UTC).isoformat(), } yield format_sse(metrics, event="dashboard_update") await asyncio.sleep(5) # Update every 5 seconds except asyncio.CancelledError: logger.info(f"Dashboard stream cancelled: {client_id}") finally: sse_manager.unregister_stream(client_id) return StreamingResponse( dashboard_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", # Disable nginx buffering "Connection": "keep-alive", }, ) @sse_router.get("/surgio/operations") async def surgio_operations_events(request: Request, db: Session = Depends(get_db)): """ SSE endpoint for surgical operations real-time updates Replaces WebSocket in src/ui/templates/apps/surgio.html """ client_id = f"surgio_{request.client.host}_{int(time.time())}" # type: ignore[union-attr] async def surgio_generator(): sse_manager.register_stream(client_id) try: # Send connection confirmation yield format_sse( {"type": "connected", "message": "Surgio events stream connected"}, event="connection", ) # Main update loop while True: # Get active operations (replace with real query) operations_data = { "active_operations": [ { "id": 1, "patient": "Smith, John", "procedure": "Appendectomy", "status": "in_progress", "start_time": "14:30", "progress": 45, }, { "id": 2, "patient": "Doe, Jane", "procedure": "Knee Arthroscopy", "status": "prep", "start_time": "15:00", "progress": 10, }, ], "timestamp": datetime.now(UTC).isoformat(), } yield format_sse(operations_data, event="operations_update") await asyncio.sleep(3) # Update every 3 seconds except asyncio.CancelledError: logger.info(f"Surgio stream cancelled: {client_id}") finally: sse_manager.unregister_stream(client_id) return StreamingResponse( surgio_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive", }, ) @sse_router.get("/notifications") async def notifications_events(request: Request): """ SSE endpoint for user notifications """ client_id = f"notifications_{request.client.host}_{int(time.time())}" # type: ignore[union-attr] async def notifications_generator(): sse_manager.register_stream(client_id) try: # Send connection confirmation yield format_sse( {"type": "connected", "message": "Notifications stream connected"}, event="connection", ) # Simulated notification stream notification_count = 0 while True: await asyncio.sleep(10) # Check every 10 seconds # Simulate occasional notifications if notification_count % 3 == 0: notification = { "id": notification_count, "title": "New Lab Result", "message": "Lab results are ready for Patient #12345", "severity": "info", "timestamp": datetime.now(UTC).isoformat(), } yield format_sse(notification, event="notification") notification_count += 1 except asyncio.CancelledError: logger.info(f"Notifications stream cancelled: {client_id}") finally: sse_manager.unregister_stream(client_id) return StreamingResponse( notifications_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive", }, ) @sse_router.get("/sse-health") async def sse_health(): """ Health check endpoint for SSE service """ return { "status": "healthy", "service": "sse", "active_streams": sse_manager.get_active_count(), "timestamp": datetime.now(UTC).isoformat(), } # Helper functions for integration async def broadcast_to_stream( event_type: str, data: dict[str, Any], stream_filter: str | None = None ): """ Broadcast event to active SSE streams Args: event_type: Type of event to broadcast data: Event data dictionary stream_filter: Optional filter for stream IDs (e.g., "dashboard_*") """ # This would require storing stream generators, which is complex # For now, clients poll the SSE endpoints # Future: Implement with Redis pub/sub or similar logger.info(f"Broadcasting {event_type} to streams (filter: {stream_filter})") pass def create_sse_response(generator: AsyncGenerator) -> StreamingResponse: """ Helper to create SSE StreamingResponse with proper headers Args: generator: Async generator yielding SSE-formatted strings Returns: StreamingResponse configured for SSE """ return StreamingResponse( generator, media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive", }, )