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

226 statements  

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

1import asyncio 

2import json 

3import time 

4from collections.abc import Callable 

5from pathlib import Path 

6 

7try: 

8 from watchdog.events import FileSystemEvent, FileSystemEventHandler 

9 from watchdog.observers import Observer 

10 

11 WATCHDOG_AVAILABLE = True 

12except ImportError: 

13 FileSystemEvent = None 

14 FileSystemEventHandler = None 

15 Observer = None 

16 WATCHDOG_AVAILABLE = False 

17 

18import contextlib 

19 

20from rich.console import Console 

21 

22from crackerjack.services.secure_path_utils import SecurePathValidator 

23 

24console = Console() 

25 

26 

27if WATCHDOG_AVAILABLE: 

28 

29 class ProgressFileHandler(FileSystemEventHandler): 

30 def __init__( 

31 self, callback: Callable[[str, dict], None], progress_dir: Path 

32 ) -> None: 

33 super().__init__() 

34 self.callback = callback 

35 self.progress_dir = SecurePathValidator.validate_safe_path(progress_dir) 

36 self._last_processed: dict[str, float] = {} 

37 self._debounce_delay = 0.1 

38 

39 def on_modified(self, event: FileSystemEvent) -> None: 

40 if event.is_directory: 

41 return 

42 

43 try: 

44 file_path = Path(event.src_path) 

45 

46 # Validate that the file path is within our allowed progress directory 

47 validated_path = SecurePathValidator.validate_safe_path( 

48 file_path, self.progress_dir 

49 ) 

50 

51 if ( 

52 not validated_path.name.startswith("job-") 

53 or validated_path.suffix != ".json" 

54 ): 

55 return 

56 

57 now = time.time() 

58 if validated_path.name in self._last_processed: 

59 if ( 

60 now - self._last_processed[validated_path.name] 

61 < self._debounce_delay 

62 ): 

63 return 

64 

65 self._last_processed[validated_path.name] = now 

66 

67 job_id = validated_path.stem.replace("job-", "") 

68 except Exception: 

69 # If path validation fails, skip processing this file 

70 return 

71 

72 try: 

73 # Validate file size before reading 

74 SecurePathValidator.validate_file_size(validated_path) 

75 

76 with validated_path.open() as f: 

77 progress_data = json.load(f) 

78 

79 self.callback(job_id, progress_data) 

80 

81 except (json.JSONDecodeError, FileNotFoundError, OSError) as e: 

82 console.print( 

83 f"[yellow]Warning: Failed to read progress file {file_path}: {e}[/ yellow]", 

84 ) 

85 

86 def on_created(self, event: FileSystemEvent) -> None: 

87 self.on_modified(event) 

88else: 

89 

90 class ProgressFileHandler: 

91 def __init__(self, callback: Callable[[str, dict], None]) -> None: 

92 pass 

93 

94 

95class AsyncProgressMonitor: 

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

97 self.progress_dir = SecurePathValidator.validate_safe_path(progress_dir) 

98 self.observer: Observer | None = None 

99 self.subscribers: dict[str, set[Callable[[dict], None]]] = {} 

100 self._running = False 

101 

102 self.progress_dir.mkdir(exist_ok=True) 

103 

104 if not WATCHDOG_AVAILABLE: 

105 console.print( 

106 "[yellow]Warning: watchdog not available, falling back to polling[/ yellow]", 

107 ) 

108 

109 async def start(self) -> None: 

110 if not WATCHDOG_AVAILABLE: 

111 return 

112 

113 self._running = True 

114 

115 handler = ProgressFileHandler(self._on_file_changed, self.progress_dir) 

116 

117 self.observer = Observer() 

118 self.observer.schedule(handler, str(self.progress_dir), recursive=False) 

119 self.observer.start() 

120 

121 console.print( 

122 f"[green]📁 Started monitoring progress directory: {self.progress_dir}[/ green]", 

123 ) 

124 

125 async def stop(self) -> None: 

126 self._running = False 

127 

128 if self.observer: 

129 self.observer.stop() 

130 self.observer.join() 

131 self.observer = None 

132 

133 console.print("[yellow]📁 Stopped progress directory monitoring[/ yellow]") 

