Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/websocket/jobs.py: 0%

206 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import asyncio 

2import json 

3import time 

4import uuid 

5from contextlib import suppress 

6from pathlib import Path 

7from typing import Any 

8 

9from rich.console import Console 

10 

11from crackerjack.core.timeout_manager import TimeoutStrategy, get_timeout_manager 

12from crackerjack.services.input_validator import get_input_validator 

13from crackerjack.services.secure_path_utils import SecurePathValidator 

14 

15console = Console() 

16 

17 

18class JobManager: 

19 def __init__(self, progress_dir: Path) -> None: 

20 # Validate and secure the progress directory path 

21 self.progress_dir = SecurePathValidator.validate_safe_path(progress_dir) 

22 self.active_connections: dict[str, set[Any]] = {} 

23 self.known_jobs: set[str] = set() 

24 self.is_running = True 

25 

26 self.progress_dir.mkdir(exist_ok=True) 

27 

28 def validate_job_id(self, job_id: str) -> bool: 

29 """Validate job ID using secure input validator.""" 

30 if not job_id: 

31 return False 

32 

33 # First check if it's a valid UUID 

34 with suppress(ValueError): 

35 uuid.UUID(job_id) 

36 return True 

37 

38 # Use secure input validator for additional validation 

39 validator = get_input_validator() 

40 result = validator.validate_job_id(job_id) 

41 return result.valid 

42 

43 def add_connection(self, job_id: str, websocket: Any) -> None: 

44 if job_id not in self.active_connections: 

45 self.active_connections[job_id] = set() 

46 self.active_connections[job_id].add(websocket) 

47 

48 def remove_connection(self, job_id: str, websocket: Any) -> None: 

49 if job_id in self.active_connections: 

50 self.active_connections[job_id].discard(websocket) 

51 if not self.active_connections[job_id]: 

52 del self.active_connections[job_id] 

53 

54 async def broadcast_to_job(self, job_id: str, data: dict) -> None: 

55 if job_id not in self.active_connections: 

56 return 

57 

58 timeout_manager = get_timeout_manager() 

59 connections = self.active_connections[job_id].copy() 

60 

61 # Create tasks for all websocket sends with timeout 

62 send_tasks = [] 

63 for websocket in connections: 

64 task = asyncio.create_task( 

65 timeout_manager.with_timeout( 

66 "websocket_broadcast", 

67 websocket.send_json(data), 

68 timeout=2.0, # Quick broadcast timeout 

69 strategy=TimeoutStrategy.FAIL_FAST, 

70 ) 

71 ) 

72 send_tasks.append((websocket, task)) 

73 

74 # Wait for all sends with timeout 

75 if send_tasks: 

76 try: 

77 # Use asyncio.wait with timeout for batch sending 

78 done, pending = await asyncio.wait( 

79 [task for _, task in send_tasks], 

80 timeout=5.0, # Overall timeout for all broadcasts 

81 return_when=asyncio.ALL_COMPLETED, 

82 ) 

83 

84 # Cancel any pending tasks and remove failed connections 

85 for websocket, task in send_tasks: 

86 if task in pending: 

87 task.cancel() 

88 self.remove_connection(job_id, websocket) 

89 elif task in done: 

90 try: 

91 await task 

92 except Exception: 

93 self.remove_connection(job_id, websocket) 

94 

95 # Wait for cancelled tasks to complete 

96 if pending: 

97 await asyncio.gather(*pending, return_exceptions=True) 

98 

99 except Exception as e: 

100 console.print(f"[red]Broadcast error: {e}[/red]") 

101 # Remove all connections on serious broadcast failure 

102 for websocket, task in send_tasks: 

103 if not task.done(): 

104 task.cancel() 

105 self.remove_connection(job_id, websocket) 

106 

107 def get_latest_job_id(self) -> str | None: 

108 if not self.progress_dir.exists(): 

109 return None 

110 

111 progress_files = list(self.progress_dir.glob("job-*.json")) 

112 if not progress_files: 

113 return None 

114 

115 latest_file = max(progress_files, key=lambda f: f.stat().st_mtime) 

116 return self.extract_job_id_from_file(latest_file) 

117 

118 def extract_job_id_from_file(self, progress_file: Path) -> str | None: 

119 return ( 

120 progress_file.stem[4:] if progress_file.stem.startswith("job -") else None 

121 ) 

122 

123 def get_job_progress(self, job_id: str) -> dict | None: 

124 if not self.validate_job_id(job_id): 

125 return None 

126 

127 # Use secure path joining to create progress file path 

128 try: 

129 progress_file = SecurePathValidator.secure_path_join( 

130 self.progress_dir, f"job-{job_id}.json" 

131 ) 

