Compare commits

..
4 changed files with 125 additions and 21 deletions

No files matched your search

+16 -9
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import abc
import filecmp
import hashlib
import json
import os
@@ -166,11 +167,18 @@ class DirectoryExportSink(ExportSink):
@staticmethod
def _content_unchanged(target: Path, new_bytes: bytes) -> bool:
"""True if ``target`` already holds byte-identical content (BLAKE2b)."""
return (
hashlib.blake2b(target.read_bytes()).hexdigest()
== hashlib.blake2b(new_bytes).hexdigest()
)
"""
True if ``target`` already holds byte-identical content (BLAKE2b).
The existing file is hashed in chunks rather than read into memory.
"""
if target.stat().st_size != len(new_bytes):
return False
with target.open("rb") as handle:
return (
hashlib.file_digest(handle, "blake2b").hexdigest()
== hashlib.blake2b(new_bytes).hexdigest()
)
def add_json(self, content: list | dict, arcname: str) -> None:
target = (self._target / arcname).resolve()
@@ -214,10 +222,9 @@ class DirectoryExportSink(ExportSink):
def _commit_streamed_file(self, target: Path, tmp: Path) -> None:
if target in self._snapshot:
self._snapshot.discard(target)
if self._compare_json and self._content_unchanged(
target,
tmp.read_bytes(),
):
# A streamed manifest can be very large, so compare the two files
# in chunks instead of reading them into memory
if self._compare_json and filecmp.cmp(target, tmp, shallow=False):
tmp.unlink()
return
tmp.rename(target)
+21 -10
View File
@@ -6,6 +6,7 @@ import zipfile
from collections.abc import Callable
from pathlib import Path
from tempfile import TemporaryDirectory
from tempfile import mkstemp
from celery import Task
from celery import shared_task
@@ -896,25 +897,26 @@ def build_share_link_bundle(bundle_id: int) -> None:
documents = list(bundle.documents.all().order_by("pk"))
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
temp_zip_path = Path(temp_zip_path_str)
try:
strategy_class = (
ArchiveOnlyStrategy
if bundle.file_version == ShareLink.FileVersion.ARCHIVE
else OriginalsOnlyStrategy
)
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
output_dir = settings.SHARE_LINK_BUNDLE_DIR
output_dir.mkdir(parents=True, exist_ok=True)
final_path = (output_dir / f"{bundle.slug}.zip").resolve()
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir:
temp_zip_path = Path(tmp_dir) / "bundle.zip"
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
final_path.unlink(missing_ok=True)
shutil.move(temp_zip_path, final_path)
if final_path.exists():
final_path.unlink()
shutil.move(temp_zip_path, final_path)
bundle.file_path = f"{bundle.slug}.zip"
bundle.size_bytes = final_path.stat().st_size
@@ -945,7 +947,16 @@ def build_share_link_bundle(bundle_id: int) -> None:
"timestamp": timezone.now().isoformat(),
}
bundle.save(update_fields=["status", "last_error"])
try:
temp_zip_path.unlink()
except OSError:
pass
raise
finally:
try:
temp_zip_path.unlink(missing_ok=True)
except OSError:
pass
@shared_task
+78
View File
@@ -91,6 +91,84 @@ class TestDirectoryExportSink:
writer.close()
assert json.loads((target / "manifest.json").read_text()) == [{"pk": 1}]
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param(_dumps({"version": "x"}), True, id="identical"),
pytest.param(_dumps({"version": "y"}), False, id="same-size-different"),
],
)
def test_add_json_compare_json(
self,
tmp_path: Path,
*,
existing: str,
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
(target / "metadata.json").write_text(existing)
os.utime(target / "metadata.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
sink.add_json({"version": "x"}, "metadata.json")
assert json.loads((target / "metadata.json").read_text()) == (
json.loads(existing) if unchanged else {"version": "x"}
)
# An unchanged file is not rewritten, so its mtime is left alone
assert ((target / "metadata.json").stat().st_mtime == 1) is unchanged
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param([{"pk": 1}], True, id="identical"),
pytest.param([{"pk": 2}], False, id="changed"),
],
)
def test_stream_compare_json(
self,
tmp_path: Path,
*,
existing: list[dict],
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
# Write the existing manifest the same way the sink does
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=False,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer: StreamingManifestWriter = StreamingManifestWriter(handle)
for record in existing:
writer.write_record(record)
writer.close()
os.utime(target / "manifest.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer = StreamingManifestWriter(handle)
writer.write_record({"pk": 1})
writer.close()
assert json.loads((target / "manifest.json").read_text()) == (
existing if unchanged else [{"pk": 1}]
)
assert ((target / "manifest.json").stat().st_mtime == 1) is unchanged
assert not (target / "manifest.json.tmp").exists()
def test_add_file_skips_when_size_and_mtime_match(
self,
tmp_path: Path,
+10 -2
View File
@@ -434,9 +434,13 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
"documents.tasks.OriginalsOnlyStrategy.add_document",
side_effect=RuntimeError("zip failure"),
),
self.assertRaises(RuntimeError),
mock.patch("pathlib.Path.unlink") as unlink_mock,
):
build_share_link_bundle(bundle.pk)
unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
None,
] * 5
with self.assertRaises(RuntimeError):
build_share_link_bundle(bundle.pk)
bundle.refresh_from_db()
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
@@ -444,6 +448,10 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
assert isinstance(bundle.last_error, dict)
self.assertEqual(bundle.last_error.get("message"), "zip failure")
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
self.assertTrue(scratch_zips)
for path in scratch_zips:
path.unlink(missing_ok=True)
def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
# Should not raise when bundle does not exist