134 

135 def subscribe(self, job_id: str, callback: Callable[[dict], None]) -> None: 

136 if job_id not in self.subscribers: 

137 self.subscribers[job_id] = set() 

138 

139 self.subscribers[job_id].add(callback) 

140 console.print(f"[cyan]📋 Subscribed to job updates: {job_id}[/ cyan]") 

141 

142 def unsubscribe(self, job_id: str, callback: Callable[[dict], None]) -> None: 

143 if job_id in self.subscribers: 

144 self.subscribers[job_id].discard(callback) 

145 

146 if not self.subscribers[job_id]: 

147 del self.subscribers[job_id] 

148 

149 console.print(f"[cyan]📋 Unsubscribed from job updates: {job_id}[/ cyan]") 

150 

151 def _on_file_changed(self, job_id: str, progress_data: dict) -> None: 

152 if job_id in self.subscribers: 

153 for callback in self.subscribers[job_id].copy(): 

154 try: 

155 callback(progress_data) 

156 except Exception as e: 

157 console.print( 

158 f"[red]Error in progress callback for job {job_id}: {e}[/ red]", 

159 ) 

160 

161 self.subscribers[job_id].discard(callback) 

162 

163 async def get_current_progress(self, job_id: str) -> dict | None: 

164 progress_file = self.progress_dir / f"job-{job_id}.json" 

165 

166 if not progress_file.exists(): 

167 return None 

168 

169 try: 

170 with progress_file.open() as f: 

171 return json.load(f) 

172 except (json.JSONDecodeError, OSError): 

173 return None 

174 

175 async def cleanup_completed_jobs(self, max_age_minutes: int = 60) -> int: 

176 if not self.progress_dir.exists(): 

177 return 0 

178 

179 cleaned = 0 

180 cutoff_time = time.time() - (max_age_minutes * 60) 

181 

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

183 try: 

184 if progress_file.stat().st_mtime < cutoff_time: 

185 with progress_file.open() as f: 

186 data = json.load(f) 

187 

188 if data.get("status") in ("completed", "failed"): 

189 progress_file.unlink() 

190 cleaned += 1 

191 console.print( 

192 f"[dim]🧹 Cleaned up old progress file: {progress_file.name}[/ dim]", 

193 ) 

194 

195 except (json.JSONDecodeError, OSError, KeyError): 

196 from contextlib import suppress 

197 

198 with suppress(OSError): 

199 progress_file.unlink() 

200 cleaned += 1 

201 console.print( 

202 f"[dim]🧹 Removed corrupted progress file: {progress_file.name}[/ dim]", 

203 ) 

204 

205 return cleaned 

206 

207 

208class PollingProgressMonitor: 

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

210 self.progress_dir = SecurePathValidator.validate_safe_path(progress_dir) 

211 self.subscribers: dict[str, set[Callable[[dict], None]]] = {} 

212 self._running = False 

213 self._poll_task: asyncio.Task | None = None 

214 self._file_mtimes: dict[str, float] = {} 

215 

216 self.progress_dir.mkdir(exist_ok=True) 

217 

218 async def start(self) -> None: 

219 self._running = True 

220 self._poll_task = asyncio.create_task(self._poll_loop()) 

221 console.print( 

222 f"[yellow]📁 Started polling progress directory: {self.progress_dir}[/ yellow]", 

223 ) 

224 

225 async def stop(self) -> None: 

226 self._running = False 

227 

228 if self._poll_task: 

229 self._poll_task.cancel() 

230 with contextlib.suppress(asyncio.CancelledError): 

231 await self._poll_task 

232 self._poll_task = None 

233 

234 console.print("[yellow]📁 Stopped progress directory polling[/ yellow]") 

235 

236 async def _poll_loop(self) -> None: 

237 while self._running: 

238 try: 

239 await self._check_files() 

240 await asyncio.sleep(0.5) 

241 except asyncio.CancelledError: 

242 break 

243 except Exception as e: 

244 console.print(f"[red]Error in polling loop: {e}[/ red]") 

245 await asyncio.sleep(1) 

246 

247 async def _check_files(self) -> None: 

