refactor: move recipes and acquisition to packages

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:49:49 +01:00
1 parent 664776ae91
commit 0e4e5f450d
35 files changed
+2186 -2071

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Archive recipes: romset identification, rebuilt pinned archives, and the recipe and build of every archive the collection holds."""
+179
View File
@@ -0,0 +1,179 @@
"""Build: an archive rebuilt from the members the collection holds, verified before it lands."""
from __future__ import annotations
import hashlib
import os
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
from core.paths import REPO_ROOT
from core.torrentzip import write_torrentzip, zlib_ng_version
from recipes.ledger import is_archive_path
from recipes.members import _member_sha1, _opener
# --- build ------------------------------------------------------------------
@dataclass
class Source:
path: Path
member: str | None # None for a loose file
@dataclass
class AtomIndex:
"""Where each member sha1 can be read in the collection."""
loose: dict[str, Path] = field(default_factory=dict)
inside: dict[str, list[tuple[Path, str]]] = field(default_factory=dict)
@classmethod
def from_collection(cls, ledger: dict[str, dict], db: dict, root: Path) -> AtomIndex:
index = cls()
for entry in (db.get("files") or {}).values():
path = root / entry.get("path", "")
if not is_archive_path(entry.get("path", "")) and path.is_file():
index.loose.setdefault(entry["sha1"], path)
for archive, record in sorted(ledger.items()):
path = root / archive
if not path.is_file():
continue
for member in record.get("members", []):
index.inside.setdefault(member["sha1"], []).append((path, member["name"]))
return index
def find(self, sha1: str, own: Path) -> Source | None:
"""A loose copy first, then another archive, then the archive itself."""
if sha1 in self.loose:
return Source(self.loose[sha1], None)
holders = self.inside.get(sha1, [])
for path, member in holders:
if path != own:
return Source(path, member)
for path, member in holders:
return Source(path, member)
return None
def held(self, sha1: str) -> bool:
return sha1 in self.loose or sha1 in self.inside
@dataclass
class BuildResult:
path: str
status: str # exact, canonical, impossible, failed
output: str = ""
detail: str = ""
missing: list[dict] = field(default_factory=list)
own_members: int = 0
def _members_match(built: Path, members: list[dict]) -> str:
"""Empty when *built* holds exactly *members*, else what differs."""
expected = sorted((m["name"], m["size"], m["crc32"], m["sha1"]) for m in members)
with zipfile.ZipFile(built) as archive:
names = [info.filename for info in archive.infolist() if not info.is_dir()]
sizes = {info.filename: info.file_size for info in archive.infolist()}
crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()}
held = sorted(
(name, sizes[name], crcs[name], _member_sha1(built, name)) for name in names
)
if held == expected:
return ""
missing = sorted(set(expected) - set(held))
extra = sorted(set(held) - set(expected))
return f"members differ: expected {missing[:3]}, built {extra[:3]}"
def _file_sha1(path: Path) -> str:
digest = hashlib.sha1()
with path.open("rb") as handle:
while chunk := handle.read(16 * 1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
def destination(record_path: str, output_dir: Path) -> Path:
"""Where a build lands: the archive's path below ``bios/``, under *output_dir*."""
parts = Path(record_path).parts
relative = Path(*parts[1:]) if parts and parts[0] == "bios" else Path(record_path)
return output_dir / relative
def build_archive(
record: dict,
atoms: AtomIndex,
output_dir: Path,
root: Path = REPO_ROOT,
attempts: int = 2,
) -> BuildResult:
"""Build *record* from held members into *output_dir*, verified.
The bytes are written to a scratch file beside the destination and read
back from disk: an exact recipe must give its recorded sha1, a canonical
one its members. A mismatch is built once more, then refused: nothing
wrong is ever moved to the destination. Under zlib-ng an exact recipe is
checked by its members only and never reported exact.
"""
path = record["path"]
own = root / path
sources: list[tuple[str, Source]] = []
missing: list[dict] = []
for member in record["members"]:
source = atoms.find(member["sha1"], own)
if source is None:
missing.append(member)
else:
sources.append((member["name"], source))
if missing:
return BuildResult(path, "impossible", missing=missing)
own_members = sum(1 for _name, source in sources if source.path == own)
ng = zlib_ng_version()
exact = record["rebuild"] == "exact" and not ng
target = destination(path, output_dir)
target.parent.mkdir(parents=True, exist_ok=True)
scratch = target.with_name(f".{target.name}.{os.getpid()}.part")
detail = ""
try:
for _attempt in range(attempts):
with scratch.open("wb") as handle:
write_torrentzip(
handle,
[(name, _opener(source.path, source.member)) for name, source in sources],
)
if exact:
written = _file_sha1(scratch)
detail = "" if written == record["sha1"] else (
f"sha1 {written} is not the recorded {record['sha1']}"
)
else:
detail = _members_match(scratch, record["members"])
if not detail:
os.replace(scratch, target)
status = "exact" if exact else "canonical"
note = (
f"zlib-ng {ng}: exact bytes not claimed, members verified"
if ng and record["rebuild"] == "exact" else ""
)
return BuildResult(path, status, str(target), note, own_members=own_members)
finally:
if scratch.exists():
scratch.unlink()
return BuildResult(path, "failed", detail=detail, own_members=own_members)
def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list[dict]:
"""Records named by a path (relative or absolute) or by a file name."""
candidate = Path(wanted)
if candidate.is_absolute():
try:
candidate = candidate.resolve().relative_to(root.resolve())
except ValueError:
return []
key = candidate.as_posix()
if key in ledger:
return [ledger[key]]
return [record for path, record in sorted(ledger.items()) if Path(path).name == wanted]
+229
View File
@@ -0,0 +1,229 @@
"""Capture: a recipe record for every archive the database lists."""
from __future__ import annotations
import hashlib
import zipfile
from collections import defaultdict
from collections.abc import Callable, Iterable
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from typing import BinaryIO
from core.torrentzip import write_torrentzip, zlib_ng_version
from recipes.ledger import database_archives
from recipes.members import _member_sha1, _opener
_TORRENTZIP_COMMENT = b"TORRENTZIPPED-"
# --- capture ----------------------------------------------------------------
class HashSink:
"""A write target that hashes what it receives, and keeps it if asked."""
def __init__(self, handle: BinaryIO | None = None) -> None:
self.handle = handle
self.sha1 = hashlib.sha1()
self.md5 = hashlib.md5()
self.size = 0
def write(self, data: bytes) -> int:
self.sha1.update(data)
self.md5.update(data)
self.size += len(data)
if self.handle is not None:
self.handle.write(data)
return len(data)
def _file_infos(path: Path) -> tuple[list[zipfile.ZipInfo], list[str], bool]:
with zipfile.ZipFile(path) as archive:
infos = archive.infolist()
torrentzip = archive.comment.startswith(_TORRENTZIP_COMMENT)
files = [info for info in infos if not info.is_dir()]
directories = [info.filename for info in infos if info.is_dir()]
return files, directories, torrentzip
def read_archive(path: Path, sha1: str) -> dict:
"""Members, directories and rebuild class of the archive at *path*.
A TorrentZip archive is rebuilt from its own members: equal bytes make
the recipe ``exact``. A mismatch is rebuilt once more before it is
believed, because this host sometimes computes wrongly under load. Any
other archive is ``canonical`` and only its members are read.
"""
files, directories, torrentzip = _file_infos(path)
rebuild = "canonical"
by_name: dict[str, str] = {}
if torrentzip:
for _attempt in range(2):
sink = HashSink()
written = write_torrentzip(
sink, [(info.filename, _opener(path, info.filename)) for info in files]
)
by_name = {member.name: member.sha1 for member in written}
if sink.sha1.hexdigest() == sha1:
rebuild = "exact"
break
else:
by_name = {info.filename: _member_sha1(path, info.filename) for info in files}
record: dict = {
"rebuild": rebuild,
"members": [
{
"name": info.filename,
"size": info.file_size,
"crc32": f"{info.CRC:08x}",
"sha1": by_name[info.filename],
}
for info in files
],
}
if directories:
record["directories"] = directories
return record
def _read_job(job: tuple[str, str]) -> tuple[str, dict | str]:
path, sha1 = job
try:
return path, read_archive(Path(path), sha1)
except (OSError, zipfile.BadZipFile, UnicodeEncodeError) as exc:
return path, f"{type(exc).__name__}: {exc}"
def _hash_values(value: object) -> set[str]:
raw = value if isinstance(value, list) else str(value or "").split(",")
return {str(item).strip().lower() for item in raw if str(item).strip()}
def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str]]:
"""Container hash -> who pins it: ``platform:<name>`` or ``profile:<name>``.
A ``zipped_file`` entry pins a ROM inside the archive, and a Recalbox
archive md5 is the composite of its members (``zip_digest: composite``,
Bios.cpp:64-68): neither pins the container bytes.
"""
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
pins: dict[str, set[str]] = defaultdict(set)
for platform in list_registered_platforms(platforms_dir):
config = load_platform_config(platform, platforms_dir)
for system in config.get("systems", {}).values():
for entry in system.get("files", []) or []:
if entry.get("zipped_file") or entry.get("zip_digest") == "composite":
continue
for key in ("md5", "sha1", "alt_md5"):
for value in _hash_values(entry.get(key)):
pins[value].add(f"platform:{platform}")
for name, profile in load_emulator_profiles(emulators_dir, skip_aliases=False).items():
for entry in profile.get("files", []) or []:
for key in ("md5", "sha1", "sha256"):
for value in _hash_values(entry.get(key)):
pins[value].add(f"profile:{name}")
return dict(pins)
MemberList = tuple[tuple[str, str], ...]
def recipe_index(emulators_dir: str, recipes_dir: str) -> dict[MemberList, set[str]]:
"""Sorted (name, crc32) -> labels of the recipes with exactly those members.
Matching on the member list, not the archive name, credits a DAT that
knows the set under another name (``aga.zip`` is MAME's ``isa_aga``).
"""
from model.profiles import load_emulator_profiles
from recipes.romsets import collect_recipes, load_dat_recipes
index: dict[MemberList, set[str]] = defaultdict(set)
profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
for per_label in collect_recipes(profiles).values():
for label, recipe in per_label.items():
index[tuple(sorted(recipe))].add(f"profile:{label}")
for per_label in load_dat_recipes(recipes_dir).values():
for label, recipe in per_label.items():
index[tuple(sorted(recipe))].add(label)
return dict(index)
def member_key(members: Iterable[dict]) -> MemberList:
return tuple(sorted((m["name"], m["crc32"]) for m in members))
def capture(
db: dict,
previous: dict[str, dict],
index: dict[MemberList, set[str]],
pins: dict[str, set[str]],
workers: int = 4,
log: Callable[[str], None] = print,
) -> tuple[dict[str, dict], dict[str, str]]:
"""A record for every archive in *db*, and the archives that could not be read.
A previous record whose sha1 still names the file is kept as read: the
container bytes fix the members. Sources and pins are recomputed every
time, since profiles, snapshots and platform lists move.
"""
if zlib_ng_version():
raise ZlibNgError(zlib_ng_version())
archives = database_archives(db)
reused: dict[str, dict] = {}
jobs: list[tuple[str, str]] = []
for path, entry in sorted(archives.items()):
old = previous.get(path)
if old and old.get("sha1") == entry["sha1"] and old.get("members"):
reused[path] = old
else:
jobs.append((path, entry["sha1"]))
read: dict[str, dict] = {}
failed: dict[str, str] = {}
if jobs:
log(f" reading {len(jobs)} archives ({len(reused)} unchanged)")
with ProcessPoolExecutor(max_workers=workers) as pool:
for path, result in pool.map(_read_job, jobs, chunksize=4):
if isinstance(result, str):
failed[path] = result
else:
read[path] = result
records: dict[str, dict] = {}
for path, entry in sorted(archives.items()):
body = reused.get(path) or read.get(path)
if body is None:
continue
record = {
"path": path,
"sha1": entry["sha1"],
"md5": entry["md5"],
"size": entry["size"],
"rebuild": body["rebuild"],
"members": body["members"],
}
if body.get("directories"):
record["directories"] = body["directories"]
record["sources"] = sorted(index.get(member_key(body["members"]), set())) + [
"collection"
]
pinned = set()
for value in (entry["md5"], entry["sha1"], entry.get("sha256", "")):
pinned |= pins.get(str(value).lower(), set())
if pinned:
record["bytes_pinned"] = True
record["pins"] = sorted(pinned)
records[path] = record
return records, failed
class ZlibNgError(RuntimeError):
def __init__(self, version: str | None) -> None:
super().__init__(
f"this Python deflates with zlib-ng {version}: TorrentZip bytes are "
"stock zlib's level-9 output, so an exact rebuild cannot be proven "
"or claimed here. Run under a Python linked against stock zlib."
)
+213
View File
@@ -0,0 +1,213 @@
"""Which recipe rebuilds a held archive, and which pinned archives the collection lacks but can rebuild."""
from __future__ import annotations
import hashlib
import sys
import zipfile
from collections import defaultdict
from pathlib import Path
from core.torrentzip import is_torrentzip
from model.platforms import load_platform_config
from model.registry import list_registered_platforms
from recipes.pool import AtomPool
from recipes.romsets import Recipe
def identify_archive(
path: Path, recipes: dict[str, Recipe], pool: AtomPool
) -> str | None:
"""Return the recipe label that reproduces *path* byte for byte.
Equal bytes need equal (name, crc32) members, which the archive's
central directory gives without inflating anything: building every
recipe at DEFLATE level 9 first took 94 s and 1 GB at pipeline step 1c.
"""
held = _member_list(path)
if held is None:
return None
original = path.read_bytes()
md5, size = hashlib.md5(original).hexdigest(), len(original)
for label, recipe in sorted(recipes.items()):
if sorted((name, crc.lower()) for name, crc in recipe) != held:
continue
if pool.digest(recipe) == (md5, size):
return label
return None
def _member_list(path: Path) -> list[tuple[str, str]] | None:
"""Sorted (name, crc32) of an archive's members, from its directory."""
try:
with zipfile.ZipFile(path) as archive:
return sorted(
(info.filename, format(info.CRC, "08x"))
for info in archive.infolist() if not info.is_dir()
)
except (zipfile.BadZipFile, OSError) as exc:
print(f" UNREADABLE: {path}: {exc}", file=sys.stderr)
return None
def reconstruct(
target_md5: str, recipes: dict[str, Recipe], pool: AtomPool
) -> tuple[str, bytes] | None:
"""Return the (label, bytes) whose TorrentZip build matches *target_md5*."""
target = target_md5.lower()
for label, recipe in sorted(recipes.items()):
known = pool.digest(recipe)
if known is not None and known[0] == target:
blob = pool.build(recipe)
if blob is not None and hashlib.md5(blob).hexdigest() == target:
return label, blob
return None
def platform_targets(platforms_dir: str) -> dict[str, set[str]]:
"""Container MD5s the platforms pin, per archive name.
``zipped_file`` entries pin an inner ROM instead of the container, so
their MD5 is not an archive hash and is skipped. So is a Recalbox md5,
the composite of the members (``zip_digest: composite``, Bios.cpp:64-68):
no container build can ever give it.
"""
targets: dict[str, set[str]] = defaultdict(set)
for name in list_registered_platforms(platforms_dir):
config = load_platform_config(name, platforms_dir)
for system in config.get("systems", {}).values():
for entry in system.get("files", []) or []:
archive = entry.get("name", "")
if (
not archive.endswith(".zip")
or entry.get("zipped_file")
or entry.get("zip_digest") == "composite"
):
continue
for value in str(entry.get("md5") or "").split(","):
value = value.strip().lower()
if len(value) == 32:
targets[archive].add(value)
return dict(targets)
def _is_archive(path: Path) -> bool:
"""Whether *path* is a readable ZIP.
A name index entry can be an alias: ``d2fdc.zip`` names a loose Apple II
ROM, not an archive. Recipes only describe archives.
"""
try:
with zipfile.ZipFile(path):
return True
except (OSError, zipfile.BadZipFile):
return False
def _local_paths(archive: str, db: dict) -> list[Path]:
matches = db["indexes"]["by_name"].get(archive) or []
if isinstance(matches, str):
matches = [matches]
paths = [Path(db["files"][sha1]["path"]) for sha1 in matches if sha1 in db["files"]]
return [path for path in paths if path.is_file() and _is_archive(path)]
def identify_report(
recipes: dict[str, dict[str, Recipe]], pool: AtomPool, db: dict
) -> dict:
"""Label every archive the collection holds with the version it matches."""
identified: list[dict] = []
unidentified: list[dict] = []
for archive, per_profile in sorted(recipes.items()):
for path in _local_paths(archive, db):
label = identify_archive(path, per_profile, pool)
record = {
"archive": archive,
"path": str(path),
"torrentzip": is_torrentzip(path),
}
if label:
record["recipe"] = label
identified.append(record)
else:
record["candidates"] = sorted(per_profile)
unidentified.append(record)
return {"identified": identified, "unidentified": unidentified}
def missing_report(
recipes: dict[str, dict[str, Recipe]],
pool: AtomPool,
db: dict,
platforms_dir: str,
) -> dict:
"""Pinned archives the collection lacks, split by why they are absent."""
have = set(db["indexes"]["by_md5"])
constructible: list[dict] = []
no_recipe: list[dict] = []
unreproducible: list[dict] = []
for archive, pinned in sorted(platform_targets(platforms_dir).items()):
per_profile = recipes.get(archive, {})
for target in sorted(pinned - have):
if not per_profile:
no_recipe.append({"archive": archive, "md5": target})
continue
found = reconstruct(target, per_profile, pool)
if found:
label, blob = found
constructible.append(
{
"archive": archive,
"md5": target,
"recipe": label,
"size": len(blob),
}
)
else:
usable = [
label
for label, recipe in per_profile.items()
if all(crc in pool for _name, crc in recipe)
]
unreproducible.append(
{
"archive": archive,
"md5": target,
"recipes_tried": sorted(usable),
"reason": (
"no recipe reproduces this MD5: the pinned archive is "
"not TorrentZip or follows a recipe not documented here"
if usable
else "ROMs for every documented recipe are missing"
),
}
)
return {
"constructible": constructible,
"unreproducible": unreproducible,
"no_recipe": no_recipe,
}
def write_reconstructions(
entries: list[dict],
recipes: dict[str, dict[str, Recipe]],
pool: AtomPool,
bios_dir: Path,
db: dict,
) -> list[str]:
"""Write each constructible archive beside its set, as a variant."""
written: list[str] = []
for entry in entries:
archive = entry["archive"]
recipe = recipes[archive][entry["recipe"]]
blob = pool.build(recipe)
if blob is None:
continue
siblings = _local_paths(archive, db)
parent = siblings[0].parent if siblings else bios_dir
destination = parent / ".variants" / f"{archive}.{entry['md5'][:8]}"
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(blob)
written.append(str(destination))
return written
+122
View File
@@ -0,0 +1,122 @@
"""A recipe for every archive the collection holds, and the build that uses it.
The collection must be able to regenerate each archive it serves from the
ROMs it holds plus a committed recipe, without any copy of that archive
from elsewhere. ``recipes/archives.json`` is that recipe list: one record
per archive in ``database.json``, keyed by its path.
A record names the members in archive order, each with its size, crc32 and
sha1, and the container's sha1, md5 and size. ``rebuild`` says what the
build reproduces:
``exact``
The archive is TorrentZip and ``build_torrentzip()`` over its members
gives its bytes. Proven at capture by rebuilding it.
``canonical``
Same members, other container bytes: the archive was written by another
tool. The build writes the TorrentZip form and checks members only.
``sources`` lists the recipes that agree on the member list: profile
``contents:`` blocks and the MAME and FBNeo DAT snapshots under
``recipes/``, then ``collection``, the archive itself. A DAT is provenance,
never the only source. ``bytes_pinned`` marks an archive whose container
hash a platform or a profile pins, with each pin named.
The build reads each member by sha1: a loose file first, then a member of
another archive, then the archive's own copy, and verifies what it wrote
before moving it into place.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from core.paths import REPO_ROOT
ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json"
# The writer contract: build_torrentzip's layout over stock zlib. A change to
# the layout is a new builder name and a new proof of every record.
BUILDER = "torrentzip-1"
_ARCHIVE_PATH = re.compile(r"\.zip(\.[0-9a-f]{8})?$", re.IGNORECASE)
def is_archive_path(path: str) -> bool:
"""A ZIP by its name: ``x.zip`` or a ``.variants/`` copy ``x.zip.1a2b3c4d``."""
return bool(_ARCHIVE_PATH.search(path))
def database_archives(db: dict) -> dict[str, dict]:
"""Path -> database entry, for every archive the database lists."""
return {
entry["path"]: entry
for entry in (db.get("files") or {}).values()
if is_archive_path(entry.get("path", ""))
}
# --- the ledger file --------------------------------------------------------
def load_ledger(path: Path = ARCHIVES_FILE) -> dict[str, dict]:
"""Path -> record, from ``recipes/archives.json``, empty when absent."""
if not path.is_file():
return {}
with path.open(encoding="utf-8") as handle:
data = json.load(handle)
return {record["path"]: record for record in data.get("archives", [])}
def rebuild_counts(path: Path = ARCHIVES_FILE) -> dict[str, int]:
"""How many recipes rebuild ``exact`` and ``canonical``, and ``total``:
the figures the README and the site print."""
records = load_ledger(path).values()
return {
"total": len(records),
**{kind: sum(1 for r in records if r.get("rebuild") == kind)
for kind in ("exact", "canonical")},
}
def ledger_text(records: dict[str, dict]) -> str:
"""One record per line, so a diff names the archive that changed."""
lines = [
json.dumps(records[path], ensure_ascii=False, separators=(",", ":"))
for path in sorted(records)
]
body = ",\n".join(f" {line}" for line in lines)
return f'{{"builder": "{BUILDER}", "archives": [\n{body}\n]}}\n'
def write_ledger(records: dict[str, dict], path: Path = ARCHIVES_FILE) -> bool:
from core.artifacts import write_if_changed
path.parent.mkdir(parents=True, exist_ok=True)
return write_if_changed(str(path), ledger_text(records))
def missing_members(ledger: dict[str, dict], db: dict) -> list[dict]:
"""Members held nowhere: neither as a loose file nor inside any archive.
Read from the committed data alone, so it holds without the files: a
member is held when database.json has its sha1 as a file, or when the
recipe of an archive database.json lists carries it.
"""
archives = database_archives(db)
loose = {
sha1 for sha1, entry in (db.get("files") or {}).items()
if not is_archive_path(entry.get("path", ""))
}
inside = {
member["sha1"]
for path, record in ledger.items() if path in archives
for member in record.get("members", [])
}
return [
{"archive": path, "member": member["name"], "sha1": member["sha1"]}
for path, record in sorted(ledger.items())
for member in record.get("members", [])
if member["sha1"] not in loose and member["sha1"] not in inside
]
+46
View File
@@ -0,0 +1,46 @@
"""Members of a ZIP read as streams, one opener per member."""
from __future__ import annotations
import hashlib
import io
import zipfile
from collections.abc import Callable
from pathlib import Path
from core.torrentzip import Source as Readable
class _Member(io.RawIOBase):
"""One member of a ZIP, open for reading, closing the archive with it."""
def __init__(self, archive: Path, name: str) -> None:
super().__init__()
self._zip = zipfile.ZipFile(archive)
self._stream = self._zip.open(name)
def readable(self) -> bool:
return True
def read(self, size: int = -1) -> bytes:
return self._stream.read(size)
def close(self) -> None:
if not self.closed:
self._stream.close()
self._zip.close()
super().close()
def _opener(source: Path, member: str | None) -> Callable[[], Readable]:
if member is None:
return lambda: source.open("rb")
return lambda: _Member(source, member)
def _member_sha1(path: Path, name: str) -> str:
digest = hashlib.sha1()
with _Member(path, name) as stream:
while chunk := stream.read(16 * 1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
+135
View File
@@ -0,0 +1,135 @@
"""ROM bytes the collection holds, addressed by crc32, and the TorrentZip builds of recipes over them."""
from __future__ import annotations
import hashlib
import json
import sys
import zipfile
from pathlib import Path
from core.paths import REPO_ROOT
from core.torrentzip import build_torrentzip
from recipes.romsets import Recipe
class AtomPool:
"""ROM bytes in the collection, addressed by CRC32.
Members are located once and read on demand: arcade sample sets reach
hundreds of megabytes and a whole-pool preload buys nothing.
"""
def __init__(
self, bios_dir: Path, digest_cache: Path | None = None, db: dict | None = None
) -> None:
# crc32 -> (archive, member), or (file, None) for a loose ROM.
self._index: dict[str, tuple[Path, str | None]] = {}
# (md5, size) of each build, kept across runs: TorrentZip bytes are a
# function of the members alone, so a recipe hashed once is known
# until the writer changes. Rebuilding the 1 221 archives took 70 s
# of every pipeline run, 63 s of it in zlib.
self._digest_cache = digest_cache
self._digests: dict[str, list] = _read_digests(digest_cache)
self._digests_changed = False
# A recipe is built once: identification and reconstruction ask for the
# same archives, and every build re-reads and re-deflates its ROMs.
self._built: dict[tuple[tuple[str, str], ...], bytes | None] = {}
self.unreadable: list[str] = []
for archive in sorted(bios_dir.rglob("*.zip")):
try:
with zipfile.ZipFile(archive) as handle:
for info in handle.infolist():
if not info.is_dir():
self._index.setdefault(
f"{info.CRC:08x}", (archive, info.filename)
)
except (OSError, zipfile.BadZipFile) as exc:
self.unreadable.append(f"{archive}: {exc}")
# Loose ROMs, by the crc32 the database already computed: nmk004.zip
# needs nmk004.bin, which the collection holds only as a file.
root = bios_dir.resolve()
for entry in ((db or {}).get("files") or {}).values():
crc, path = str(entry.get("crc32") or "").lower(), entry.get("path", "")
if not crc or not path or path.lower().endswith(".zip"):
continue
loose = Path(path)
if root in loose.resolve().parents and loose.is_file():
self._index.setdefault(crc, (loose, None))
def __len__(self) -> int:
return len(self._index)
def __contains__(self, crc32: str) -> bool:
return crc32.lower() in self._index
def read(self, crc32: str) -> bytes:
archive, member = self._index[crc32.lower()]
if member is None:
return archive.read_bytes()
with zipfile.ZipFile(archive) as handle:
return handle.read(member)
def digest(self, recipe: Recipe) -> tuple[str, int] | None:
"""(md5, size) of the recipe's TorrentZip build, None if incomplete."""
if not all(crc in self for _name, crc in recipe):
return None
key = _recipe_key(recipe)
known = self._digests.get(key)
if known is None:
blob = self.build(recipe)
if blob is None:
return None
known = self._digests[key] = [hashlib.md5(blob).hexdigest(), len(blob)]
self._digests_changed = True
return known[0], known[1]
def save_digests(self) -> None:
"""Write the digest cache back, when this run learned anything."""
if self._digest_cache is None or not self._digests_changed:
return
from core.artifacts import write_text_atomic
self._digest_cache.parent.mkdir(parents=True, exist_ok=True)
write_text_atomic(
str(self._digest_cache), json.dumps(self._digests, sort_keys=True) + "\n"
)
def build(self, recipe: Recipe) -> bytes | None:
"""Return the TorrentZip bytes for *recipe*, or None if incomplete."""
key = tuple(recipe)
if key not in self._built:
if all(crc in self for _name, crc in recipe):
self._built[key] = build_torrentzip(
[(name, self.read(crc)) for name, crc in recipe]
)
else:
self._built[key] = None
return self._built[key]
DIGEST_CACHE = REPO_ROOT / ".cache" / "romset_digests.json"
# The writer's own source is part of every key: a change to how TorrentZip
# bytes are laid out invalidates every digest it produced.
_WRITER = hashlib.sha256(
(REPO_ROOT / "scripts" / "core" / "torrentzip.py").read_bytes()
).hexdigest()[:16]
def _recipe_key(recipe: Recipe) -> str:
members = json.dumps([[name, crc.lower()] for name, crc in recipe])
return hashlib.sha256(f"{_WRITER}:{members}".encode()).hexdigest()
def _read_digests(path: Path | None) -> dict[str, list]:
if path is None:
return {}
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except FileNotFoundError:
return {}
except (OSError, ValueError) as exc:
print(f" digest cache {path} unreadable, rebuilding: {exc}", file=sys.stderr)
return {}
return data if isinstance(data, dict) else {}
+79
View File
@@ -0,0 +1,79 @@
"""Romset recipes: the (member, crc32) lists profiles and imported DATs give per archive."""
from __future__ import annotations
import json
from collections import defaultdict
from pathlib import Path
Recipe = list[tuple[str, str]]
def load_dat_recipes(path: str | Path) -> dict[str, dict[str, Recipe]]:
"""Recipes imported from MAME or FBNeo DATs.
A DAT documents every set of one emulator version, where profiles only
document the few hundred the collection curates by hand. Labels are
prefixed so an identification says which DAT decided it.
"""
target = Path(path)
if target.is_dir():
merged: dict[str, dict[str, Recipe]] = {}
for snapshot_file in sorted(target.glob("*.json")):
merged = merge_recipes(merged, load_dat_recipes(snapshot_file))
return merged
snapshot_path = target
if not snapshot_path.is_file():
return {}
with snapshot_path.open(encoding="utf-8") as handle:
snapshot = json.load(handle)
source = snapshot.get("source", "dat")
# A recipe shared by several versions is stored once under the earliest.
# The label therefore reads "unchanged since", not "is this version".
recipes: dict[str, dict[str, Recipe]] = defaultdict(dict)
for entry in snapshot.get("entries", []):
archive = entry.get("name", "")
members = entry.get("members", []) or []
recipe = [
(str(member["name"]), str(member.get("crc32") or "").lower())
for member in members
if member.get("name") is not None
]
if not archive or not recipe or not all(crc for _name, crc in recipe):
continue
label = f"{source}:{entry.get('dat', 'unnamed')}"
recipes[archive][label] = recipe
return dict(recipes)
def merge_recipes(*sources: dict[str, dict[str, Recipe]]) -> dict[str, dict[str, Recipe]]:
"""Combine recipe sets, keeping every label distinct."""
merged: dict[str, dict[str, Recipe]] = defaultdict(dict)
for source in sources:
for archive, per_label in source.items():
merged[archive].update(per_label)
return dict(merged)
def collect_recipes(profiles: dict) -> dict[str, dict[str, Recipe]]:
"""Map each archive name to one recipe per profile that documents it.
A recipe is only usable when every member carries a CRC32: the pool is
addressed by content, so a member without one cannot be located.
"""
recipes: dict[str, dict[str, Recipe]] = defaultdict(dict)
for profile_name, profile in sorted(profiles.items()):
for entry in profile.get("files", []) or []:
contents = entry.get("contents")
archive = entry.get("name", "")
if not contents or not archive:
continue
recipe = [
(str(member["name"]), str(member.get("crc32") or "").lower())
for member in contents
if member.get("name") is not None
]
if recipe and all(crc for _name, crc in recipe):
recipes[archive][profile_name] = recipe
return dict(recipes)