Coverage for src/romfarmer/cache/manager.py: 0%
369 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""
2ROM Cache Manager
4Manages cached transformed ROM files to accelerate builds and save disk space.
5"""
7import hashlib
8import json
9import logging
10import os
11import shutil
12import subprocess
13from datetime import datetime
14from pathlib import Path
15from typing import Any
17from sqlalchemy import create_engine
18from sqlalchemy.orm import Session, sessionmaker
20from ..metadata.database import Base
21from .config import CacheConfig, CacheLinkMode, CacheResult, CacheVerifyLevel
22from .models import ROMCache, TreeCache
24logger = logging.getLogger(__name__)
27class CacheManager:
28 """
29 Manages ROM transformation cache.
31 Usage:
32 cache = CacheManager(config)
34 # Check cache before building
35 result = cache.get(source_md5, format='chd', params={'codec': 'lzma'})
36 if result.hit:
37 cache.link_to(result.cache_path, output_path)
38 else:
39 # Build the file...
40 cache.store(source_md5, built_file, format='chd', params={'codec': 'lzma'})
41 """
43 def __init__(
44 self,
45 config: CacheConfig | None = None,
46 session: Session | None = None,
47 db_path: Path | None = None,
48 action_cache=None, # type: Optional[Any] # ActionCache | None
49 ):
50 """Initialize cache manager.
52 Args:
53 config: Cache configuration (loads from env if None)
54 session: SQLAlchemy session (creates new one if None)
55 db_path: Database path (uses metadata/database/romfarmer.db if None)
56 action_cache: Optional ActionCache for alias delegation (Phase 2+).
57 When provided, store() also records aliases and
58 get_by_zip_identity() falls back to ActionCache on miss.
59 """
60 self.config = config or CacheConfig.from_env()
62 # Ensure cache directory exists
63 self.config.cache_dir.mkdir(parents=True, exist_ok=True)
65 # Phase 2 delegation: ActionCache for unified alias store
66 self._action_cache = action_cache
68 # Set up database — use the unified romfarmer.db by default
69 if session:
70 self.session = session
71 self._owns_session = False
72 else:
73 db_path = db_path or Path("metadata/database/romfarmer.db")
74 db_path.parent.mkdir(parents=True, exist_ok=True)
75 engine = create_engine(f"sqlite:///{db_path}", echo=False)
76 Base.metadata.create_all(engine)
77 SessionLocal = sessionmaker(bind=engine)
78 self.session = SessionLocal()
79 self._owns_session = True
81 # Cache for tool versions
82 self._tool_versions: dict[str, str] = {}
84 def close(self):
85 """Close database session if we own it."""
86 if self._owns_session and self.session:
87 self.session.close()
89 def __enter__(self):
90 return self
92 def __exit__(self, exc_type, exc_val, exc_tb):
93 self.close()
95 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
96 # Core Cache Operations
97 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
99 def get_by_filename(
100 self,
101 source_filename: str,
102 source_size: int,
103 format: str,
104 params: dict[str, Any] | None = None,
105 ) -> CacheResult:
106 """Look up a cached file by source filename and size (fast pre-check).
108 This allows cache lookup WITHOUT extracting archives, by reading
109 the internal filename from ZIP headers.
111 Args:
112 source_filename: Name of source file (e.g., 'Game.bin')
113 source_size: Size of source file in bytes
114 format: Output format ('chd', 'rvz', '7z', etc.)
115 params: Compression parameters
117 Returns:
118 CacheResult with hit=True if cached file found and valid
119 """
120 if not self.config.enabled:
121 return CacheResult(hit=False, message="Cache disabled")
123 params_hash = self._hash_params(params)
125 # Look up by filename + size + format + params
126 entry = (
127 self.session.query(ROMCache)
128 .filter_by(
129 source_filename=source_filename,
130 source_size=source_size,
131 format=format,
132 params_hash=params_hash,
133 )
134 .first()
135 )
137 if not entry:
138 return CacheResult(hit=False, message="Not in cache (by filename)")
140 # Verify cached file exists
141 cache_path = self.config.cache_dir / entry.cache_path
142 if not self._verify_cached_file(entry, cache_path):
143 logger.warning(f"Cache entry invalid, removing: {entry.cache_path}")
144 self.session.delete(entry)
145 self.session.commit()
146 return CacheResult(hit=False, message="Cached file missing or invalid")
148 # Update last used timestamp
149 entry.last_used = datetime.utcnow()
150 self.session.commit()
152 return CacheResult(
153 hit=True,
154 cache_path=cache_path,
155 entry=entry,
156 message="Cache hit (by filename)",
157 )
159 def get_by_zip_identity(
160 self,
161 zip_crc32: str,
162 zip_content_size: int,
163 format: str,
164 params: dict[str, Any] | None = None,
165 ) -> CacheResult:
166 """Look up a cached file by ZIP identity (CRC32 + content size).
168 This allows cache lookup WITHOUT extracting archives, by reading
169 the CRC32 and uncompressed size from ZIP headers (instant).
171 For torrentzipped archives (Myrient, etc.), CRC32 is stable and
172 can uniquely identify contents.
174 Args:
175 zip_crc32: CRC32 from ZIP header, e.g., "2578c3f9"
176 zip_content_size: Uncompressed size from ZIP header
177 format: Output format ('chd', 'rvz', '7z', etc.)
178 params: Compression parameters
180 Returns:
181 CacheResult with hit=True if cached file found and valid
182 """
183 if not self.config.enabled:
184 return CacheResult(hit=False, message="Cache disabled")
186 params_hash = self._hash_params(params)
188 # Look up by ZIP identity + format + params
189 entry = (
190 self.session.query(ROMCache)
191 .filter_by(
192 source_zip_crc32=zip_crc32,
193 source_zip_content_size=zip_content_size,
194 format=format,
195 params_hash=params_hash,
196 )
197 .first()
198 )
200 if not entry:
201 return CacheResult(hit=False, message="Not in cache (by ZIP identity)")
203 # Verify cached file exists
204 cache_path = self.config.cache_dir / entry.cache_path
205 if not self._verify_cached_file(entry, cache_path):
206 logger.warning(f"Cache entry invalid, removing: {entry.cache_path}")
207 self.session.delete(entry)
208 self.session.commit()
209 return CacheResult(hit=False, message="Cached file missing or invalid")
211 # Update last used timestamp
212 entry.last_used = datetime.utcnow()
213 self.session.commit()
215 return CacheResult(
216 hit=True,
217 cache_path=cache_path,
218 entry=entry,
219 message="Cache hit (by ZIP identity)",
220 )
222 def get(
223 self,
224 source_md5: str,
225 format: str,
226 params: dict[str, Any] | None = None,
227 tool_name: str | None = None,
228 ) -> CacheResult:
229 """Look up a cached file.
231 Args:
232 source_md5: MD5 hash of source file
233 format: Output format ('chd', 'rvz', '7z', etc.)
234 params: Compression parameters
235 tool_name: Tool used (for version checking)
237 Returns:
238 CacheResult with hit=True if cached file found and valid
239 """
240 if not self.config.enabled:
241 return CacheResult(hit=False, message="Cache disabled")
243 params_hash = self._hash_params(params)
245 # Look up in database
246 entry = (
247 self.session.query(ROMCache)
248 .filter_by(
249 source_md5=source_md5,
250 format=format,
251 params_hash=params_hash,
252 )
253 .first()
254 )
256 if not entry:
257 return CacheResult(hit=False, message="Not in cache")
259 # Check tool version if configured
260 if self.config.check_tool_version and tool_name:
261 current_version = self.get_tool_version(tool_name)
262 if current_version and entry.tool_version != current_version:
263 logger.debug(f"Cache version mismatch: {entry.tool_version} vs {current_version}")
264 return CacheResult(
265 hit=False,
266 message=f"Tool version changed: {entry.tool_version} → {current_version}",
267 )
269 # Verify cached file exists
270 cache_path = self.config.cache_dir / entry.cache_path
271 if not self._verify_cached_file(entry, cache_path):
272 # Clean up stale entry
273 logger.warning(f"Cache entry invalid, removing: {entry.cache_path}")
274 self.session.delete(entry)
275 self.session.commit()
276 return CacheResult(hit=False, message="Cached file missing or invalid")
278 # Update last used timestamp
279 entry.last_used = datetime.utcnow()
280 self.session.commit()
282 return CacheResult(
283 hit=True,
284 cache_path=cache_path,
285 entry=entry,
286 message="Cache hit",
287 )
289 def store(
290 self,
291 source_md5: str,
292 source_file: Path,
293 built_file: Path,
294 format: str,
295 params: dict[str, Any] | None = None,
296 tool_name: str | None = None,
297 tool_version: str | None = None,
298 zip_crc32: str | None = None,
299 zip_content_size: int | None = None,
300 ) -> CacheResult:
301 """Store a built file in the cache.
303 Args:
304 source_md5: MD5 hash of source file
305 source_file: Path to source file (for metadata)
306 built_file: Path to the built file to cache
307 format: Output format ('chd', 'rvz', '7z', etc.)
308 params: Compression parameters
309 tool_name: Tool used for transformation
310 tool_version: Tool version (auto-detected if None)
311 zip_crc32: CRC32 from original ZIP header (for fast pre-check)
312 zip_content_size: Uncompressed size from original ZIP header
314 Returns:
315 CacheResult with cached file path
316 """
317 if not self.config.enabled:
318 return CacheResult(hit=False, message="Cache disabled")
320 if not built_file.exists():
321 return CacheResult(hit=False, message="Built file does not exist")
323 params_hash = self._hash_params(params)
325 # Determine cache path
326 # Use nested directories for filesystem performance: ab/abc123_params.chd
327 prefix = source_md5[:2]
328 cache_subdir = self.config.cache_dir / format / prefix
329 cache_subdir.mkdir(parents=True, exist_ok=True)
331 cache_filename = f"{source_md5}_{params_hash}.{format}"
332 cache_path = cache_subdir / cache_filename
333 relative_path = f"{format}/{prefix}/{cache_filename}"
335 # Get tool version
336 if tool_name and not tool_version:
337 tool_version = self.get_tool_version(tool_name)
339 # Calculate final file hash and size
340 final_md5 = self._calculate_md5(built_file)
341 final_size = built_file.stat().st_size
342 source_size = source_file.stat().st_size if source_file.exists() else None
344 # Atomic write: copy to temp, then rename
345 temp_path = cache_path.with_suffix(".tmp")
346 try:
347 shutil.copy2(built_file, temp_path)
348 temp_path.rename(cache_path)
349 except Exception as e:
350 if temp_path.exists():
351 temp_path.unlink()
352 raise RuntimeError(f"Failed to store in cache: {e}") from e
354 # Create or update database entry
355 entry = (
356 self.session.query(ROMCache)
357 .filter_by(
358 source_md5=source_md5,
359 format=format,
360 params_hash=params_hash,
361 )
362 .first()
363 )
365 if entry:
366 # Update existing entry
367 entry.cache_path = relative_path
368 entry.final_md5 = final_md5
369 entry.final_size = final_size
370 entry.tool_name = tool_name
371 entry.tool_version = tool_version
372 entry.compression_params = json.dumps(params) if params else None
373 entry.source_filename = source_file.name
374 entry.source_size = source_size
375 entry.source_zip_crc32 = zip_crc32
376 entry.source_zip_content_size = zip_content_size
377 entry.last_used = datetime.utcnow()
378 else:
379 # Create new entry
380 entry = ROMCache(
381 source_md5=source_md5,
382 format=format,
383 params_hash=params_hash,
384 cache_path=relative_path,
385 final_md5=final_md5,
386 final_size=final_size,
387 tool_name=tool_name,
388 tool_version=tool_version,
389 compression_params=json.dumps(params) if params else None,
390 source_filename=source_file.name,
391 source_size=source_size,
392 source_zip_crc32=zip_crc32,
393 source_zip_content_size=zip_content_size,
394 )
395 self.session.add(entry)
397 self.session.commit()
399 logger.info(f"Cached: {source_file.name} → {relative_path}")
401 # Phase 2 delegation: record aliases in ActionCache so the new Executor
402 # can find this entry via either MD5 or ZIP identity lookups.
403 if self._action_cache is not None:
404 try:
405 import hashlib
407 from romfarmer.ir.identity import Identity
408 from romfarmer.ir.identity import ZipIdentity as _ZI
410 sha256_hex = hashlib.sha256(cache_path.read_bytes()).hexdigest()
411 zi = None
412 if zip_crc32 and zip_content_size and source_file.exists():
413 zi = _ZI(
414 member_crc32=int(zip_crc32, 16)
415 if isinstance(zip_crc32, str)
416 else int(zip_crc32),
417 member_size=zip_content_size,
418 member_name=source_file.name,
419 )
420 alias_ident = Identity(
421 sha256=sha256_hex,
422 md5=final_md5,
423 size=final_size,
424 zip_identity=zi,
425 )
426 self._action_cache.record_aliases(alias_ident)
427 except Exception as _e:
428 logger.debug(f"ActionCache alias delegation failed (non-fatal): {_e}")
430 return CacheResult(
431 hit=True,
432 cache_path=cache_path,
433 entry=entry,
434 message="Stored in cache",
435 )
437 def link_to(
438 self,
439 cache_path: Path,
440 output_path: Path,
441 mode: CacheLinkMode | None = None,
442 ) -> bool:
443 """Link or copy cached file to output location.
445 Args:
446 cache_path: Path to cached file
447 output_path: Desired output path
448 mode: Link mode (uses config default if None)
450 Returns:
451 True if successful
452 """
453 mode = mode or self.config.link_mode
454 output_path.parent.mkdir(parents=True, exist_ok=True)
456 # Remove existing file if present
457 if output_path.exists() or output_path.is_symlink():
458 output_path.unlink()
460 try:
461 if mode == CacheLinkMode.HARDLINK:
462 try:
463 os.link(cache_path, output_path)
464 logger.debug(f"Hardlinked: {output_path.name}")
465 return True
466 except OSError:
467 # Fall back to copy if hardlink fails (cross-filesystem)
468 logger.debug("Hardlink failed, falling back to copy")
469 shutil.copy2(cache_path, output_path)
470 return True
472 elif mode == CacheLinkMode.SYMLINK:
473 os.symlink(cache_path.resolve(), output_path)
474 logger.debug(f"Symlinked: {output_path.name}")
475 return True
477 else: # COPY
478 shutil.copy2(cache_path, output_path)
479 logger.debug(f"Copied: {output_path.name}")
480 return True
482 except Exception as e:
483 logger.error(f"Failed to link {cache_path} to {output_path}: {e}")
484 return False
486 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
487 # Tool Version Detection
488 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
490 def get_tool_version(self, tool_name: str) -> str | None:
491 """Get version string for a tool.
493 Args:
494 tool_name: Tool name ('chdman', '7z', 'dolphin-tool', etc.)
496 Returns:
497 Version string or None if not detectable
498 """
499 if tool_name in self._tool_versions:
500 return self._tool_versions[tool_name]
502 version = None
504 try:
505 if tool_name == "chdman":
506 result = subprocess.run(["chdman"], capture_output=True, text=True, timeout=5)
507 # Parse: "chdman - MAME Compressed Hunks of Data (CHD) manager 0.262"
508 output = result.stdout + result.stderr
509 import re
511 match = re.search(r"(\d+\.\d+)", output)
512 if match:
513 version = f"mame{match.group(1).replace('.', '')}"
515 elif tool_name == "7z":
516 result = subprocess.run(["7z"], capture_output=True, text=True, timeout=5)
517 import re
519 match = re.search(r"(\d+\.\d+)", result.stdout)
520 if match:
521 version = match.group(1)
523 elif tool_name == "dolphin-tool":
524 result = subprocess.run(
525 ["dolphin-tool", "--version"], capture_output=True, text=True, timeout=5
526 )
527 version = result.stdout.strip()
529 # Add more tools as needed
531 except Exception as e:
532 logger.debug(f"Could not detect {tool_name} version: {e}")
534 self._tool_versions[tool_name] = version
535 return version
537 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
538 # Cache Statistics and Maintenance
539 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
541 def get_stats(self) -> dict[str, Any]:
542 """Get cache statistics.
544 Returns:
545 Dictionary with cache stats
546 """
547 total_entries = self.session.query(ROMCache).count()
549 # Group by format
550 from sqlalchemy import func
552 format_stats = (
553 self.session.query(
554 ROMCache.format,
555 func.count(ROMCache.id),
556 func.sum(ROMCache.final_size),
557 )
558 .group_by(ROMCache.format)
559 .all()
560 )
562 formats = {}
563 total_size = 0
564 chd_count = 0
565 rvz_count = 0
566 z7_count = 0
568 for fmt, count, size in format_stats:
569 formats[fmt] = {"count": count, "size": size or 0}
570 total_size += size or 0
571 if fmt == "chd":
572 chd_count = count
573 elif fmt == "rvz":
574 rvz_count = count
575 elif fmt == "7z":
576 z7_count = count
578 # Get tool versions used
579 tool_versions = {}
580 tool_stats = (
581 self.session.query(
582 ROMCache.tool_name,
583 ROMCache.tool_version,
584 )
585 .distinct()
586 .all()
587 )
588 for tool, version in tool_stats:
589 if tool and version:
590 tool_versions[tool] = version
592 return {
593 "enabled": self.config.enabled,
594 "cache_dir": str(self.config.cache_dir),
595 "link_mode": self.config.link_mode.value,
596 "verify_level": self.config.verify_level.value,
597 "total_entries": total_entries,
598 "total_size": total_size,
599 "total_size_bytes": total_size,
600 "total_size_human": self._human_size(total_size),
601 "formats": formats,
602 "chd_count": chd_count,
603 "rvz_count": rvz_count,
604 "7z_count": z7_count,
605 "tool_versions": tool_versions,
606 }
608 def verify_all(self) -> dict[str, list]:
609 """Verify all cached files exist.
611 Returns:
612 Dict with 'valid', 'invalid', and 'missing' lists
613 """
614 valid = []
615 invalid = []
616 missing = []
618 for entry in self.session.query(ROMCache).all():
619 cache_path = self.config.cache_dir / entry.cache_path
620 if not cache_path.exists():
621 missing.append(entry.cache_key)
622 elif not self._verify_cached_file(entry, cache_path):
623 invalid.append(entry.cache_key)
624 else:
625 valid.append(entry.cache_key)
627 return {"valid": valid, "invalid": invalid, "missing": missing}
629 def get_old_entries(self, days: int = 90) -> list:
630 """Get cache entries older than specified days.
632 Args:
633 days: Age threshold in days
635 Returns:
636 List of old ROMCache entries
637 """
638 from datetime import timedelta
640 cutoff = datetime.utcnow() - timedelta(days=days)
642 return self.session.query(ROMCache).filter(ROMCache.last_used < cutoff).all()
644 def prune(self, days: int = 90) -> int:
645 """Remove cache entries older than specified days.
647 Args:
648 days: Age threshold in days
650 Returns:
651 Number of entries removed
652 """
653 entries = self.get_old_entries(days)
654 count = len(entries)
656 for entry in entries:
657 cache_path = self.config.cache_dir / entry.cache_path
658 if cache_path.exists():
659 cache_path.unlink()
660 self.session.delete(entry)
662 self.session.commit()
663 return count
665 def clear(self, format: str | None = None) -> int:
666 """Clear cache entries.
668 Args:
669 format: Only clear entries of this format (all if None)
671 Returns:
672 Number of entries removed
673 """
674 query = self.session.query(ROMCache)
675 if format:
676 query = query.filter_by(format=format)
678 entries = query.all()
679 count = len(entries)
681 for entry in entries:
682 # Delete file
683 cache_path = self.config.cache_dir / entry.cache_path
684 if cache_path.exists():
685 cache_path.unlink()
686 # Delete DB entry
687 self.session.delete(entry)
689 self.session.commit()
691 return count
693 def remove_orphans(self) -> int:
694 """Remove DB entries for missing files.
696 Returns:
697 Number of orphan entries removed
698 """
699 removed = 0
700 for entry in self.session.query(ROMCache).all():
701 cache_path = self.config.cache_dir / entry.cache_path
702 if not cache_path.exists():
703 self.session.delete(entry)
704 removed += 1
706 self.session.commit()
707 return removed
709 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
710 # Tree Cache Operations (folder-based outputs)
711 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
713 def get_tree(
714 self,
715 source_md5: str,
716 format: str,
717 params: dict[str, Any] | None = None,
718 ) -> CacheResult:
719 """Look up a cached tree (folder output) by source hash.
721 Args:
722 source_md5: MD5 hash of source file
723 format: Output format ('ps3-jb', 'daphne', 'scummvm', etc.)
724 params: Transformation parameters
726 Returns:
727 CacheResult with tree_hash in entry if hit
728 """
729 if not self.config.enabled:
730 return CacheResult(hit=False, message="Cache disabled")
732 params_hash = self._hash_params(params)
734 entry = (
735 self.session.query(TreeCache)
736 .filter_by(
737 source_md5=source_md5,
738 format=format,
739 params_hash=params_hash,
740 )
741 .first()
742 )
744 if not entry:
745 return CacheResult(hit=False, message="Not in tree cache")
747 entry.last_used = datetime.utcnow()
748 self.session.commit()
750 return CacheResult(
751 hit=True,
752 entry=entry,
753 message=f"Tree cache hit ({entry.total_files} files, {entry.folder_name})",
754 )
756 def get_tree_by_filename(
757 self,
758 source_filename: str,
759 source_size: int,
760 format: str,
761 params: dict[str, Any] | None = None,
762 ) -> CacheResult:
763 """Look up a cached tree by source filename and size.
765 Args:
766 source_filename: Name of source file
767 source_size: Size of source file in bytes
768 format: Output format
769 params: Transformation parameters
771 Returns:
772 CacheResult with tree_hash in entry if hit
773 """
774 if not self.config.enabled:
775 return CacheResult(hit=False, message="Cache disabled")
777 params_hash = self._hash_params(params)
779 entry = (
780 self.session.query(TreeCache)
781 .filter_by(
782 source_filename=source_filename,
783 source_size=source_size,
784 format=format,
785 params_hash=params_hash,
786 )
787 .first()
788 )
790 if not entry:
791 return CacheResult(hit=False, message="Not in tree cache (by filename)")
793 entry.last_used = datetime.utcnow()
794 self.session.commit()
796 return CacheResult(
797 hit=True,
798 entry=entry,
799 message=f"Tree cache hit by filename ({entry.total_files} files)",
800 )
802 def get_tree_by_zip_identity(
803 self,
804 zip_crc32: str,
805 zip_content_size: int,
806 format: str,
807 params: dict[str, Any] | None = None,
808 ) -> CacheResult:
809 """Look up a cached tree by ZIP identity.
811 Args:
812 zip_crc32: CRC32 from ZIP header
813 zip_content_size: Uncompressed size from ZIP header
814 format: Output format
815 params: Transformation parameters
817 Returns:
818 CacheResult with tree_hash in entry if hit
819 """
820 if not self.config.enabled:
821 return CacheResult(hit=False, message="Cache disabled")
823 params_hash = self._hash_params(params)
825 entry = (
826 self.session.query(TreeCache)
827 .filter_by(
828 source_zip_crc32=zip_crc32,
829 source_zip_content_size=zip_content_size,
830 format=format,
831 params_hash=params_hash,
832 )
833 .first()
834 )
836 if not entry:
837 return CacheResult(hit=False, message="Not in tree cache (by ZIP identity)")
839 entry.last_used = datetime.utcnow()
840 self.session.commit()
842 return CacheResult(
843 hit=True,
844 entry=entry,
845 message=f"Tree cache hit by ZIP identity ({entry.total_files} files)",
846 )
848 def store_tree(
849 self,
850 source_md5: str,
851 tree_hash: str,
852 total_files: int,
853 total_size: int,
854 folder_name: str,
855 format: str,
856 platform: str = "",
857 params: dict[str, Any] | None = None,
858 tool_name: str | None = None,
859 tool_version: str | None = None,
860 source_filename: str | None = None,
861 source_size: int | None = None,
862 zip_crc32: str | None = None,
863 zip_content_size: int | None = None,
864 ) -> CacheResult:
865 """Store a tree cache entry.
867 This records the mapping from source file → tree manifest hash.
868 The actual tree contents should already be ingested into the CAS
869 via TreeStore.ingest().
871 Args:
872 source_md5: MD5 hash of source file
873 tree_hash: SHA-256 hash of tree manifest
874 total_files: Number of files in tree
875 total_size: Total size of all files in bytes
876 folder_name: Output folder name (e.g., "BLUS30455.ps3")
877 format: Output format (e.g., "ps3-jb")
878 platform: Platform identifier
879 params: Transformation parameters
880 tool_name: Tool used
881 tool_version: Tool version
882 source_filename: Original filename
883 source_size: Original file size
884 zip_crc32: CRC32 from ZIP header
885 zip_content_size: Uncompressed size from ZIP header
887 Returns:
888 CacheResult
889 """
890 if not self.config.enabled:
891 return CacheResult(hit=False, message="Cache disabled")
893 params_hash = self._hash_params(params)
895 # Get tool version if not provided
896 if tool_name and not tool_version:
897 tool_version = self.get_tool_version(tool_name)
899 # Create or update
900 entry = (
901 self.session.query(TreeCache)
902 .filter_by(
903 source_md5=source_md5,
904 format=format,
905 params_hash=params_hash,
906 )
907 .first()
908 )
910 if entry:
911 entry.tree_hash = tree_hash
912 entry.total_files = total_files
913 entry.total_size = total_size
914 entry.folder_name = folder_name
915 entry.platform = platform
916 entry.tool_name = tool_name
917 entry.tool_version = tool_version
918 entry.transformation_params = json.dumps(params) if params else None
919 entry.source_filename = source_filename
920 entry.source_size = source_size
921 entry.source_zip_crc32 = zip_crc32
922 entry.source_zip_content_size = zip_content_size
923 entry.last_used = datetime.utcnow()
924 else:
925 entry = TreeCache(
926 source_md5=source_md5,
927 format=format,
928 params_hash=params_hash,
929 tree_hash=tree_hash,
930 total_files=total_files,
931 total_size=total_size,
932 folder_name=folder_name,
933 platform=platform,
934 tool_name=tool_name,
935 tool_version=tool_version,
936 transformation_params=json.dumps(params) if params else None,
937 source_filename=source_filename,
938 source_size=source_size,
939 source_zip_crc32=zip_crc32,
940 source_zip_content_size=zip_content_size,
941 )
942 self.session.add(entry)
944 self.session.commit()
946 logger.info(
947 f"Tree cached: {source_filename or source_md5[:8]} → "
948 f"{tree_hash[:12]}... ({total_files} files, {folder_name})"
949 )
951 return CacheResult(
952 hit=True,
953 entry=entry,
954 message="Stored in tree cache",
955 )
957 def get_tree_stats(self) -> dict[str, Any]:
958 """Get tree cache statistics."""
959 from sqlalchemy import func
961 total_entries = self.session.query(TreeCache).count()
963 format_stats = (
964 self.session.query(
965 TreeCache.format,
966 func.count(TreeCache.id),
967 func.sum(TreeCache.total_size),
968 func.sum(TreeCache.total_files),
969 )
970 .group_by(TreeCache.format)
971 .all()
972 )
974 formats = {}
975 total_size = 0
976 total_files = 0
978 for fmt, count, size, files in format_stats:
979 formats[fmt] = {
980 "trees": count,
981 "total_size": size or 0,
982 "total_files": files or 0,
983 }
984 total_size += size or 0
985 total_files += files or 0
987 return {
988 "total_trees": total_entries,
989 "total_size": total_size,
990 "total_size_human": self._human_size(total_size),
991 "total_files_across_trees": total_files,
992 "formats": formats,
993 }
995 def get_all_tree_hashes(self) -> set[str]:
996 """Get all tree hashes from the cache (for GC)."""
997 results = self.session.query(TreeCache.tree_hash).all()
998 return {r[0] for r in results}
1000 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1001 # Private Helpers
1002 # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1004 def _hash_params(self, params: dict[str, Any] | None) -> str:
1005 """Create a stable hash of compression parameters."""
1006 if not params:
1007 return "default"
1009 # Sort keys for stable ordering
1010 sorted_json = json.dumps(params, sort_keys=True)
1011 return hashlib.md5(sorted_json.encode()).hexdigest()[:16]
1013 def _verify_cached_file(self, entry: ROMCache, cache_path: Path) -> bool:
1014 """Verify a cached file based on verify level."""
1015 if self.config.verify_level == CacheVerifyLevel.NONE:
1016 return True
1018 if not cache_path.exists():
1019 return False
1021 if self.config.verify_level == CacheVerifyLevel.EXISTS:
1022 return True
1024 if self.config.verify_level == CacheVerifyLevel.SIZE:
1025 return cache_path.stat().st_size == entry.final_size
1027 if self.config.verify_level == CacheVerifyLevel.MD5:
1028 return self._calculate_md5(cache_path) == entry.final_md5
1030 return True
1032 def _calculate_md5(self, file_path: Path) -> str:
1033 """Calculate MD5 hash of a file."""
1034 hash_md5 = hashlib.md5()
1035 with open(file_path, "rb") as f:
1036 for chunk in iter(lambda: f.read(8192), b""):
1037 hash_md5.update(chunk)
1038 return hash_md5.hexdigest()
1040 def _human_size(self, size_bytes: int) -> str:
1041 """Convert bytes to human readable string."""
1042 for unit in ["B", "KB", "MB", "GB", "TB"]:
1043 if abs(size_bytes) < 1024.0:
1044 return f"{size_bytes:.1f} {unit}"
1045 size_bytes /= 1024.0
1046 return f"{size_bytes:.1f} PB"