132 if not progress_file.exists(): 

133 return None 

134 

135 # Validate file size before reading 

136 SecurePathValidator.validate_file_size(progress_file) 

137 

138 return json.loads(progress_file.read_text()) 

139 except (json.JSONDecodeError, OSError): 

140 return None 

141 

142 async def _process_progress_file(self, progress_file: Path) -> None: 

143 # Validate the progress file path is within our allowed directory 

144 try: 

145 validated_file = SecurePathValidator.validate_safe_path( 

146 progress_file, self.progress_dir 

147 ) 

148 except Exception: 

149 # If path validation fails, skip processing this file 

150 return 

151 

152 job_id = self.extract_job_id_from_file(validated_file) 

153 if not (job_id and self.validate_job_id(job_id)): 

154 return 

155 

156 progress_data = self.get_job_progress(job_id) 

157 if progress_data and job_id not in self.known_jobs: 

158 self.known_jobs.add(job_id) 

159 console.print(f"[green]New job detected: {job_id}[/ green]") 

160 await self.broadcast_to_job(job_id, progress_data) 

161 

162 async def _monitor_directory_changes(self) -> None: 

163 timeout_manager = get_timeout_manager() 

164 consecutive_errors = 0 

165 max_consecutive_errors = 5 

166 

167 while self.is_running: 

168 try: 

169 # Monitor directory changes with timeout protection 

170 async with timeout_manager.timeout_context( 

171 "file_operations", 

172 timeout=10.0, # Timeout for directory monitoring cycle 

173 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION, 

174 ): 

175 if self.progress_dir.exists(): 

176 # Process files with individual timeouts 

177 for progress_file in self.progress_dir.glob("job-*.json"): 

178 try: 

179 await timeout_manager.with_timeout( 

180 "file_operations", 

181 self._process_progress_file(progress_file), 

182 timeout=5.0, # Per-file timeout 

183 strategy=TimeoutStrategy.FAIL_FAST, 

184 ) 

185 except Exception as e: 

186 console.print( 

187 f"[yellow]File processing error: {e}[/yellow]" 

188 ) 

189 continue 

190 

191 # Reset error count on successful cycle 

192 consecutive_errors = 0 

193 await asyncio.sleep(1) 

194 

195 except Exception as e: 

196 consecutive_errors += 1 

197 console.print(f"[red]Progress monitoring error: {e}[/red]") 

198 

199 # Implement exponential backoff for repeated errors 

200 if consecutive_errors >= max_consecutive_errors: 

201 console.print( 

202 f"[red]Too many consecutive errors ({consecutive_errors}), stopping monitor[/red]" 

203 ) 

204 break 

205 

206 # Exponential backoff with max delay 

207 delay = min(5 * (2 ** (consecutive_errors - 1)), 60) 

208 await asyncio.sleep(delay) 

209 

210 async def monitor_progress_files(self) -> None: 

211 from crackerjack.mcp.file_monitor import create_progress_monitor 

212 

213 console.print("[blue]Starting progress file monitoring...[/blue]") 

214 timeout_manager = get_timeout_manager() 

215 

216 try: 

217 # Start file monitor with timeout protection 

218 async with timeout_manager.timeout_context( 

219 "file_operations", 

220 timeout=30.0, # Monitor startup timeout 

221 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION, 

222 ): 

223 monitor = create_progress_monitor(self.progress_dir) 

224 await monitor.start() 

225 

226 def on_progress_update(job_id: str, progress_data: dict) -> None: 

227 if job_id and self.validate_job_id(job_id): 

228 # Create broadcast task with timeout handling 

229 async def safe_broadcast(): 

230 try: 

231 await timeout_manager.with_timeout( 

232 "websocket_broadcast", 

233 self.broadcast_to_job(job_id, progress_data), 

234 timeout=5.0, 

235 strategy=TimeoutStrategy.FAIL_FAST, 

236 ) 

237 except Exception as e: 

238 console.print( 

239 f"[yellow]Broadcast failed for job {job_id}: {e}[/yellow]" 

240 ) 

241 

242 asyncio.create_task(safe_broadcast()) 

243 

244 if job_id not in self.known_jobs: 

245 self.known_jobs.add(job_id) 

246 console.print(f"[green]New job detected: {job_id}[/green]") 

247 

248 # Start directory monitoring with proper timeout handling 

249 await self._monitor_directory_changes() 

250 

251 except Exception as e: 

252 console.print(f"[red]Progress monitoring setup error: {e}[/red]") 

253 

254 async def cleanup_old_jobs(self) -> None: 

255 timeout_manager = get_timeout_manager() 

