|
| 1 | +""" |
| 2 | +WebSocket endpoint for real-time playground indexing progress. |
| 3 | +
|
| 4 | +This provides instant updates as files are indexed, giving users |
| 5 | +a smooth streaming experience instead of polling every 2 seconds. |
| 6 | +
|
| 7 | +Channel format: job:{job_id}:events |
| 8 | +Message types: connected, cloning, progress, completed, error |
| 9 | +""" |
| 10 | +import json |
| 11 | +import asyncio |
| 12 | +from typing import Optional |
| 13 | + |
| 14 | +from fastapi import WebSocket, WebSocketDisconnect |
| 15 | + |
| 16 | +from dependencies import redis_client |
| 17 | +from services.observability import logger |
| 18 | +from services.anonymous_indexer import AnonymousIndexingJob |
| 19 | + |
| 20 | + |
| 21 | +# How long between messages before sending a ping |
| 22 | +PING_INTERVAL_SECONDS = 30 |
| 23 | + |
| 24 | +# How long to wait for any activity before closing |
| 25 | +IDLE_TIMEOUT_SECONDS = 120 |
| 26 | + |
| 27 | + |
| 28 | +async def websocket_playground_index(websocket: WebSocket, job_id: str): |
| 29 | + """ |
| 30 | + Stream indexing progress to client via WebSocket. |
| 31 | + |
| 32 | + Subscribes to Redis pub/sub channel for this job and forwards |
| 33 | + all events to the connected client. Closes when job completes |
| 34 | + or fails, or if client disconnects. |
| 35 | + |
| 36 | + No auth required - job_id is an unguessable UUID that acts as |
| 37 | + a bearer token. Only the session that created the job knows it. |
| 38 | + """ |
| 39 | + # Validate job_id format (basic sanity check) |
| 40 | + if not job_id or len(job_id) < 10: |
| 41 | + # Must accept before we can close with a reason |
| 42 | + await websocket.accept() |
| 43 | + await websocket.close(code=4400, reason="Invalid job ID") |
| 44 | + return |
| 45 | + |
| 46 | + # Validate we have Redis (required for pub/sub) |
| 47 | + if not redis_client: |
| 48 | + logger.error("WebSocket failed - no Redis connection") |
| 49 | + await websocket.accept() |
| 50 | + await websocket.close(code=4500, reason="Service unavailable") |
| 51 | + return |
| 52 | + |
| 53 | + # Check if job exists before subscribing |
| 54 | + job_manager = AnonymousIndexingJob(redis_client) |
| 55 | + job = job_manager.get_job(job_id) |
| 56 | + |
| 57 | + if not job: |
| 58 | + await websocket.accept() |
| 59 | + await websocket.close(code=4404, reason="Job not found") |
| 60 | + return |
| 61 | + |
| 62 | + # Accept the WebSocket connection |
| 63 | + await websocket.accept() |
| 64 | + logger.info("WebSocket connected", job_id=job_id[:12]) |
| 65 | + |
| 66 | + # Handle race condition: job might already be complete |
| 67 | + job_status = job.get("status") |
| 68 | + if job_status == "completed": |
| 69 | + await websocket.send_json({ |
| 70 | + "type": "completed", |
| 71 | + "job_id": job_id, |
| 72 | + "repo_id": job.get("repo_id"), |
| 73 | + "stats": job.get("stats"), |
| 74 | + "message": "Indexing already complete" |
| 75 | + }) |
| 76 | + await websocket.close() |
| 77 | + return |
| 78 | + elif job_status == "failed": |
| 79 | + await websocket.send_json({ |
| 80 | + "type": "error", |
| 81 | + "job_id": job_id, |
| 82 | + "error": job.get("error"), |
| 83 | + "message": job.get("error_message", "Indexing failed"), |
| 84 | + "recoverable": False |
| 85 | + }) |
| 86 | + await websocket.close() |
| 87 | + return |
| 88 | + |
| 89 | + channel = f"job:{job_id}:events" |
| 90 | + pubsub = redis_client.pubsub() |
| 91 | + |
| 92 | + try: |
| 93 | + # Subscribe to job's event channel |
| 94 | + await asyncio.to_thread(pubsub.subscribe, channel) |
| 95 | + logger.debug("Subscribed to channel", channel=channel) |
| 96 | + |
| 97 | + # Send initial ack with current state |
| 98 | + await websocket.send_json({ |
| 99 | + "type": "connected", |
| 100 | + "job_id": job_id, |
| 101 | + "current_status": job_status, |
| 102 | + "message": "Listening for indexing events" |
| 103 | + }) |
| 104 | + |
| 105 | + # Listen for messages |
| 106 | + last_activity = asyncio.get_event_loop().time() |
| 107 | + |
| 108 | + while True: |
| 109 | + current_time = asyncio.get_event_loop().time() |
| 110 | + |
| 111 | + # Check for idle timeout |
| 112 | + if current_time - last_activity > IDLE_TIMEOUT_SECONDS: |
| 113 | + logger.warning("WebSocket idle timeout", job_id=job_id[:12]) |
| 114 | + await websocket.send_json({ |
| 115 | + "type": "error", |
| 116 | + "message": "Connection timed out - no activity" |
| 117 | + }) |
| 118 | + break |
| 119 | + |
| 120 | + # Check for new message (non-blocking with short timeout) |
| 121 | + message = await asyncio.to_thread( |
| 122 | + pubsub.get_message, |
| 123 | + ignore_subscribe_messages=True, |
| 124 | + timeout=PING_INTERVAL_SECONDS |
| 125 | + ) |
| 126 | + |
| 127 | + if message is None: |
| 128 | + # No message - send ping to keep connection alive |
| 129 | + try: |
| 130 | + await websocket.send_json({"type": "ping"}) |
| 131 | + except Exception: |
| 132 | + logger.debug("Client disconnected during ping", job_id=job_id[:12]) |
| 133 | + break |
| 134 | + continue |
| 135 | + |
| 136 | + if message["type"] != "message": |
| 137 | + continue |
| 138 | + |
| 139 | + # Got a message - reset activity timer |
| 140 | + last_activity = current_time |
| 141 | + |
| 142 | + # Parse and forward the event |
| 143 | + try: |
| 144 | + event_data = json.loads(message["data"]) |
| 145 | + await websocket.send_json(event_data) |
| 146 | + |
| 147 | + # Close connection after terminal events |
| 148 | + event_type = event_data.get("type") |
| 149 | + if event_type in ("completed", "error"): |
| 150 | + logger.info( |
| 151 | + "Job finished, closing WebSocket", |
| 152 | + job_id=job_id[:12], |
| 153 | + event_type=event_type |
| 154 | + ) |
| 155 | + break |
| 156 | + |
| 157 | + except json.JSONDecodeError: |
| 158 | + logger.warning("Invalid JSON in pub/sub message", job_id=job_id[:12]) |
| 159 | + continue |
| 160 | + except Exception as e: |
| 161 | + logger.error("Error forwarding message", error=str(e), job_id=job_id[:12]) |
| 162 | + continue |
| 163 | + |
| 164 | + except WebSocketDisconnect: |
| 165 | + logger.debug("WebSocket disconnected by client", job_id=job_id[:12]) |
| 166 | + |
| 167 | + except Exception as e: |
| 168 | + logger.error("WebSocket error", error=str(e), job_id=job_id[:12]) |
| 169 | + try: |
| 170 | + await websocket.send_json({ |
| 171 | + "type": "error", |
| 172 | + "message": "Internal server error" |
| 173 | + }) |
| 174 | + except Exception: |
| 175 | + pass |
| 176 | + |
| 177 | + finally: |
| 178 | + # Clean up pub/sub subscription |
| 179 | + try: |
| 180 | + await asyncio.to_thread(pubsub.unsubscribe, channel) |
| 181 | + await asyncio.to_thread(pubsub.close) |
| 182 | + except Exception: |
| 183 | + pass |
| 184 | + |
| 185 | + # Close WebSocket if still open |
| 186 | + try: |
| 187 | + await websocket.close() |
| 188 | + except Exception: |
| 189 | + pass |
| 190 | + |
| 191 | + logger.debug("WebSocket cleanup complete", job_id=job_id[:12]) |
0 commit comments