Handler for Server-Sent Events (SSE) for real-time progress updates
| 27 | print("✅ RAG Agent initialized successfully.") |
| 28 | |
| 29 | class ServerSentEventsHandler: |
| 30 | """Handler for Server-Sent Events (SSE) for real-time progress updates""" |
| 31 | |
| 32 | active_connections: Dict[str, Any] = {} |
| 33 | |
| 34 | @classmethod |
| 35 | def add_connection(cls, session_id: str, response_handler): |
| 36 | """Add a new SSE connection""" |
| 37 | cls.active_connections[session_id] = response_handler |
| 38 | logger.info(f"SSE connection added for session: {session_id}") |
| 39 | |
| 40 | @classmethod |
| 41 | def remove_connection(cls, session_id: str): |
| 42 | """Remove an SSE connection""" |
| 43 | if session_id in cls.active_connections: |
| 44 | del cls.active_connections[session_id] |
| 45 | logger.info(f"SSE connection removed for session: {session_id}") |
| 46 | |
| 47 | @classmethod |
| 48 | def send_event(cls, session_id: str, event_type: str, data: Dict[str, Any]): |
| 49 | """Send an SSE event to a specific session""" |
| 50 | if session_id not in cls.active_connections: |
| 51 | return |
| 52 | |
| 53 | try: |
| 54 | handler = cls.active_connections[session_id] |
| 55 | event_data = json.dumps(data) |
| 56 | message = f"event: {event_type}\ndata: {event_data}\n\n" |
| 57 | handler.wfile.write(message.encode('utf-8')) |
| 58 | handler.wfile.flush() |
| 59 | except Exception as e: |
| 60 | logger.error(f"Failed to send SSE event: {e}") |
| 61 | cls.remove_connection(session_id) |
| 62 | |
| 63 | class RealtimeProgressTracker(ProgressTracker): |
| 64 | """Enhanced ProgressTracker that sends updates via Server-Sent Events""" |
nothing calls this directly
no outgoing calls
no test coverage detected