diff --git a/CHANGELOG.md b/CHANGELOG.md index 80baae6..2988996 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed +- Interrupted downloads and downloads that fail size or checksum validation preserve any existing destination file. + ### Added - Workflow download steps support an optional `user_agent` field. - Download `--user-agent` CLI option and `user_agent` Python API argument to override the header on file HEAD and GET requests, including redirects and authentication retries. Download manifests preserve the override for replay. diff --git a/databusclient/api/download.py b/databusclient/api/download.py index f2aead7..74f065f 100644 --- a/databusclient/api/download.py +++ b/databusclient/api/download.py @@ -602,44 +602,43 @@ def _download_file( total_size_in_bytes = int(response.headers.get("content-length", 0)) block_size = 1024 # 1 KiB - progress_bar = tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True) - with open(filename, "wb") as f: - for data in response.iter_content(block_size): - progress_bar.update(len(data)) - f.write(data) - progress_bar.close() - - # --- 5. Verify download size --- - if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: - raise IOError("Downloaded size does not match Content-Length header") - - # --- 6. Validate checksum on original downloaded file (BEFORE conversion) --- + # Stage on the destination filesystem so an unsuccessful transfer cannot + # truncate an existing download and the final replacement is atomic. actual_checksum = None - if validate_checksum: - try: - actual_checksum, _ = compute_sha256_and_length(filename) - except (OSError, IOError) as e: - print(f"WARNING: error computing checksum for {filename}: {e}") - actual_checksum = None - - if expected_checksum is None: - print( - f"WARNING: no expected checksum available for {filename}; skipping validation" - ) - elif actual_checksum is None: - print( - f"WARNING: could not compute checksum for {filename}; skipping validation" - ) - else: - if actual_checksum.lower() != expected_checksum.lower(): - try: - os.remove(filename) - except OSError: - pass + with tempfile.TemporaryDirectory(dir=dirpath or ".") as staging_dir: + staged_file = os.path.join(staging_dir, "download") + with ( + tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True) as progress_bar, + open(staged_file, "wb") as output, + ): + for data in response.iter_content(block_size): + output.write(data) + progress_bar.update(len(data)) + + if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: + raise IOError("Downloaded size does not match Content-Length header") + + if validate_checksum: + try: + actual_checksum, _ = compute_sha256_and_length(staged_file) + except OSError as e: + print(f"WARNING: error computing checksum for {filename}: {e}") + + if expected_checksum is None: + print( + f"WARNING: no expected checksum available for {filename}; skipping validation" + ) + elif actual_checksum is None: + print( + f"WARNING: could not compute checksum for {filename}; skipping validation" + ) + elif actual_checksum.lower() != expected_checksum.lower(): raise IOError( f"Checksum mismatch for {filename}: expected {expected_checksum}, got {actual_checksum}" ) + os.replace(staged_file, filename) + # --- 7. Unified compression/format conversion pass --- source_compression = _detect_compression_format(file) should_convert_compression, source_fmt = _should_convert_compression( diff --git a/pyproject.toml b/pyproject.toml index d44c548..c9d07c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "databusclient" -version = "1.3.2" +version = "1.3.3" description = "A simple client for submitting, downloading, and deleting data on the DBpedia Databus" authors = ["DBpedia Association"] license = "Apache-2.0 License" diff --git a/tests/test_download_atomic_write.py b/tests/test_download_atomic_write.py new file mode 100644 index 0000000..f68da5b --- /dev/null +++ b/tests/test_download_atomic_write.py @@ -0,0 +1,79 @@ +"""Verify that only a complete, validated transfer replaces a download.""" + +from hashlib import sha256 +from unittest.mock import Mock + +import pytest +import requests + +from databusclient.api.download import _download_file + + +URL = "https://example.org/file.nt" +PAYLOAD = b"new file" + + +@pytest.fixture +def response(monkeypatch): + head = Mock(status_code=200, headers={}) + get = Mock(status_code=200, headers={"content-length": str(len(PAYLOAD))}) + get.iter_content.return_value = iter([PAYLOAD]) + monkeypatch.setattr(requests, "head", Mock(return_value=head)) + monkeypatch.setattr(requests, "get", Mock(return_value=get)) + return get + + +@pytest.mark.parametrize("existing_file", [False, True]) +@pytest.mark.parametrize("failure", ["interruption", "length", "checksum"]) +def test_failed_transfer_preserves_destination( + tmp_path, response, existing_file, failure +): + destination = tmp_path / "file.nt" + if existing_file: + destination.write_bytes(b"original file") + + if failure == "interruption": + + def interrupted_chunks(_chunk_size): + yield PAYLOAD[:3] + raise requests.exceptions.ChunkedEncodingError("connection interrupted") + + response.iter_content.side_effect = interrupted_chunks + error = requests.exceptions.ChunkedEncodingError + message = "connection interrupted" + elif failure == "length": + response.iter_content.return_value = iter([PAYLOAD[:3]]) + error = OSError + message = "Content-Length" + else: + error = OSError + message = "Checksum mismatch" + + with pytest.raises(error, match=message): + _download_file( + URL, + str(tmp_path), + validate_checksum=failure == "checksum", + expected_checksum=sha256(b"different data").hexdigest(), + ) + + if existing_file: + assert list(tmp_path.iterdir()) == [destination] + assert destination.read_bytes() == b"original file" + else: + assert list(tmp_path.iterdir()) == [] + + +def test_validated_transfer_replaces_destination(tmp_path, response): + destination = tmp_path / "file.nt" + destination.write_bytes(b"original file") + + _download_file( + URL, + str(tmp_path), + validate_checksum=True, + expected_checksum=sha256(PAYLOAD).hexdigest(), + ) + + assert list(tmp_path.iterdir()) == [destination] + assert destination.read_bytes() == PAYLOAD