fix: remove the games cache scratch on a failure

A cache write that failed left index.json.<pid>.part behind, one more
on each run. The cache and the install record now write through one
scratch file beside the target, removed when the write fails and named
when it cannot be.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:04:39 +01:00
1 parent 5d0c2fd3c6
commit bf34e71804
8 files changed
+59 -43

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@
# and Invoke-WebRequest throws on a cut transfer before the hash is read:
# the site's build rewrites this line there (scripts/sitebootstrap.py).
$mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
$defaultInstallSha256 = "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171"
$defaultInstallSha256 = "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
$maximumInstallerBytes = 8MB
+20 -15
View File
@@ -1816,6 +1816,24 @@ def _replace_with_copy(src: Path, dest: Path) -> None:
raise
def write_atomically(path: Path, data: bytes) -> None:
"""Write data at path through a scratch file beside it, removed when the
write fails; a scratch that cannot be removed is named in the error."""
fd, scratch = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".part")
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
os.replace(scratch, path)
except OSError as exc:
if os.path.lexists(scratch):
try:
os.unlink(scratch)
except OSError as left:
exc.strerror = (f"{exc.strerror or exc}, and {scratch} stays "
f"({left.strerror or left})")
raise
# FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows.
# Before Python 3.12 lstat does not report a junction as a link, and
# os.walk(followlinks=False) descends into it.
@@ -7890,9 +7908,7 @@ def _cache_write(path: Path, data: bytes) -> None:
costs a second read, never the run."""
try:
path.parent.mkdir(parents=True, exist_ok=True)
scratch = path.with_name(f"{path.name}.{os.getpid()}.part")
scratch.write_bytes(data)
os.replace(scratch, path)
write_atomically(path, data)
except OSError as exc:
if os.environ.get("RETROBIOS_DEBUG"):
print(f" Not cached: {path} ({exc.strerror or exc})", file=sys.stderr)
@@ -9839,23 +9855,12 @@ def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | N
places = [found] + [place for place in places if place != found]
failure = "nothing could be written beside the folder"
for path in places:
scratch: Path | None = None
try:
path.parent.mkdir(exist_ok=True)
_check_holder(path.parent)
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.",
suffix=".part", delete=False) as handle:
scratch = Path(handle.name)
handle.write(text)
os.replace(scratch, path)
write_atomically(path, text.encode("utf-8"))
except OSError as exc:
failure = exc.strerror or str(exc)
if scratch is not None and os.path.lexists(scratch):
try:
scratch.unlink()
except OSError as left:
failure += f", and {scratch} stays ({left.strerror or left})"
continue
return path, ""
return None, failure
+1 -1
View File
@@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins
# curl or wget stop on a cut transfer before the hash is read: the site's
# build rewrites this line there (scripts/sitebootstrap.py).
MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
DEFAULT_INSTALL_SHA256="7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171"
DEFAULT_INSTALL_SHA256="5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
MAX_INSTALLER_BYTES=8388608
+8 -8
View File
@@ -27,8 +27,8 @@
{
"dest": "roms/ports/retrobios/install.py",
"repo_path": "install.py",
"size": 1450806,
"sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171",
"size": 1450902,
"sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b",
"executable": false
},
{
@@ -71,8 +71,8 @@
"muos": {
"archive": {
"dest": "ARCHIVE/RetroBIOS.muxapp",
"size": 1504431,
"sha256": "ae2c3d83d3ef556166787f9d86ff3aa4aa51fd069211c2052c9935f2c1e29219"
"size": 1504527,
"sha256": "657b9c3a63251ef77487ca4e819a66b48219163c36e46d4e53f503f16d9d7ade"
},
"members": [
{
@@ -92,8 +92,8 @@
{
"name": "RetroBIOS/install.py",
"repo_path": "install.py",
"size": 1450806,
"sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171",
"size": 1450902,
"sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b",
"executable": false
},
{
@@ -166,8 +166,8 @@
{
"dest": ".config/modules/retrobios/install.py",
"repo_path": "install.py",
"size": 1450806,
"sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171",
"size": 1450902,
"sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b",
"executable": false
},
{
+2 -4
View File
@@ -12,7 +12,7 @@ from pathlib import Path
from typing import NamedTuple
from installer.cards import games_part
from installer.host_fs import _is_dir
from installer.host_fs import _is_dir, write_atomically
from installer.network import _read_capped
CACHE_VARIABLE = "RETROBIOS_CACHE"
@@ -64,9 +64,7 @@ def _cache_write(path: Path, data: bytes) -> None:
costs a second read, never the run."""
try:
path.parent.mkdir(parents=True, exist_ok=True)
scratch = path.with_name(f"{path.name}.{os.getpid()}.part")
scratch.write_bytes(data)
os.replace(scratch, path)
write_atomically(path, data)
except OSError as exc:
if os.environ.get("RETROBIOS_DEBUG"):
print(f" Not cached: {path} ({exc.strerror or exc})", file=sys.stderr)
+18
View File
@@ -239,6 +239,24 @@ def _replace_with_copy(src: Path, dest: Path) -> None:
raise
def write_atomically(path: Path, data: bytes) -> None:
"""Write data at path through a scratch file beside it, removed when the
write fails; a scratch that cannot be removed is named in the error."""
fd, scratch = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".part")
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
os.replace(scratch, path)
except OSError as exc:
if os.path.lexists(scratch):
try:
os.unlink(scratch)
except OSError as left:
exc.strerror = (f"{exc.strerror or exc}, and {scratch} stays "
f"({left.strerror or left})")
raise
# FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows.
# Before Python 3.12 lstat does not report a junction as a link, and
# os.walk(followlinks=False) descends into it.
+2 -14
View File
@@ -9,14 +9,13 @@ import os
import re
import stat
import sys
import tempfile
from collections.abc import Callable, Iterable
from pathlib import Path, PurePosixPath
from typing import NamedTuple
from installer.arguments import build_parser
from installer.events import EVENTS
from installer.host_fs import _clear_read_only, _is_dir, _is_link, _replace_with_copy
from installer.host_fs import _clear_read_only, _is_dir, _is_link, _replace_with_copy, write_atomically
from installer.invocation import _INVOCATION, _VALUED_OPTIONS, _command_rank, installer_id
from installer.local_check import _digest_file
from installer.offline import LOCAL
@@ -345,23 +344,12 @@ def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | N
places = [found] + [place for place in places if place != found]
failure = "nothing could be written beside the folder"
for path in places:
scratch: Path | None = None
try:
path.parent.mkdir(exist_ok=True)
_check_holder(path.parent)
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.",
suffix=".part", delete=False) as handle:
scratch = Path(handle.name)
handle.write(text)
os.replace(scratch, path)
write_atomically(path, text.encode("utf-8"))
except OSError as exc:
failure = exc.strerror or str(exc)
if scratch is not None and os.path.lexists(scratch):
try:
scratch.unlink()
except OSError as left:
failure += f", and {scratch} stays ({left.strerror or left})"
continue
return path, ""
return None, failure
+7
View File
@@ -758,6 +758,13 @@ class Cache(GamesTestCase):
self.assertEqual(len(counted), 2)
self.assertEqual(plan.games[0].dat_regions, frozenset({"japan"}))
def test_a_cache_write_that_fails_leaves_no_scratch(self):
# Each failing run left one index.json.<pid>.part beside the cache.
cached = self.card.cache / "games"
(cached / "index.json").mkdir(parents=True)
install._cache_write(cached / "index.json", b"{}")
self.assertEqual([p.name for p in cached.iterdir()], ["index.json"])
def test_the_index_is_cached_and_read_offline_without_the_list_beside_it(self):
self.card.game("MD", "eu.md", MD_EU)
index = (self.card.lists / "games" / "index.json").read_bytes()