Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
65 changes: 32 additions & 33 deletions databusclient/api/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
79 changes: 79 additions & 0 deletions tests/test_download_atomic_write.py
Original file line number Diff line number Diff line change
@@ -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