248 if not self.progress_dir.exists(): 

249 return 

250 

251 current_files = {} 

252 

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

254 try: 

255 # Validate file path is within our allowed directory 

256 validated_file = SecurePathValidator.validate_safe_path( 

257 progress_file, self.progress_dir 

258 ) 

259 

260 mtime = validated_file.stat().st_mtime 

261 current_files[validated_file.name] = mtime 

262 

263 if ( 

264 validated_file.name not in self._file_mtimes 

265 or mtime > self._file_mtimes[validated_file.name] 

266 ): 

267 job_id = validated_file.stem.replace("job-", "") 

268 

269 try: 

270 # Validate file size before reading 

271 SecurePathValidator.validate_file_size(validated_file) 

272 with validated_file.open() as f: 

273 progress_data = json.load(f) 

274 

275 self._notify_subscribers(job_id, progress_data) 

276 

277 except (json.JSONDecodeError, OSError) as e: 

278 console.print( 

279 f"[yellow]Warning: Failed to read progress file {progress_file}: {e}[/ yellow]", 

280 ) 

281 

282 except OSError: 

283 continue 

284 

285 self._file_mtimes = current_files 

286 

287 def _notify_subscribers(self, job_id: str, progress_data: dict) -> None: 

288 if job_id in self.subscribers: 

289 for callback in self.subscribers[job_id].copy(): 

290 try: 

291 callback(progress_data) 

292 except Exception as e: 

293 console.print( 

294 f"[red]Error in progress callback for job {job_id}: {e}[/ red]", 

295 ) 

296 self.subscribers[job_id].discard(callback) 

297 

298 def subscribe(self, job_id: str, callback: Callable[[dict], None]) -> None: 

299 if job_id not in self.subscribers: 

300 self.subscribers[job_id] = set() 

301 

302 self.subscribers[job_id].add(callback) 

303 console.print(f"[cyan]📋 Subscribed to job updates: {job_id} (polling)[/ cyan]") 

304 

305 def unsubscribe(self, job_id: str, callback: Callable[[dict], None]) -> None: 

306 if job_id in self.subscribers: 

307 self.subscribers[job_id].discard(callback) 

308 

309 if not self.subscribers[job_id]: 

310 del self.subscribers[job_id] 

311 

312 console.print( 

313 f"[cyan]📋 Unsubscribed from job updates: {job_id} (polling)[/ cyan]", 

314 ) 

315 

316 async def get_current_progress(self, job_id: str) -> dict | None: 

317 progress_file = self.progress_dir / f"job-{job_id}.json" 

318 

319 if not progress_file.exists(): 

320 return None 

321 

322 try: 

323 with progress_file.open() as f: 

324 return json.load(f) 

325 except (json.JSONDecodeError, OSError): 

326 return None 

327 

328 async def cleanup_completed_jobs(self, max_age_minutes: int = 60) -> int: 

329 if not self.progress_dir.exists(): 

330 return 0 

331 

332 cleaned = 0 

333 cutoff_time = time.time() - (max_age_minutes * 60) 

334 

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

336 try: 

337 if progress_file.stat().st_mtime < cutoff_time: 

338 with progress_file.open() as f: 

339 data = json.load(f) 

340 

341 if data.get("status") in ("completed", "failed"): 

342 progress_file.unlink() 

343 cleaned += 1 

344 console.print( 

345 f"[dim]🧹 Cleaned up old progress file: {progress_file.name}[/ dim]", 

346 ) 

347 

348 except (json.JSONDecodeError, OSError, KeyError): 

349 from contextlib import suppress 

350 

351 with suppress(OSError): 

352 progress_file.unlink() 

353 cleaned += 1 

354 console.print( 

355 f"[dim]🧹 Removed corrupted progress file: {progress_file.name}[/ dim]", 

356 ) 

357 

358 return cleaned 

359 

360 

361def create_progress_monitor( 

362 progress_dir: Path, 

363) -> AsyncProgressMonitor | PollingProgressMonitor: 

364 if WATCHDOG_AVAILABLE: 

365 return AsyncProgressMonitor(progress_dir) 

366 return PollingProgressMonitor(progress_dir)