256 

257 while self.is_running: 

258 try: 

259 # Cleanup cycle with timeout protection 

260 await timeout_manager.with_timeout( 

261 "file_operations", 

262 self._perform_cleanup_cycle(), 

263 timeout=30.0, # Cleanup timeout 

264 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION, 

265 ) 

266 await asyncio.sleep(3600) # 1 hour between cleanups 

267 except Exception as e: 

268 console.print(f"[red]Cleanup error: {e}[/red]") 

269 # Shorter sleep on error to retry sooner 

270 await asyncio.sleep(1800) # 30 minutes on error 

271 

272 async def _perform_cleanup_cycle(self) -> None: 

273 if not self.progress_dir.exists(): 

274 return 

275 

276 cutoff_time = self._calculate_cleanup_cutoff_time() 

277 old_job_files = self._find_old_job_files(cutoff_time) 

278 

279 for progress_file in old_job_files: 

280 self._cleanup_old_job_file(progress_file) 

281 

282 def _calculate_cleanup_cutoff_time(self) -> float: 

283 return time.time() - (24 * 60 * 60) 

284 

285 def _find_old_job_files(self, cutoff_time: float) -> list[Path]: 

286 return [ 

287 progress_file 

288 for progress_file in self.progress_dir.glob("job - *.json") 

289 if progress_file.stat().st_mtime < cutoff_time 

290 ] 

291 

292 def _cleanup_old_job_file(self, progress_file: Path) -> None: 

293 job_id = self.extract_job_id_from_file(progress_file) 

294 

295 if job_id not in self.active_connections: 

296 progress_file.unlink(missing_ok=True) 

297 console.print(f"[yellow]Cleaned up old job: {job_id}[/ yellow]") 

298 

299 async def timeout_stuck_jobs(self) -> None: 

300 timeout_manager = get_timeout_manager() 

301 

302 while self.is_running: 

303 try: 

304 # Timeout check with its own timeout protection 

305 await timeout_manager.with_timeout( 

306 "file_operations", 

307 self._check_and_timeout_stuck_jobs(), 

308 timeout=60.0, # Timeout check timeout 

309 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION, 

310 ) 

311 await asyncio.sleep(300) # 5 minutes between checks 

312 except Exception as e: 

313 console.print(f"[red]Timeout check error: {e}[/red]") 

314 # Continue checking even on errors 

315 await asyncio.sleep(300) 

316 

317 async def _check_and_timeout_stuck_jobs(self) -> None: 

318 if not self.progress_dir.exists(): 

319 return 

320 

321 current_time = time.time() 

322 timeout_seconds = 30 * 60 

323 

324 for progress_file in self.progress_dir.glob("job-* .json"): 

325 await self._process_job_timeout_check( 

326 progress_file, 

327 current_time, 

328 timeout_seconds, 

329 ) 

330 

331 async def _process_job_timeout_check( 

332 self, 

333 progress_file: Path, 

334 current_time: float, 

335 timeout_seconds: int, 

336 ) -> None: 

337 try: 

338 # Validate the progress file path is secure 

339 validated_file = SecurePathValidator.validate_safe_path( 

340 progress_file, self.progress_dir 

341 ) 

342 

343 # Validate file size before reading 

344 SecurePathValidator.validate_file_size(validated_file) 

345 

346 progress_data = json.loads(validated_file.read_text()) 

347 

348 if self._should_timeout_job( 

349 progress_data, 

350 validated_file, 

351 current_time, 

352 timeout_seconds, 

353 ): 

354 self._timeout_job(progress_data, validated_file) 

355 

356 except (json.JSONDecodeError, OSError, Exception): 

357 # Catch validation errors as well as file errors 

358 pass 

359 

360 def _should_timeout_job( 

361 self, 

362 progress_data: dict, 

363 progress_file: Path, 

364 current_time: float, 

365 timeout_seconds: int, 

366 ) -> bool: 

367 return ( 

368 progress_data.get("status") == "running" 

369 and current_time - progress_file.stat().st_mtime > timeout_seconds 

370 ) 

371 

372 def _timeout_job(self, progress_data: dict, progress_file: Path) -> None: 

373 progress_data["status"] = "failed" 

374 progress_data["message"] = "Job timed out (no updates for 30 minutes)" 

375 

376 progress_file.write_text(json.dumps(progress_data, indent=2)) 

377 

378 job_id = progress_data.get("job_id", "unknown") 

379 console.print(f"[red]Job {job_id} timed out and marked as failed[/ red]") 

380 

381 def cleanup(self) -> None: 

382 self.is_running = False 

383 console.print("[blue]Job manager cleanup completed[/ blue]")