mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-25 10:58:52 -06:00
refactor: move leaf modules into packages
core: hashing, artifacts, ziptools, deterministic_zip, romdir, sect233r1, crypto_verify, paths (REPO_ROOT). model: safeparse (needs yaml), dumpcatalog, largefiles, alternatives. resolve: nativemode, validation, launchers, slot, truth, gamedata, and exporter/baseline.py and exporter/candidates.py as resolve/reconcile.py and resolve/categories.py, which truth and gamedata read. Every importer follows. Modules one level deeper read the repository root from core.paths instead of __file__.
This commit is contained in:
1 parent
23d8a770f1
commit
c784aef883
167 files changed
+412
-434
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Data loading: database, platforms and registry, profiles, targets, systems, catalogues."""
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Entries a core accepts in place of one another.
|
||||
|
||||
A profile writes ``group:`` on the entries of one search list. Yabause tries
|
||||
saturn_bios.bin, sega_101.bin, then mpr-17933.bin and loads the first it
|
||||
finds (libretro.c:1035-1049): it needs one of them and none in particular.
|
||||
The requirement belongs to the set, in the profile's ``groups:`` map, and a
|
||||
member's ``required`` is derived from the sets it is in: true when one of
|
||||
them is required. A fallback two machine models share (pom2's apple2.rom)
|
||||
then needs no value of its own. ``priority`` keeps the order the code reads
|
||||
the members in.
|
||||
|
||||
Holding one member fills the set, so the other members are not missing. A
|
||||
set nobody holds is one gap, reported under its first member with the set's
|
||||
requirement, never one gap per member. A --required-only build keeps one
|
||||
member of a required set, the first the code would load among those held.
|
||||
Every reader goes through this module so that verify, the gap report, the
|
||||
packs and the manifests agree.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Hashable, Iterable, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
_UNRANKED = 1 << 30
|
||||
|
||||
|
||||
def groups_of(entry: dict) -> tuple[str, ...]:
|
||||
"""The sets an entry belongs to: one name, a list for a file two machine
|
||||
models both fall back on, or a map from set to the entry's rank there."""
|
||||
value = entry.get("group")
|
||||
if not value:
|
||||
return ()
|
||||
values = value if isinstance(value, (list, dict)) else [value]
|
||||
return tuple(str(v) for v in values if v)
|
||||
|
||||
|
||||
def rank_in(entry: dict, group: str) -> int | None:
|
||||
"""The rank of an entry in one of its sets: the map's value when the
|
||||
entry ranks differently in each (pom2's apple2.rom is second for the ][
|
||||
and third at boot), else its priority."""
|
||||
value = entry.get("group")
|
||||
if isinstance(value, dict) and isinstance(value.get(group), int):
|
||||
return value[group]
|
||||
priority = entry.get("priority")
|
||||
return priority if isinstance(priority, int) else None
|
||||
|
||||
|
||||
def set_requirements(profile: dict) -> dict[str, bool]:
|
||||
"""The requirement of each set the profile declares."""
|
||||
declared = profile.get("groups") or {}
|
||||
return {
|
||||
str(name): bool((spec or {}).get("required", True))
|
||||
for name, spec in declared.items()
|
||||
}
|
||||
|
||||
|
||||
def derive_member_requirements(profile: dict) -> None:
|
||||
"""Write on each member the requirement its sets give it.
|
||||
|
||||
Read once when a profile is loaded, so every reader sees ``required``
|
||||
as it always has. A member is required when one of its sets is.
|
||||
"""
|
||||
requirements = set_requirements(profile)
|
||||
for entry in profile.get("files") or []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
names = groups_of(entry)
|
||||
if names and "required" not in entry:
|
||||
entry["required"] = any(requirements.get(n, True) for n in names)
|
||||
|
||||
|
||||
def required_groups(entry: dict, profile: dict) -> list[str]:
|
||||
"""The required sets of its profile an entry is a member of."""
|
||||
requirements = set_requirements(profile)
|
||||
return [n for n in groups_of(entry) if requirements.get(n, True)]
|
||||
|
||||
|
||||
def set_fields(entry: dict, profile: dict) -> dict:
|
||||
"""What a --required-only build reads on a core file to keep one member
|
||||
of a set: the entry's required sets, each with its rank there."""
|
||||
sets = required_groups(entry, profile)
|
||||
if not sets:
|
||||
return {}
|
||||
return {"required_groups": {group: rank_in(entry, group) for group in sets}}
|
||||
|
||||
|
||||
def set_keys(owner: Hashable, entry: dict) -> tuple[tuple, ...]:
|
||||
"""The keys of an entry's sets, scoped to its owner (a profile, or a
|
||||
profile under one build)."""
|
||||
return tuple((owner, group) for group in groups_of(entry))
|
||||
|
||||
|
||||
def slot_set_keys(owner: Hashable, entries: Iterable[dict]) -> tuple[tuple, ...]:
|
||||
"""The sets the entries on one destination belong to. A destination has
|
||||
one outcome however many versions it lists, so its versions' sets are
|
||||
settled together."""
|
||||
keys: list[tuple] = []
|
||||
for entry in entries:
|
||||
keys.extend(k for k in set_keys(owner, entry) if k not in keys)
|
||||
return tuple(keys)
|
||||
|
||||
|
||||
def _rank(rank: int | None, position: int) -> tuple[int, int]:
|
||||
return (rank if isinstance(rank, int) else _UNRANKED, position)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Standing:
|
||||
"""The member kept as the one gap of the sets nobody holds."""
|
||||
|
||||
others: list[str]
|
||||
required: bool
|
||||
|
||||
|
||||
def settle_sets(
|
||||
members: Sequence[tuple[tuple[tuple, ...], dict, bool]],
|
||||
set_required: Callable[[tuple], bool] = lambda _key: True,
|
||||
) -> tuple[set[int], dict[int, Standing]]:
|
||||
"""Which unheld members are excused, and which one stands for its set.
|
||||
|
||||
``members`` lists ``(set keys, entry, fills)`` in the order the profile
|
||||
declares them, where ``fills`` says the member is held (or answered by a
|
||||
declaration that reports it). Returns the positions to leave out of a
|
||||
report and, for each set no member fills, the position kept as its one
|
||||
gap with the names of the others and the set's requirement. A member
|
||||
fills or not on its own: a held one is never excused, and an unheld one
|
||||
stays reported when it stands for at least one unfilled set.
|
||||
"""
|
||||
by_set: dict[tuple, list[int]] = {}
|
||||
for position, (keys, _entry, _fills) in enumerate(members):
|
||||
for key in keys:
|
||||
by_set.setdefault(key, []).append(position)
|
||||
|
||||
standing: dict[int, Standing] = {}
|
||||
for key, positions in by_set.items():
|
||||
if any(members[p][2] for p in positions):
|
||||
continue
|
||||
first = min(positions, key=lambda p: _rank(rank_in(members[p][1], key[1]), p))
|
||||
held_up = standing.setdefault(first, Standing([], False))
|
||||
held_up.required = held_up.required or set_required(key)
|
||||
for p in positions:
|
||||
name = str(members[p][1].get("name", ""))
|
||||
if p != first and name not in held_up.others:
|
||||
held_up.others.append(name)
|
||||
|
||||
excused = {
|
||||
position
|
||||
for position, (keys, _entry, fills) in enumerate(members)
|
||||
if keys and not fills and position not in standing
|
||||
}
|
||||
return excused, standing
|
||||
|
||||
|
||||
def required_only_spares(
|
||||
entries: Sequence[dict],
|
||||
owner: Callable[[dict], Hashable],
|
||||
held: Callable[[dict], bool],
|
||||
gone: Callable[[dict], bool] = lambda _entry: False,
|
||||
sets: Callable[[dict], dict[str, int | None]] = lambda e: e.get("required_groups") or {},
|
||||
) -> set[int]:
|
||||
"""The ids of the held members a --required-only build leaves out.
|
||||
|
||||
``sets`` maps the required sets of an entry to its rank in each: a core
|
||||
file of a platform pack carries them as ``required_groups``.
|
||||
|
||||
A required set needs one file: the build keeps the member the code
|
||||
would load first among those it holds and still carries (``gone`` says
|
||||
a region filter took it), by ``priority`` then declaration order, and
|
||||
drops the others. A member of an optional set is not touched here,
|
||||
nor one that another required set of its own still needs.
|
||||
"""
|
||||
candidates: dict[tuple, list[tuple[tuple[int, int], int]]] = {}
|
||||
for position, entry in enumerate(entries):
|
||||
if not held(entry) or gone(entry):
|
||||
continue
|
||||
for group, rank in sets(entry).items():
|
||||
candidates.setdefault((owner(entry), group), []).append(
|
||||
(_rank(rank, position), position)
|
||||
)
|
||||
kept: set[int] = set()
|
||||
members: set[int] = set()
|
||||
for ranked in candidates.values():
|
||||
members.update(position for _rank_key, position in ranked)
|
||||
kept.add(min(ranked)[1])
|
||||
return {id(entries[p]) for p in members - kept}
|
||||
|
||||
|
||||
def core_file_spares(
|
||||
entries: Sequence[dict], gone: Callable[[dict], bool] = lambda _entry: False,
|
||||
) -> set[int]:
|
||||
"""The core files of a platform pack a --required-only build leaves out.
|
||||
|
||||
A set the platform declares a member of is carried by that declaration,
|
||||
so its other members are spares. Otherwise one held member per required
|
||||
set stays, as in an emulator pack. Read by the builder, the manifest
|
||||
and verify alike.
|
||||
"""
|
||||
answered = {id(e) for e in entries if e.get("set_declared")}
|
||||
# An archive under the core's own folder is read before the same name
|
||||
# at the root (Kronos), so archive units rank first among equals.
|
||||
rest = sorted(
|
||||
(e for e in entries if id(e) not in answered),
|
||||
key=lambda e: not e.get("archive"),
|
||||
)
|
||||
return answered | required_only_spares(
|
||||
rest,
|
||||
owner=lambda e: e.get("source_profile") or e.get("profile") or "",
|
||||
held=lambda e: e.get("in_repo", True) is not False,
|
||||
gone=gone,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Dump catalogues joined onto the collection.
|
||||
|
||||
Redump, No-Intro and TOSEC annotate what the repo holds. They are an
|
||||
opinion on provenance, never an authority: the emulator source is."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_if_changed
|
||||
|
||||
|
||||
DEFAULT_PROVENANCE_DIR = "provenance"
|
||||
|
||||
def load_provenance_snapshots(provenance_dir: str = DEFAULT_PROVENANCE_DIR) -> dict:
|
||||
"""Load dump-catalog snapshots from provenance/*.json.
|
||||
|
||||
Returns {source_name: snapshot} where snapshot holds the normalized
|
||||
entries written by the redump scraper or the pack importer. Missing
|
||||
directory means no snapshots: returns an empty dict.
|
||||
"""
|
||||
snapshots: dict[str, dict] = {}
|
||||
prov_path = Path(provenance_dir)
|
||||
if not prov_path.is_dir():
|
||||
return snapshots
|
||||
for path in sorted(prov_path.glob("*.json")):
|
||||
with open(path) as f:
|
||||
snapshot = json.load(f)
|
||||
source = snapshot.get("source")
|
||||
if source and snapshot.get("entries"):
|
||||
snapshots[source] = snapshot
|
||||
return snapshots
|
||||
|
||||
def build_provenance_index(snapshots: dict) -> dict:
|
||||
"""Index snapshot entries by sha1 and by (md5, size) per source.
|
||||
|
||||
First entry wins on hash collisions within a source. Entries are
|
||||
pre-sorted at snapshot write time so the outcome is deterministic.
|
||||
"""
|
||||
index = {}
|
||||
for source, snapshot in snapshots.items():
|
||||
by_sha1 = {}
|
||||
by_md5_size = {}
|
||||
for entry in snapshot["entries"]:
|
||||
sha1 = entry.get("sha1", "")
|
||||
md5 = entry.get("md5", "")
|
||||
if sha1 and sha1 not in by_sha1:
|
||||
by_sha1[sha1] = entry
|
||||
if md5 and entry.get("size"):
|
||||
key = (md5, entry["size"])
|
||||
if key not in by_md5_size:
|
||||
by_md5_size[key] = entry
|
||||
index[source] = {"by_sha1": by_sha1, "by_md5_size": by_md5_size}
|
||||
return index
|
||||
|
||||
def annotate_provenance(files: dict, snapshots: dict) -> dict[str, int]:
|
||||
"""Attach a provenance field to database file entries.
|
||||
|
||||
Matches by SHA1 first, then MD5 + size. Returns per-source match
|
||||
counts. Files without any catalog match keep no provenance field.
|
||||
"""
|
||||
index = build_provenance_index(snapshots)
|
||||
counts = dict.fromkeys(index, 0)
|
||||
for sha1, entry in files.items():
|
||||
matches = {}
|
||||
for source in sorted(index):
|
||||
src_index = index[source]
|
||||
hit = src_index["by_sha1"].get(sha1) or src_index["by_md5_size"].get(
|
||||
(entry.get("md5", ""), entry.get("size", 0))
|
||||
)
|
||||
if hit:
|
||||
matches[source] = {
|
||||
"dat": hit.get("dat", ""),
|
||||
"name": hit.get("name", ""),
|
||||
"description": hit.get("description", ""),
|
||||
}
|
||||
counts[source] += 1
|
||||
if matches:
|
||||
entry["provenance"] = matches
|
||||
else:
|
||||
entry.pop("provenance", None)
|
||||
return counts
|
||||
|
||||
def build_snapshot(
|
||||
source: str, imported_at: str, dats: dict, entries: list[dict]
|
||||
) -> dict:
|
||||
"""A provenance snapshot, sorted for determinism."""
|
||||
return {
|
||||
"source": source,
|
||||
"imported_at": imported_at,
|
||||
"dats": dict(sorted(dats.items())),
|
||||
"entries": sorted(entries, key=lambda e: (e["dat"], e["name"])),
|
||||
}
|
||||
|
||||
|
||||
def write_snapshot(path: str, snapshot: dict) -> bool:
|
||||
"""Write a snapshot. Timestamps alone never count as a change."""
|
||||
return write_if_changed(path, json.dumps(snapshot, indent=2) + "\n")
|
||||
|
||||
|
||||
def write_provenance_snapshot(
|
||||
path: str, source: str, imported_at: str, dats: dict, entries: list[dict]
|
||||
) -> bool:
|
||||
"""Write a normalized provenance snapshot."""
|
||||
return write_snapshot(path, build_snapshot(source, imported_at, dats, entries))
|
||||
@@ -0,0 +1,441 @@
|
||||
"""Files too large for the repository.
|
||||
|
||||
They live as release assets and are fetched at build time, verified
|
||||
against the hash the caller declares."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import set_plain_mode
|
||||
from core.hashing import compute_hashes
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
LARGE_FILES_RELEASE = "large-files"
|
||||
LARGE_FILES_REPO = "Abdess/retrobios"
|
||||
LARGE_FILES_CACHE = ".cache/large"
|
||||
# Verified revisions, hard-linked as <sha1>/<asset> beside the cache. A name
|
||||
# in the cache is replaced when the release serves new bytes under it, so a
|
||||
# path handed out by name could hold other bytes by the time the caller read
|
||||
# them. Nothing ever writes other bytes under a sha1. The asset name stays
|
||||
# last: callers read the extension (an archive is packed as one).
|
||||
VERIFIED_STORE = ".by-sha1"
|
||||
ORPHAN_GRACE = 24 * 3600
|
||||
GITIGNORE = REPO_ROOT / ".gitignore"
|
||||
|
||||
_UNSAFE_ASSET_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
|
||||
|
||||
|
||||
def registered_paths(gitignore_text: str) -> list[str]:
|
||||
"""The bios/ paths .gitignore lists, which are the release assets."""
|
||||
return [
|
||||
line.strip()
|
||||
for line in gitignore_text.splitlines()
|
||||
if line.strip().startswith("bios/")
|
||||
]
|
||||
|
||||
|
||||
def load_registered_paths(gitignore: str | Path = GITIGNORE) -> list[str]:
|
||||
try:
|
||||
return registered_paths(Path(gitignore).read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
|
||||
|
||||
def asset_names(registered: Iterable[str]) -> dict[str, str]:
|
||||
"""Map each registered path to the name of its release asset.
|
||||
|
||||
A path whose basename no other registered path shares is published
|
||||
under that basename. A path whose basename is shared is published under
|
||||
its location below bios/, segments joined by "--" and every character
|
||||
outside [A-Za-z0-9._-] replaced by "_":
|
||||
bios/Id Software/Wolfenstein Enemy Territory/etmain/pak0.pk3 becomes
|
||||
Id_Software--Wolfenstein_Enemy_Territory--etmain--pak0.pk3. The name
|
||||
depends on the path only, never on the bytes, so rebuilding a file
|
||||
keeps its asset.
|
||||
"""
|
||||
paths = sorted(set(registered))
|
||||
counts = Counter(os.path.basename(p) for p in paths)
|
||||
names: dict[str, str] = {}
|
||||
for registered_path in paths:
|
||||
base = os.path.basename(registered_path)
|
||||
if counts[base] == 1:
|
||||
names[registered_path] = base
|
||||
continue
|
||||
rel = registered_path.removeprefix("bios/")
|
||||
names[registered_path] = "--".join(
|
||||
_UNSAFE_ASSET_CHARS.sub("_", part) for part in rel.split("/")
|
||||
)
|
||||
owners: dict[str, str] = {}
|
||||
for registered_path, name in names.items():
|
||||
# GitHub publishes a space as a dot, so both spellings are taken.
|
||||
for spelling in {name, name.replace(" ", ".")}:
|
||||
other = owners.setdefault(spelling, registered_path)
|
||||
if other != registered_path:
|
||||
raise ValueError(
|
||||
f"release asset {spelling!r} named by both {other!r} "
|
||||
f"and {registered_path!r}"
|
||||
)
|
||||
return names
|
||||
|
||||
|
||||
def asset_name(path: str, registered: Iterable[str]) -> str:
|
||||
"""The release asset name of *path* among the *registered* paths."""
|
||||
return asset_names([*registered, path])[path]
|
||||
|
||||
|
||||
def published_asset_name(name: str) -> str:
|
||||
"""The name GitHub serves an asset under: it publishes a space as a dot."""
|
||||
return name.replace(" ", ".")
|
||||
|
||||
|
||||
def asset_candidates(name: str, registered: Iterable[str]) -> list[str]:
|
||||
"""Assets that may hold *name*, a registered path or a bare file name.
|
||||
|
||||
A bare name shared by several registered paths has one asset per path,
|
||||
and the caller's hash tells them apart. A bare name no registered path
|
||||
carries has none.
|
||||
"""
|
||||
registered = list(registered)
|
||||
if "/" in name:
|
||||
return [asset_name(name, registered)]
|
||||
names = asset_names(registered)
|
||||
matches = [
|
||||
names[p] for p in sorted(names) if os.path.basename(p) == name
|
||||
]
|
||||
# A pinned revision is stored as .variants/<name>.<md5 prefix>: ROCKNIX
|
||||
# pins PS3UPDAT.PUP to the variant, and asking for the bare name never
|
||||
# reached its asset.
|
||||
matches += [
|
||||
names[p] for p in sorted(names)
|
||||
if "/.variants/" in p and os.path.basename(p).startswith(name + ".")
|
||||
]
|
||||
# A bare name no registered path carries is no asset: .gitignore is the
|
||||
# registry. Asking the release anyway cost a 404 per name on every
|
||||
# online build and named an upload that never existed.
|
||||
return matches
|
||||
|
||||
|
||||
def fetch_large_file(
|
||||
name: str,
|
||||
dest_dir: str = LARGE_FILES_CACHE,
|
||||
expected_sha1: str = "",
|
||||
expected_md5: str = "",
|
||||
*,
|
||||
offline: bool = False,
|
||||
registered: Iterable[str] | None = None,
|
||||
) -> str | None:
|
||||
"""Return a verified cached large file, downloading it only when allowed.
|
||||
|
||||
*name* is a registered bios/ path or a bare file name. asset_names()
|
||||
turns it into the asset to fetch, and a bare name shared by several
|
||||
registered paths tries each of their assets until one verifies.
|
||||
"""
|
||||
if not name or name.endswith("/"):
|
||||
# A directory entry names a tree, never one asset: asked for
|
||||
# "caesar3/", the store answered with .cache/large/ itself.
|
||||
return None
|
||||
if registered is None:
|
||||
registered = load_registered_paths()
|
||||
for asset in asset_candidates(name, registered):
|
||||
cached = _fetch_asset(
|
||||
asset, dest_dir, expected_sha1, expected_md5, offline=offline
|
||||
)
|
||||
if cached:
|
||||
return cached
|
||||
return None
|
||||
|
||||
|
||||
def _download(name: str, tmp_path: str) -> bool:
|
||||
"""Stream the first release URL of *name* that answers into *tmp_path*."""
|
||||
# Only a name no candidate answers is reported: a spaced name is
|
||||
# published dotted, and logging its first 404 read as a missing asset.
|
||||
failures: list[str] = []
|
||||
for candidate, url in _asset_urls(name):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
return True
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
|
||||
# A stalled or cut stream is a timeout or IncompleteRead, not
|
||||
# a URLError: it escaped this handler and left its scratch.
|
||||
failures.append(f" large file {candidate}: {exc}")
|
||||
for failure in failures:
|
||||
print(failure, file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def _fetch_asset(
|
||||
name: str,
|
||||
dest_dir: str,
|
||||
expected_sha1: str,
|
||||
expected_md5: str,
|
||||
*,
|
||||
offline: bool,
|
||||
) -> str | None:
|
||||
cached = os.path.join(dest_dir, name)
|
||||
# Between the existence test and the hash, a concurrent run can drop the
|
||||
# same stale entry: the file is gone by the time this one reads it, and
|
||||
# both of them try to unlink it.
|
||||
def _drop(path: str) -> None:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(path)
|
||||
|
||||
if os.path.isdir(cached):
|
||||
return None
|
||||
if os.path.exists(cached):
|
||||
snapshot = _read_once(cached)
|
||||
if snapshot is None:
|
||||
pass
|
||||
elif _matches(snapshot[0], expected_sha1, expected_md5):
|
||||
pinned = _pin_verified(cached, snapshot, dest_dir, name)
|
||||
if pinned:
|
||||
return pinned
|
||||
elif not _replaced_on_release(name, snapshot[0]["sha256"], snapshot[1], offline):
|
||||
# A copy of this asset that answers another hash: the caller
|
||||
# wants a different revision under the same name, and the
|
||||
# release still serves this one. Keeping it is what lets the
|
||||
# next caller for the primary find it.
|
||||
return None
|
||||
# Otherwise the release was re-uploaded since this copy was cached
|
||||
# (gh release upload --clobber): only a download can answer, and
|
||||
# it replaces the copy only if it verifies.
|
||||
|
||||
# RETROBIOS_OFFLINE forbids every download whatever a caller passes: the
|
||||
# CI test job sets it, since tests fetching 252 MB assets into the shared
|
||||
# cache filled the runner's disk and changed what later tests resolved.
|
||||
if offline or os.environ.get("RETROBIOS_OFFLINE"):
|
||||
return None
|
||||
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
# A per-process scratch name: two runs fetching the same asset into one
|
||||
# shared path interleave their writes into a full-size, corrupt file.
|
||||
tmp_fd, tmp_path = tempfile.mkstemp(
|
||||
dir=dest_dir, prefix=os.path.basename(cached) + ".", suffix=".tmp"
|
||||
)
|
||||
os.close(tmp_fd)
|
||||
try:
|
||||
if not _download(name, tmp_path):
|
||||
return None
|
||||
snapshot = _read_once(tmp_path)
|
||||
if snapshot is None or not _matches(snapshot[0], expected_sha1, expected_md5):
|
||||
return None
|
||||
set_plain_mode(tmp_path)
|
||||
pinned = _pin_verified(tmp_path, snapshot, dest_dir, name)
|
||||
os.replace(tmp_path, cached)
|
||||
_prune_verified(dest_dir)
|
||||
return pinned
|
||||
finally:
|
||||
_drop(tmp_path)
|
||||
|
||||
|
||||
def _pin_verified(
|
||||
path: str, snapshot: tuple[dict[str, str], int, int], dest_dir: str, name: str,
|
||||
) -> str | None:
|
||||
"""The verified revision at *path*, as <sha1>/<name> in VERIFIED_STORE.
|
||||
|
||||
*snapshot* is what _read_once read: the link is kept only if it holds
|
||||
that inode, so a copy another run promoted after the hash is never
|
||||
passed off as the one verified. None when the name moved in between.
|
||||
"""
|
||||
revision = os.path.join(dest_dir, VERIFIED_STORE, snapshot[0]["sha1"])
|
||||
final = os.path.join(revision, name)
|
||||
# A prune removes an empty revision directory: one that went between
|
||||
# makedirs and link is made again, once.
|
||||
for _attempt in range(2):
|
||||
os.makedirs(revision, exist_ok=True)
|
||||
# The link must hold the inode just verified. An older link left by a
|
||||
# copy that lost its cache name has one link left, and the prune of
|
||||
# this very download removed it after it was returned.
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
if os.stat(final).st_ino == snapshot[2]:
|
||||
return final
|
||||
scratch = os.path.join(revision, f".{os.getpid()}.{os.urandom(4).hex()}.tmp")
|
||||
try:
|
||||
os.link(path, scratch)
|
||||
except FileNotFoundError:
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
continue
|
||||
try:
|
||||
if os.stat(scratch).st_ino != snapshot[2]:
|
||||
return None
|
||||
os.replace(scratch, final)
|
||||
return final
|
||||
finally:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(scratch)
|
||||
return None
|
||||
|
||||
|
||||
def _prune_verified(dest_dir: str) -> None:
|
||||
"""Drop the revisions no cache name has held for ORPHAN_GRACE seconds.
|
||||
|
||||
Losing its cache name changes the inode's ctime, so a revision another
|
||||
run pinned just before the release replaced it stays readable while that
|
||||
run packs it.
|
||||
"""
|
||||
store = os.path.join(dest_dir, VERIFIED_STORE)
|
||||
now = time.time()
|
||||
for revision in os.scandir(store):
|
||||
if not revision.is_dir():
|
||||
continue
|
||||
for entry in os.scandir(revision.path):
|
||||
if entry.name.endswith(".tmp"):
|
||||
continue
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
stat = entry.stat()
|
||||
if stat.st_nlink == 1 and now - stat.st_ctime > ORPHAN_GRACE:
|
||||
os.unlink(entry.path)
|
||||
# Another run may be linking a copy into it: left for the next prune.
|
||||
with contextlib.suppress(FileNotFoundError, OSError):
|
||||
os.rmdir(revision.path)
|
||||
|
||||
|
||||
def _asset_urls(name: str) -> list[tuple[str, str]]:
|
||||
"""Release URLs an asset may be published under, with their names.
|
||||
|
||||
GitHub rewrites spaces to dots in release asset names, so a file whose
|
||||
name contains spaces is published under a dotted name.
|
||||
"""
|
||||
candidates = [name]
|
||||
if " " in name:
|
||||
candidates.append(name.replace(" ", "."))
|
||||
return [
|
||||
(
|
||||
candidate,
|
||||
(
|
||||
f"https://github.com/{LARGE_FILES_REPO}/releases/download/"
|
||||
f"{LARGE_FILES_RELEASE}/{urllib.parse.quote(candidate)}"
|
||||
),
|
||||
)
|
||||
for candidate in candidates
|
||||
]
|
||||
|
||||
|
||||
def _read_once(path: str) -> tuple[dict[str, str], int, int] | None:
|
||||
"""Digests, size and inode of the file at *path*, all read from one
|
||||
file, or None when it is gone.
|
||||
|
||||
Every judgement on a cache copy reads this one snapshot. Hashed, then
|
||||
hashed again by path for the release check, a copy another run promoted
|
||||
in between answered the second question: the copy the caller wanted was
|
||||
in the cache and the caller was told there was none.
|
||||
"""
|
||||
# A promotion is an os.replace, so it changes the inode: the same inode
|
||||
# on both sides of the read means the digests describe that one file.
|
||||
for _attempt in range(3):
|
||||
try:
|
||||
before = os.stat(path)
|
||||
hashes = compute_hashes(path)
|
||||
after = os.stat(path)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns):
|
||||
return hashes, after.st_size, after.st_ino
|
||||
return None
|
||||
|
||||
|
||||
def _replaced_on_release(name: str, sha256: str, size: int, offline: bool) -> bool:
|
||||
"""Whether the release now serves other bytes than the cached copy,
|
||||
whose *sha256* and *size* the caller read.
|
||||
|
||||
The release lists a sha256 per asset: a dump rebuilt at the same size
|
||||
(the eight 251658304-byte DSi NANDs) differs only there, and judged by
|
||||
size the stale copy was kept for good. Without a digest the sizes are
|
||||
compared, as check_release_assets does. No download either way:
|
||||
offline or unreadable, the copy is assumed current.
|
||||
"""
|
||||
if offline:
|
||||
return False
|
||||
digest = next(
|
||||
(d for candidate, _url in _asset_urls(name)
|
||||
if (d := _served_digests().get(candidate))),
|
||||
None,
|
||||
)
|
||||
if digest:
|
||||
return sha256 != digest
|
||||
served = _served_size(name)
|
||||
return served is not None and served != size
|
||||
|
||||
|
||||
_digests_cache: dict[str, str] | None = None
|
||||
|
||||
|
||||
def _served_digests() -> dict[str, str]:
|
||||
"""sha256 of each asset the release serves, by asset name, empty when
|
||||
the API cannot be read."""
|
||||
global _digests_cache
|
||||
if _digests_cache is not None:
|
||||
return _digests_cache
|
||||
url = (
|
||||
f"https://api.github.com/repos/{LARGE_FILES_REPO}/releases/tags/"
|
||||
f"{LARGE_FILES_RELEASE}"
|
||||
)
|
||||
headers = {"User-Agent": "retrobios/1.0", "Accept": "application/vnd.github+json"}
|
||||
from common import github_token
|
||||
|
||||
token = github_token()
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
digests: dict[str, str] = {}
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(url, headers=headers), timeout=60
|
||||
) as resp:
|
||||
release = json.load(resp)
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
|
||||
print(f" large files release listing: {exc}", file=sys.stderr)
|
||||
release = {}
|
||||
for asset in release.get("assets") or []:
|
||||
digest = str(asset.get("digest") or "")
|
||||
if digest.startswith("sha256:"):
|
||||
digests[asset.get("name", "")] = digest.removeprefix("sha256:").lower()
|
||||
_digests_cache = digests
|
||||
return digests
|
||||
|
||||
|
||||
def _served_size(name: str) -> int | None:
|
||||
"""Size of the asset the release serves now, or None when unreadable."""
|
||||
for candidate, url in _asset_urls(name):
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
length = resp.headers.get("Content-Length")
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
|
||||
print(f" large file {candidate}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
if length and length.isdigit():
|
||||
return int(length)
|
||||
return None
|
||||
|
||||
|
||||
def _matches(hashes: dict, expected_sha1: str, expected_md5: str) -> bool:
|
||||
"""Whether computed hashes answer the caller's declaration."""
|
||||
if expected_sha1 and hashes["sha1"].lower() != expected_sha1.lower():
|
||||
return False
|
||||
if expected_md5:
|
||||
md5_list = [m.strip().lower() for m in expected_md5.split(",") if m.strip()]
|
||||
return hashes["md5"].lower() in md5_list
|
||||
return True
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Parsers for input the repo does not control.
|
||||
|
||||
Upstream DATs and scraped documents are data, never instructions, and
|
||||
the parsers here are the boundary that keeps it that way."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
from types import ModuleType
|
||||
from typing import Any, TextIO
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError: # optional at import time
|
||||
yaml = None
|
||||
|
||||
|
||||
def parse_untrusted_xml(
|
||||
content: str | bytes, label: str = "XML", comments: bool = False
|
||||
) -> ET.Element:
|
||||
"""Parse XML fetched from a third party.
|
||||
|
||||
ElementTree expands internal entities, so a document that declares them
|
||||
can make the parser build a payload far larger than the bytes downloaded.
|
||||
Nothing this project reads (DAT packs, es_bios.xml, Emulators.xml) ever
|
||||
declares one, so a declaration is grounds to refuse the document rather
|
||||
than something to expand carefully.
|
||||
|
||||
The check targets <!ENTITY rather than <!DOCTYPE because Logiqx DATs
|
||||
legitimately carry a doctype pointing at logiqx.com, and ElementTree does
|
||||
not resolve external entities, so a doctype alone fetches nothing.
|
||||
`comments` keeps comments in the tree, for a file rewritten in place.
|
||||
"""
|
||||
text = content if isinstance(content, str) else content.decode("utf-8", "replace")
|
||||
if "<!ENTITY" in text.upper():
|
||||
raise ValueError(f"XML entity declarations are not allowed in {label}")
|
||||
if comments:
|
||||
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
|
||||
return ET.fromstring(content, parser=parser)
|
||||
return ET.fromstring(content)
|
||||
|
||||
def require_yaml() -> ModuleType:
|
||||
"""Import and return yaml, exiting if PyYAML is not installed."""
|
||||
try:
|
||||
import yaml as _yaml
|
||||
|
||||
return _yaml
|
||||
except ImportError:
|
||||
import sys
|
||||
|
||||
print("Error: PyYAML required (pip install pyyaml)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
def _pick_yaml_loader() -> type[yaml.constructor.SafeConstructor] | None:
|
||||
"""Prefer the libyaml loader when the wheel ships it.
|
||||
|
||||
Reading the emulator profiles is the single most expensive step of every
|
||||
command here: 375 files, and the pure-Python scanner accounts for roughly
|
||||
70% of a verify run. The C loader parses the same documents about eight
|
||||
times faster and pyyaml only exposes it when libyaml was available at
|
||||
build time, so the pure-Python class stays as the fallback.
|
||||
"""
|
||||
if yaml is None:
|
||||
return None
|
||||
base = getattr(yaml, "CSafeLoader", None) or yaml.SafeLoader
|
||||
|
||||
def construct_mapping(
|
||||
self: yaml.constructor.SafeConstructor, node: yaml.MappingNode, deep: bool = False
|
||||
) -> dict:
|
||||
"""Refuse a mapping that names a key twice.
|
||||
|
||||
PyYAML keeps the last value without a word: the registry once
|
||||
carried two target_source keys for Recalbox and read only one. Only
|
||||
a mapping that came out shorter than its source is re-read. No data
|
||||
here uses merge keys (<<), which would count as repeats too.
|
||||
"""
|
||||
mapping = base.construct_mapping(self, node, deep=deep)
|
||||
if len(mapping) < len(node.value):
|
||||
seen: set = set()
|
||||
for key_node, _value in node.value:
|
||||
key = self.construct_object(key_node, deep=deep)
|
||||
if key in seen:
|
||||
raise yaml.constructor.ConstructorError(
|
||||
None, None, f"duplicate key {key!r}", key_node.start_mark
|
||||
)
|
||||
seen.add(key)
|
||||
return mapping
|
||||
|
||||
return type("_UniqueKeyLoader", (base,), {"construct_mapping": construct_mapping})
|
||||
|
||||
_YAML_LOADER = _pick_yaml_loader()
|
||||
|
||||
def yaml_load(stream: str | TextIO) -> Any:
|
||||
"""Parse YAML from a string or file object, safely and quickly."""
|
||||
if yaml is None:
|
||||
return require_yaml() # exits with the install hint
|
||||
return yaml.load(stream, Loader=_YAML_LOADER)
|
||||
|
||||
|
||||
def yaml_load_upstream(stream: str | TextIO) -> Any:
|
||||
"""Parse a third party's YAML the way its own PyYAML code reads it.
|
||||
|
||||
Our files refuse a repeated key, but a platform's file is data we transcribe,
|
||||
and its code keeps the last value. Batocera 43.1's configgen-defaults.yml
|
||||
names rtcw's core twice, and refusing it stopped the rescrape.
|
||||
"""
|
||||
if yaml is None:
|
||||
return require_yaml()
|
||||
return yaml.load(stream, Loader=getattr(yaml, "CSafeLoader", None) or yaml.SafeLoader)
|
||||
Reference in new issue
Block a user