diff --git a/README.md b/README.md
index a6fb16ac..6828ad3f 100644
--- a/README.md
+++ b/README.md
@@ -130,12 +130,12 @@ The `download` command retrieves Databus files, versions, artifacts, groups, col
### Deploy
-The `deploy` command publishes datasets using distribution arguments, metadata JSON files, or WebDAV/Nextcloud uploads. See the [deploy docs](doc/cli-usage.md#cli-deploy).
+The `deploy` command publishes datasets using distribution arguments, metadata JSON files, or WebDAV/Nextcloud uploads, with configurable HTTP retries (`--max-retries`, `--request-timeout`). See the [deploy docs](doc/cli-usage.md#cli-deploy).
### Delete
-The `delete` command removes Databus versions, artifacts, groups, or collections and provides dry-run and confirmation safeguards. See the [delete docs](doc/cli-usage.md#cli-delete).
+The `delete` command removes Databus versions, artifacts, groups, or collections and provides dry-run, confirmation safeguards, and configurable HTTP retries (`--max-retries`, `--request-timeout`). See the [delete docs](doc/cli-usage.md#cli-delete).
### Manifest
diff --git a/databusclient/api/delete.py b/databusclient/api/delete.py
index d631f42f..2c9326de 100644
--- a/databusclient/api/delete.py
+++ b/databusclient/api/delete.py
@@ -14,6 +14,7 @@
from databusclient.api.utils import (
fetch_databus_jsonld,
get_databus_id_parts_from_file_url,
+ get_http_session,
)
@@ -23,16 +24,26 @@ class DeleteQueue:
Allows adding multiple databus URIs to a queue and executing their deletion in batch.
"""
- def __init__(self, databus_key: str, manifest_context=None):
+ def __init__(
+ self,
+ databus_key: str,
+ manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
+ ):
"""Create a DeleteQueue bound to a given Databus API key.
Args:
databus_key: API key used to authenticate deletion requests.
manifest_context: Optional ManifestContext to record deletion
outcomes into. Passed through to _delete_list on execute().
+ session: Optional HTTP session with retry strategy.
+ timeout: Request timeout in seconds.
"""
self.databus_key = databus_key
self.manifest_context = manifest_context
+ self.session = session
+ self.timeout = timeout
self.queue: set[str] = set()
def add_uri(self, databusURI: str):
@@ -74,11 +85,18 @@ def execute(self):
Each queued URI will be deleted using `_delete_resource`.
Passes manifest_context through so deletions are recorded.
"""
+ del_kwargs = {
+ "force": True,
+ "manifest_context": self.manifest_context,
+ }
+ import inspect
+ if "session" in inspect.signature(_delete_list).parameters:
+ del_kwargs["session"] = self.session
+ del_kwargs["timeout"] = self.timeout
_delete_list(
list(self.sorted_queue()),
self.databus_key,
- force=True,
- manifest_context=self.manifest_context,
+ **del_kwargs,
)
@@ -122,6 +140,8 @@ def _delete_resource(
force: bool = False,
queue: DeleteQueue = None,
manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
):
"""Delete a single Databus resource (version, artifact, group).
@@ -134,6 +154,8 @@ def _delete_resource(
dry_run: If True, do not perform the deletion but only print what would be deleted.
force: If True, skip confirmation prompt and proceed with deletion.
queue: If queue is provided, add the URI to the queue instead of deleting immediately.
+ session: Optional HTTP session to use for requests.
+ timeout: Request timeout in seconds.
"""
# Confirm the deletion request, skip the request or cancel deletion process
@@ -158,9 +180,12 @@ def _delete_resource(
queue.add_uri(databusURI)
return
+ if session is None:
+ session = get_http_session()
+
print(f"[DELETE] {databusURI}")
headers = {"accept": "*/*", "X-API-KEY": databus_key}
- response = requests.delete(databusURI, headers=headers, timeout=30)
+ response = session.delete(databusURI, headers=headers, timeout=timeout)
if response.status_code in (200, 204):
print(f"Successfully deleted: {databusURI}")
@@ -179,6 +204,8 @@ def _delete_list(
force: bool = False,
queue: DeleteQueue = None,
manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
):
"""Delete a list of Databus resources.
@@ -188,10 +215,19 @@ def _delete_list(
dry_run: If True, do not perform the deletion but only print what would be deleted.
force: If True, skip confirmation prompt and proceed with deletion.
queue: If queue is provided, add the URIs to the queue instead of deleting immediately.
+ session: Optional HTTP session with retry strategy.
+ timeout: Request timeout in seconds.
"""
for databusURI in databusURIs:
_delete_resource(
- databusURI, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
@@ -202,6 +238,8 @@ def _delete_artifact(
force: bool = False,
queue: DeleteQueue = None,
manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
):
"""Delete an artifact and all its versions.
@@ -214,8 +252,10 @@ def _delete_artifact(
dry_run: If True, do not perform the deletion but only print what would be deleted.
force: If True, skip confirmation prompt and proceed with deletion.
queue: If queue is provided, add the URI to the queue instead of deleting immediately.
+ session: Optional HTTP session with retry strategy.
+ timeout: Request timeout in seconds.
"""
- artifact_body = fetch_databus_jsonld(databusURI, databus_key)
+ artifact_body = fetch_databus_jsonld(databusURI, databus_key, session=session, timeout=timeout)
json_dict = json.loads(artifact_body)
versions = json_dict.get("databus:hasVersion")
@@ -235,11 +275,27 @@ def _delete_artifact(
else:
# Delete all versions
_delete_list(
- version_uris, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ version_uris,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
# Finally, delete the artifact itself
- _delete_resource(databusURI, databus_key, dry_run=dry_run, force=force, queue=queue,manifest_context=manifest_context)
+ _delete_resource(
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
+ )
def _delete_group(
@@ -249,6 +305,8 @@ def _delete_group(
force: bool = False,
queue: DeleteQueue = None,
manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
):
"""Delete a group and all its artifacts and versions.
@@ -261,8 +319,10 @@ def _delete_group(
dry_run: If True, do not perform the deletion but only print what would be deleted.
force: If True, skip confirmation prompt and proceed with deletion.
queue: If queue is provided, add the URI to the queue instead of deleting immediately.
+ session: Optional HTTP session with retry strategy.
+ timeout: Request timeout in seconds.
"""
- group_body = fetch_databus_jsonld(databusURI, databus_key)
+ group_body = fetch_databus_jsonld(databusURI, databus_key, session=session, timeout=timeout)
json_dict = json.loads(group_body)
artifacts = json_dict.get("databus:hasArtifact")
@@ -292,14 +352,38 @@ def _delete_group(
# Delete all artifacts (which deletes their versions)
for artifact_uri in artifact_uris:
_delete_artifact(
- artifact_uri, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ artifact_uri,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
# Finally, delete the group itself
- _delete_resource(databusURI, databus_key, dry_run=dry_run, force=force, queue=queue,manifest_context=manifest_context)
+ _delete_resource(
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
+ )
-def delete(databusURIs: List[str], databus_key: str, dry_run: bool, force: bool, manifest_context=None):
+def delete(
+ databusURIs: List[str],
+ databus_key: str,
+ dry_run: bool = False,
+ force: bool = False,
+ manifest_context=None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
+):
"""Delete a dataset from the databus.
Delete a group, artifact, or version identified by the given databus URI.
@@ -310,9 +394,15 @@ def delete(databusURIs: List[str], databus_key: str, dry_run: bool, force: bool,
databus_key: Databus API key to authenticate the deletion requests.
dry_run: If True, will only print what would be deleted without performing actual deletions.
force: If True, skip confirmation prompt and proceed with deletion.
+ session: Optional HTTP session with retry strategy.
+ timeout: Request timeout in seconds.
"""
+ if session is None:
+ session = get_http_session()
- queue = DeleteQueue(databus_key, manifest_context=manifest_context)
+ queue = DeleteQueue(
+ databus_key, manifest_context=manifest_context, session=session, timeout=timeout
+ )
for databusURI in databusURIs:
_host, _account, group, artifact, version, file = (
@@ -322,24 +412,52 @@ def delete(databusURIs: List[str], databus_key: str, dry_run: bool, force: bool,
if group == "collections" and artifact is not None:
print(f"Deleting collection: {databusURI}")
_delete_resource(
- databusURI, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
elif file is not None:
print(f"Deleting file is not supported via API: {databusURI}")
elif version is not None:
print(f"Deleting version: {databusURI}")
_delete_resource(
- databusURI, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
elif artifact is not None:
print(f"Deleting artifact and all its versions: {databusURI}")
_delete_artifact(
- databusURI, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
elif group is not None and group != "collections":
print(f"Deleting group and all its artifacts and versions: {databusURI}")
_delete_group(
- databusURI, databus_key, dry_run=dry_run, force=force, queue=queue, manifest_context=manifest_context
+ databusURI,
+ databus_key,
+ dry_run=dry_run,
+ force=force,
+ queue=queue,
+ manifest_context=manifest_context,
+ session=session,
+ timeout=timeout,
)
else:
print(f"Deleting {databusURI} is not supported.")
diff --git a/databusclient/api/deploy.py b/databusclient/api/deploy.py
index 2c8cd081..3228432e 100644
--- a/databusclient/api/deploy.py
+++ b/databusclient/api/deploy.py
@@ -11,6 +11,7 @@
from typing import Dict, List, Optional, Tuple, Union
import requests
+from databusclient.api.utils import get_http_session
_debug = False
@@ -176,14 +177,18 @@ def _get_file_stats(distribution_str: str) -> Tuple[Optional[str], Optional[int]
return sha256sum, content_length
-def _load_file_stats(url: str) -> Tuple[str, int]:
+def _load_file_stats(
+ url: str, session: requests.Session | None = None, timeout: int = 30
+) -> Tuple[str, int]:
"""Download the file at ``url`` and compute its SHA-256 and length.
This is used as a fallback when the caller did not supply checksum/size
information in the CLI or metadata file.
"""
+ if session is None:
+ session = get_http_session()
- resp = requests.get(url, timeout=30)
+ resp = session.get(url, timeout=timeout)
if resp.status_code >= 400:
raise requests.exceptions.RequestException(response=resp)
@@ -192,7 +197,11 @@ def _load_file_stats(url: str) -> Tuple[str, int]:
return sha256sum, content_length
-def get_file_info(distribution_str: str) -> Tuple[Dict[str, str], str, str, str, int]:
+def get_file_info(
+ distribution_str: str,
+ session: requests.Session | None = None,
+ timeout: int = 30,
+) -> Tuple[Dict[str, str], str, str, str, int]:
"""Return parsed file information for a distribution string.
Returns a tuple `(cvs, format_extension, compression, sha256sum, size)`.
@@ -210,7 +219,9 @@ def get_file_info(distribution_str: str) -> Tuple[Dict[str, str], str, str, str,
if sha256sum is None or content_length is None:
__url = str(distribution_str).split("|")[0]
- sha256sum, content_length = _load_file_stats(__url)
+ sha256sum, content_length = _load_file_stats(
+ __url, session=session, timeout=timeout
+ )
return cvs, format_extension, compression, sha256sum, content_length
@@ -320,6 +331,8 @@ def create_dataset(
group_title: str = None,
group_abstract: str = None,
group_description: str = None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
) -> Dict[str, Union[List[Dict[str, Union[bool, str, int, float, List]]], str]]:
"""
Creates a Databus Dataset as a python dict from distributions and submitted metadata. WARNING: If file stats (sha256sum, content length)
@@ -376,7 +389,7 @@ def create_dataset(
compression,
sha256sum,
content_length,
- ) = get_file_info(dst_string)
+ ) = get_file_info(dst_string, session=session, timeout=timeout)
if not cvs and len(distributions) > 1:
raise BadArgumentException(
@@ -463,6 +476,8 @@ def deploy(
verify_parts: bool = False,
log_level: DeployLogLevel = DeployLogLevel.debug,
debug: bool = False,
+ session: requests.Session | None = None,
+ timeout: int = 30,
) -> None:
"""Deploys a dataset to the databus. The endpoint is inferred from the DataID identifier.
Parameters
@@ -487,11 +502,14 @@ def deploy(
except (KeyError, IndexError, TypeError) as e:
raise DeployError(f"Invalid dataid structure: {e}")
+ if session is None:
+ session = get_http_session()
+
api_uri = (
base
+ f"/api/publish?verify-parts={str(verify_parts).lower()}&log-level={log_level.name}"
)
- resp = requests.post(api_uri, data=data, headers=headers, timeout=30)
+ resp = session.post(api_uri, data=data, headers=headers, timeout=timeout)
if debug or _debug:
try:
@@ -517,6 +535,8 @@ def deploy_from_metadata(
artifact_version_description: str,
license_url: str,
apikey: str,
+ session: requests.Session | None = None,
+ timeout: int = 30,
) -> None:
"""
Deploy a dataset from metadata entries.
@@ -550,7 +570,7 @@ def deploy_from_metadata(
)
print(f"Deploying dataset version: {version_id}")
- deploy(dataset, apikey)
+ deploy(dataset, apikey, session=session, timeout=timeout)
print(f"Successfully deployed to {version_id}")
print(f"Deployed {len(metadata)} file(s):")
diff --git a/databusclient/api/utils.py b/databusclient/api/utils.py
index ba6dfe5a..bb967531 100644
--- a/databusclient/api/utils.py
+++ b/databusclient/api/utils.py
@@ -7,6 +7,50 @@
from typing import Optional, Tuple
import hashlib
import requests
+from requests.adapters import HTTPAdapter
+from urllib3.util import Retry
+
+
+def get_http_session(
+ retries: int = 3,
+ backoff_factor: float = 0.5,
+ status_forcelist: Tuple[int, ...] = (429, 500, 502, 503, 504),
+ allowed_methods: Optional[frozenset] = None,
+ backoff_jitter: float = 0.1,
+) -> requests.Session:
+ """Create and configure a requests Session with HTTP retry strategy and exponential backoff.
+
+ Args:
+ retries: Total number of retries to allow.
+ backoff_factor: Backoff factor to apply between attempts.
+ status_forcelist: Set of HTTP status codes to force retry on.
+ allowed_methods: Set of HTTP methods allowed for retry.
+ backoff_jitter: Jitter to add to backoff delay.
+
+ Returns:
+ Configured requests.Session object.
+ """
+ session = requests.Session()
+ kwargs = {
+ "total": retries,
+ "backoff_factor": backoff_factor,
+ "status_forcelist": status_forcelist,
+ "raise_on_status": False,
+ }
+ if allowed_methods is not None:
+ kwargs["allowed_methods"] = allowed_methods
+
+ try:
+ kwargs["backoff_jitter"] = backoff_jitter
+ retry_strategy = Retry(**kwargs)
+ except TypeError:
+ kwargs.pop("backoff_jitter", None)
+ retry_strategy = Retry(**kwargs)
+
+ adapter = HTTPAdapter(max_retries=retry_strategy)
+ session.mount("http://", adapter)
+ session.mount("https://", adapter)
+ return session
def get_databus_id_parts_from_file_url(
@@ -28,28 +72,36 @@ def get_databus_id_parts_from_file_url(
A tuple containing (host, accountId, groupId, artifactId, versionId, fileId).
Each element is a string or None if not present.
"""
-
uri = uri.removeprefix("https://").removeprefix("http://")
parts = uri.strip("/").split("/")
parts += [None] * (6 - len(parts)) # pad with None if less than 6 parts
return tuple(parts[:6]) # return only the first 6 parts
-def fetch_databus_jsonld(uri: str, databus_key: str | None = None) -> str:
+def fetch_databus_jsonld(
+ uri: str,
+ databus_key: str | None = None,
+ session: requests.Session | None = None,
+ timeout: int = 30,
+) -> str:
"""Fetch the JSON-LD representation of a Databus resource.
Args:
uri: Full Databus resource URI.
databus_key: Optional API key for protected resources.
+ session: Optional HTTP session to use for requests.
+ timeout: Request timeout in seconds.
Returns:
The response body as a string containing JSON-LD.
"""
-
headers = {"Accept": "application/ld+json"}
if databus_key is not None:
headers["X-API-KEY"] = databus_key
- response = requests.get(uri, headers=headers, timeout=30)
+ if session is not None:
+ response = session.get(uri, headers=headers, timeout=timeout)
+ else:
+ response = requests.get(uri, headers=headers, timeout=timeout)
response.raise_for_status()
return response.text
diff --git a/databusclient/cli.py b/databusclient/cli.py
index 996407ab..a98538f5 100644
--- a/databusclient/cli.py
+++ b/databusclient/cli.py
@@ -10,6 +10,7 @@
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.utils import get_http_session
from databusclient.manifest.context import ManifestContext
from databusclient.manifest.writer import ManifestWriter
from databusclient.manifest.replay import ManifestReplayError, replay_manifest, load_manifest
@@ -77,6 +78,22 @@ def app():
)
@click.option("--remote", help="rclone remote name (e.g., 'nextcloud')")
@click.option("--path", help="Remote path on Nextcloud (e.g., 'datasets/mydataset')")
+@click.option(
+ "--max-retries",
+ "--retries",
+ "retries",
+ default=3,
+ show_default=True,
+ type=int,
+ help="Maximum number of HTTP retries for network requests",
+)
+@click.option(
+ "--request-timeout",
+ default=30,
+ show_default=True,
+ type=int,
+ help="Timeout in seconds for HTTP network requests",
+)
@click.argument("distributions", nargs=-1)
def deploy(
version_id,
@@ -89,6 +106,8 @@ def deploy(
webdav_url,
remote,
path,
+ retries: int,
+ request_timeout: int,
distributions: List[str],
manifest_path,
):
@@ -99,6 +118,8 @@ def deploy(
- Upload & deploy via Nextcloud (--webdav-url, --remote, --path)
"""
+ session = api_deploy.get_http_session(retries=retries)
+
# Sanity checks for conflicting options
if metadata_file and any([distributions, webdav_url, remote, path]):
raise click.UsageError(
@@ -145,11 +166,15 @@ def _write_manifest():
artifact_version_description=description,
license_url=license_url,
distributions=distributions,
+ session=session,
+ timeout=request_timeout,
)
if manifest_context:
manifest_context.replay_params["deploy_mode"] = "classic"
manifest_context.replay_params["resolved_distributions"] = dataid["@graph"][-1].get("distribution", [])
- api_deploy.deploy(dataid=dataid, api_key=apikey)
+ manifest_context.replay_params["retries"] = retries
+ manifest_context.replay_params["request_timeout"] = request_timeout
+ api_deploy.deploy(dataid=dataid, api_key=apikey, session=session, timeout=request_timeout)
if manifest_context:
for dist in distributions:
url = str(dist).split("|")[0]
@@ -171,8 +196,10 @@ def _write_manifest():
if manifest_context:
manifest_context.replay_params["deploy_mode"] = "metadata"
manifest_context.replay_params["resolved_metadata"] = metadata
+ manifest_context.replay_params["retries"] = retries
+ manifest_context.replay_params["request_timeout"] = request_timeout
api_deploy.deploy_from_metadata(
- metadata, version_id, title, abstract, description, license_url, apikey
+ metadata, version_id, title, abstract, description, license_url, apikey, session=session, timeout=request_timeout
)
if manifest_context:
for entry in metadata:
@@ -205,10 +232,12 @@ def _write_manifest():
click.echo(f"→ Uploading to: {remote}:{path}")
if manifest_context:
manifest_context.replay_params["deploy_mode"] = "webdav"
+ manifest_context.replay_params["retries"] = retries
+ manifest_context.replay_params["request_timeout"] = request_timeout
try:
metadata = webdav.upload_to_webdav(distributions, remote, path, webdav_url)
api_deploy.deploy_from_metadata(
- metadata, version_id, title, abstract, description, license_url, apikey
+ metadata, version_id, title, abstract, description, license_url, apikey, session=session, timeout=request_timeout
)
if manifest_context:
for entry in metadata:
@@ -442,7 +471,31 @@ def download(
default=None,
help="Write a JSON-LD manifest of this operation to PATH.",
)
-def delete(databusuris: List[str], databus_key: str, dry_run: bool, force: bool, manifest_path: str):
+@click.option(
+ "--max-retries",
+ "--retries",
+ "retries",
+ default=3,
+ show_default=True,
+ type=int,
+ help="Maximum number of HTTP retries for network requests",
+)
+@click.option(
+ "--request-timeout",
+ default=30,
+ show_default=True,
+ type=int,
+ help="Timeout in seconds for HTTP network requests",
+)
+def delete(
+ databusuris: List[str],
+ databus_key: str,
+ dry_run: bool,
+ force: bool,
+ manifest_path: str,
+ retries: int,
+ request_timeout: int,
+):
"""
Delete a dataset from the databus.
@@ -456,8 +509,11 @@ def delete(databusuris: List[str], databus_key: str, dry_run: bool, force: bool,
manifest_context.record_params({
"databusURIs": list(databusuris),
"dry_run": dry_run,
+ "retries": retries,
+ "request_timeout": request_timeout,
})
+ session = get_http_session(retries=retries)
try:
api_delete(
databusURIs=databusuris,
@@ -465,6 +521,8 @@ def delete(databusuris: List[str], databus_key: str, dry_run: bool, force: bool,
dry_run=dry_run,
force=force,
manifest_context=manifest_context,
+ session=session,
+ timeout=request_timeout,
)
except Exception as exc:
if manifest_context:
diff --git a/databusclient/manifest/replay.py b/databusclient/manifest/replay.py
index 4def7bc2..06537345 100644
--- a/databusclient/manifest/replay.py
+++ b/databusclient/manifest/replay.py
@@ -2,6 +2,7 @@
import json
from typing import Any, Dict, Optional
from databusclient.api.download import download as api_download
+from databusclient.api.utils import get_http_session
from databusclient.api.delete import delete as api_delete
from databusclient.api.deploy import (
create_dataset as api_create_dataset,
@@ -128,6 +129,10 @@ def _replay_delete(
# same pattern as vault_token / databus_key.
force = bool(overrides.get("force", False))
+ retries = int(overrides.get("retries") or replay_params.get("retries", 3))
+ timeout = int(overrides.get("request_timeout") or replay_params.get("request_timeout", 30))
+ session = get_http_session(retries=retries)
+
if dry_run:
api_delete(
databusURIs=databus_uris,
@@ -135,6 +140,8 @@ def _replay_delete(
dry_run=True,
force=True,
manifest_context=None,
+ session=session,
+ timeout=timeout,
)
return {"command": "delete", "executed": False, "dry_run": True}
@@ -158,6 +165,8 @@ def _replay_delete(
dry_run=False,
force=True,
manifest_context=None,
+ session=session,
+ timeout=timeout,
)
return {"command": "delete", "executed": True, "dry_run": False}
@@ -268,9 +277,23 @@ def _replay_deploy(
"The API key is never stored in the manifest."
)
+ retries = int(overrides.get("retries") or replay_params.get("retries", 3))
+ timeout = int(overrides.get("request_timeout") or replay_params.get("request_timeout", 30))
+ session = get_http_session(retries=retries)
+
+ import inspect
kwargs = _build_deploy_kwargs(replay_params)
- dataid = api_create_dataset(**kwargs)
- api_deploy_call(dataid=dataid, api_key=api_key)
+ create_kwargs = dict(kwargs)
+ if "session" in inspect.signature(api_create_dataset).parameters:
+ create_kwargs["session"] = session
+ create_kwargs["timeout"] = timeout
+ dataid = api_create_dataset(**create_kwargs)
+
+ deploy_kwargs = {"dataid": dataid, "api_key": api_key}
+ if "session" in inspect.signature(api_deploy_call).parameters:
+ deploy_kwargs["session"] = session
+ deploy_kwargs["timeout"] = timeout
+ api_deploy_call(**deploy_kwargs)
return {"command": "deploy", "executed": True}
diff --git a/databusclient/workflow/steps.py b/databusclient/workflow/steps.py
index 320e616c..c9fdb8da 100644
--- a/databusclient/workflow/steps.py
+++ b/databusclient/workflow/steps.py
@@ -19,6 +19,7 @@
deploy_from_metadata,
)
from databusclient.api.download import download as api_download
+from databusclient.api.utils import get_http_session
from databusclient.extensions import webdav
from databusclient.manifest.context import ManifestContext
@@ -183,15 +184,29 @@ def _run_classic_mode(self, resolved: Dict[str, Any], name: str) -> list:
f"'path') to deploy locally modified files."
)
- dataid = create_dataset(
- version_id=resolved["version_id"],
- artifact_version_title=resolved["title"],
- artifact_version_abstract=resolved["abstract"],
- artifact_version_description=resolved["description"],
- license_url=resolved["license"],
- distributions=files,
- )
- api_deploy_call(dataid=dataid, api_key=resolved["api_key"])
+ retries = int(resolved.get("retries", 3))
+ timeout = int(resolved.get("timeout", 30))
+ session = get_http_session(retries=retries)
+
+ import inspect
+ dataid_kwargs = {
+ "version_id": resolved["version_id"],
+ "artifact_version_title": resolved["title"],
+ "artifact_version_abstract": resolved["abstract"],
+ "artifact_version_description": resolved["description"],
+ "license_url": resolved["license"],
+ "distributions": files,
+ }
+ if "session" in inspect.signature(create_dataset).parameters:
+ dataid_kwargs["session"] = session
+ dataid_kwargs["timeout"] = timeout
+ dataid = create_dataset(**dataid_kwargs)
+
+ deploy_kwargs = {"dataid": dataid, "api_key": resolved["api_key"]}
+ if "session" in inspect.signature(api_deploy_call).parameters:
+ deploy_kwargs["session"] = session
+ deploy_kwargs["timeout"] = timeout
+ api_deploy_call(**deploy_kwargs)
return files
def _run_webdav_mode(self, resolved: Dict[str, Any], name: str) -> list:
@@ -207,15 +222,33 @@ def _run_webdav_mode(self, resolved: Dict[str, Any], name: str) -> list:
metadata = webdav.upload_to_webdav(
local_files, resolved["remote"], resolved["path"], resolved["webdav_url"]
)
- deploy_from_metadata(
- metadata,
- resolved["version_id"],
- resolved["title"],
- resolved["abstract"],
- resolved["description"],
- resolved["license"],
- resolved["api_key"],
- )
+ retries = int(resolved.get("retries", 3))
+ timeout = int(resolved.get("timeout", 30))
+ session = get_http_session(retries=retries)
+
+ import inspect
+ if "session" in inspect.signature(deploy_from_metadata).parameters:
+ deploy_from_metadata(
+ metadata,
+ resolved["version_id"],
+ resolved["title"],
+ resolved["abstract"],
+ resolved["description"],
+ resolved["license"],
+ resolved["api_key"],
+ session=session,
+ timeout=timeout,
+ )
+ else:
+ deploy_from_metadata(
+ metadata,
+ resolved["version_id"],
+ resolved["title"],
+ resolved["abstract"],
+ resolved["description"],
+ resolved["license"],
+ resolved["api_key"],
+ )
return [entry.get("url", "") for entry in metadata]
@@ -242,12 +275,18 @@ def run(self, step_config: Dict[str, Any], context: StepContext) -> None:
if not api_key:
raise StepValidationError(f"Step '{name}': delete step requires 'api_key'.")
+ retries = int(resolved.get("retries", 3))
+ timeout = int(resolved.get("timeout", 30))
+ session = get_http_session(retries=retries)
+
api_delete(
databusURIs=uris,
databus_key=api_key,
dry_run=resolved.get("dry_run", False),
force=True,
manifest_context=context.manifest_context,
+ session=session,
+ timeout=timeout,
)
context.set_output(name, "output_files", [])
diff --git a/doc/cli-usage.md b/doc/cli-usage.md
index 26826481..3ac67cfa 100644
--- a/doc/cli-usage.md
+++ b/doc/cli-usage.md
@@ -160,7 +160,11 @@ databusclient deploy [OPTIONS] [DISTRIBUTIONS]...
- `--metadata`
- Path to a metadata JSON file, for metadata-based deploy (Mode 2).
- `--webdav-url`, `--remote`, `--path`
- - WebDAV/Nextcloud URL, rclone remote name, and remote path, for upload-and-deploy (Mode 3).
+ - WebDAV/Nextcloud URL, rclone remote name, and remote path, for upload-and-deploy (Mode 3). Note: WebDAV file uploads execute via `rclone` subprocess outside the Python requests session.
+- `--max-retries`, `--retries`
+ - Maximum number of HTTP retries for network requests with exponential backoff and jitter where supported by urllib3 (fallback on older versions does not include jitter; default: `3`). Status codes retried: `429, 500, 502, 503, 504`. Applied to idempotent requests (e.g. `GET` during fallback file statistics fetching when checksum or size is omitted from distributions). The Databus publish `POST` request does not retry on status codes by default to prevent accidental non-idempotent re-submission.
+- `--request-timeout`
+ - Timeout in seconds for HTTP network requests (default: `30`).
**Help and further information on deploy command:**
```bash
@@ -260,6 +264,8 @@ If you want to perform a dry run without actual deletion, use the `--dry-run` op
As security measure, the delete command will prompt you for confirmation before proceeding with the deletion. If you want to skip this prompt, you can use the `--force` option.
+You can configure the HTTP retry policy using `--max-retries` / `--retries` (default: `3`, retries `429, 500, 502, 503, 504` with exponential backoff and jitter where supported by urllib3 on `DELETE` requests) and `--request-timeout` (default: `30` seconds).
+
#### Examples of using the delete command
**Delete Version**: delete a specific version
@@ -460,7 +466,7 @@ Each step declares an `on_error` behavior (defaults to `fail` if not set):
|---|---|
| `fail` | Stop the entire workflow immediately if this step fails. |
| `continue` | Log the failure and move on to the next step anyway. |
-| `retry` | Retry the step up to `max_attempts` times, waiting `delay_seconds` between attempts. If all attempts fail, the workflow stops. |
+| `retry` | Run the step for up to `max_attempts` total attempts (counting the initial execution; with `max_attempts: 1`, the step runs once and is not rerun), waiting `delay_seconds` between attempts. If all attempts fail, the workflow stops. |
```yaml
- name: fetch_dataset
@@ -474,6 +480,11 @@ Each step declares an `on_error` behavior (defaults to `fail` if not set):
A retry re-runs the entire step from scratch, not just the part that failed.
+##### HTTP-level retries vs. Workflow-level step retries
+
+- **HTTP-level retry policy (`retries`, `timeout`)**: Workflow steps (`deploy`, `delete`) accept optional `retries` (default: `3`) and `timeout` (default: `30`) properties in their step configuration. Transient HTTP failures (such as 503 Service Unavailable, 429 Rate Limited, 502/504 gateways) are retried at the transport layer for eligible idempotent HTTP methods (e.g. GET and DELETE, while publish POST does not receive status-code retries) using exponential backoff and jitter (where supported by urllib3) without restarting the step.
+- **Workflow-level step retry policy (`on_error: retry`)**: Operates at the orchestration layer. If all HTTP retries within a step are exhausted and an exception is raised, `on_error: retry` re-runs the entire step from scratch for up to `max_attempts` total attempts (which counts the initial step execution; with `max_attempts: 1`, the step runs once and is not rerun), with each new step attempt receiving a fresh series of HTTP retry attempts.
+
**Delete steps never prompt for confirmation inside a workflow** — since workflows are meant to run unattended, a `delete` step always behaves as if `--force` was passed.
#### Examples
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_retry.py b/tests/test_retry.py
new file mode 100644
index 00000000..c2170a8c
--- /dev/null
+++ b/tests/test_retry.py
@@ -0,0 +1,238 @@
+"""Tests for HTTP retry session helper and CLI options."""
+
+import requests
+from click.testing import CliRunner
+from requests.adapters import HTTPAdapter
+
+from databusclient.api.utils import get_http_session, fetch_databus_jsonld
+from databusclient.cli import app
+
+
+def test_get_http_session_defaults():
+ session = get_http_session()
+ assert isinstance(session, requests.Session)
+
+ http_adapter = session.adapters.get("http://")
+ https_adapter = session.adapters.get("https://")
+
+ assert isinstance(http_adapter, HTTPAdapter)
+ assert isinstance(https_adapter, HTTPAdapter)
+ assert http_adapter.max_retries.total == 3
+
+
+def test_get_http_session_custom_retries():
+ session = get_http_session(retries=5, backoff_factor=1.0)
+ http_adapter = session.adapters.get("https://")
+
+ assert http_adapter.max_retries.total == 5
+ assert http_adapter.max_retries.backoff_factor == 1.0
+
+
+def test_get_http_session_with_jitter():
+ session = get_http_session(retries=4, backoff_factor=0.5, backoff_jitter=0.2)
+ http_adapter = session.adapters.get("https://")
+ assert http_adapter.max_retries.total == 4
+ if hasattr(http_adapter.max_retries, "backoff_jitter"):
+ assert http_adapter.max_retries.backoff_jitter == 0.2
+
+
+def test_fetch_databus_jsonld_with_custom_session():
+ class MockResponse:
+ status_code = 200
+ text = '{"@context": "https://databus.dbpedia.org/context.jsonld"}'
+
+ def raise_for_status(self):
+ pass
+
+ class MockSession(requests.Session):
+ def get(self, url, headers=None, timeout=None):
+ assert timeout == 15
+ assert headers["Accept"] == "application/ld+json"
+ assert headers["X-API-KEY"] == "test_key"
+ return MockResponse()
+
+ session = MockSession()
+ result = fetch_databus_jsonld(
+ "https://databus.dbpedia.org/test",
+ databus_key="test_key",
+ session=session,
+ timeout=15,
+ )
+ assert result == '{"@context": "https://databus.dbpedia.org/context.jsonld"}'
+
+
+def test_cli_delete_force_and_retry_options(monkeypatch):
+ captured = {}
+
+ def fake_api_delete(**kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr("databusclient.cli.api_delete", fake_api_delete)
+
+ runner = CliRunner()
+ result = runner.invoke(
+ app,
+ [
+ "delete",
+ "https://databus.dbpedia.org/user/group/artifact/version",
+ "--databus-key",
+ "test-key",
+ "--force",
+ "--retries",
+ "5",
+ "--request-timeout",
+ "45",
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured["force"] is True
+ assert captured["timeout"] == 45
+ assert captured["session"].adapters["https://"].max_retries.total == 5
+
+
+def test_cli_delete_max_retries_alias(monkeypatch):
+ captured = {}
+
+ def fake_api_delete(**kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr("databusclient.cli.api_delete", fake_api_delete)
+
+ runner = CliRunner()
+ result = runner.invoke(
+ app,
+ [
+ "delete",
+ "https://databus.dbpedia.org/user/group/artifact/version",
+ "--databus-key",
+ "test-key",
+ "--force",
+ "--max-retries",
+ "7",
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured["session"].adapters["https://"].max_retries.total == 7
+
+
+def test_retry_local_server_503_twice_then_200():
+ import threading
+ from http.server import HTTPServer, BaseHTTPRequestHandler
+
+ class FlakyHandler(BaseHTTPRequestHandler):
+ attempts = 0
+
+ def do_GET(self):
+ FlakyHandler.attempts += 1
+ if FlakyHandler.attempts <= 2:
+ self.send_response(503)
+ self.end_headers()
+ self.wfile.write(b"Service Unavailable")
+ else:
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b"Success!")
+
+ def log_message(self, *args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), FlakyHandler)
+ port = server.server_port
+ t = threading.Thread(target=server.serve_forever)
+ t.daemon = True
+ t.start()
+
+ try:
+ session = get_http_session(retries=3, backoff_factor=0.01)
+ resp = session.get(f"http://127.0.0.1:{port}/")
+ assert resp.status_code == 200
+ assert resp.text == "Success!"
+ assert FlakyHandler.attempts == 3
+ finally:
+ server.shutdown()
+
+
+def test_retry_local_server_persistent_503_limit():
+ import threading
+ from http.server import HTTPServer, BaseHTTPRequestHandler
+
+ class Persistent503Handler(BaseHTTPRequestHandler):
+ attempts = 0
+
+ def do_GET(self):
+ Persistent503Handler.attempts += 1
+ self.send_response(503)
+ self.end_headers()
+ self.wfile.write(b"Service Unavailable")
+
+ def log_message(self, *args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), Persistent503Handler)
+ port = server.server_port
+ t = threading.Thread(target=server.serve_forever)
+ t.daemon = True
+ t.start()
+
+ try:
+ # retries=2: 1 initial attempt + 2 retries = 3 attempts total
+ session = get_http_session(retries=2, backoff_factor=0.01)
+ resp = session.get(f"http://127.0.0.1:{port}/")
+ assert resp.status_code == 503
+ assert Persistent503Handler.attempts == 3
+ finally:
+ server.shutdown()
+
+
+def test_file_stat_fetch_honors_retry_settings_when_checksum_omitted():
+ import hashlib
+ import threading
+ from http.server import HTTPServer, BaseHTTPRequestHandler
+ from databusclient.api.deploy import create_dataset
+
+ class FlakyFileHandler(BaseHTTPRequestHandler):
+ attempts = 0
+
+ def do_GET(self):
+ FlakyFileHandler.attempts += 1
+ if FlakyFileHandler.attempts == 1:
+ self.send_response(503)
+ self.end_headers()
+ self.wfile.write(b"Temporary Error")
+ else:
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b"data content for sha")
+
+ def log_message(self, *args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), FlakyFileHandler)
+ port = server.server_port
+ t = threading.Thread(target=server.serve_forever)
+ t.daemon = True
+ t.start()
+
+ try:
+ session = get_http_session(retries=2, backoff_factor=0.01)
+ # Distribution string without checksum or size:
+ dist_url = f"http://127.0.0.1:{port}/test.ttl"
+ dataset = create_dataset(
+ version_id="https://databus.dbpedia.org/user/group/artifact/2026-01-01",
+ artifact_version_title="Test Title",
+ artifact_version_abstract="Test Abstract",
+ artifact_version_description="Test Description",
+ license_url="https://example.org/license",
+ distributions=[dist_url],
+ session=session,
+ timeout=10,
+ )
+ assert FlakyFileHandler.attempts == 2
+ dist = dataset["@graph"][-1]["distribution"][0]
+ expected_sha = hashlib.sha256(b"data content for sha").hexdigest()
+ assert dist["sha256sum"] == expected_sha
+ assert dist["byteSize"] == len(b"data content for sha")
+ finally:
+ server.shutdown()