refactor: restore large files with one copy

model.largefiles.restore_verified replaces generate_db _restore and
release restore _copy_verified: a scratch copy beside the target,
hashed, then renamed into place with a plain mode.

generate_db now refuses to put back a cached asset whose copy does not
hash to its database entry. The entry is still kept, as for an asset
the cache cannot supply. The restore script copies once instead of
through a second scratch.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 20:03:26 +01:00
1 parent ab0805e6cb
commit 4dc4dc0429
5 files changed
+51 -61

No files matched your search

+2 -24
View File
@@ -13,9 +13,7 @@ from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
import tempfile
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -27,7 +25,6 @@ from core.hashing import compute_hashes
from model.registry import list_registered_platforms
from core.artifacts import (
repository_output_lock,
set_plain_mode,
write_if_changed,
write_text_atomic,
)
@@ -388,25 +385,6 @@ def _load_gitignored_large_files() -> set[str]:
return set(load_registered_paths(".gitignore"))
def _restore(cached: str, path: str) -> None:
"""Copy a fetched asset to its registered path, whole or not at all.
An interrupted copy at the final name is a truncated file the next scan
hashes and publishes. A scratch beside it is swapped in only once full.
"""
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
fd, scratch = tempfile.mkstemp(dir=directory, prefix=".restore-")
os.close(fd)
try:
shutil.copy2(cached, scratch)
set_plain_mode(scratch)
os.replace(scratch, path)
finally:
if os.path.exists(scratch):
os.remove(scratch)
def _preserve_large_file_entries(files: dict, db_path: str) -> int:
"""Keep the entries of release assets the checkout does not hold.
@@ -418,7 +396,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int:
would send the installer to the repository for it. A fetched asset is
written back to its registered path.
"""
from model.largefiles import fetch_large_file
from model.largefiles import fetch_large_file, restore_verified
registered = _load_gitignored_large_files()
if not registered:
@@ -455,7 +433,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int:
expected_md5=entry.get("md5", ""),
)
if cached and not os.path.exists(path):
_restore(cached, path)
restore_verified(cached, path, sha1)
files[sha1] = entry
count += 1
return count
+29 -1
View File
@@ -11,6 +11,7 @@ import json
import os
import sys
import re
import shutil
import tempfile
import time
import urllib.error
@@ -21,7 +22,7 @@ from collections.abc import Iterable
from pathlib import Path
from core.artifacts import set_plain_mode
from core.hashing import compute_hashes, parse_hash_list
from core.hashing import compute_hashes, file_digest, parse_hash_list
from core.paths import REPO_ROOT
@@ -160,6 +161,33 @@ def fetch_large_file(
return None
def restore_verified(source: str, path: str, sha1: str) -> bool:
"""Copy a cached asset to its registered path, only if the copy hashes to sha1.
The cache was hashed before the copy, and another run can replace a
cached name in between (a re-uploaded asset): the copy is what counts.
Whole or absent: a scan running beside a plain copy hashed the truncated
file and published that in the database.
"""
directory = os.path.dirname(os.path.abspath(path))
os.makedirs(directory, exist_ok=True)
handle, scratch = tempfile.mkstemp(
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
)
os.close(handle)
try:
shutil.copy2(source, scratch)
if file_digest(Path(scratch)) != sha1:
print(f"Changed in the cache while restoring: {source}", file=sys.stderr)
return False
set_plain_mode(scratch)
os.replace(scratch, path)
return True
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(scratch)
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
+2 -31
View File
@@ -2,14 +2,11 @@
from __future__ import annotations
import contextlib
import os
import sys
import tempfile
from pathlib import Path
from model.largefiles import registered_paths
from core.artifacts import copy_file_atomic, set_plain_mode
from model.largefiles import registered_paths, restore_verified
from core.hashing import file_digest
from model.database import load_database
@@ -39,32 +36,6 @@ def index_cache(cache_dir: str) -> dict[str, str]:
return index
def _copy_verified(source: str, path: str, sha1: str) -> bool:
"""Copy *source* to *path* only if the copy hashes to *sha1*.
The cache was hashed before the copy, and another run can replace a
cached name in between (a re-uploaded asset): the copy is what counts.
Whole or absent: a scan running beside a plain copy hashed the truncated
file and published that in the database.
"""
handle, scratch = tempfile.mkstemp(
dir=os.path.dirname(os.path.abspath(path)),
prefix=f".{os.path.basename(path)}.", suffix=".tmp",
)
os.close(handle)
try:
copy_file_atomic(source, scratch)
if file_digest(Path(scratch)) != sha1:
print(f"Changed in the cache while restoring: {source}", file=sys.stderr)
return False
set_plain_mode(scratch)
os.replace(scratch, path)
return True
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(scratch)
def restore(
cache_dir: str, db_path: str, gitignore: str
) -> tuple[int, list[str]]:
@@ -88,7 +59,7 @@ def restore(
unsatisfied.append(path)
continue
os.makedirs(os.path.dirname(path), exist_ok=True)
if not _copy_verified(source, path, sha1):
if not restore_verified(source, path, sha1):
unsatisfied.append(path)
continue
print(f"Restored: {path}")
+1 -1
View File
@@ -55,7 +55,7 @@ class EveryWriterGoesThroughIt(unittest.TestCase):
for name, helper in (
("generate_pack.py", "write_text_atomic("),
("release_record.py", "write_text_atomic("),
("restore_large_files.py", "copy_file_atomic("),
("restore_large_files.py", "restore_verified("),
):
source = script_source(name)
with self.subTest(script=name):
+17 -4
View File
@@ -453,29 +453,42 @@ class PreservedLargeFileEntries(unittest.TestCase):
cache.parent.mkdir()
cache.write_bytes(b"firmware")
largefiles.fetch_large_file = lambda *_a, **_k: str(cache)
sha1 = hashlib.sha1(b"firmware").hexdigest()
db_path = self._write_db(
{"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}}
{sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}}
)
files: dict = {}
count = self.generate_db._preserve_large_file_entries(files, db_path)
self.assertEqual(count, 1)
self.assertEqual(files["b" * 40]["path"], "bios/Sony/PS3/FW.PUP")
self.assertEqual(files[sha1]["path"], "bios/Sony/PS3/FW.PUP")
self.assertEqual((self.tmp / "bios/Sony/PS3/FW.PUP").read_bytes(), b"firmware")
def test_a_cached_copy_with_other_bytes_is_not_restored(self):
cache = self.tmp / "cache" / "FW.PUP"
cache.parent.mkdir()
cache.write_bytes(b"replaced")
largefiles.fetch_large_file = lambda *_a, **_k: str(cache)
sha1 = hashlib.sha1(b"firmware").hexdigest()
db_path = self._write_db(
{sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}}
)
self.generate_db._preserve_large_file_entries({}, db_path)
self.assertEqual(list((self.tmp / "bios/Sony/PS3").iterdir()), [])
def test_an_interrupted_restore_leaves_no_file_behind(self):
cache = self.tmp / "cache" / "FW.PUP"
cache.parent.mkdir()
cache.write_bytes(b"firmware")
largefiles.fetch_large_file = lambda *_a, **_k: str(cache)
db_path = self._write_db(
{"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}}
{hashlib.sha1(b"firmware").hexdigest(): {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}}
)
def interrupted(_src, dst, *_a, **_k):
Path(dst).write_bytes(b"firm")
raise KeyboardInterrupt
with mock.patch.object(self.generate_db.shutil, "copy2", interrupted), \
with mock.patch.object(largefiles.shutil, "copy2", interrupted), \
self.assertRaises(KeyboardInterrupt):
self.generate_db._preserve_large_file_entries({}, db_path)
directory = self.tmp / "bios/Sony/PS3"