diff --git a/databusclient/api/download.py b/databusclient/api/download.py index f2aead78..0bfa56ac 100644 --- a/databusclient/api/download.py +++ b/databusclient/api/download.py @@ -6,13 +6,17 @@ from typing import List, Optional, Tuple import re import shutil +from datetime import datetime, timezone +import email.utils +import contextlib +import math import tempfile +import time from urllib.parse import urljoin, urlparse import requests from SPARQLWrapper import JSON, SPARQLWrapper from tqdm import tqdm -from datetime import datetime, timezone from databusclient.version import __version__ @@ -43,6 +47,11 @@ "xz": lzma, } +DEFAULT_MAX_RETRIES = 3 +DEFAULT_RETRY_BACKOFF_BASE = 1.0 +MAX_RETRY_DELAY = 60.0 +RETRYABLE_STATUS_CODES = frozenset({408, 429, 500, 502, 503, 504}) + DEFAULT_USER_AGENT = ( f"databus-python-client/{__version__} " "(https://github.com/dbpedia/databus-python-client)" @@ -427,6 +436,87 @@ def _resolve_checksums_for_urls(file_urls: List[str], databus_key: str | None) - return checksums +class _TruncatedDownloadError(IOError): + """Raised when the number of downloaded bytes does not match Content-Length.""" + + +def _validate_max_retries(max_retries: int) -> int: + if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0: + raise ValueError( + f"max_retries must be a non-negative integer, got {max_retries!r}" + ) + return max_retries + + +def _is_transient_download_error(exc: Exception) -> bool: + if isinstance(exc, requests.exceptions.SSLError): + return False + if isinstance( + exc, + ( + requests.exceptions.Timeout, + requests.exceptions.ConnectionError, + requests.exceptions.ChunkedEncodingError, + _TruncatedDownloadError, + ), + ): + return True + if isinstance(exc, requests.exceptions.HTTPError): + response = getattr(exc, "response", None) + if response is not None and response.status_code in RETRYABLE_STATUS_CODES: + return True + return False + + +def _parse_retry_after(value: str) -> float | None: + raw = value.strip() + if not raw: + return None + try: + seconds = float(raw) + return seconds if math.isfinite(seconds) and seconds >= 0 else None + except ValueError: + pass + try: + dt = email.utils.parsedate_to_datetime(raw) + except (TypeError, ValueError, IndexError): + return None + if dt is None: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return max(0.0, (dt - datetime.now(dt.tzinfo)).total_seconds()) + + +def _compute_retry_delay( + retry_num: int, + exc: Exception, + backoff_base: float = DEFAULT_RETRY_BACKOFF_BASE, + max_delay: float = MAX_RETRY_DELAY, +) -> float: + delay = min(backoff_base * (2 ** (retry_num - 1)), max_delay) + if isinstance(exc, requests.exceptions.HTTPError): + response = getattr(exc, "response", None) + if response is not None: + retry_after = response.headers.get("Retry-After") + if retry_after is not None: + parsed = _parse_retry_after(retry_after) + if parsed is not None: + return min(parsed, max_delay) + return delay + + +def _format_retry_reason(exc: Exception) -> str: + if isinstance(exc, requests.exceptions.HTTPError): + response = getattr(exc, "response", None) + if response is not None: + return f"HTTP {response.status_code}" + detail = str(exc).strip() + if detail: + return f"{type(exc).__name__}: {detail}" + return type(exc).__name__ + + def _download_file( url, localDir, @@ -443,6 +533,70 @@ def _download_file( expected_checksum: str | None = None, manifest_context=None, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, +) -> None: + """Download a file with automatic retries and exponential backoff on transient failures.""" + max_retries = _validate_max_retries(max_retries) + + for attempt in range(max_retries + 1): + try: + _download_file_once( + url=url, + localDir=localDir, + vault_token_file=vault_token_file, + databus_key=databus_key, + auth_url=auth_url, + client_id=client_id, + compression=compression, + convert_format=convert_format, + graph_name=graph_name, + base_uri=base_uri, + graph_mode=graph_mode, + validate_checksum=validate_checksum, + expected_checksum=expected_checksum, + manifest_context=manifest_context, + user_agent=user_agent, + ) + if attempt > 0: + print( + f"Download succeeded for {url} on retry {attempt}/{max_retries}." + ) + return + except Exception as exc: + if not _is_transient_download_error(exc): + raise + reason = _format_retry_reason(exc) + if attempt >= max_retries: + if max_retries > 0: + print( + f"Download failed for {url} after {max_retries} retries ({reason})." + ) + raise + retry_num = attempt + 1 + delay = _compute_retry_delay(retry_num, exc) + print( + f"WARNING: Transient download error for {url} ({reason}). " + f"Retrying in {delay:g}s (attempt {retry_num}/{max_retries})..." + ) + time.sleep(delay) + + +def _download_file_once( + url, + localDir, + vault_token_file=None, + databus_key=None, + auth_url=None, + client_id=None, + compression=None, + convert_format=None, + graph_name=None, + base_uri=None, + graph_mode=None, + validate_checksum: bool = False, + expected_checksum: str | None = None, + manifest_context=None, + user_agent: str | None = None, ) -> None: """Download a file from the internet with a progress bar using tqdm. @@ -528,90 +682,112 @@ def _download_file( 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." - ) + try: + 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." + ) - # --- 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}" + # 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." + ) - # Retry with token - response = requests.get(url, headers=headers, stream=True, timeout=30) + # --- 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 + close_fn = getattr(response, "close", None) + if callable(close_fn): + close_fn() + 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", + ) + return + else: + raise e - 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", - ) - return - else: - raise e + # --- 4. Download with progress bar --- + total_size_in_bytes = int(response.headers.get("content-length", 0)) + block_size = 1024 # 1 KiB - # --- 4. Download with progress bar --- - 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) + try: + with open(filename, "wb") as f: + for data in response.iter_content(block_size): + progress_bar.update(len(data)) + f.write(data) + except BaseException: + with contextlib.suppress(OSError): + if os.path.exists(filename): + os.remove(filename) + raise + finally: + progress_bar.close() - 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() + finally: + # Guard for lightweight test doubles that omit close() + close_fn = getattr(response, "close", None) + if callable(close_fn): + close_fn() # --- 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") + with contextlib.suppress(OSError): + if os.path.exists(filename): + os.remove(filename) + raise _TruncatedDownloadError( + "Downloaded size does not match Content-Length header" + ) # --- 6. Validate checksum on original downloaded file (BEFORE conversion) --- actual_checksum = None @@ -892,6 +1068,7 @@ def _download_files( validate_checksum: bool = False, checksums: dict | None = None, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download multiple files from the databus. @@ -932,6 +1109,7 @@ def _download_files( expected_checksum=expected, manifest_context=manifest_context, user_agent=user_agent, + max_retries=max_retries, ) @@ -1084,6 +1262,7 @@ def _download_collection( manifest_context=None, validate_checksum: bool = False, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download all files in a databus collection. @@ -1130,6 +1309,7 @@ def _download_collection( validate_checksum=validate_checksum, checksums=checksums if checksums else None, user_agent=user_agent, + max_retries=max_retries, ) @@ -1148,6 +1328,7 @@ def _download_version( manifest_context=None, validate_checksum: bool = False, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download all files in a databus artifact version. @@ -1192,6 +1373,7 @@ def _download_version( validate_checksum=validate_checksum, checksums=checksums, user_agent=user_agent, + max_retries=max_retries, ) @@ -1211,6 +1393,7 @@ def _download_artifact( manifest_context=None, validate_checksum: bool = False, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download files in a databus artifact. @@ -1262,6 +1445,7 @@ def _download_artifact( validate_checksum=validate_checksum, checksums=checksums, user_agent=user_agent, + max_retries=max_retries, ) @@ -1342,6 +1526,7 @@ def _download_group( manifest_context=None, validate_checksum: bool = False, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download files in a databus group. @@ -1382,6 +1567,7 @@ def _download_group( manifest_context=manifest_context, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, ) @@ -1436,6 +1622,7 @@ def download( validate_checksum: bool = False, manifest_context=None, user_agent: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, ) -> None: """Download datasets from databus. @@ -1458,8 +1645,10 @@ 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. + max_retries: Maximum retry attempts for transient download failures (0 to disable). """ _validate_graph_mode(graph_mode) + max_retries = _validate_max_retries(max_retries) for databusURI in databusURIs: host, account, group, artifact, version, file = get_databus_id_parts_from_file_url(databusURI) @@ -1491,6 +1680,7 @@ def download( manifest_context=manifest_context, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, ) elif file is not None: print(f"Downloading file: {databusURI}") @@ -1518,6 +1708,7 @@ def download( validate_checksum=validate_checksum, expected_checksum=expected, user_agent=user_agent, + max_retries=max_retries, ) elif version is not None: print(f"Downloading version: {databusURI}") @@ -1536,6 +1727,7 @@ def download( manifest_context=manifest_context, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, ) elif artifact is not None: print( @@ -1557,6 +1749,7 @@ def download( manifest_context=manifest_context, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, ) elif group is not None and group != "collections": print( @@ -1578,6 +1771,7 @@ def download( manifest_context=manifest_context, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, ) elif account is not None: print("accountId not supported yet") # TODO @@ -1622,4 +1816,5 @@ def download( validate_checksum=validate_checksum, checksums=checksums if checksums else None, user_agent=user_agent, + max_retries=max_retries, ) diff --git a/databusclient/cli.py b/databusclient/cli.py index 996407ab..cd5c4134 100644 --- a/databusclient/cli.py +++ b/databusclient/cli.py @@ -9,7 +9,12 @@ from databusclient import __version__ import databusclient.api.deploy as api_deploy from databusclient.api.delete import delete as api_delete -from databusclient.api.download import DownloadAuthError, download as api_download, format_download_connection_error +from databusclient.api.download import ( + DEFAULT_MAX_RETRIES, + DownloadAuthError, + download as api_download, + format_download_connection_error, +) from databusclient.manifest.context import ManifestContext from databusclient.manifest.writer import ManifestWriter from databusclient.manifest.replay import ManifestReplayError, replay_manifest, load_manifest @@ -328,6 +333,14 @@ def _write_manifest(): "--user-agent", help="Override the HTTP User-Agent header for file download requests.", ) +@click.option( + "--max-retries", + "max_retries", + type=click.IntRange(min=0), + default=DEFAULT_MAX_RETRIES, + show_default=True, + help="Maximum number of retry attempts for transient download failures (0 to disable).", +) def download( databusuris: List[str], localdir, @@ -345,6 +358,7 @@ def download( validate_checksum, manifest_path, user_agent, + max_retries, ): """ Download datasets from databus, optionally using vault access if vault options are provided. @@ -375,6 +389,7 @@ def download( "all_versions": all_versions, "validate_checksum": validate_checksum, "user_agent": user_agent, + "max_retries": max_retries, "authurl": authurl, "clientid": clientid, }) @@ -395,6 +410,7 @@ def download( graph_mode=graph_mode, validate_checksum=validate_checksum, user_agent=user_agent, + max_retries=max_retries, manifest_context=manifest_context, ) except DownloadAuthError as e: diff --git a/databusclient/manifest/replay.py b/databusclient/manifest/replay.py index 4def7bc2..9e6d9fb5 100644 --- a/databusclient/manifest/replay.py +++ b/databusclient/manifest/replay.py @@ -1,7 +1,10 @@ from __future__ import annotations import json from typing import Any, Dict, Optional -from databusclient.api.download import download as api_download +from databusclient.api.download import ( + DEFAULT_MAX_RETRIES, + download as api_download, +) from databusclient.api.delete import delete as api_delete from databusclient.api.deploy import ( create_dataset as api_create_dataset, @@ -81,6 +84,11 @@ def _build_download_kwargs( "base_uri": replay_params.get("base_uri"), "graph_mode": replay_params.get("graph_mode"), "user_agent": replay_params.get("user_agent"), + "max_retries": ( + DEFAULT_MAX_RETRIES + if replay_params.get("max_retries") is None + else replay_params.get("max_retries") + ), "validate_checksum": bool(replay_params.get("validate_checksum", False)), "manifest_context": None, } diff --git a/databusclient/workflow/steps.py b/databusclient/workflow/steps.py index 320e616c..0717940d 100644 --- a/databusclient/workflow/steps.py +++ b/databusclient/workflow/steps.py @@ -69,22 +69,26 @@ def run(self, step_config: Dict[str, Any], context: StepContext) -> None: capture_context = context.manifest_context or ManifestContext(command="download") files_before = len(capture_context.files) - api_download( - localDir=local_dir, - endpoint=resolved.get("databus"), - databusURIs=uris, - token=resolved.get("vault_token"), - databus_key=resolved.get("databus_key"), - all_versions=resolved.get("all_versions", False), - compression=resolved.get("convert_to") or resolved.get("compression"), - convert_format=resolved.get("format"), - graph_name=resolved.get("graph_name"), - base_uri=resolved.get("base_uri"), - graph_mode=resolved.get("graph_mode"), - user_agent=resolved.get("user_agent"), - validate_checksum=resolved.get("validate_checksum", False), - manifest_context=capture_context, - ) + download_kwargs: Dict[str, Any] = { + "localDir": local_dir, + "endpoint": resolved.get("databus"), + "databusURIs": uris, + "token": resolved.get("vault_token"), + "databus_key": resolved.get("databus_key"), + "all_versions": resolved.get("all_versions", False), + "compression": resolved.get("convert_to") or resolved.get("compression"), + "convert_format": resolved.get("format"), + "graph_name": resolved.get("graph_name"), + "base_uri": resolved.get("base_uri"), + "graph_mode": resolved.get("graph_mode"), + "user_agent": resolved.get("user_agent"), + "validate_checksum": resolved.get("validate_checksum", False), + "manifest_context": capture_context, + } + if "max_retries" in resolved and resolved["max_retries"] is not None: + download_kwargs["max_retries"] = resolved["max_retries"] + + api_download(**download_kwargs) new_entries = capture_context.files[files_before:] resolved_urls = [e["url"] for e in new_entries if e.get("status") == "success"] diff --git a/doc/cli-usage.md b/doc/cli-usage.md index 26826481..0ac54e66 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)"`. +- `--max-retries` + - Maximum number of retry attempts for transient download failures (connection timeouts, network errors, and temporary HTTP 408/429/5xx errors) using exponential backoff. Default: `3`. Use `0` to disable retries. **Help and further information on download command:** ```bash diff --git a/tests/test_download_retries.py b/tests/test_download_retries.py new file mode 100644 index 00000000..1a194408 --- /dev/null +++ b/tests/test_download_retries.py @@ -0,0 +1,699 @@ +from datetime import datetime, timedelta, timezone +import email.utils +import hashlib +import json +from types import SimpleNamespace + +import pytest +import requests +from click.testing import CliRunner + +import databusclient.api.download as dl +from databusclient.api.download import DownloadAuthError +from databusclient.cli import app +from databusclient.manifest.context import ManifestContext +from databusclient.manifest.replay import replay_manifest + + +class FakeResponse: + def __init__(self, status_code=200, content=b"hello world", headers=None, chunks=None): + self.status_code = status_code + self._content = content + self._chunks = chunks + self.closed = False + self.headers = dict(headers or {}) + if "content-length" not in {k.lower() for k in self.headers} and status_code == 200: + self.headers["content-length"] = str(len(content)) + + def raise_for_status(self): + if self.status_code >= 400: + raise requests.exceptions.HTTPError( + f"{self.status_code} Error", response=self + ) + + def iter_content(self, chunk_size=1024): + if self._chunks is not None: + for chunk in self._chunks: + if isinstance(chunk, BaseException): + raise chunk + yield chunk + else: + yield self._content + + def close(self): + self.closed = True + + +def _stub_sleep(monkeypatch): + sleeps = [] + monkeypatch.setattr(dl, "time", SimpleNamespace(sleep=lambda s: sleeps.append(s))) + return sleeps + + +def test_retry_succeeds_after_connect_timeout_with_exponential_backoff( + monkeypatch, tmp_path, capsys +): + sleeps = _stub_sleep(monkeypatch) + attempts = {"head": 0} + + def fake_head(*args, **kwargs): + attempts["head"] += 1 + if attempts["head"] <= 3: + raise requests.exceptions.ConnectTimeout("timed out") + return FakeResponse(status_code=200) + + monkeypatch.setattr("requests.head", fake_head) + monkeypatch.setattr("requests.get", lambda *a, **k: FakeResponse(content=b"ok")) + + dl._download_file( + "https://zenodo.org/records/1/files/data.ttl", + localDir=str(tmp_path), + max_retries=3, + ) + + assert (tmp_path / "data.ttl").read_bytes() == b"ok" + assert attempts["head"] == 4 + assert sleeps == [1.0, 2.0, 4.0] + out = capsys.readouterr().out + assert "attempt 1/3" in out + assert "attempt 2/3" in out + assert "attempt 3/3" in out + assert "Download succeeded" in out + assert "on retry 3/3" in out + + +def test_retry_succeeds_after_connection_error(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + raise requests.exceptions.ConnectionError("reset by peer") + return FakeResponse(content=b"recovered") + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert (tmp_path / "file.ttl").read_bytes() == b"recovered" + assert calls["get"] == 2 + assert sleeps == [1.0] + + +@pytest.mark.parametrize("status_code", [408, 429, 500, 502, 503, 504]) +def test_retry_succeeds_on_transient_http_status(monkeypatch, tmp_path, capsys, status_code): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + return FakeResponse(status_code=status_code) + return FakeResponse(content=b"done") + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert (tmp_path / "file.ttl").read_bytes() == b"done" + assert calls["get"] == 2 + assert sleeps == [1.0] + assert f"HTTP {status_code}" in capsys.readouterr().out + + +def test_retry_respects_numeric_and_capped_retry_after_header(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + return FakeResponse(status_code=429, headers={"Retry-After": "5"}) + if calls["get"] == 2: + return FakeResponse(status_code=429, headers={"Retry-After": "86400"}) + return FakeResponse(content=b"ok") + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=3) + + assert sleeps == [5.0, dl.MAX_RETRY_DELAY] + + +@pytest.mark.parametrize("bad_value", ["inf", "-inf", "nan", "-5", "garbage", ""]) +def test_invalid_retry_after_falls_back_to_backoff(bad_value): + resp = FakeResponse(status_code=429, headers={"Retry-After": bad_value}) + exc = requests.exceptions.HTTPError("429", response=resp) + assert dl._compute_retry_delay(2, exc) == 2.0 + + +def test_http_date_retry_after_is_parsed_and_clamped(): + future = datetime.now(timezone.utc) + timedelta(seconds=12) + header = email.utils.format_datetime(future, usegmt=True) + resp = FakeResponse(status_code=503, headers={"Retry-After": header}) + exc = requests.exceptions.HTTPError("503", response=resp) + delay = dl._compute_retry_delay(1, exc) + assert 0.0 <= delay <= 15.0 + + far_future = datetime.now(timezone.utc) + timedelta(hours=2) + far_header = email.utils.format_datetime(far_future, usegmt=True) + far_resp = FakeResponse(status_code=503, headers={"Retry-After": far_header}) + far_exc = requests.exceptions.HTTPError("503", response=far_resp) + assert dl._compute_retry_delay(1, far_exc) == dl.MAX_RETRY_DELAY + + +def test_exponential_backoff_is_capped_at_max_retry_delay(): + exc = requests.exceptions.ConnectTimeout("timeout") + assert dl._compute_retry_delay(10, exc) == dl.MAX_RETRY_DELAY + + +def test_retry_on_truncated_stream_and_chunked_encoding_error_closes_response( + monkeypatch, tmp_path +): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + responses = [] + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + r = FakeResponse(status_code=200, content=b"short", headers={"content-length": "100"}) + elif calls["get"] == 2: + r = FakeResponse( + status_code=200, + headers={"content-length": "10"}, + chunks=[b"abc", requests.exceptions.ChunkedEncodingError("stream broke")], + ) + else: + r = FakeResponse(content=b"complete!!") + responses.append(r) + return r + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=3) + + assert (tmp_path / "file.ttl").read_bytes() == b"complete!!" + assert calls["get"] == 3 + assert sleeps == [1.0, 2.0] + assert all(r.closed for r in responses) + + +def test_partial_file_is_removed_after_truncation_exhaustion(monkeypatch, tmp_path): + _stub_sleep(monkeypatch) + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + monkeypatch.setattr( + "requests.get", + lambda *a, **k: FakeResponse( + status_code=200, content=b"partial", headers={"content-length": "100"} + ), + ) + + with pytest.raises(IOError, match="Content-Length"): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=1) + + assert not (tmp_path / "file.ttl").exists() + + +def test_partial_file_is_removed_after_mid_stream_error_exhaustion(monkeypatch, tmp_path): + _stub_sleep(monkeypatch) + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + monkeypatch.setattr( + "requests.get", + lambda *a, **k: FakeResponse( + status_code=200, + headers={"content-length": "10"}, + chunks=[b"abc", requests.exceptions.ChunkedEncodingError("dropped")], + ), + ) + + with pytest.raises(requests.exceptions.ChunkedEncodingError): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=1) + + assert not (tmp_path / "file.ttl").exists() + + +def test_retry_exhaustion_raises_and_logs_outcome(monkeypatch, tmp_path, capsys): + sleeps = _stub_sleep(monkeypatch) + calls = {"head": 0} + + def always_timeout(*args, **kwargs): + calls["head"] += 1 + raise requests.exceptions.ReadTimeout("still timing out") + + monkeypatch.setattr("requests.head", always_timeout) + + with pytest.raises(requests.exceptions.ReadTimeout): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert calls["head"] == 3 + assert sleeps == [1.0, 2.0] + out = capsys.readouterr().out + assert "Download failed" in out + assert "after 2 retries" in out + + +def test_retry_exhaustion_on_http_503_logs_status(monkeypatch, tmp_path, capsys): + sleeps = _stub_sleep(monkeypatch) + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + monkeypatch.setattr("requests.get", lambda *a, **k: FakeResponse(status_code=503)) + + with pytest.raises(requests.exceptions.HTTPError): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert sleeps == [1.0, 2.0] + out = capsys.readouterr().out + assert "HTTP 503" in out + assert "after 2 retries" in out + + +def test_zero_max_retries_disables_retries(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"head": 0} + + def fail_once(*args, **kwargs): + calls["head"] += 1 + raise requests.exceptions.ConnectTimeout("timeout") + + monkeypatch.setattr("requests.head", fail_once) + + with pytest.raises(requests.exceptions.ConnectTimeout): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=0) + + assert calls["head"] == 1 + assert sleeps == [] + + +@pytest.mark.parametrize("invalid_value", [-1, True, 1.5, "3"]) +def test_invalid_max_retries_raises_value_error(tmp_path, invalid_value): + with pytest.raises(ValueError, match="non-negative integer"): + dl._download_file( + "https://example.org/file.ttl", + localDir=str(tmp_path), + max_retries=invalid_value, + ) + + +def test_ssl_error_does_not_retry(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"head": 0} + + def ssl_fail(*args, **kwargs): + calls["head"] += 1 + raise requests.exceptions.SSLError("certificate verify failed") + + monkeypatch.setattr("requests.head", ssl_fail) + + with pytest.raises(requests.exceptions.SSLError): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=3) + + assert calls["head"] == 1 + assert sleeps == [] + + +def test_forbidden_403_does_not_retry(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def forbidden(*args, **kwargs): + calls["get"] += 1 + return FakeResponse(status_code=403) + + monkeypatch.setattr("requests.get", forbidden) + + with pytest.raises(DownloadAuthError): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=3) + + assert calls["get"] == 1 + assert sleeps == [] + + +def test_not_found_404_skips_without_retry(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def not_found(*args, **kwargs): + calls["get"] += 1 + return FakeResponse(status_code=404) + + monkeypatch.setattr("requests.get", not_found) + + dl._download_file("https://example.org/missing.ttl", localDir=str(tmp_path), max_retries=3) + + assert calls["get"] == 1 + assert sleeps == [] + assert not (tmp_path / "missing.ttl").exists() + + +def test_checksum_mismatch_does_not_retry(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + return FakeResponse(content=b"actual data") + + monkeypatch.setattr("requests.get", fake_get) + + with pytest.raises(IOError, match="Checksum mismatch"): + dl._download_file( + "https://example.org/file.ttl", + localDir=str(tmp_path), + validate_checksum=True, + expected_checksum="0" * 64, + max_retries=3, + ) + + assert calls["get"] == 1 + assert sleeps == [] + assert not (tmp_path / "file.ttl").exists() + + +def test_checksum_validation_succeeds_after_retry(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + payload = b"valid payload" + expected = hashlib.sha256(payload).hexdigest() + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + return FakeResponse(status_code=503) + return FakeResponse(content=payload) + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file( + "https://example.org/file.ttl", + localDir=str(tmp_path), + validate_checksum=True, + expected_checksum=expected, + max_retries=2, + ) + + assert calls["get"] == 2 + assert sleeps == [1.0] + assert (tmp_path / "file.ttl").read_bytes() == payload + + +def test_manifest_records_single_entry_after_retry(monkeypatch, tmp_path): + _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + if calls["get"] == 1: + return FakeResponse(status_code=502) + return FakeResponse(content=b"data") + + monkeypatch.setattr("requests.get", fake_get) + ctx = ManifestContext(command="download") + + dl._download_file( + "https://example.org/file.ttl", + localDir=str(tmp_path), + manifest_context=ctx, + max_retries=2, + ) + + assert len(ctx.files) == 1 + assert ctx.files[0]["status"] == "success" + + +def test_download_threads_max_retries_to_download_file(monkeypatch, tmp_path): + captured = {} + + def fake_download_file(url, localDir, **kwargs): + captured["url"] = url + captured["max_retries"] = kwargs.get("max_retries") + + monkeypatch.setattr(dl, "_download_file", fake_download_file) + + dl.download( + localDir=str(tmp_path), + endpoint="https://databus.dbpedia.org", + databusURIs=["https://databus.dbpedia.org/user/group/artifact/1.0/data.ttl"], + max_retries=5, + ) + + assert captured["max_retries"] == 5 + + +def test_cli_max_retries_option_passed_and_recorded_in_manifest(monkeypatch, tmp_path): + captured = {} + + def fake_download(**kwargs): + captured.update(kwargs) + + monkeypatch.setattr("databusclient.cli.api_download", fake_download) + manifest_path = tmp_path / "manifest.jsonld" + + result = CliRunner().invoke( + app, + [ + "download", + "https://databus.dbpedia.org/user/group/artifact/1.0/data.ttl", + "--max-retries", + "5", + "--manifest", + str(manifest_path), + ], + ) + + assert result.exit_code == 0, result.output + assert captured["max_retries"] == 5 + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + assert manifest["dbus:replayParams"]["max_retries"] == 5 + + +def test_manifest_replay_passes_recorded_and_default_max_retries(monkeypatch, tmp_path): + captured_calls = [] + + def fake_download(**kwargs): + captured_calls.append(kwargs) + + monkeypatch.setattr("databusclient.manifest.replay.api_download", fake_download) + + new_manifest = tmp_path / "new.jsonld" + new_manifest.write_text( + json.dumps( + { + "dbus:command": "download", + "dbus:endpoint": "https://databus.dbpedia.org", + "dbus:replayParams": { + "databusURIs": ["https://databus.dbpedia.org/u/g/a/1.0/f.ttl"], + "max_retries": 4, + }, + } + ), + encoding="utf-8", + ) + old_manifest = tmp_path / "old.jsonld" + old_manifest.write_text( + json.dumps( + { + "dbus:command": "download", + "dbus:endpoint": "https://databus.dbpedia.org", + "dbus:replayParams": { + "databusURIs": ["https://databus.dbpedia.org/u/g/a/1.0/f.ttl"], + }, + } + ), + encoding="utf-8", + ) + + replay_manifest(str(new_manifest)) + replay_manifest(str(old_manifest)) + + assert captured_calls[0]["max_retries"] == 4 + assert captured_calls[1]["max_retries"] == dl.DEFAULT_MAX_RETRIES + + +def test_cli_rejects_negative_max_retries(): + result = CliRunner().invoke( + app, + [ + "download", + "https://databus.dbpedia.org/user/group/artifact/1.0/data.ttl", + "--max-retries", + "-1", + ], + ) + assert result.exit_code != 0 + + +def test_response_closed_on_503_403_and_404_error_paths(monkeypatch, tmp_path): + _stub_sleep(monkeypatch) + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + + r_503_first = FakeResponse(status_code=503) + r_200 = FakeResponse(content=b"ok") + seq = iter([r_503_first, r_200]) + monkeypatch.setattr("requests.get", lambda *a, **k: next(seq)) + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=1) + assert r_503_first.closed + assert r_200.closed + + r_403 = FakeResponse(status_code=403) + monkeypatch.setattr("requests.get", lambda *a, **k: r_403) + with pytest.raises(DownloadAuthError): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=1) + assert r_403.closed + + r_404 = FakeResponse(status_code=404) + monkeypatch.setattr("requests.get", lambda *a, **k: r_404) + dl._download_file("https://example.org/missing.ttl", localDir=str(tmp_path), max_retries=1) + assert r_404.closed + + +def test_keyboard_interrupt_removes_partial_file(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + calls = {"get": 0} + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + resp = FakeResponse( + status_code=200, + headers={"content-length": "10"}, + chunks=[b"abc", KeyboardInterrupt()], + ) + + def fake_get(*args, **kwargs): + calls["get"] += 1 + return resp + + monkeypatch.setattr("requests.get", fake_get) + + with pytest.raises(KeyboardInterrupt): + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert not (tmp_path / "file.ttl").exists() + assert resp.closed + assert calls["get"] == 1 + assert sleeps == [] + + +def test_head_503_falls_through_to_get_and_succeeds(monkeypatch, tmp_path): + sleeps = _stub_sleep(monkeypatch) + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=503)) + monkeypatch.setattr("requests.get", lambda *a, **k: FakeResponse(content=b"from get")) + + dl._download_file("https://example.org/file.ttl", localDir=str(tmp_path), max_retries=2) + + assert (tmp_path / "file.ttl").read_bytes() == b"from get" + assert sleeps == [] + + +def test_user_agent_sent_on_head_and_get_for_every_retry(monkeypatch, tmp_path): + _stub_sleep(monkeypatch) + seen_head_ua = [] + seen_get_ua = [] + + def fake_head(url, headers=None, **kwargs): + seen_head_ua.append((headers or {}).get("User-Agent")) + return FakeResponse(status_code=200) + + def fake_get(url, headers=None, **kwargs): + seen_get_ua.append((headers or {}).get("User-Agent")) + if len(seen_get_ua) == 1: + return FakeResponse(status_code=503) + return FakeResponse(content=b"ok") + + monkeypatch.setattr("requests.head", fake_head) + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file( + "https://example.org/file.ttl", + localDir=str(tmp_path), + user_agent="CustomBot/1.0", + max_retries=2, + ) + + assert seen_head_ua == ["CustomBot/1.0", "CustomBot/1.0"] + assert seen_get_ua == ["CustomBot/1.0", "CustomBot/1.0"] + + +def test_workflow_download_step_retry_interaction(monkeypatch, tmp_path): + from databusclient.workflow.context import StepContext + from databusclient.workflow.parser import _validate_step + from databusclient.workflow.steps import DownloadStep + + captured = [] + monkeypatch.setattr( + "databusclient.workflow.steps.api_download", + lambda **kwargs: captured.append(kwargs), + ) + + step = DownloadStep() + base = { + "name": "dl", + "command": "download", + "uri": "https://databus.dbpedia.org/u/g/a/1.0/f.ttl", + "localDir": str(tmp_path), + } + + parsed_with_retries = _validate_step({**base, "max_retries": 4}, 0, set()) + assert parsed_with_retries["max_retries"] == 4 + + step.run(dict(base), StepContext()) + step.run( + {**base, "on_error": "retry", "retry": {"max_attempts": 2, "delay_seconds": 1}}, + StepContext(), + ) + step.run({**base, "on_error": "retry", "max_retries": 4}, StepContext()) + + assert "max_retries" not in captured[0] + assert "max_retries" not in captured[1] + assert captured[2]["max_retries"] == 4 + + +def test_vault_auth_retry_sends_authorization_and_closes_401_response( + monkeypatch, tmp_path +): + sleeps = _stub_sleep(monkeypatch) + vault_host = next(iter(dl.VAULT_REQUIRED_HOSTS)) + url = f"https://{vault_host}/protected/data.ttl" + + monkeypatch.setattr("requests.head", lambda *a, **k: FakeResponse(status_code=200)) + monkeypatch.setattr(dl, "__get_vault_access__", lambda *a, **k: "secret-access-token") + + r_401_1 = FakeResponse(status_code=401, headers={"WWW-Authenticate": "Bearer"}) + r_503 = FakeResponse(status_code=503) + r_401_2 = FakeResponse(status_code=401, headers={"WWW-Authenticate": "Bearer"}) + r_200 = FakeResponse(content=b"protected-data") + seq = iter([r_401_1, r_503, r_401_2, r_200]) + seen_auth_headers = [] + + def fake_get(req_url, headers=None, **kwargs): + seen_auth_headers.append((headers or {}).get("Authorization")) + return next(seq) + + monkeypatch.setattr("requests.get", fake_get) + + dl._download_file( + url, + localDir=str(tmp_path), + vault_token_file="dummy-token-file", + max_retries=2, + ) + + assert (tmp_path / "data.ttl").read_bytes() == b"protected-data" + assert sleeps == [1.0] + assert seen_auth_headers == [ + None, + "Bearer secret-access-token", + None, + "Bearer secret-access-token", + ] + assert r_401_1.closed + assert r_503.closed + assert r_401_2.closed + assert r_200.closed