Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/websocket/websocket_handler.py: 0%
70 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import asyncio
2from pathlib import Path
4from fastapi import FastAPI, WebSocket, WebSocketDisconnect
5from rich.console import Console
7from crackerjack.core.timeout_manager import TimeoutStrategy, get_timeout_manager
9from .jobs import JobManager
11console = Console()
14class WebSocketHandler:
15 def __init__(self, job_manager: JobManager, progress_dir: Path) -> None:
16 self.job_manager = job_manager
17 self.progress_dir = progress_dir
18 self.timeout_manager = get_timeout_manager()
20 async def handle_connection(self, websocket: WebSocket, job_id: str) -> None:
21 if not self.job_manager.validate_job_id(job_id):
22 await websocket.close(code=1008, reason="Invalid job ID")
23 return
25 try:
26 # Add timeout to the entire connection handling
27 async with self.timeout_manager.timeout_context(
28 "websocket_connection",
29 timeout=3600.0, # 1 hour max connection time
30 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
31 ):
32 await websocket.accept()
33 self.job_manager.add_connection(job_id, websocket)
35 console.print(f"[green]WebSocket connected for job: {job_id}[/green]")
37 # Send initial progress with timeout
38 try:
39 async with self.timeout_manager.timeout_context(
40 "websocket_broadcast",
41 timeout=5.0,
42 strategy=TimeoutStrategy.FAIL_FAST,
43 ):
44 initial_progress = self.job_manager.get_job_progress(job_id)
45 if initial_progress:
46 await websocket.send_json(initial_progress)
47 else:
48 await websocket.send_json(
49 {
50 "job_id": job_id,
51 "status": "waiting",
52 "message": "Waiting for job to start...",
53 "overall_progress": 0,
54 "iteration": 0,
55 "max_iterations": 10,
56 "current_stage": "Initializing",
57 },
58 )
59 except Exception as e:
60 console.print(
61 f"[red]Failed to send initial progress for {job_id}: {e}[/red]"
62 )
64 # Message handling loop with timeout protection
65 message_count = 0
66 max_messages = 10000 # Prevent infinite message loops
68 while message_count < max_messages:
69 try:
70 # Add timeout to individual message operations
71 async with self.timeout_manager.timeout_context(
72 "websocket_message",
73 timeout=30.0, # 30 second timeout per message
74 strategy=TimeoutStrategy.FAIL_FAST,
75 ):
76 # Use asyncio.wait_for for additional protection
77 data = await asyncio.wait_for(
78 websocket.receive_text(),
79 timeout=25.0, # Slightly less than timeout context
80 )
82 message_count += 1
83 console.print(
84 f"[blue]Received message {message_count} for {job_id}: {data[:100]}...[/blue]",
85 )
87 # Respond with timeout protection
88 await asyncio.wait_for(
89 websocket.send_json(
90 {
91 "type": "echo",
92 "message": f"Received: {data}",
93 "job_id": job_id,
94 "message_count": message_count,
95 },
96 ),
97 timeout=5.0,
98 )
100 except TimeoutError:
101 console.print(
102 f"[yellow]Message timeout for {job_id} after {message_count} messages[/yellow]"
103 )
104 break
105 except WebSocketDisconnect:
106 console.print(
107 f"[yellow]WebSocket disconnected for job: {job_id}[/yellow]"
108 )
109 break
110 except Exception as e:
111 console.print(
112 f"[red]WebSocket message error for job {job_id}: {e}[/red]"
113 )
114 break
116 if message_count >= max_messages:
117 console.print(
118 f"[yellow]WebSocket connection limit reached for {job_id}: {max_messages} messages[/yellow]"
119 )
121 except TimeoutError:
122 console.print(
123 f"[yellow]WebSocket connection timeout for job: {job_id}[/yellow]"
124 )
125 try:
126 await websocket.close(code=1001, reason="Connection timeout")
127 except Exception:
128 pass
129 except WebSocketDisconnect:
130 console.print(f"[yellow]WebSocket disconnected for job: {job_id}[/yellow]")
131 except Exception as e:
132 console.print(f"[red]WebSocket error for job {job_id}: {e}[/red]")
133 try:
134 await websocket.close(code=1011, reason="Internal error")
135 except Exception:
136 pass
137 finally:
138 # Always clean up connection
139 try:
140 self.job_manager.remove_connection(job_id, websocket)
141 except Exception as e:
142 console.print(f"[red]Error removing connection for {job_id}: {e}[/red]")
145def register_websocket_routes(
146 app: FastAPI,
147 job_manager: JobManager,
148 progress_dir: Path,
149) -> None:
150 handler = WebSocketHandler(job_manager, progress_dir)
152 @app.websocket("/ws/progress/{job_id}")
153 async def websocket_progress_endpoint(websocket: WebSocket, job_id: str) -> None:
154 await handler.handle_connection(websocket, job_id)