Coverage for /Users/les/Projects/crackerjack/crackerjack/services/enhanced_filesystem.py: 0%
262 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 hashlib
3import time
4from collections.abc import Iterator
5from pathlib import Path
6from typing import Any
8import aiofiles
10from crackerjack.errors import FileError
11from crackerjack.models.protocols import FileSystemInterface
12from crackerjack.services.logging import LoggingContext, get_logger
15class FileCache:
16 def __init__(self, max_size: int = 1000, default_ttl: float = 300.0) -> None:
17 self.max_size = max_size
18 self.default_ttl = default_ttl
19 self._cache: dict[str, dict[str, Any]] = {}
20 self._access_times: dict[str, float] = {}
21 self.logger = get_logger("crackerjack.filesystem.cache")
23 def get(self, key: str) -> str | None:
24 if key not in self._cache:
25 return None
27 cache_entry = self._cache[key]
28 now = time.time()
30 if now - cache_entry["timestamp"] > cache_entry["ttl"]:
31 self._evict(key)
32 return None
34 self._access_times[key] = now
35 self.logger.debug("Cache hit", key=key)
36 return cache_entry["content"]
38 def put(self, key: str, content: str, ttl: float | None = None) -> None:
39 if len(self._cache) >= self.max_size:
40 self._evict_lru()
42 now = time.time()
43 self._cache[key] = {
44 "content": content,
45 "timestamp": now,
46 "ttl": ttl or self.default_ttl,
47 "size": len(content),
48 }
49 self._access_times[key] = now
50 self.logger.debug("Cache put", key=key, size=len(content))
52 def _evict(self, key: str) -> None:
53 self._cache.pop(key, None)
54 self._access_times.pop(key, None)
56 def _evict_lru(self) -> None:
57 if not self._access_times:
58 return
60 lru_key = min(self._access_times, key=lambda k: self._access_times.get(k, 0.0))
61 self._evict(lru_key)
62 self.logger.debug("Cache LRU eviction", key=lru_key)
64 def clear(self) -> None:
65 self._cache.clear()
66 self._access_times.clear()
67 self.logger.debug("Cache cleared")
69 def get_stats(self) -> dict[str, Any]:
70 total_size = sum(entry["size"] for entry in self._cache.values())
71 return {
72 "entries": len(self._cache),
73 "max_size": self.max_size,
74 "total_content_size": total_size,
75 "memory_usage_mb": total_size / (1024 * 1024),
76 }
79class BatchFileOperations:
80 def __init__(self, batch_size: int = 10) -> None:
81 self.batch_size = batch_size
82 self.read_queue: list[tuple[Path, asyncio.Future[str]]] = []
83 self.write_queue: list[tuple[Path, str, asyncio.Future[None]]] = []
84 self.logger = get_logger("crackerjack.filesystem.batch")
86 async def queue_read(self, path: Path) -> str:
87 future: asyncio.Future[str] = asyncio.Future()
88 self.read_queue.append((path, future))
90 if len(self.read_queue) >= self.batch_size:
91 await self._flush_reads()
93 return await future
95 async def queue_write(self, path: Path, content: str) -> None:
96 future: asyncio.Future[None] = asyncio.Future()
97 self.write_queue.append((path, content, future))
99 if len(self.write_queue) >= self.batch_size:
100 await self._flush_writes()
102 await future
104 async def flush_all(self) -> None:
105 await asyncio.gather(
106 self._flush_reads(),
107 self._flush_writes(),
108 return_exceptions=True,
109 )
111 async def _flush_reads(self) -> None:
112 if not self.read_queue:
113 return
115 with LoggingContext("batch_file_reads", count=len(self.read_queue)):
116 batch = self.read_queue.copy()
117 self.read_queue.clear()
119 from itertools import starmap
121 tasks = list(starmap(self._read_single_async, batch))
123 await asyncio.gather(*tasks, return_exceptions=True)
125 async def _flush_writes(self) -> None:
126 if not self.write_queue:
127 return
129 with LoggingContext("batch_file_writes", count=len(self.write_queue)):
130 batch = self.write_queue.copy()
131 self.write_queue.clear()
133 from itertools import starmap
135 tasks = list(starmap(self._write_single_async, batch))
137 await asyncio.gather(*tasks, return_exceptions=True)
139 async def _read_single_async(self, path: Path, future: asyncio.Future[str]) -> None:
140 try:
141 async with aiofiles.open(path, encoding="utf-8") as f:
142 content = await f.read()
143 future.set_result(content)
144 except Exception as e:
145 future.set_exception(e)
147 async def _write_single_async(
148 self,
149 path: Path,
150 content: str,
151 future: asyncio.Future[None],
152 ) -> None:
153 try:
154 path.parent.mkdir(parents=True, exist_ok=True)
155 async with aiofiles.open(path, "w", encoding="utf-8") as f:
156 await f.write(content)
157 future.set_result(None)
158 except Exception as e:
159 future.set_exception(e)
162class EnhancedFileSystemService(FileSystemInterface):
163 def __init__(
164 self,
165 cache_size: int = 1000,
166 cache_ttl: float = 300.0,
167 batch_size: int = 10,
168 enable_async: bool = True,
169 ) -> None:
170 self.cache = FileCache(cache_size, cache_ttl)
171 self.batch_ops = BatchFileOperations(batch_size) if enable_async else None
172 self.enable_async = enable_async
173 self.logger = get_logger("crackerjack.filesystem.enhanced")
175 self._file_timestamps: dict[str, float] = {}
177 def read_file(self, path: str | Path) -> str:
178 path_obj = Path(path) if isinstance(path, str) else path
180 with LoggingContext("read_file", path=str(path_obj)):
181 cache_key = self._get_cache_key(path_obj)
182 cached_content = self._get_from_cache(cache_key, path_obj)
184 if cached_content is not None:
185 return cached_content
187 content = self._read_file_direct(path_obj)
189 self.cache.put(cache_key, content)
190 self._file_timestamps[str(path_obj)] = path_obj.stat().st_mtime
192 return content
194 def write_file(self, path: str | Path, content: str) -> None:
195 if not content:
196 raise TypeError("Content must be a non-empty string")
198 path_obj = Path(path) if isinstance(path, str) else path
200 with LoggingContext("write_file", path=str(path_obj), size=len(content)):
201 self._write_file_direct(path_obj, content)
203 cache_key = self._get_cache_key(path_obj)
204 self.cache._evict(cache_key)
205 self._file_timestamps[str(path_obj)] = time.time()
207 async def read_file_async(self, path: Path) -> str:
208 if not self.enable_async or not self.batch_ops:
209 return self.read_file(path)
211 cache_key = self._get_cache_key(path)
212 cached_content = self._get_from_cache(cache_key, path)
214 if cached_content is not None:
215 return cached_content
217 content = await self.batch_ops.queue_read(path)
219 self.cache.put(cache_key, content)
220 self._file_timestamps[str(path)] = path.stat().st_mtime
222 return content
224 async def write_file_async(self, path: Path, content: str) -> None:
225 if not self.enable_async or not self.batch_ops:
226 self.write_file(path, content)
227 return
229 await self.batch_ops.queue_write(path, content)
231 cache_key = self._get_cache_key(path)
232 self.cache._evict(cache_key)
233 self._file_timestamps[str(path)] = time.time()
235 async def read_multiple_files(self, paths: list[Path]) -> dict[Path, str]:
236 results = {}
238 if not self.enable_async or not self.batch_ops:
239 for path in paths:
240 try:
241 results[path] = self.read_file(path)
242 except Exception as e:
243 self.logger.exception(
244 "Failed to read file",
245 path=str(path),
246 error=str(e),
247 )
248 results[path] = ""
249 return results
251 with LoggingContext("read_multiple_files", count=len(paths)):
252 tasks = [self.read_file_async(path) for path in paths]
254 results_list = await asyncio.gather(*tasks, return_exceptions=True)
256 for path, result in zip(paths, results_list, strict=False):
257 if isinstance(result, Exception):
258 self.logger.error(
259 "Failed to read file",
260 path=str(path),
261 error=str(result),
262 )
263 results[path] = ""
264 else:
265 results[path] = result
267 return results
269 async def write_multiple_files(self, file_data: dict[Path, str]) -> None:
270 if not self.enable_async or not self.batch_ops:
271 for path, content in file_data.items():
272 try:
273 self.write_file(path, content)
274 except Exception as e:
275 self.logger.exception(
276 "Failed to write file",
277 path=str(path),
278 error=str(e),
279 )
280 return
282 with LoggingContext("write_multiple_files", count=len(file_data)):
283 from itertools import starmap
285 tasks = list(starmap(self.write_file_async, file_data.items()))
287 await asyncio.gather(*tasks, return_exceptions=True)
289 def _get_cache_key(self, path: Path) -> str:
290 path_str = str(path.resolve())
291 return hashlib.md5(path_str.encode(), usedforsecurity=False).hexdigest()
293 def _get_from_cache(self, cache_key: str, path: Path) -> str | None:
294 if not path.exists():
295 return None
297 path_str = str(path)
298 if path_str in self._file_timestamps:
299 current_mtime = path.stat().st_mtime
300 cached_mtime = self._file_timestamps[path_str]
302 if current_mtime > cached_mtime:
303 self.cache._evict(cache_key)
304 del self._file_timestamps[path_str]
305 return None
307 return self.cache.get(cache_key)
309 def _read_file_direct(self, path: Path) -> str:
310 try:
311 if not path.exists():
312 raise FileError(
313 message=f"File does not exist: {path}",
314 details=f"Attempted to read file at {path.absolute()}",
315 recovery="Check file path and ensure file exists",
316 )
317 return path.read_text(encoding="utf-8")
318 except PermissionError as e:
319 raise FileError(
320 message=f"Permission denied reading file: {path}",
321 details=str(e),
322 recovery="Check file permissions and user access rights",
323 ) from e
324 except UnicodeDecodeError as e:
325 raise FileError(
326 message=f"Unable to decode file as UTF-8: {path}",
327 details=str(e),
328 recovery="Ensure file is text - based and UTF-8 encoded",
329 ) from e
330 except OSError as e:
331 raise FileError(
332 message=f"System error reading file: {path}",
333 details=str(e),
334 recovery="Check disk space and file system integrity",
335 ) from e
337 def _write_file_direct(self, path: Path, content: str) -> None:
338 try:
339 try:
340 path.parent.mkdir(parents=True, exist_ok=True)
341 except OSError as e:
342 raise FileError(
343 message=f"Cannot create parent directory: {path.parent}",
344 details=str(e),
345 recovery="Check directory permissions and disk space",
346 ) from e
348 path.write_text(content, encoding="utf-8")
350 except PermissionError as e:
351 raise FileError(
352 message=f"Permission denied writing file: {path}",
353 details=str(e),
354 recovery="Check file and directory permissions",
355 ) from e
356 except OSError as e:
357 raise FileError(
358 message=f"System error writing file: {path}",
359 details=str(e),
360 recovery="Check disk space and file system integrity",
361 ) from e
363 def file_exists(self, path: str | Path) -> bool:
364 return (Path(path) if isinstance(path, str) else path).exists()
366 def create_directory(self, path: str | Path) -> None:
367 path_obj = Path(path) if isinstance(path, str) else path
368 try:
369 path_obj.mkdir(parents=True, exist_ok=True)
370 self.logger.debug("Directory created", path=str(path_obj))
371 except OSError as e:
372 raise FileError(
373 message=f"Cannot create directory: {path_obj}",
374 details=str(e),
375 recovery="Check parent directory permissions and disk space",
376 ) from e
378 def delete_file(self, path: str | Path) -> None:
379 path_obj = Path(path) if isinstance(path, str) else path
381 try:
382 if path_obj.exists():
383 path_obj.unlink()
385 cache_key = self._get_cache_key(path_obj)
386 self.cache._evict(cache_key)
387 self._file_timestamps.pop(str(path_obj), None)
389 self.logger.debug("File deleted", path=str(path_obj))
390 except OSError as e:
391 raise FileError(
392 message=f"Cannot delete file: {path_obj}",
393 details=str(e),
394 recovery="Check file permissions",
395 ) from e
397 def list_files(self, path: str | Path, pattern: str = "*") -> Iterator[Path]:
398 path_obj = Path(path) if isinstance(path, str) else path
400 if not path_obj.is_dir():
401 raise FileError(
402 message=f"Path is not a directory: {path_obj}",
403 details=f"Cannot list files in {path_obj}",
404 recovery="Ensure path points to a valid directory",
405 )
407 try:
408 yield from path_obj.glob(pattern)
409 except OSError as e:
410 raise FileError(
411 message=f"Cannot list files in directory: {path_obj}",
412 details=str(e),
413 recovery="Check directory permissions",
414 ) from e
416 async def flush_operations(self) -> None:
417 if self.batch_ops:
418 await self.batch_ops.flush_all()
420 def get_cache_stats(self) -> dict[str, Any]:
421 return self.cache.get_stats()
423 def clear_cache(self) -> None:
424 self.cache.clear()
425 self._file_timestamps.clear()
427 def exists(self, path: str | Path) -> bool:
428 return (Path(path) if isinstance(path, str) else path).exists()
430 def mkdir(self, path: str | Path, parents: bool = False) -> None:
431 path_obj = Path(path) if isinstance(path, str) else path
432 try:
433 path_obj.mkdir(parents=parents, exist_ok=True)
434 except OSError as e:
435 raise FileError(
436 message=f"Cannot create directory: {path_obj}",
437 details=str(e),
438 recovery="Check parent directory permissions",
439 ) from e