diff --git a/README.md b/README.md
index a6fb16ac..164e72d8 100644
--- a/README.md
+++ b/README.md
@@ -125,7 +125,7 @@ The command-line interface provides commands for downloading, deploying, and del
### Download
-The `download` command retrieves Databus files, versions, artifacts, groups, collections, or SPARQL query results. It supports authentication, checksum validation, compression conversion, and RDF or tabular format conversion. See the [download docs](doc/cli-usage.md#cli-download).
+The `download` command retrieves Databus files, versions, artifacts, groups, collections, or SPARQL query results. It supports authentication, checksum validation, compression conversion, RDF or tabular format conversion, and resuming interrupted downloads with `-c` / `--resume`. See the [download docs](doc/cli-usage.md#cli-download).
### Deploy
diff --git a/databusclient/api/download.py b/databusclient/api/download.py
index f2aead78..9222076b 100644
--- a/databusclient/api/download.py
+++ b/databusclient/api/download.py
@@ -443,6 +443,7 @@ def _download_file(
expected_checksum: str | None = None,
manifest_context=None,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download a file from the internet with a progress bar using tqdm.
@@ -463,6 +464,8 @@ def _download_file(
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
expected_checksum: The expected checksum of the file.
+ manifest_context: ManifestContext instance to record download metadata.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
_validate_graph_mode(graph_mode)
source_url = url
@@ -478,8 +481,17 @@ def _download_file(
if dirpath:
os.makedirs(dirpath, exist_ok=True) # Create the necessary directories
+ # Check for existing partial file if resume requested
+ existing_bytes = 0
+ total_size_in_bytes = 0
+ if resume and os.path.isfile(filename):
+ existing_bytes = os.path.getsize(filename)
+
# --- 1. Get redirect URL by requesting HEAD ---
- headers = {"User-Agent": DEFAULT_USER_AGENT if user_agent is None else user_agent}
+ headers = {
+ "User-Agent": DEFAULT_USER_AGENT if user_agent is None else user_agent,
+ "Accept-Encoding": "identity",
+ }
# --- 1a. public databus ---
response = requests.head(url, headers=headers, timeout=30, allow_redirects=False)
@@ -521,97 +533,236 @@ def _download_file(
headers["X-API-KEY"] = databus_key
response = requests.head(url, headers=headers, timeout=30)
- # --- 2. Try direct GET to redirected URL ---
- headers["Accept-Encoding"] = (
- "identity" # disable gzip to get correct content-length
- )
- response = requests.get(
- url, headers=headers, stream=True, allow_redirects=True, timeout=30
- )
- www = response.headers.get(
- "WWW-Authenticate", ""
- ) # Check if authentication is required
-
- # --- 3. Handle authentication responses ---
- # 3a. Server requests Bearer auth. Only attempt token exchange for hosts
- # we explicitly consider Vault-protected (VAULT_REQUIRED_HOSTS). This avoids
- # sending tokens to unrelated hosts and makes auth behavior predictable.
- if response.status_code == 401 and "bearer" in www.lower():
- # If host is not configured for Vault, do not attempt token exchange.
- if host not in VAULT_REQUIRED_HOSTS:
- raise DownloadAuthError(
- "Server requests Bearer authentication but this host is not configured for Vault token exchange."
- " Try providing a databus API key with --databus-key or contact your administrator."
- )
+ file_already_complete = False
+ if response.status_code == 200 and response.headers.get("content-length"):
+ try:
+ head_remote_total = int(response.headers.get("content-length"))
+ if head_remote_total > 0:
+ total_size_in_bytes = head_remote_total
+ except (ValueError, TypeError):
+ pass
+
+ if (
+ existing_bytes > 0
+ and response.status_code == 200
+ and response.headers.get("content-length")
+ ):
+ try:
+ remote_total = int(response.headers.get("content-length"))
+ if remote_total > 0 and existing_bytes == remote_total:
+ print(
+ f"File {filename} is already completely downloaded ({existing_bytes} bytes)."
+ )
+ file_already_complete = True
+ total_size_in_bytes = existing_bytes
+ elif remote_total > 0 and existing_bytes > remote_total:
+ print(
+ f"Existing file {filename} ({existing_bytes} bytes) is larger than remote size ({remote_total} bytes). Restarting download."
+ )
+ existing_bytes = 0
+ except (ValueError, TypeError):
+ pass
+
+ if not file_already_complete:
+ if existing_bytes > 0:
+ headers["Range"] = f"bytes={existing_bytes}-"
+ etag = response.headers.get("ETag")
+ last_mod = response.headers.get("Last-Modified")
+ if etag:
+ headers["If-Range"] = etag
+ elif last_mod:
+ headers["If-Range"] = last_mod
+
+ # --- 2. Try direct GET to redirected URL ---
+ headers["Accept-Encoding"] = (
+ "identity" # disable gzip to get correct content-length
+ )
+ response = requests.get(
+ url, headers=headers, stream=True, allow_redirects=True, timeout=30
+ )
+ www = response.headers.get(
+ "WWW-Authenticate", ""
+ ) # Check if authentication is required
+
+ # --- 3. Handle authentication responses ---
+ # 3a. Server requests Bearer auth. Only attempt token exchange for hosts
+ # we explicitly consider Vault-protected (VAULT_REQUIRED_HOSTS). This avoids
+ # sending tokens to unrelated hosts and makes auth behavior predictable.
+ if response.status_code == 401 and "bearer" in www.lower():
+ # If host is not configured for Vault, do not attempt token exchange.
+ if host not in VAULT_REQUIRED_HOSTS:
+ raise DownloadAuthError(
+ "Server requests Bearer authentication but this host is not configured for Vault token exchange."
+ " Try providing a databus API key with --databus-key or contact your administrator."
+ )
- # Host requires Vault; ensure token file provided.
- if not vault_token_file:
- raise DownloadAuthError(
- f"Vault token required for host '{host}', but no token was provided. Please use --vault-token."
+ # Host requires Vault; ensure token file provided.
+ if not vault_token_file:
+ raise DownloadAuthError(
+ f"Vault token required for host '{host}', but no token was provided. Please use --vault-token."
+ )
+
+ # --- 3b. Fetch Vault token and retry ---
+ # Token exchange is potentially sensitive and should only be performed
+ # for known hosts. __get_vault_access__ handles reading the refresh
+ # token and exchanging it; errors are translated to DownloadAuthError
+ # for user-friendly CLI output.
+ vault_token = __get_vault_access__(
+ url, vault_token_file, auth_url, client_id
)
+ headers["Authorization"] = f"Bearer {vault_token}"
- # --- 3b. Fetch Vault token and retry ---
- # Token exchange is potentially sensitive and should only be performed
- # for known hosts. __get_vault_access__ handles reading the refresh
- # token and exchanging it; errors are translated to DownloadAuthError
- # for user-friendly CLI output.
- vault_token = __get_vault_access__(url, vault_token_file, auth_url, client_id)
- headers["Authorization"] = f"Bearer {vault_token}"
+ # Retry with token
+ response = requests.get(url, headers=headers, stream=True, timeout=30)
- # Retry with token
- response = requests.get(url, headers=headers, stream=True, timeout=30)
+ # Map common auth failures to friendly messages
+ if response.status_code == 401:
+ raise DownloadAuthError(
+ "Vault token is invalid or expired. Please generate a new token."
+ )
+ if response.status_code == 403:
+ raise DownloadAuthError(
+ "Vault token is valid but has insufficient permissions to access this file."
+ )
- # Map common auth failures to friendly messages
- if response.status_code == 401:
- raise DownloadAuthError(
- "Vault token is invalid or expired. Please generate a new token."
- )
+ # 3c. Generic forbidden without Bearer challenge
if response.status_code == 403:
raise DownloadAuthError(
- "Vault token is valid but has insufficient permissions to access this file."
+ "Access forbidden: your token or API key does not have permission to download this file."
)
- # 3c. Generic forbidden without Bearer challenge
- if response.status_code == 403:
- raise DownloadAuthError(
- "Access forbidden: your token or API key does not have permission to download this file."
- )
-
- # 3d. Generic unauthorized without Bearer
- if response.status_code == 401:
- raise DownloadAuthError(
- "Unauthorized: access denied. Check your --databus-key or --vault-token settings."
- )
+ # 3d. Generic unauthorized without Bearer
+ if response.status_code == 401:
+ raise DownloadAuthError(
+ "Unauthorized: access denied. Check your --databus-key or --vault-token settings."
+ )
- try:
- response.raise_for_status() # Raise if still failing
- except requests.exceptions.HTTPError as e:
- if response.status_code == 404:
- print(f"WARNING: Skipping file {url} because it was not found (404).")
- if manifest_context is not None:
- manifest_context.record_file(
- url=url,
- status="failed",
- error_message="404 Not Found",
+ try:
+ if response.status_code == 416 and existing_bytes > 0:
+ # Content-Range format for 416: bytes */
+ content_range = response.headers.get("Content-Range", "")
+ cr_match = re.search(r"bytes\s+\*/(\d+)", content_range)
+ if cr_match:
+ if int(cr_match.group(1)) == existing_bytes:
+ print(
+ f"Server returned 416 Range Not Satisfiable for {url}. File {filename} is already completely downloaded."
+ )
+ total_size_in_bytes = existing_bytes
+ file_already_complete = True
+ else:
+ print(
+ f"Server returned 416 Range Not Satisfiable with mismatched size for {url}. Restarting download from scratch."
+ )
+ existing_bytes = 0
+ if os.path.exists(filename):
+ os.remove(filename)
+ headers.pop("Range", None)
+ headers.pop("If-Range", None)
+ response = requests.get(
+ url, headers=headers, stream=True, allow_redirects=True, timeout=30
+ )
+ response.raise_for_status()
+ else:
+ # No Content-Range header provided with 416; accept existing file
+ print(
+ f"Server returned 416 Range Not Satisfiable for {url}. File {filename} may already be completely downloaded."
+ )
+ total_size_in_bytes = existing_bytes
+ file_already_complete = True
+ else:
+ response.raise_for_status() # Raise if still failing
+ except requests.exceptions.HTTPError as e:
+ if response.status_code == 404:
+ print(f"WARNING: Skipping file {url} because it was not found (404).")
+ if manifest_context is not None:
+ manifest_context.record_file(
+ url=url,
+ status="failed",
+ error_message="404 Not Found",
+ )
+ return
+ else:
+ raise e
+
+ if not file_already_complete:
+ # --- 4. Download with progress bar ---
+ is_partial = response.status_code == 206
+ content_len = int(response.headers.get("content-length", 0))
+
+ if is_partial and existing_bytes > 0:
+ content_range = response.headers.get("Content-Range", "")
+ cr_match = re.search(r"bytes\s+(\d+)-(\d+)/((\d+)|\*)", content_range)
+ if cr_match:
+ range_start = int(cr_match.group(1))
+ if range_start == existing_bytes:
+ total_str = cr_match.group(4)
+ if total_str and total_str.isdigit():
+ total_size_in_bytes = int(total_str)
+ elif content_len > 0:
+ total_size_in_bytes = existing_bytes + content_len
+ elif total_size_in_bytes > 0:
+ # Keep expected total size from earlier HEAD request
+ pass
+ else:
+ total_size_in_bytes = 0
+ file_mode = "ab"
+ initial_bytes = existing_bytes
+ else:
+ # Server sent partial content starting at wrong offset; discard and restart with full GET
+ print(
+ f"Content-Range start {range_start} does not match local size {existing_bytes}. Restarting download."
+ )
+ headers.pop("Range", None)
+ headers.pop("If-Range", None)
+ response = requests.get(
+ url, headers=headers, stream=True, allow_redirects=True, timeout=30
+ )
+ try:
+ response.raise_for_status()
+ except requests.exceptions.HTTPError as e:
+ if response.status_code == 404:
+ print(f"WARNING: Skipping file {url} because it was not found (404).")
+ if manifest_context is not None:
+ manifest_context.record_file(
+ url=url,
+ status="failed",
+ error_message="404 Not Found",
+ )
+ return
+ raise e
+ content_len = int(response.headers.get("content-length", 0))
+ file_mode = "wb"
+ total_size_in_bytes = content_len
+ initial_bytes = 0
+ else:
+ total_size_in_bytes = (
+ (existing_bytes + content_len) if content_len > 0 else 0
)
- return
+ file_mode = "ab"
+ initial_bytes = existing_bytes
else:
- raise e
+ file_mode = "wb"
+ total_size_in_bytes = content_len
+ initial_bytes = 0
- # --- 4. Download with progress bar ---
- total_size_in_bytes = int(response.headers.get("content-length", 0))
- block_size = 1024 # 1 KiB
+ 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()
+ progress_bar = tqdm(
+ total=total_size_in_bytes,
+ initial=initial_bytes,
+ unit="iB",
+ unit_scale=True,
+ )
+ with open(filename, file_mode) 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")
+ # --- 5. Verify download size ---
+ final_size = os.path.getsize(filename)
+ if total_size_in_bytes != 0 and final_size != total_size_in_bytes:
+ raise IOError("Downloaded size does not match Content-Length header")
# --- 6. Validate checksum on original downloaded file (BEFORE conversion) ---
actual_checksum = None
@@ -892,6 +1043,7 @@ def _download_files(
validate_checksum: bool = False,
checksums: dict | None = None,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download multiple files from the databus.
@@ -911,6 +1063,7 @@ def _download_files(
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
checksums: Dictionary mapping URLs to their expected checksums.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
for url in urls:
expected = None
@@ -932,6 +1085,7 @@ def _download_files(
expected_checksum=expected,
manifest_context=manifest_context,
user_agent=user_agent,
+ resume=resume,
)
@@ -1084,6 +1238,7 @@ def _download_collection(
manifest_context=None,
validate_checksum: bool = False,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download all files in a databus collection.
@@ -1103,6 +1258,7 @@ def _download_collection(
validate_checksum: Whether to validate checksums after downloading.
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
query = _get_sparql_query_of_collection(uri, databus_key=databus_key)
file_urls = _get_file_download_urls_from_sparql_query(
@@ -1130,6 +1286,7 @@ def _download_collection(
validate_checksum=validate_checksum,
checksums=checksums if checksums else None,
user_agent=user_agent,
+ resume=resume,
)
@@ -1148,6 +1305,7 @@ def _download_version(
manifest_context=None,
validate_checksum: bool = False,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download all files in a databus artifact version.
@@ -1166,6 +1324,7 @@ def _download_version(
validate_checksum: Whether to validate checksums after downloading.
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
json_str = fetch_databus_jsonld(uri, databus_key=databus_key)
file_urls = _get_file_download_urls_from_artifact_jsonld(json_str)
@@ -1192,6 +1351,7 @@ def _download_version(
validate_checksum=validate_checksum,
checksums=checksums,
user_agent=user_agent,
+ resume=resume,
)
@@ -1211,6 +1371,7 @@ def _download_artifact(
manifest_context=None,
validate_checksum: bool = False,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download files in a databus artifact.
@@ -1230,6 +1391,7 @@ def _download_artifact(
validate_checksum: Whether to validate checksums after downloading.
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
json_str = fetch_databus_jsonld(uri, databus_key=databus_key)
versions = _get_databus_versions_of_artifact(json_str, all_versions=all_versions)
@@ -1262,6 +1424,7 @@ def _download_artifact(
validate_checksum=validate_checksum,
checksums=checksums,
user_agent=user_agent,
+ resume=resume,
)
@@ -1342,6 +1505,7 @@ def _download_group(
manifest_context=None,
validate_checksum: bool = False,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download files in a databus group.
@@ -1361,6 +1525,7 @@ def _download_group(
validate_checksum: Whether to validate checksums after downloading.
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
json_str = fetch_databus_jsonld(uri, databus_key=databus_key)
artifacts = _get_databus_artifacts_of_group(json_str)
@@ -1382,6 +1547,7 @@ def _download_group(
manifest_context=manifest_context,
validate_checksum=validate_checksum,
user_agent=user_agent,
+ resume=resume,
)
@@ -1436,6 +1602,7 @@ def download(
validate_checksum: bool = False,
manifest_context=None,
user_agent: str | None = None,
+ resume: bool = False,
) -> None:
"""Download datasets from databus.
@@ -1458,6 +1625,8 @@ def download(
validate_checksum: Whether to validate checksums after downloading.
user_agent: HTTP User-Agent for file HEAD and GET requests. None uses
the versioned databus-python-client default.
+ manifest_context: ManifestContext instance to record download metadata.
+ resume: Whether to resume partially downloaded files via HTTP Range headers.
"""
_validate_graph_mode(graph_mode)
for databusURI in databusURIs:
@@ -1490,7 +1659,8 @@ def download(
graph_mode=graph_mode,
manifest_context=manifest_context,
validate_checksum=validate_checksum,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
elif file is not None:
print(f"Downloading file: {databusURI}")
@@ -1517,7 +1687,8 @@ def download(
manifest_context=manifest_context,
validate_checksum=validate_checksum,
expected_checksum=expected,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
elif version is not None:
print(f"Downloading version: {databusURI}")
@@ -1535,7 +1706,8 @@ def download(
graph_mode=graph_mode,
manifest_context=manifest_context,
validate_checksum=validate_checksum,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
elif artifact is not None:
print(
@@ -1556,7 +1728,8 @@ def download(
graph_mode=graph_mode,
manifest_context=manifest_context,
validate_checksum=validate_checksum,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
elif group is not None and group != "collections":
print(
@@ -1577,7 +1750,8 @@ def download(
graph_mode=graph_mode,
manifest_context=manifest_context,
validate_checksum=validate_checksum,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
elif account is not None:
print("accountId not supported yet") # TODO
@@ -1621,5 +1795,6 @@ def download(
manifest_context=manifest_context,
validate_checksum=validate_checksum,
checksums=checksums if checksums else None,
- user_agent=user_agent,
+ user_agent=user_agent,
+ resume=resume,
)
diff --git a/databusclient/cli.py b/databusclient/cli.py
index 996407ab..f0220549 100644
--- a/databusclient/cli.py
+++ b/databusclient/cli.py
@@ -328,6 +328,13 @@ def _write_manifest():
"--user-agent",
help="Override the HTTP User-Agent header for file download requests.",
)
+@click.option(
+ "--resume",
+ "-c",
+ is_flag=True,
+ default=False,
+ help="Resume partially downloaded files using HTTP Range requests.",
+)
def download(
databusuris: List[str],
localdir,
@@ -345,6 +352,7 @@ def download(
validate_checksum,
manifest_path,
user_agent,
+ resume,
):
"""
Download datasets from databus, optionally using vault access if vault options are provided.
@@ -377,6 +385,7 @@ def download(
"user_agent": user_agent,
"authurl": authurl,
"clientid": clientid,
+ "resume": resume,
})
try:
api_download(
@@ -396,6 +405,7 @@ def download(
validate_checksum=validate_checksum,
user_agent=user_agent,
manifest_context=manifest_context,
+ resume=resume,
)
except DownloadAuthError as e:
if manifest_context:
diff --git a/databusclient/manifest/replay.py b/databusclient/manifest/replay.py
index 4def7bc2..718956ea 100644
--- a/databusclient/manifest/replay.py
+++ b/databusclient/manifest/replay.py
@@ -82,6 +82,7 @@ def _build_download_kwargs(
"graph_mode": replay_params.get("graph_mode"),
"user_agent": replay_params.get("user_agent"),
"validate_checksum": bool(replay_params.get("validate_checksum", False)),
+ "resume": bool(replay_params.get("resume", False)),
"manifest_context": None,
}
diff --git a/databusclient/workflow/steps.py b/databusclient/workflow/steps.py
index 320e616c..d01b88e9 100644
--- a/databusclient/workflow/steps.py
+++ b/databusclient/workflow/steps.py
@@ -82,6 +82,7 @@ def run(self, step_config: Dict[str, Any], context: StepContext) -> None:
base_uri=resolved.get("base_uri"),
graph_mode=resolved.get("graph_mode"),
user_agent=resolved.get("user_agent"),
+ resume=resolved.get("resume", False),
validate_checksum=resolved.get("validate_checksum", False),
manifest_context=capture_context,
)
diff --git a/doc/cli-usage.md b/doc/cli-usage.md
index 26826481..725ae6d5 100644
--- a/doc/cli-usage.md
+++ b/doc/cli-usage.md
@@ -42,6 +42,8 @@ databusclient download $DOWNLOADTARGET
- Validates the checksums of downloaded files against the checksums provided by the Databus. If a checksum does not match, an error is raised and the file is deleted.
- `--user-agent`
- Overrides the HTTP User-Agent header for file download requests. Default: `databus-python-client/ (https://github.com/dbpedia/databus-python-client)`. Example: `--user-agent "DatabusDownloadBot/1.0 (mailto:you@example.org)"`.
+- `-c, --resume`
+ - Resumes interrupted downloads if partial files already exist on disk using HTTP `Range` request headers. If the remote host supports byte ranges (returns `206 Partial Content`), only the missing bytes are downloaded and appended to the existing file. If the remote host does not support range requests (returns `200 OK`), the download safely restarts from scratch. If the local file is already fully downloaded, the download is skipped.
**Help and further information on download command:**
```bash
@@ -55,6 +57,11 @@ databusclient download --help
databusclient download https://databus.dbpedia.org/dbpedia/mappings/mappingbased-literals/2022.12.01/mappingbased-literals_lang=az.ttl.bz2
```
+**Resume Interrupted Download**: continue an interrupted file download without re-downloading existing bytes
+```bash
+databusclient download https://databus.dbpedia.org/dbpedia/mappings/mappingbased-literals/2022.12.01/mappingbased-literals_lang=az.ttl.bz2 --resume
+```
+
**Download Version**: download of all files of a specific version
```bash
databusclient download https://databus.dbpedia.org/dbpedia/mappings/mappingbased-literals/2022.12.01
diff --git a/pyproject.toml b/pyproject.toml
index d44c5483..613fae94 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "databusclient"
-version = "1.3.2"
+version = "1.4.0"
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.py b/tests/test_download.py
index b1746d38..c67a72c9 100644
--- a/tests/test_download.py
+++ b/tests/test_download.py
@@ -254,3 +254,477 @@ def test_converted_output_gets_graph_sidecar_at_final_path(monkeypatch, tmp_path
assert not (tmp_path / "data.ttl.bz2").exists()
assert not (tmp_path / "data.ttl.bz2.graph").exists()
assert (tmp_path / "data.ttl.graph").read_text(encoding="utf-8") == url
+
+
+def test_resume_partial_download_appends_bytes(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"hello ")
+
+ recorded_headers = {}
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "12"}
+
+ class MockPartialGetResp:
+ status_code = 206
+
+ def __init__(self):
+ self.content = b"world!"
+ self.headers = {"content-length": str(len(self.content))}
+
+ def iter_content(self, block_size):
+ yield self.content
+
+ def raise_for_status(self):
+ pass
+
+ def mock_head(req_url, *args, **kwargs):
+ return MockHeadResp()
+
+ def mock_get(req_url, *args, **kwargs):
+ if "headers" in kwargs:
+ recorded_headers.update(kwargs["headers"])
+ return MockPartialGetResp()
+
+ monkeypatch.setattr("requests.head", mock_head)
+ monkeypatch.setattr("requests.get", mock_get)
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert recorded_headers.get("Range") == "bytes=6-"
+ assert target_file.read_bytes() == b"hello world!"
+
+
+def test_resume_server_falls_back_to_200(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"old_partial_data")
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "18"}
+
+ class MockFullGetResp:
+ status_code = 200
+
+ def __init__(self):
+ self.content = b"fresh_full_content"
+ self.headers = {"content-length": str(len(self.content))}
+
+ def iter_content(self, block_size):
+ yield self.content
+
+ def raise_for_status(self):
+ pass
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", lambda *a, **k: MockFullGetResp())
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert target_file.read_bytes() == b"fresh_full_content"
+
+
+def test_resume_already_complete_file_416(monkeypatch, tmp_path):
+ import requests
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ content = b"already completed content"
+ target_file.write_bytes(content)
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {} # HEAD does not include content-length, forcing GET
+
+ class Mock416GetResp:
+ status_code = 416
+ headers = {}
+
+ def raise_for_status(self):
+ raise requests.exceptions.HTTPError("416 Range Not Satisfiable", response=self)
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", lambda *a, **k: Mock416GetResp())
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert target_file.read_bytes() == content
+
+
+def test_resume_already_complete_file_via_head(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ content = b"already completed content"
+ target_file.write_bytes(content)
+
+ get_called = False
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": str(len(content))}
+
+ def mock_get(*args, **kwargs):
+ nonlocal get_called
+ get_called = True
+ raise AssertionError("GET should not be called when HEAD confirms file is complete")
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", mock_get)
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert not get_called
+ assert target_file.read_bytes() == content
+
+
+def test_cli_resume_flag(monkeypatch, tmp_path):
+ import json
+
+ captured = {}
+
+ def fake_download(**kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr("databusclient.cli.api_download", fake_download)
+ manifest_path = tmp_path / "download.jsonld"
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "download",
+ "https://example.org/data.ttl",
+ "--resume",
+ "--manifest",
+ str(manifest_path),
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured["resume"] is True
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ assert manifest["dbus:replayParams"]["resume"] is True
+
+ # Also test short alias -c
+ result_short = CliRunner().invoke(
+ app,
+ [
+ "download",
+ "https://example.org/data.ttl",
+ "-c",
+ ],
+ )
+ assert result_short.exit_code == 0
+ assert captured["resume"] is True
+
+
+def test_resume_content_range_mismatch_restarts(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"corrupt")
+
+ calls = []
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "10"}
+
+ class MockMismatch206GetResp:
+ status_code = 206
+
+ def __init__(self):
+ self.content = b"partial_content_wrong_offset"
+ self.headers = {
+ "content-length": "10",
+ "Content-Range": "bytes 0-9/10",
+ }
+
+ def iter_content(self, block_size):
+ yield self.content
+
+ def raise_for_status(self):
+ pass
+
+ class MockFull200GetResp:
+ status_code = 200
+
+ def __init__(self):
+ self.content = b"0123456789"
+ self.headers = {"content-length": "10"}
+
+ def iter_content(self, block_size):
+ yield self.content
+
+ def raise_for_status(self):
+ pass
+
+ def mock_get(req_url, *args, **kwargs):
+ headers = kwargs.get("headers", {})
+ if "Range" in headers:
+ calls.append("range")
+ return MockMismatch206GetResp()
+ calls.append("full")
+ return MockFull200GetResp()
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", mock_get)
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert calls == ["range", "full"]
+ # File should have been restarted and overwritten with the full payload
+ assert target_file.read_bytes() == b"0123456789"
+
+
+def test_resume_416_mismatch_restarts(monkeypatch, tmp_path):
+ import requests
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"wrong_length_content_12345")
+
+ calls = []
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {}
+
+ class Mock416GetResp:
+ status_code = 416
+ headers = {"Content-Range": "bytes */10"}
+
+ def raise_for_status(self):
+ raise requests.exceptions.HTTPError("416", response=self)
+
+ class MockFullGetResp:
+ status_code = 200
+ headers = {"content-length": "10"}
+
+ def iter_content(self, block_size):
+ yield b"0123456789"
+
+ def raise_for_status(self):
+ pass
+
+ def mock_get(req_url, *args, **kwargs):
+ if not calls:
+ calls.append("416")
+ return Mock416GetResp()
+ calls.append("200")
+ return MockFullGetResp()
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", mock_get)
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert calls == ["416", "200"]
+ assert target_file.read_bytes() == b"0123456789"
+
+
+def test_resume_if_range_header_sent(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"hello ")
+
+ recorded_headers = {}
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "12", "ETag": '"etag-val-123"'}
+
+ class MockPartialGetResp:
+ status_code = 206
+ headers = {"content-length": "6", "Content-Range": "bytes 6-11/12"}
+
+ def iter_content(self, block_size):
+ yield b"world!"
+
+ def raise_for_status(self):
+ pass
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+
+ def mock_get(req_url, *args, **kwargs):
+ if "headers" in kwargs:
+ recorded_headers.update(kwargs["headers"])
+ return MockPartialGetResp()
+
+ monkeypatch.setattr("requests.get", mock_get)
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert recorded_headers.get("Range") == "bytes=6-"
+ assert recorded_headers.get("If-Range") == '"etag-val-123"'
+ assert target_file.read_bytes() == b"hello world!"
+
+
+def test_manifest_replay_forwards_resume():
+ from databusclient.manifest.replay import _build_download_kwargs
+
+ manifest = {"@id": "https://example.org/manifest"}
+ replay_params = {
+ "databusURIs": ["https://databus.dbpedia.org/user/group/artifact/version"],
+ "resume": True,
+ }
+ kwargs = _build_download_kwargs(manifest, replay_params, overrides={})
+ assert kwargs.get("resume") is True
+
+
+def test_resume_chunked_206_unknown_total(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"hello ")
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {} # No content-length
+
+ class MockChunked206GetResp:
+ status_code = 206
+
+ def __init__(self):
+ self.content = b"world!"
+ self.headers = {
+ "Content-Range": "bytes 6-11/*",
+ }
+
+ def iter_content(self, block_size):
+ yield self.content
+
+ def raise_for_status(self):
+ pass
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", lambda *a, **k: MockChunked206GetResp())
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert target_file.read_bytes() == b"hello world!"
+
+
+def test_head_request_includes_accept_encoding_identity(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ head_headers = {}
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "5"}
+
+ class MockGetResp:
+ status_code = 200
+ headers = {"content-length": "5"}
+
+ def iter_content(self, block_size):
+ yield b"12345"
+
+ def raise_for_status(self):
+ pass
+
+ def mock_head(req_url, *args, **kwargs):
+ head_headers.update(kwargs.get("headers", {}))
+ return MockHeadResp()
+
+ monkeypatch.setattr("requests.head", mock_head)
+ monkeypatch.setattr("requests.get", lambda *a, **k: MockGetResp())
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ assert head_headers.get("Accept-Encoding") == "identity"
+
+
+def test_resume_mismatched_range_start_replacement_404_handled(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+ from databusclient.manifest.context import ManifestContext
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"hello ")
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "12"}
+
+ class Mock206WrongStartResp:
+ status_code = 206
+ headers = {
+ "Content-Range": "bytes 0-5/12",
+ "content-length": "6",
+ }
+
+ def raise_for_status(self):
+ pass
+
+ class Mock404Resp:
+ status_code = 404
+ headers = {}
+
+ def raise_for_status(self):
+ import requests
+ raise requests.exceptions.HTTPError(response=self)
+
+ get_calls = []
+
+ def mock_get(req_url, *args, **kwargs):
+ get_calls.append(kwargs.get("headers", {}))
+ if len(get_calls) == 1:
+ return Mock206WrongStartResp()
+ return Mock404Resp()
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", mock_get)
+
+ ctx = ManifestContext(command="download")
+ # Should not raise an unhandled exception when replacement GET returns 404
+ dl._download_file(url, localDir=str(tmp_path), resume=True, manifest_context=ctx)
+ assert len(ctx.files) == 1
+ assert ctx.files[0]["status"] == "failed"
+
+
+def test_resume_server_ignores_range_returns_200(monkeypatch, tmp_path):
+ import databusclient.api.download as dl
+
+ url = "https://example.org/file.bin"
+ target_file = tmp_path / "file.bin"
+ target_file.write_bytes(b"old partial data")
+
+ class MockHeadResp:
+ status_code = 200
+ headers = {"content-length": "10"}
+
+ class Mock200GetResp:
+ status_code = 200
+ headers = {"content-length": "10"}
+
+ def iter_content(self, block_size):
+ yield b"0123456789"
+
+ def raise_for_status(self):
+ pass
+
+ monkeypatch.setattr("requests.head", lambda *a, **k: MockHeadResp())
+ monkeypatch.setattr("requests.get", lambda *a, **k: Mock200GetResp())
+
+ dl._download_file(url, localDir=str(tmp_path), resume=True)
+
+ # File must be overwritten cleanly with full 10 bytes, not appended
+ assert target_file.read_bytes() == b"0123456789"
+