From 47bb48571c76d06281666ae7409aab33643954c1 Mon Sep 17 00:00:00 2001 From: KrisEnigma Date: Sun, 8 Nov 2026 01:18:43 -0300 Subject: [PATCH] fix: retry locked cache writes and link release downloads Windows AV or a concurrent reader could deny replacing a just-written cache file, which stalled warming and dropped titles; also stamp Windows-first download links into the release notes. --- .github/workflows/release.yml | 3 +- CHANGELOG.md | 5 +++ packaging/release-header.md | 10 +++-- src/couch_doom/asset_cache.py | 7 +-- src/couch_doom/atomic.py | 28 ++++++++++++ src/couch_doom/music_cache.py | 52 ++++++++++++---------- tests/test_atomic.py | 82 +++++++++++++++++++++++++++++++++++ tests/test_release_header.py | 25 +++++++++++ 8 files changed, 180 insertions(+), 32 deletions(-) create mode 100644 src/couch_doom/atomic.py create mode 100644 tests/test_atomic.py create mode 100644 tests/test_release_header.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2a1efb2..907ed54 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -164,7 +164,8 @@ jobs: exit 1 fi {\ - cat packaging/release-header.md + # __TAG__ becomes this release so the header's download links stay clickable and Windows-first. + sed "s/__TAG__/${GITHUB_REF_NAME}/g" packaging/release-header.md printf '\n%s\n\n' "$section" echo 'Controls and setup details are in `How to use.txt`, inside every ZIP and tar.gz download.' } > notes.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b865140..8c10fc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ Each release's notes on GitHub are its own section below, behind the download instructions in `packaging/release-header.md`. Keep the `**New in X.Y.Z**` heading format: the release workflow and the in-app update notice both look for it. +**New in 1.2.11** + +- Windows: art and music cache writes retry when antivirus or another reader briefly locks a file, so a custom `cache_dir` next to CouchDoom no longer stalls the cache walk or drops titles and readmes. +- Release notes put direct download links first (Windows, then macOS, Linux, Steam Deck), so you do not have to dig through the alphabetical asset list. + **New in 1.2.10** - Windows: when an update can't replace the CouchDoom folder because another program still has it open, CouchDoom waits longer and explains what went wrong more clearly. diff --git a/packaging/release-header.md b/packaging/release-header.md index e9af900..54d62fe 100644 --- a/packaging/release-header.md +++ b/packaging/release-header.md @@ -1,9 +1,11 @@ **Download the file for your system below.** No Python needed. Builds aren't code-signed, so your OS may ask you to approve the first launch. -- **Windows:** `CouchDoom-…-windows-x64.zip`. Extract it and run `CouchDoom.exe`. On the "unknown publisher" warning, choose **More info → Run anyway**. -- **macOS:** `CouchDoom-…-macos-arm64.dmg` (Apple Silicon) or `CouchDoom-…-macos-x64.dmg` (Intel, macOS 10.15 or newer). Open it and drag `CouchDoom.app` to Applications. If macOS blocks the first launch, go to **System Settings → Privacy & Security** and click **Open Anyway**. A ZIP of the same build is there as a fallback. -- **Linux:** `CouchDoom-…-linux-x64.tar.gz` (PCs) or `CouchDoom-…-linux-arm64.tar.gz` (ARM boards such as the Raspberry Pi 4 and 5). Extract it and run `./CouchDoom`. Needs glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later). -- **Steam Deck:** the `linux-x64` file. In Desktop Mode, extract it and add `CouchDoom` to Steam with **Add a Non-Steam Game** so it starts from Game Mode. GZDoom and DoomRunner from Discover are detected automatically. +GitHub lists release assets alphabetically, so Windows sits near the bottom of that list. Prefer the links here (Windows first); the `.sha256` files and macOS ZIPs stay in the asset list for the in-app updater. + +- **Windows:** [`CouchDoom-__TAG__-windows-x64.zip`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-windows-x64.zip). Extract it and run `CouchDoom.exe`. On the "unknown publisher" warning, choose **More info → Run anyway**. +- **macOS:** [`CouchDoom-__TAG__-macos-arm64.dmg`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-macos-arm64.dmg) (Apple Silicon) or [`CouchDoom-__TAG__-macos-x64.dmg`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-macos-x64.dmg) (Intel, macOS 10.15 or newer). Open it and drag `CouchDoom.app` to Applications. If macOS blocks the first launch, go to **System Settings → Privacy & Security** and click **Open Anyway**. A ZIP of the same build is in the asset list as a fallback for updates. +- **Linux:** [`CouchDoom-__TAG__-linux-x64.tar.gz`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-linux-x64.tar.gz) (PCs) or [`CouchDoom-__TAG__-linux-arm64.tar.gz`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-linux-arm64.tar.gz) (ARM boards such as the Raspberry Pi 4 and 5). Extract it and run `./CouchDoom`. Needs glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later). +- **Steam Deck:** the [`linux-x64`](https://github.com/KrisEnigma/couch-doom/releases/download/__TAG__/CouchDoom-__TAG__-linux-x64.tar.gz) file. In Desktop Mode, extract it and add `CouchDoom` to Steam with **Add a Non-Steam Game** so it starts from Game Mode. GZDoom and DoomRunner from Discover are detected automatically. CouchDoom plays the presets you've already set up in [DoomRunner](https://github.com/Youda008/DoomRunner), [ZDL](https://github.com/lcferrum/qzdl), [Doom Launcher](https://github.com/nstlaurent/DoomLauncher) or [Doom Launcher 667](https://github.com/Realm667/DoomLauncher667). With GZDoom, UZDoom or VKDoom alone, it lists one preset for each IWAD that port can find. It finds them on its own and never changes them. If you use more than one launcher, it asks which to show; you can switch later from the menu. diff --git a/src/couch_doom/asset_cache.py b/src/couch_doom/asset_cache.py index f1f0b3c..1fd41de 100644 --- a/src/couch_doom/asset_cache.py +++ b/src/couch_doom/asset_cache.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import Any +from .atomic import replace_when_free from .endoom import Endoom from .options import Preset from .readme import Readme @@ -130,7 +131,7 @@ def name_cache_file(key: str, label: str) -> None: if current is None or current == dest: return try: - current.replace(dest) + replace_when_free(current, dest) except OSError: return _drop_other_copies(key, keep=dest) @@ -267,7 +268,7 @@ def put(key: str, assets: CachedAssets, label: str | None = None) -> None: "ts": time.time(), } tmp.write_text(json.dumps(data), encoding="utf-8") - os.replace(tmp, path) + replace_when_free(tmp, path) if slug: _drop_other_copies(key, keep=path) with _INDEX_LOCK: @@ -303,7 +304,7 @@ def save_preset_keys(mapping: dict[str, str]) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(f"preset_keys.{os.getpid()}-{threading.get_ident()}.tmp") tmp.write_text(json.dumps(mapping), encoding="utf-8") - os.replace(tmp, path) + replace_when_free(tmp, path) except Exception: if tmp is not None: try: diff --git a/src/couch_doom/atomic.py b/src/couch_doom/atomic.py new file mode 100644 index 0000000..e4edfba --- /dev/null +++ b/src/couch_doom/atomic.py @@ -0,0 +1,28 @@ +"""Atomic file swaps that tolerate brief Windows locks (antivirus, concurrent readers).""" +from __future__ import annotations + +import os +import time +from pathlib import Path + + +def replace_timeout() -> float: + # AV and Explorer often hold a just-written cache file for a moment on Windows. + return 5.0 if os.name == "nt" else 1.0 + + +def replace_when_free(source: Path, destination: Path, timeout: float | None = None) -> None: + """Move ``source`` onto ``destination``, retrying PermissionError until ``timeout``.""" + if timeout is None: + timeout = replace_timeout() + deadline = time.monotonic() + timeout + delay = 0.05 + while True: + try: + os.replace(source, destination) + return + except PermissionError: + if time.monotonic() >= deadline: + raise + time.sleep(delay) + delay = min(delay * 1.5, 0.25) diff --git a/src/couch_doom/music_cache.py b/src/couch_doom/music_cache.py index ad50da1..4f1ed44 100644 --- a/src/couch_doom/music_cache.py +++ b/src/couch_doom/music_cache.py @@ -11,6 +11,7 @@ from typing import Collection, Sequence from .archive import ArchiveSource +from .atomic import replace_when_free from .cache_paths import cache_dir MAX_STREAM_BYTES = 256 * 1024 * 1024 @@ -49,35 +50,38 @@ def selection_key(asset_key: str, iwad: Path | None = None, files: Sequence[Path def get_selection(key: str) -> tuple[bool, dict | None]: - try: - path = _manifest_path(key) - data = json.loads(path.read_text(encoding="utf-8")) - if not isinstance(data, dict) or data.get("version") != MANIFEST_VERSION or not isinstance(data.get("result"), dict): - return False, None + with _LOCK: try: - os.utime(path, None) - except OSError: - pass - return True, data["result"] - except (OSError, ValueError, TypeError): - return False, None + path = _manifest_path(key) + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict) or data.get("version") != MANIFEST_VERSION or not isinstance(data.get("result"), dict): + return False, None + try: + os.utime(path, None) + except OSError: + pass + return True, data["result"] + except (OSError, ValueError, TypeError): + return False, None def put_selection(key: str, result: dict) -> None: path = _manifest_path(key) temp_path: Path | None = None - try: - with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, - prefix=path.name + ".", suffix=".part", delete=False) as f: - temp_path = Path(f.name) - json.dump({"version": MANIFEST_VERSION, "result": result}, f, separators=(",", ":")) - f.flush() - os.fsync(f.fileno()) - os.replace(temp_path, path) - except Exception: - if temp_path: - temp_path.unlink(missing_ok=True) - raise + with _LOCK: + try: + with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, + prefix=path.name + ".", suffix=".part", delete=False) as f: + temp_path = Path(f.name) + json.dump({"version": MANIFEST_VERSION, "result": result}, f, separators=(",", ":")) + f.flush() + os.fsync(f.fileno()) + replace_when_free(temp_path, path) + temp_path = None + except Exception: + if temp_path: + temp_path.unlink(missing_ok=True) + raise def invalidate_selections(present_keys: set[str]) -> None: @@ -128,7 +132,7 @@ def cache_stream(source: ArchiveSource, suffix: str, cancel: threading.Event, raise OSError(f"incomplete music extraction: expected {source.size}, copied {copied}") if cancel.is_set(): raise InterruptedError("music cache population cancelled") - os.replace(temp_path, path) + replace_when_free(temp_path, path) temp_path = None prune({*protected, path}) return path diff --git a/tests/test_atomic.py b/tests/test_atomic.py new file mode 100644 index 0000000..605052a --- /dev/null +++ b/tests/test_atomic.py @@ -0,0 +1,82 @@ +"""replace_when_free retries brief PermissionError locks.""" +from __future__ import annotations + +from pathlib import Path +from unittest.mock import patch + +import pytest + +from couch_doom import atomic + + +def test_replace_when_free_swaps_the_file(tmp_path): + source = tmp_path / "next.json" + destination = tmp_path / "live.json" + destination.write_text("old", encoding="utf-8") + source.write_text("new", encoding="utf-8") + + atomic.replace_when_free(source, destination) + + assert destination.read_text(encoding="utf-8") == "new" + assert not source.exists() + + +def test_replace_when_free_retries_permission_errors(tmp_path, monkeypatch): + source = tmp_path / "next.json" + destination = tmp_path / "live.json" + destination.write_text("old", encoding="utf-8") + source.write_text("new", encoding="utf-8") + calls = [] + real = atomic.os.replace + + def flaky(src, dst): + calls.append(src) + if len(calls) < 3: + raise PermissionError(5, "Access is denied") + return real(src, dst) + + monkeypatch.setattr(atomic.time, "sleep", lambda _s: None) + with patch.object(atomic.os, "replace", flaky): + atomic.replace_when_free(source, destination, timeout=1.0) + + assert len(calls) == 3 + assert destination.read_text(encoding="utf-8") == "new" + + +def test_replace_when_free_raises_after_timeout(tmp_path, monkeypatch): + source = tmp_path / "next.json" + destination = tmp_path / "live.json" + source.write_text("new", encoding="utf-8") + destination.write_text("old", encoding="utf-8") + + def always_busy(src, dst): + raise PermissionError(5, "Access is denied") + + monkeypatch.setattr(atomic.time, "sleep", lambda _s: None) + with patch.object(atomic.os, "replace", always_busy), pytest.raises(PermissionError): + atomic.replace_when_free(source, destination, timeout=0.01) + + assert destination.read_text(encoding="utf-8") == "old" + assert source.exists() + + +def test_music_selection_cache_retries_a_locked_replace(tmp_path, monkeypatch): + from couch_doom import music_cache + + monkeypatch.setattr(music_cache, "cache_dir", lambda: tmp_path) + calls = [] + real = atomic.os.replace + + def flaky(src, dst): + calls.append(Path(src).name) + if len(calls) < 2: + raise PermissionError(5, "Access is denied") + return real(src, dst) + + monkeypatch.setattr(atomic.time, "sleep", lambda _s: None) + with patch.object(atomic.os, "replace", flaky): + music_cache.put_selection("preset-a", {"track": None}) + found, result = music_cache.get_selection("preset-a") + + assert found and result == {"track": None} + assert len(calls) == 2 diff --git a/tests/test_release_header.py b/tests/test_release_header.py new file mode 100644 index 0000000..a01658e --- /dev/null +++ b/tests/test_release_header.py @@ -0,0 +1,25 @@ +"""Release notes header keeps Windows-first download links the workflow can stamp.""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HEADER = (ROOT / "packaging" / "release-header.md").read_text(encoding="utf-8") + + +def test_release_header_lists_windows_before_other_platforms(): + windows = HEADER.index("**Windows:**") + macos = HEADER.index("**macOS:**") + linux = HEADER.index("**Linux:**") + steam = HEADER.index("**Steam Deck:**") + assert windows < macos < linux < steam + + +def test_release_header_uses_tag_placeholders_for_download_links(): + assert "CouchDoom-__TAG__-windows-x64.zip" in HEADER + assert "releases/download/__TAG__/CouchDoom-__TAG__-windows-x64.zip" in HEADER + assert "CouchDoom-__TAG__-macos-arm64.dmg" in HEADER + assert "CouchDoom-__TAG__-linux-x64.tar.gz" in HEADER + + +def test_release_workflow_stamps_the_tag_into_the_header(): + workflow = (ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + assert 'sed "s/__TAG__/${GITHUB_REF_NAME}/g" packaging/release-header.md' in workflow