fix(archives): fix zipfile writes where zipfile_inflate64 is imported (#5678)

zipfile_inflate64 replaces zipfile._get_compressor with a one-argument
wrapper, while CPython 3.13+ passes compresslevel too, so every zip write
raises TypeError once it is imported. Each writer had to call
ensure_zipfile_writable() first, and a new writer that forgot it broke.

Wrap the patched function right after the import in utils/archives.py,
the only module that imports zipfile_inflate64, and drop the per-site
calls and the helper.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-11-20 07:03:48 -05:00
committed by GitHub
parent c9d06c8ee2
commit 38d0a671df
13 changed files with 31 additions and 75 deletions

View File

@@ -193,7 +193,6 @@ from utils.validation import (
from utils.zip_cache import (
BULK_CACHE_MAX_ROMS,
ZipFileEntry,
ensure_zipfile_writable,
get_bulk_namespace,
get_cache_key,
get_cached_zip,
@@ -1774,7 +1773,6 @@ async def get_rom_content(
zip_buffer = BytesIO()
now = datetime.now()
ensure_zipfile_writable()
with ZipFile(zip_buffer, "w") as zip_file:
# Add content files
for file in files:

View File

@@ -104,7 +104,6 @@ from utils.uploads import (
sanitize_asset_filename,
)
from utils.validation import RomIdScope, narrow_rom_id_scope
from utils.zip_cache import ensure_zipfile_writable
def _build_save_schema(
@@ -860,8 +859,6 @@ def _restored_response(restored: RestoredFiles, save: Save) -> Response:
SAVE_PATH_HEADER: quote(path),
},
)
# `zipfile_inflate64`, imported for ROM archives, breaks `writestr()` until this runs.
ensure_zipfile_writable()
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
for path, data in sorted(restored.items()):

View File

@@ -18,7 +18,6 @@ from handler.streaming.config import ResolvedContainer, emulator_labels
from logger.logger import log
from models.assets import Save, State
from models.rom import Rom
from utils.zip_cache import ensure_zipfile_writable
# Charged on each entry's expanded size, so a small, highly compressible
# upload cannot inflate past the ceiling any stored save archive has.
@@ -156,7 +155,6 @@ def build_import_archive(
Returns:
The archive bytes, and the manifest's `files` list actually written.
"""
ensure_zipfile_writable()
staged: _Staged = {}
budget = _ArchiveBudget()
if base is not None:

View File

@@ -40,7 +40,6 @@ from models.rom import Rom
from models.user import User
from utils.memory_cards import content_hash_of_bytes
from utils.uploads import apply_datetime_tag
from utils.zip_cache import ensure_zipfile_writable
_IGNORED_CATEGORY = "SYSTEM"
_SAVEDATA_CATEGORY = "SAVEDATA"
@@ -323,9 +322,6 @@ def _load_bundle_member_names(path: Path) -> list[str]:
def _write_bundle(entries: dict[str, bytes]) -> bytes:
# `zipfile_inflate64` is imported elsewhere for ROM archive reading, and
# breaks `writestr()` until this runs.
ensure_zipfile_writable()
buffer = BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
for name, data in entries.items():

View File

@@ -23,7 +23,6 @@ from models.rom import Rom, RomFile, RomFileCategory
from models.user import User
from utils.nginx import content_disposition
from utils.rom_patcher import PatcherInputError
from utils.zip_cache import ensure_zipfile_writable
def _patch_file(rom: Rom) -> RomFile:
@@ -226,7 +225,6 @@ class TestPatchingALibraryFile:
node: None,
):
archive = io.BytesIO()
ensure_zipfile_writable()
with zipfile.ZipFile(archive, "w") as zipped:
zipped.writestr("game.sfc", b"rom")
zipped.writestr("readme.txt", b"hi")

View File

@@ -38,7 +38,6 @@ from models.device import Device
from models.permission import HiddenEntity, PermEntity
from models.rom import Rom, RomFile
from models.user import User
from utils.zip_cache import ensure_zipfile_writable
UNIT = b"stored unit"
GAME = SigilGame(result=SimpleNamespace(platform="psx"), game_ids=("SLUS-01041",))
@@ -57,7 +56,6 @@ def _stored(save: Save, data: bytes = UNIT) -> Save:
def _neutral_gba_unit() -> bytes:
ensure_zipfile_writable()
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as zf:
zf.writestr("save.sram", b"battery")

View File

@@ -117,7 +117,6 @@ from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout
from models.user import Role, User
from utils.memory_cards import content_hash_of_bytes
from utils.uploads import apply_datetime_tag
from utils.zip_cache import ensure_zipfile_writable
# ── Fixtures / helpers ────────────────────────────────────────────────────────
@@ -6507,7 +6506,6 @@ def _exit_archive(
) -> bytes:
"""A webstation exit archive whose manifest labels each member with its kind,
each member stamped with its `written` time when one is given."""
ensure_zipfile_writable()
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
for path, (_kind, content) in members.items():

View File

@@ -17,7 +17,6 @@ import pytest
from logger.logger import log
from utils import archives
from utils.zip_cache import ensure_zipfile_writable
def _fake_7z_listing(names: list[str]) -> str:
@@ -712,9 +711,6 @@ def _tar_bytes(members: dict[str, bytes]) -> bytes:
def _zip_bytes(
members: dict[str, bytes], compression: int = zipfile.ZIP_DEFLATED
) -> bytes:
# Importing `archives` patches zipfile for Enhanced Deflate, which
# leaves the writer unusable until this is called.
ensure_zipfile_writable()
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression) as z:
for name, data in members.items():
@@ -1049,3 +1045,23 @@ def test_real_ppmd_zip_hashes_through_7zz(tmp_path):
("Game (USA) (Track 01).bin", len(track), hashlib.sha1(track).hexdigest()),
("Game (USA).cue", len(cue), hashlib.sha1(cue).hexdigest()),
]
@pytest.mark.parametrize(
"compression",
[zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED, zipfile.ZIP_ZSTANDARD],
)
def test_zip_writes_after_inflate64_patch(compression: int, tmp_path: Path) -> None:
src = tmp_path / "src.bin"
src.write_bytes(b"from disk")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression, compresslevel=1) as z:
z.writestr("a.txt", b"hello")
z.write(src, arcname="b.bin")
with z.open("c.txt", "w") as member:
member.write(b"streamed")
with zipfile.ZipFile(buf) as z:
assert z.read("a.txt") == b"hello"
assert z.read("b.bin") == b"from disk"
assert z.read("c.txt") == b"streamed"

View File

@@ -24,7 +24,6 @@ from utils.rom_patcher.patcher import (
MIN_PATCH_OUTPUT_GROWTH_BYTES,
max_patch_output_size,
)
from utils.zip_cache import ensure_zipfile_writable
def _write_zip(
@@ -33,7 +32,6 @@ def _write_zip(
*,
comment: bytes = b"",
) -> None:
ensure_zipfile_writable()
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.comment = comment
for name, content in members.items():

View File

@@ -428,25 +428,6 @@ class TestZipFileEntryFromRomFile:
)
class TestEnsureZipfileWritable:
def test_writestr_works_after_inflate64_patch(self, library, mocker):
# Simulates the zipfile_inflate64 patch: a wrapper that drops the
# compresslevel argument, which breaks ZipFile.write() on CPython 3.13.
import zipfile
original = zipfile._get_compressor # type: ignore[attr-defined]
def one_arg_wrapper(compress_type):
return original(compress_type)
mocker.patch.object(zipfile, "_get_compressor", one_arg_wrapper)
result = build_library_zip(m3u_content=b"a.bin", m3u_filename="game.m3u")
with ZipFile(result) as zf:
assert zf.read("a.bin") == b"data"
assert zf.read("game.m3u") == b"a.bin"
class TestCachedZipReadability:
def test_build_leaves_archive_nginx_readable(self, library):
result = build_library_zip()

View File

@@ -29,6 +29,17 @@ from utils.filesystem import (
ArchiveFormat,
)
_inflate64_get_compressor = zipfile._get_compressor # type: ignore[attr-defined]
def _get_compressor(compress_type: int, compresslevel: int | None = None) -> object:
# zipfile_inflate64's patch takes only compress_type, but CPython passes
# compresslevel too, so every zip write would raise TypeError without this.
return _inflate64_get_compressor(compress_type)
zipfile._get_compressor = _get_compressor # type: ignore[attr-defined]
# 7zip archives are read through 7zz.
SEVEN_ZIP_PATH = "/usr/bin/7zz"
# RAR archives are read through bsdtar.

View File

@@ -27,7 +27,6 @@ from utils.archives import (
read_zip_archive_files,
)
from utils.filesystem import COMPRESSED_FILE_EXTENSIONS
from utils.zip_cache import ensure_zipfile_writable
PATCHER_SCRIPT = Path(__file__).parent / "patcher.js"
@@ -189,7 +188,6 @@ def _rebuild_zip(
except (EOFError, OSError, RuntimeError, zipfile.BadZipFile, zlib.error) as e:
raise PatcherInputError("The ROM archive could not be read") from e
ensure_zipfile_writable()
try:
with (
source_archive,

View File

@@ -120,36 +120,6 @@ def _namespace_build_lock(namespace_dir: Path) -> Generator[None]:
os.close(fd)
def ensure_zipfile_writable() -> None:
"""Restore ``zipfile._get_compressor`` to a writable signature.
``zipfile_inflate64`` (imported in ``handler/filesystem/roms_handler.py``
to support Enhanced Deflate) replaces ``zipfile._get_compressor`` with a
wrapper that only accepts ``compress_type``. CPython 3.13 calls it with
``(compress_type, compresslevel)``, so ``ZipFile.write()``/``writestr()``
raise ``TypeError``. Wrap it once with a signature-compatible shim that
drops the extra arg, matching inflate64's own behavior (it already ignores
``compresslevel``). Idempotent and safe to call from any thread.
"""
current = zipfile._get_compressor # type: ignore[attr-defined]
if getattr(current, "_romm_compresslevel_safe", False):
return
# Probe with two args: the stdlib accepts them, inflate64's wrapper does not.
try:
current(zipfile.ZIP_STORED, None)
return
except TypeError:
pass
@functools.wraps(current)
def _get_compressor(compress_type: int, compresslevel: int | None = None) -> object:
return current(compress_type)
_get_compressor._romm_compresslevel_safe = True # type: ignore[attr-defined]
zipfile._get_compressor = _get_compressor # type: ignore[attr-defined]
def build_cached_zip(
namespace: str,
entries: list[ZipFileEntry],
@@ -184,7 +154,6 @@ def _write_cached_zip(
os.close(fd)
try:
os.chmod(tmp_path, SERVED_FILE_MODE)
ensure_zipfile_writable()
with zipfile.ZipFile(tmp_path, "w") as zf:
for entry in entries:
src = Path(LIBRARY_BASE_PATH) / entry.full_path