Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(gallery): serve bulk downloads only once the archive is complete (#10270)

Alexander Eichhorn9264acf9e542
diff --git a/invokeai/app/services/bulk_download/bulk_download_default.py b/invokeai/app/services/bulk_download/bulk_download_default.py
index 6a6129a349..276857fa10 100644
--- a/invokeai/app/services/bulk_download/bulk_download_default.py
+++ b/invokeai/app/services/bulk_download/bulk_download_default.py
@@ -1,3 +1,4 @@
+import os
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Optional, Union
@@ -102,11 +103,20 @@ class BulkDownloadService(BulkDownloadBase):
zip_file_name = bulk_download_item_id + ".zip"
zip_file_path = self._bulk_downloads_folder / (zip_file_name)
- with ZipFile(zip_file_path, "w") as zip_file:
- for image_dto in image_dtos:
- image_zip_path = Path(image_dto.image_category.value) / image_dto.image_name
- image_disk_path = self._invoker.services.images.get_path(image_dto.image_name)
- zip_file.write(image_disk_path, arcname=image_zip_path)
+ # Clients poll for the final name, so it must only appear once the archive is complete. The ".partial" name
+ # fails get_path's ".zip" check, and the rename within the same folder is atomic. The temp name is short and
+ # independent of the item id: a board-derived id can already use the whole filename length limit.
+ partial_path = self._bulk_downloads_folder / f"{uuid_string()}.zip.partial"
+ try:
+ with ZipFile(partial_path, "w") as zip_file:
+ for image_dto in image_dtos:
+ image_zip_path = Path(image_dto.image_category.value) / image_dto.image_name
+ image_disk_path = self._invoker.services.images.get_path(image_dto.image_name)
+ zip_file.write(image_disk_path, arcname=image_zip_path)
+ os.replace(partial_path, zip_file_path)
+ except BaseException:
+ partial_path.unlink(missing_ok=True)
+ raise
return str(zip_file_name)
diff --git a/tests/app/services/bulk_download/test_bulk_download.py b/tests/app/services/bulk_download/test_bulk_download.py
index b568c108ef..e193898c4f 100644
--- a/tests/app/services/bulk_download/test_bulk_download.py
+++ b/tests/app/services/bulk_download/test_bulk_download.py
@@ -109,6 +109,117 @@ def test_handler_image_names(tmp_path: Path, monkeypatch: Any, mock_image_dto: I
)
+def prepare_two_image_download(tmp_path: Path, monkeypatch: Any, mock_image_dto: ImageDTO, mock_invoker: Invoker):
+ """Patch the invoker for a two-image download; returns the dtos and the disk path lookup to patch."""
+ monkeypatch.setattr("invokeai.app.services.bulk_download.bulk_download_default.uuid_string", lambda: "test")
+
+ first = mock_image_dto
+ second = mock_image_dto.model_copy(update={"image_name": "second_image.png"})
+ dtos = {dto.image_name: dto for dto in (first, second)}
+ monkeypatch.setattr(mock_invoker.services.images, "get_dto", lambda name: dtos[name])
+
+ disk_dir = tmp_path / "images_on_disk"
+ disk_dir.mkdir()
+ for name in dtos:
+ (disk_dir / name).write_text(f"contents of {name}")
+ return list(dtos), disk_dir
+
+
+def test_archive_is_not_downloadable_until_complete(
+ tmp_path: Path, monkeypatch: Any, mock_image_dto: ImageDTO, mock_invoker: Invoker
+):
+ """A client polling get_path must never be handed a half-written archive."""
+ names, disk_dir = prepare_two_image_download(tmp_path, monkeypatch, mock_image_dto, mock_invoker)
+ service = BulkDownloadService()
+ service.start(mock_invoker)
+
+ visible_while_writing: list[bool] = []
+
+ def get_path(name: str) -> str:
+ if name == names[1]:
+ # The first image is already written into the archive at this point.
+ try:
+ service.get_path("test.zip")
+ visible_while_writing.append(True)
+ except BulkDownloadTargetException:
+ visible_while_writing.append(False)
+ return str(disk_dir / name)
+
+ monkeypatch.setattr(mock_invoker.services.images, "get_path", get_path)
+
+ service.handler(names, None, None)
+
+ assert visible_while_writing == [False]
+ with ZipFile(service.get_path("test.zip")) as zip_file:
+ assert zip_file.testzip() is None
+ assert sorted(zip_file.namelist()) == sorted(f"general/{name}" for name in names)
+ for name in names:
+ assert zip_file.read(f"general/{name}").decode() == f"contents of {name}"
+ assert [p.name for p in (tmp_path / "bulk_downloads").iterdir()] == ["test.zip"]
+
+
+def test_archive_with_longest_valid_filename_is_created(
+ tmp_path: Path, monkeypatch: Any, mock_image_dto: ImageDTO, mock_invoker: Invoker
+):
+ """A board download whose archive name uses the full 255-character filename limit must still work."""
+ expected_zip_path, expected_image_path, mock_image_contents = prepare_handler_test(
+ tmp_path, monkeypatch, mock_image_dto, mock_invoker
+ )
+ service = BulkDownloadService()
+ service.start(mock_invoker)
+
+ max_filename_length = 255 # component limit of ext4, APFS and NTFS
+ # The item id is "<board name>_test" (uuid_string is patched) and the archive adds ".zip".
+ board_name = "b" * (max_filename_length - len("_test.zip"))
+ monkeypatch.setattr(
+ mock_invoker.services.board_records,
+ "get",
+ lambda *args, **kwargs: BoardRecord(
+ board_id="12345",
+ board_name=board_name,
+ user_id="test_user",
+ created_at="None",
+ updated_at="None",
+ archived=False,
+ ),
+ )
+
+ item_id = service.generate_item_id("12345")
+ assert len(item_id + ".zip") == max_filename_length
+ service.handler(None, "12345", item_id)
+
+ zip_path = Path(service.get_path(item_id + ".zip"))
+ with ZipFile(zip_path) as zip_file:
+ assert zip_file.read(f"general/{mock_image_dto.image_name}").decode() == mock_image_contents
+ assert [p.name for p in zip_path.parent.iterdir()] == [zip_path.name]
+ assert isinstance(mock_invoker.services.events.events[-1], BulkDownloadCompleteEvent)
+
+
+def test_failed_archive_leaves_no_file_behind(
+ tmp_path: Path, monkeypatch: Any, mock_image_dto: ImageDTO, mock_invoker: Invoker
+):
+ """If writing fails midway, no partial archive may remain or become downloadable."""
+ names, disk_dir = prepare_two_image_download(tmp_path, monkeypatch, mock_image_dto, mock_invoker)
+ service = BulkDownloadService()
+ service.start(mock_invoker)
+
+ def get_path(name: str) -> str:
+ return str(disk_dir / ("missing.png" if name == names[1] else name))
+
+ monkeypatch.setattr(mock_invoker.services.images, "get_path", get_path)
+
+ with pytest.raises(FileNotFoundError):
+ service.handler(names, None, None)
+
+ events = mock_invoker.services.events.events
+ assert isinstance(events[0], BulkDownloadStartedEvent)
+ assert isinstance(events[-1], BulkDownloadErrorEvent)
+ assert not any(isinstance(event, BulkDownloadCompleteEvent) for event in events)
+ with pytest.raises(BulkDownloadTargetException):
+ service.get_path("test.zip")
+ assert list((tmp_path / "bulk_downloads").iterdir()) == []
+
+
def test_generate_id(monkeypatch: Any):
"""Test that the generate_id method generates a unique id."""