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
« 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
7try:
8 from watchdog.events import FileSystemEvent, FileSystemEventHandler
9 from watchdog.observers import Observer
11 WATCHDOG_AVAILABLE = True
12except ImportError:
13 FileSystemEvent = None
14 FileSystemEventHandler = None
15 Observer = None
16 WATCHDOG_AVAILABLE = False
18import contextlib
20from rich.console import Console
22from crackerjack.services.secure_path_utils import SecurePathValidator
24console = Console()
27if WATCHDOG_AVAILABLE:
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
39 def on_modified(self, event: FileSystemEvent) -> None:
40 if event.is_directory:
41 return
43 try:
44 file_path = Path(event.src_path)
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 )
51 if (
52 not validated_path.name.startswith("job-")
53 or validated_path.suffix != ".json"
54 ):
55 return
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
65 self._last_processed[validated_path.name] = now
67 job_id = validated_path.stem.replace("job-", "")
68 except Exception:
69 # If path validation fails, skip processing this file
70 return
72 try:
73 # Validate file size before reading
74 SecurePathValidator.validate_file_size(validated_path)
76 with validated_path.open() as f:
77 progress_data = json.load(f)
79 self.callback(job_id, progress_data)
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 )
86 def on_created(self, event: FileSystemEvent) -> None:
87 self.on_modified(event)
88else:
90 class ProgressFileHandler:
91 def __init__(self, callback: Callable[[str, dict], None]) -> None:
92 pass
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
102 self.progress_dir.mkdir(exist_ok=True)
104 if not WATCHDOG_AVAILABLE:
105 console.print(
106 "[yellow]Warning: watchdog not available, falling back to polling[/ yellow]",
107 )
109 async def start(self) -> None:
110 if not WATCHDOG_AVAILABLE:
111 return
113 self._running = True
115 handler = ProgressFileHandler(self._on_file_changed, self.progress_dir)
117 self.observer = Observer()
118 self.observer.schedule(handler, str(self.progress_dir), recursive=False)
119 self.observer.start()
121 console.print(
122 f"[green]📁 Started monitoring progress directory: {self.progress_dir}[/ green]",
123 )
125 async def stop(self) -> None:
126 self._running = False
128 if self.observer:
129 self.observer.stop()
130 self.observer.join()
131 self.observer = None
133 console.print("[yellow]📁 Stopped progress directory monitoring[/ yellow]")
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()
139 self.subscribers[job_id].add(callback)
140 console.print(f"[cyan]📋 Subscribed to job updates: {job_id}[/ cyan]")
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)
146 if not self.subscribers[job_id]:
147 del self.subscribers[job_id]
149 console.print(f"[cyan]📋 Unsubscribed from job updates: {job_id}[/ cyan]")
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 )
161 self.subscribers[job_id].discard(callback)
163 async def get_current_progress(self, job_id: str) -> dict | None:
164 progress_file = self.progress_dir / f"job-{job_id}.json"
166 if not progress_file.exists():
167 return None
169 try:
170 with progress_file.open() as f:
171 return json.load(f)
172 except (json.JSONDecodeError, OSError):
173 return None
175 async def cleanup_completed_jobs(self, max_age_minutes: int = 60) -> int:
176 if not self.progress_dir.exists():
177 return 0
179 cleaned = 0
180 cutoff_time = time.time() - (max_age_minutes * 60)
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)
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 )
195 except (json.JSONDecodeError, OSError, KeyError):
196 from contextlib import suppress
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 )
205 return cleaned
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] = {}
216 self.progress_dir.mkdir(exist_ok=True)
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 )
225 async def stop(self) -> None:
226 self._running = False
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
234 console.print("[yellow]📁 Stopped progress directory polling[/ yellow]")
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)
247 async def _check_files(self) -> None:
248 if not self.progress_dir.exists():
249 return
251 current_files = {}
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 )
260 mtime = validated_file.stat().st_mtime
261 current_files[validated_file.name] = mtime
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-", "")
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)
275 self._notify_subscribers(job_id, progress_data)
277 except (json.JSONDecodeError, OSError) as e:
278 console.print(
279 f"[yellow]Warning: Failed to read progress file {progress_file}: {e}[/ yellow]",
280 )
282 except OSError:
283 continue
285 self._file_mtimes = current_files
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)
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()
302 self.subscribers[job_id].add(callback)
303 console.print(f"[cyan]📋 Subscribed to job updates: {job_id} (polling)[/ cyan]")
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)
309 if not self.subscribers[job_id]:
310 del self.subscribers[job_id]
312 console.print(
313 f"[cyan]📋 Unsubscribed from job updates: {job_id} (polling)[/ cyan]",
314 )
316 async def get_current_progress(self, job_id: str) -> dict | None:
317 progress_file = self.progress_dir / f"job-{job_id}.json"
319 if not progress_file.exists():
320 return None
322 try:
323 with progress_file.open() as f:
324 return json.load(f)
325 except (json.JSONDecodeError, OSError):
326 return None
328 async def cleanup_completed_jobs(self, max_age_minutes: int = 60) -> int:
329 if not self.progress_dir.exists():
330 return 0
332 cleaned = 0
333 cutoff_time = time.time() - (max_age_minutes * 60)
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)
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 )
348 except (json.JSONDecodeError, OSError, KeyError):
349 from contextlib import suppress
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 )
358 return cleaned
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)