Files
romm/backend/utils/archive_7zip.py
Michael Manganiello 477d9b1744 feat: Add streaming support for 7zip hashing
At the moment, 7zip files are generating memory issues and even OOM
errors on user installations. This is because the current stable release
of `py7zr` does not support decompression streaming, and RomM needs to
decompress the each 7zip file in the library into memory to be able to
calculate hashes.

This change introduces a `py7zr` fork I created to have a stable commit
SHA to refer to in case upstream gets any forced pushes. It includes the
contents of the pull request the `py7zr` creator is working on to
support decompression streaming [1].

The way decompression streaming is implemented in `py7zr` is different
than the other compression utilities. Instead of being able to provide a
`bytes` iterator, we need to provide a `Py7zIO` implementation that
will call a callback on each read and write operation.

[1] https://github.com/miurahr/py7zr/pull/620
2024-11-08 21:31:11 -03:00

60 lines
1.6 KiB
Python

from typing import Callable
from py7zr import Py7zIO, WriterFactory
class CallbackIO(Py7zIO):
"""Py7zIO implementation that calls a callback on write and read."""
def __init__(
self,
filename: str,
on_write: Callable[[bytes | bytearray], None],
on_read: Callable[[int | None], bytes],
):
self.filename = filename
self.on_write = on_write
self.on_read = on_read
self._size = 0
def write(self, s: bytes | bytearray) -> int:
print(f"{self.__class__.__name__}: write. filename={self.filename}")
length = len(s)
self._size += length
self.on_write(s)
return length
def read(self, size: int | None = None) -> bytes:
return self.on_read(size)
def seek(self, offset: int, whence: int = 0) -> int:
return 0
def flush(self) -> None: ...
def size(self) -> int:
return self._size
class CallbackIOFactory(WriterFactory):
"""WriterFactory implementation that creates CallbackIO instances."""
def __init__(
self,
on_write: Callable[[bytes | bytearray], None],
on_read: Callable[[int | None], bytes],
):
self.products: dict[str, CallbackIO] = {}
self.on_write = on_write
self.on_read = on_read
def create(self, filename: str) -> CallbackIO:
product = CallbackIO(
filename=filename, on_write=self.on_write, on_read=self.on_read
)
self.products[filename] = product
return product
def get(self, filename: str) -> Py7zIO:
return self.products[filename]