From 7e571f2ea6ced12b85308935ed470e5c4343bdd3 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:05:16 +0100 Subject: [PATCH 1/9] Retry API calls once on proxy 502/503, stop delivery on maintenance update_db (download) and add_file_db (upload) now retry once, after 1 s, when the API answers 502 or 503 without a JSON body. Such an answer comes from the proxy (Traefik), e.g. when the backend closed an idle connection, so the request did not reach the backend and a retry is safe. A 503 with a JSON body comes from dds_web (maintenance). It is raised as the new ServiceUnavailableError and is not retried. The delivery stops: - the failing file is marked as failed and saved in the failed delivery log as before, so retry_add_file_db can still add uploaded files - files not started yet are cancelled (same flag as Ctrl+C) - files already running finish their current step - the error is raised once from the main thread after the workers are done, and the command exits with 1 update_db now also catches ApiResponseError, so a failed update does not stop the other downloads. Changes: - utils: perform_request_with_retry(), backend 503 -> ServiceUnavailableError - constants: API_TRANSIENT_STATUS_CODES, API_RETRY_WAIT - base: stop_for_maintenance(), raise_if_service_unavailable() - custom_decorators: cancel message says "Service unavailable" on maintenance - tests/test_api_retry.py: mocked 502/503/500/400 and maintenance cases --- dds_cli/__main__.py | 3 + dds_cli/base.py | 20 +++ dds_cli/constants.py | 9 + dds_cli/custom_decorators.py | 7 +- dds_cli/data_getter.py | 15 +- dds_cli/data_putter.py | 11 +- dds_cli/exceptions.py | 7 + dds_cli/utils.py | 41 +++++ tests/test_api_retry.py | 309 +++++++++++++++++++++++++++++++++++ 9 files changed, 417 insertions(+), 5 deletions(-) create mode 100644 tests/test_api_retry.py diff --git a/dds_cli/__main__.py b/dds_cli/__main__.py index 1aca90c6b..f28fadcd7 100644 --- a/dds_cli/__main__.py +++ b/dds_cli/__main__.py @@ -1922,6 +1922,9 @@ def get_data( progress=progress, ) ] = next_file + + # Maintenance stopped the download: exit with the error + getter.raise_if_service_unavailable() except ( dds_cli.exceptions.InvalidMethodError, OSError, diff --git a/dds_cli/base.py b/dds_cli/base.py index 74dfd73da..806aede77 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -62,6 +62,8 @@ def __init__( # Keyboardinterrupt self.stop_doing = False + # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' + self.service_unavailable = None # Authenticate the user and get the token if authenticate: @@ -117,6 +119,24 @@ def __exit__(self, exception_type, exception_value, traceback, max_fileerrs: int # Public methods ############################### Public methods # + def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: + """Stop the delivery because the DDS backend is unavailable (e.g. maintenance). + + Called from the worker threads. Files not yet started are cancelled (same flag + as Ctrl+C), ongoing files finish their current step. The caller marks its own + file as failed, so it is saved in the failed delivery log as usual. + Call 'raise_if_service_unavailable' after the threads are done. + """ + if self.service_unavailable is None: + self.service_unavailable = err + LOG.error("%s. Stopping: files not started yet are cancelled.", err) + self.stop_doing = True + + def raise_if_service_unavailable(self) -> None: + """Raise the error saved by 'stop_for_maintenance', if any.""" + if self.service_unavailable is not None: + raise self.service_unavailable + def set_token(self, token_dict: dict) -> None: """Sets the token for the base class. Called from auth class to set the token when authenticating diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 538f0d218..0cc5e2263 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -6,6 +6,13 @@ TODO: Move other constants here from __init__.py. """ +# Retry once on these API status codes, but only if the answer came from the proxy +# (Traefik, no JSON body). A 502 there usually means the backend closed an idle +# connection, i.e. the request did not reach the backend, so a retry is safe. +# A 503 from the DDS backend (maintenance) is never retried. +API_TRANSIENT_STATUS_CODES = (502, 503) +API_RETRY_WAIT = 1 # seconds + # Timeout settings for upload and download READ_TIMEOUT = 300 CONNECT_TIMEOUT = 60 @@ -17,6 +24,8 @@ # Import these constants when using '*' __all__ = [ + "API_TRANSIENT_STATUS_CODES", + "API_RETRY_WAIT", "READ_TIMEOUT", "CONNECT_TIMEOUT", "DOWNLOAD_MAX_RETRIES", diff --git a/dds_cli/custom_decorators.py b/dds_cli/custom_decorators.py index a26048fa3..e0556abc8 100644 --- a/dds_cli/custom_decorators.py +++ b/dds_cli/custom_decorators.py @@ -40,7 +40,12 @@ def wrapped(self, file, *args, **kwargs): # Check if keyboardinterrupt in dds if self.stop_doing: # TODO (ina): Add save to status here - message = f"KeyboardInterrupt - cancelling file {escape(file)}" + reason = ( + "Service unavailable" + if getattr(self, "service_unavailable", None) + else "KeyboardInterrupt" + ) + message = f"{reason} - cancelling file {escape(file)}" LOG.warning(message) return False # Do not proceed diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 3df12826a..cd30825fe 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -387,9 +387,11 @@ def update_db(self, file): filename = {"name": fileinfo["name_in_db"]} params = {"project": self.project} - # Send file info to API + # Send file info to API. + # Catch all API errors: a failed update must not stop the other downloads. + # Exception: maintenance (ServiceUnavailableError) stops the files not started yet. try: - response_json, _ = dds_cli.utils.perform_request( + response_json, _ = dds_cli.utils.perform_request_with_retry( DDSEndpoint.FILE_UPDATE, method="put", params=params, @@ -397,7 +399,14 @@ def update_db(self, file): headers=self.token, error_message="Failed to update file information", ) - except dds_cli.exceptions.ApiRequestError as err: + except dds_cli.exceptions.ServiceUnavailableError as err: + self.stop_for_maintenance(err) + message = str(err) + except ( + dds_cli.exceptions.ApiRequestError, + dds_cli.exceptions.ApiResponseError, + dds_cli.exceptions.DDSCLIException, + ) as err: updated_in_db = False message = str(err) else: diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index e3ab3a2fe..7c9c9ecbf 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -191,6 +191,9 @@ def put( # Single project metadata refresh after batch (date_updated / last_updated_by) putter.touch_project_after_upload() + # Maintenance stopped the upload: exit with the error + putter.raise_if_service_unavailable() + ############################################################################### # CLASSES ########################################################### CLASSES # @@ -453,7 +456,8 @@ def add_file_db(self, file): # Send file info to API - post if new file, put if overwrite request_method = "put" if fileinfo["overwrite"] else "post" try: - response_json, _ = dds_cli.utils.perform_request( + # Retry once on 502/503 before we fall back to 'retry_add_file_db' at the end. + response_json, _ = dds_cli.utils.perform_request_with_retry( DDSEndpoint.FILE_NEW, method=request_method, params=params, @@ -465,6 +469,11 @@ def add_file_db(self, file): LOG.debug("API call for file '%s: Adding to database'", fileinfo["path_raw"]) with self._db_add_lock: self.any_successful_db_add = True + except dds_cli.exceptions.ServiceUnavailableError as err: + # Maintenance: stop the upload. Don't raise here: this file is in the bucket, + # so it must be saved in the failed delivery log ('add_file_db' failed). + self.stop_for_maintenance(err) + message = str(err) except ( dds_cli.exceptions.ApiRequestError, dds_cli.exceptions.ApiResponseError, diff --git a/dds_cli/exceptions.py b/dds_cli/exceptions.py index 43ed664fc..b53d8ad82 100644 --- a/dds_cli/exceptions.py +++ b/dds_cli/exceptions.py @@ -44,6 +44,13 @@ def __str__(self): return msg +class ServiceUnavailableError(DDSCLIException): + """The DDS backend answered 503 Service Unavailable, e.g. because maintenance is ongoing. + + Ongoing deliveries must stop: this is not retried and not ignored. + """ + + class AuthenticationError(click.ClickException): """Errors due to user authentication.""" diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 2751d7e81..336a42696 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -6,6 +6,7 @@ import http from typing import Dict, List, Union import logging +import time from datetime import datetime import requests @@ -19,6 +20,9 @@ import dds_cli.exceptions from dds_cli import __version__, DDSEndpoint +from dds_cli import constants + +LOG = logging.getLogger(__name__) console = rich.console.Console() stderr_console = rich.console.Console(stderr=True) @@ -298,6 +302,14 @@ def transform_paths(json_input): message=message, status_code=response.status_code ) + # Handle 503 from the DDS backend itself, e.g. maintenance. + # (A 503 from the proxy has no JSON body and is raised as ApiResponseError above.) + if response.status_code == http.HTTPStatus.SERVICE_UNAVAILABLE: + raise dds_cli.exceptions.ServiceUnavailableError( + message=f"{message}: {response_json.get('message', 'Service unavailable')}", + status_code=response.status_code, + ) + raise dds_cli.exceptions.DDSCLIException( message=f"{message}: {response_json.get('message', 'Unexpected error!')}", status_code=response.status_code, @@ -306,6 +318,35 @@ def transform_paths(json_input): return response_json, additional_errors +def perform_request_with_retry(*args, retries: int = 1, **kwargs): + """Same as perform_request, but retry on a transient error from the proxy (502, 503). + + A 502 from Traefik usually means that the backend closed an idle keep-alive + connection just before the request was sent. The request did not reach the + backend, so it is safe to send it again. + + Only answers without a JSON body are retried (raised as ApiResponseError), i.e. + answers from the proxy. A 503 from the DDS backend (maintenance) has a JSON body, + is raised as ServiceUnavailableError and is not retried. + """ + for attempt in range(retries + 1): + try: + return perform_request(*args, **kwargs) + except dds_cli.exceptions.ApiResponseError as err: + status_code = getattr(err, "status_code", None) + if status_code not in constants.API_TRANSIENT_STATUS_CODES or attempt >= retries: + raise + LOG.warning( + "API request failed with status %s, retrying in %ss: %s", + status_code, + constants.API_RETRY_WAIT, + err, + ) + time.sleep(constants.API_RETRY_WAIT) + # Not reached: the last attempt either returns or raises. + raise RuntimeError("perform_request_with_retry: no attempts made") + + def parse_project_errors(errors): """Parse all errors related to projects.""" msg = "" diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py new file mode 100644 index 000000000..c509a3ece --- /dev/null +++ b/tests/test_api_retry.py @@ -0,0 +1,309 @@ +"""Tests for retrying API requests on 502/503 (update_db, add_file_db).""" + +# IMPORTS ###################################################################### + +import pathlib +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +import dds_cli.exceptions +import dds_cli.utils +from dds_cli import constants +from dds_cli.data_getter import DataGetter +from dds_cli.data_putter import DataPutter + +# HELPERS ###################################################################### + + +def _prepare_data_getter(file_name): + """DataGetter with one file, without running __init__.""" + getter = DataGetter.__new__(DataGetter) + getter.filehandler = SimpleNamespace( + data={file_name: {"name_in_db": file_name, "path_downloaded": pathlib.Path(file_name)}} + ) + return getter + + +def _api_response(status_code, json_body=None): + """Mock API response. Without json_body, .json() fails like the 11-byte 'Bad Gateway'.""" + import simplejson + + response = MagicMock() + response.status_code = status_code + response.ok = status_code < 400 + response.reason = "Bad Gateway" if status_code == 502 else "OK" + if json_body is None: + response.json.side_effect = simplejson.JSONDecodeError("Expecting value", "Bad Gateway", 0) + else: + response.json.return_value = json_body + return response + + +def _update_db_getter(): + getter = _prepare_data_getter("file.bin") + getter.project = "proj00001" + getter.token = {"Authorization": "Bearer x"} + getter.stop_doing = False + getter.service_unavailable = None + return getter + + +# TESTS ######################################################################## + + +def test_update_db_retries_once_on_502(monkeypatch): + """A 502 from the proxy is retried once, and the second try succeeds.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(200, {"message": "File info updated."})]) + mock_put = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert (updated, message) == (True, "File info updated.") + assert mock_put.call_count == 2 + + +def test_update_db_502_does_not_raise(monkeypatch): + """Two 502s in a row: report the failure, but never stop the whole download.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(side_effect=lambda **_: _api_response(502)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert updated is False + assert "502" in message + assert mock_put.call_count == 2 + + +def test_update_db_no_retry_on_500(monkeypatch): + """A 500 comes from the backend itself, so it is not retried (but still caught).""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(side_effect=lambda **_: _api_response(500, {"message": "Something broke"})) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert updated is False + assert "Something broke" in message + assert mock_put.call_count == 1 + + +def _putter_with_one_file(): + import threading + from types import SimpleNamespace + + putter = DataPutter.__new__(DataPutter) + putter.project = "proj00001" + putter.token = {"Authorization": "Bearer x"} + putter._db_add_lock = threading.Lock() + putter.any_successful_db_add = False + putter.stop_doing = False + putter.service_unavailable = None + putter.filehandler = SimpleNamespace( + data={ + "file.txt": { + "path_remote": "bucketname", + "subpath": ".", + "size_raw": 4, + "size_processed": 40, + "compressed": False, + "salt": "salt", + "public_key": "key", + "checksum": "abc", + "overwrite": False, + "path_raw": "file.txt", + } + } + ) + return putter + + +def test_add_file_db_retries_once_on_502(monkeypatch): + """POST /file/new that gets a 502 is sent once more right away.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(200, {"message": "File added"})]) + mock_post = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is True + assert putter.any_successful_db_add is True + assert mock_post.call_count == 2 + + +def test_add_file_db_gives_up_after_second_502(monkeypatch): + """Two 502s: return False, so the file is handled by retry_add_file_db at the end.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_post = MagicMock(side_effect=lambda **_: _api_response(502)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + added, message = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert "502" in message + assert mock_post.call_count == 2 + + +def test_add_file_db_no_retry_on_400(monkeypatch): + """A 400 (e.g. file already exists) is not a proxy error and is not retried.""" + mock_post = MagicMock( + side_effect=lambda **_: _api_response(400, {"message": "File already exists"}) + ) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + added, _ = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert mock_post.call_count == 1 + + +def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): + """The last error is raised when all attempts fail.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + err = dds_cli.exceptions.ApiResponseError("Bad Gateway", status_code=502) + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiResponseError): + dds_cli.utils.perform_request_with_retry("url", method="put", retries=2) + + assert mock_request.call_count == 3 + + +def test_perform_request_with_retry_no_retry_on_request_error(monkeypatch): + """A connection error is not retried here (the request may have reached the backend).""" + err = dds_cli.exceptions.ApiRequestError("timeout") + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiRequestError): + dds_cli.utils.perform_request_with_retry("url", method="post") + + assert mock_request.call_count == 1 + + +# MAINTENANCE (503 FROM THE DDS BACKEND) ####################################### + +MAINTENANCE = {"message": "Maintenance of DDS is ongoing."} + + +def test_perform_request_backend_503_is_service_unavailable(monkeypatch): + """A 503 with a JSON body comes from dds_web (maintenance) -> ServiceUnavailableError.""" + monkeypatch.setattr( + "dds_cli.utils.requests.put", MagicMock(return_value=_api_response(503, MAINTENANCE)) + ) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError, match="Maintenance") as err: + dds_cli.utils.perform_request("url", method="put") + + # Still a DDSCLIException, so existing callers behave as before. + assert isinstance(err.value, dds_cli.exceptions.DDSCLIException) + assert err.value.status_code == 503 + + +def test_retry_skips_backend_503(monkeypatch): + """Maintenance is not retried.""" + mock_put = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError): + dds_cli.utils.perform_request_with_retry("url", method="put") + + assert mock_put.call_count == 1 + + +def test_retry_proxy_503(monkeypatch): + """A 503 without a JSON body comes from the proxy and is retried once.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(503), _api_response(200, {"message": "ok"})]) + mock_put = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + response_json, _ = dds_cli.utils.perform_request_with_retry("url", method="put") + + assert response_json == {"message": "ok"} + assert mock_put.call_count == 2 + + +def test_update_db_stops_download_on_maintenance(monkeypatch): + """update_db on maintenance: no retry, returns failure and stops the files not started.""" + mock_put = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + getter = _update_db_getter() + updated, message = DataGetter.update_db.__wrapped__(getter, file="file.bin") + + assert updated is False + assert "Maintenance" in message + assert mock_put.call_count == 1 + assert getter.stop_doing is True + assert isinstance(getter.service_unavailable, dds_cli.exceptions.ServiceUnavailableError) + + +def test_add_file_db_stops_upload_on_maintenance(monkeypatch): + """add_file_db on maintenance: no retry, returns failure and stops the files not started.""" + mock_post = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + putter = _putter_with_one_file() + added, message = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + assert "Maintenance" in message + assert mock_post.call_count == 1 + assert putter.any_successful_db_add is False + assert putter.stop_doing is True + assert isinstance(putter.service_unavailable, dds_cli.exceptions.ServiceUnavailableError) + + +def test_add_file_db_maintenance_marks_failed_op(monkeypatch): + """The file is in the bucket: it must get failed_op 'add_file_db', so it is saved in the + failed delivery log and 'retry_add_file_db' can add it later.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", MagicMock(return_value=_api_response(503, MAINTENANCE)) + ) + putter = _putter_with_one_file() + putter.status = {"file.txt": {"add_file_db": {"started": False, "done": False}}} + + added, _ = DataPutter.add_file_db(putter, file="file.txt") # with @update_status + + assert added is False + assert putter.status["file.txt"]["failed_op"] == "add_file_db" + + +def test_verify_proceed_cancels_new_files_on_maintenance(caplog): + """After maintenance is seen, files not started yet are not started.""" + from dds_cli.custom_decorators import verify_proceed + + called = MagicMock(return_value=(True, "")) + + @verify_proceed + def work(self, file): + return called(file) + + putter = _putter_with_one_file() + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + assert work(putter, "file.txt") is False + called.assert_not_called() + assert "Service unavailable - cancelling file" in caplog.text + + +def test_stop_for_maintenance_keeps_first_error_and_raises_later(): + """The error is raised once, from the main thread, after the workers are done.""" + putter = _putter_with_one_file() + putter.raise_if_service_unavailable() # nothing saved: no error + + first = dds_cli.exceptions.ServiceUnavailableError("first") + putter.stop_for_maintenance(first) + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("second")) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError) as err: + putter.raise_if_service_unavailable() + assert err.value is first From b8471b41e882e2609acfbe8c0b183afb53973098 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:10:50 +0100 Subject: [PATCH 2/9] Stop running transfers when maintenance is detected When another thread has seen a backend 503 (maintenance): - running downloads stop at the next chunk, the partial file is removed and no retry is made - no new download attempt is started - an upload that has finished encryption is not sent to S3, so no orphan object is left in the bucket (failed_op "put") An S3 upload that has already started is finished. If add_file_db then fails, the file is in the failed delivery log as before. Ctrl+C behaviour is unchanged. --- dds_cli/base.py | 11 +++-- dds_cli/data_getter.py | 18 +++++++- dds_cli/data_putter.py | 9 +++- tests/test_api_retry.py | 95 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 6 deletions(-) diff --git a/dds_cli/base.py b/dds_cli/base.py index 806aede77..bb7b408ac 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -40,6 +40,9 @@ class DDSBaseClass: """Data Delivery System base class. For common operations.""" + # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' + service_unavailable: typing.Optional[exceptions.ServiceUnavailableError] = None + def __init__( self, project=None, @@ -62,8 +65,6 @@ def __init__( # Keyboardinterrupt self.stop_doing = False - # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' - self.service_unavailable = None # Authenticate the user and get the token if authenticate: @@ -123,8 +124,10 @@ def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: """Stop the delivery because the DDS backend is unavailable (e.g. maintenance). Called from the worker threads. Files not yet started are cancelled (same flag - as Ctrl+C), ongoing files finish their current step. The caller marks its own - file as failed, so it is saved in the failed delivery log as usual. + as Ctrl+C). Ongoing downloads stop at the next chunk, ongoing uploads stop + before the S3 upload; an S3 upload that has already started is finished. + The caller marks its own file as failed, so it is saved in the failed + delivery log as usual. Call 'raise_if_service_unavailable' after the threads are done. """ if self.service_unavailable is None: diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index cd30825fe..588f239ea 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -257,9 +257,14 @@ def get(self, file, progress, task): backoff_factor = constants.DOWNLOAD_BACKOFF_FACTOR wait = constants.DOWNLOAD_INITIAL_WAIT retry_messages = [] + cancelled = False for attempt in range(1, max_retries + 1): error = "" + if self.service_unavailable: + # Maintenance seen by another thread: don't start a new attempt. + cancelled = True + break if attempt > 1: progress.reset(task, completed=0) # Drop the partial file from the previous attempt before retrying. @@ -287,10 +292,17 @@ def get(self, file, progress, task): content_length = 0 with file_local.open(mode="wb") as new_file: for chunk in req.iter_content(chunk_size=FileSegment.SEGMENT_SIZE_CIPHER): + if self.service_unavailable: + # Maintenance seen by another thread: stop this download. + cancelled = True + break progress.update(task, advance=len(chunk)) new_file.write(chunk) bytes_written += len(chunk) + if cancelled: + break + # Guard against silent truncation: requests/urllib3 do not # validate that bytes received == Content-Length. A clean TCP # FIN mid-stream otherwise looks like an EOF and the loop exits @@ -340,7 +352,11 @@ def get(self, file, progress, task): ) break - if not downloaded and error: + if cancelled: + error = f"Service unavailable - download of '{file_name_in_db}' cancelled" + LOG.warning(error) + self._remove_partial(file_local, file_name_in_db) + elif not downloaded and error: if retry_messages: error = " | ".join(retry_messages) + f" | Final error: {error}" LOG.error( diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index 7c9c9ecbf..4c53799cc 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -344,7 +344,14 @@ def protect_and_upload(self, file, progress): file_info["path_processed"].stat().st_size, ) - if saved: + if saved and self.service_unavailable: + # Maintenance seen by another thread: don't upload. The file could not be + # added to the database, so it would only be an orphan object in the bucket. + message = f"Service unavailable - upload of '{file_path_raw}' cancelled" + LOG.warning(message) + self.status[file]["failed_op"] = "put" + dr.DataRemover.delete_tempfile(file=file_info["path_processed"]) + elif saved: LOG.debug( "File successfully encrypted: '%s'", file_path_raw, diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index c509a3ece..a43527158 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -307,3 +307,98 @@ def test_stop_for_maintenance_keeps_first_error_and_raises_later(): with pytest.raises(dds_cli.exceptions.ServiceUnavailableError) as err: putter.raise_if_service_unavailable() assert err.value is first + + +# IN-FLIGHT FILES ON MAINTENANCE ############################################### + + +def _download_response(chunks): + response = MagicMock() + response.__enter__.return_value = response + response.__exit__.return_value = False + response.iter_content.return_value = chunks + response.raise_for_status.return_value = None + response.headers.get.return_value = 8 + return response + + +def _getter_for_download(tmp_path): + getter = _update_db_getter() + getter.filehandler.data["file.bin"].update( + {"path_downloaded": tmp_path / "file.bin", "url": "https://example.com/f", "size_stored": 8} + ) + return getter + + +def test_get_stops_running_download_on_maintenance(monkeypatch, tmp_path, caplog): + """Maintenance seen by another thread stops a running download at the next chunk.""" + getter = _getter_for_download(tmp_path) + + def chunks(): + yield b"data" + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + yield b"more" + + mock_get = MagicMock(return_value=_download_response(chunks())) + monkeypatch.setattr("dds_cli.data_getter.requests.get", mock_get) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert "Service unavailable" in message + assert mock_get.call_count == 1 # no retry + assert not (tmp_path / "file.bin").exists() # partial file removed + assert "could not be completed" not in caplog.text # no network advice + + +def test_get_not_started_on_maintenance(monkeypatch, tmp_path): + """No GET is sent once maintenance is known.""" + getter = _getter_for_download(tmp_path) + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + mock_get = MagicMock() + monkeypatch.setattr("dds_cli.data_getter.requests.get", mock_get) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert "Service unavailable" in message + mock_get.assert_not_called() + + +def test_upload_skips_s3_put_on_maintenance(monkeypatch, tmp_path): + """A file encrypted after maintenance is known is not uploaded (no orphan object).""" + processed = tmp_path / "file.txt.ccp" + processed.write_bytes(b"encrypted") + + putter = _putter_with_one_file() + putter.filehandler.data["file.txt"]["path_processed"] = processed + putter.filehandler.stream_from_file = MagicMock() + putter.keys = None + putter.silent = True + putter.method = "put" + putter.status = {"file.txt": {}} + putter.put = MagicMock() + putter.add_file_db = MagicMock() + + encryptor = MagicMock() + encryptor.encrypt_filechunks.return_value = (True, "") + encryptor_cm = MagicMock() + encryptor_cm.__enter__.return_value = encryptor + monkeypatch.setattr("dds_cli.data_putter.fe.Encryptor", MagicMock(return_value=encryptor_cm)) + + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + # Skip @verify_proceed (stop_doing would cancel before encryption) and @subpath_required + ok, message = DataPutter.protect_and_upload.__wrapped__.__wrapped__( + putter, file="file.txt", progress=MagicMock() + ) + + assert ok is False + assert "Service unavailable" in message + putter.put.assert_not_called() + putter.add_file_db.assert_not_called() + assert putter.status["file.txt"]["failed_op"] == "put" + assert not processed.exists() From 966e1df70da6fce282163f54ce33839ded423fc4 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:16:09 +0100 Subject: [PATCH 3/9] Detect a POST file/new that reached the backend before a proxy 502 A proxy 502/503 does not always mean that the backend did not get the request. If the first POST added the file, the retry fails because the file exists (500 from dds_web) and the file was reported as failed, although S3 and the database were fine. After a failed POST, ask file/match: if the file is in the database with the name_in_bucket of this upload, it was added by our own request and is treated as added. PUT (overwrite) is not checked. --- dds_cli/data_putter.py | 38 ++++++++++++++++++++- tests/test_api_retry.py | 75 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index 4c53799cc..b2d4b7069 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -487,10 +487,46 @@ def add_file_db(self, file): dds_cli.exceptions.DDSCLIException, ) as err: message = str(err) - LOG.warning(message) + if request_method == "post" and self._added_by_earlier_request(file=file): + # The first POST got a proxy 502/503 but did reach the backend, so the + # retry failed because the file already exists. The file is added. + added_to_db, message = (True, f"File '{file}' added to db.") + with self._db_add_lock: + self.any_successful_db_add = True + else: + LOG.warning(message) return added_to_db, message + def _added_by_earlier_request(self, file) -> bool: + """Check if the file is in the database with the name in bucket of this upload. + + 'name_in_bucket' is new for each upload, so a match means that one of our own + requests added the file. Any error here: return False (the file stays failed). + """ + try: + response_json, _ = dds_cli.utils.perform_request( + DDSEndpoint.FILE_MATCH, + method="get", + params={"project": self.project}, + headers=self.token, + json=[file], + error_message="Failed to check if the file is in the database", + ) + except ( + dds_cli.exceptions.ApiRequestError, + dds_cli.exceptions.ApiResponseError, + dds_cli.exceptions.DDSCLIException, + ) as err: + LOG.debug("Could not check if '%s' is in the database: %s", escape(file), err) + return False + + files_in_db = response_json.get("files") or {} + added = files_in_db.get(file) == self.filehandler.data[file]["path_remote"] + if added: + LOG.info("File '%s' was added to the database by an earlier request.", escape(file)) + return added + def retry_add_file_db(self): """Attempting to save the files to the database. diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index a43527158..636129f5f 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -53,6 +53,14 @@ def _update_db_getter(): # TESTS ######################################################################## +@pytest.fixture(autouse=True) +def file_match_empty(monkeypatch): + """GET file/match (used after a failed POST file/new): no files in the database.""" + mock_get = MagicMock(return_value=_api_response(200, {"files": None})) + monkeypatch.setattr("dds_cli.utils.requests.get", mock_get) + return mock_get + + def test_update_db_retries_once_on_502(monkeypatch): """A 502 from the proxy is retried once, and the second try succeeds.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) @@ -402,3 +410,70 @@ def test_upload_skips_s3_put_on_maintenance(monkeypatch, tmp_path): putter.add_file_db.assert_not_called() assert putter.status["file.txt"]["failed_op"] == "put" assert not processed.exists() + + +# POST REACHED THE BACKEND BUT THE CLIENT GOT A 502 ############################ + +FILE_EXISTS_500 = {"message": "Internal Server Error"} # FileExistsError is not handled + + +def test_add_file_db_502_then_exists_is_added(monkeypatch, file_match_empty): + """First POST added the row but the client got a 502; the retry fails because the + file exists. file/match shows our name_in_bucket, so the file is added.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(500, FILE_EXISTS_500)]) + mock_post = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + file_match_empty.return_value = _api_response(200, {"files": {"file.txt": "bucketname"}}) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is True + assert putter.any_successful_db_add is True + assert mock_post.call_count == 2 + assert file_match_empty.call_args.kwargs["json"] == ["file.txt"] + + +def test_add_file_db_exists_with_other_name_in_bucket_fails(monkeypatch, file_match_empty): + """The file is in the database, but from another upload: still a failure.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + file_match_empty.return_value = _api_response(200, {"files": {"file.txt": "other"}}) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + assert putter.any_successful_db_add is False + + +def test_add_file_db_match_check_fails(monkeypatch, file_match_empty): + """If file/match fails too, the file stays failed with the original error.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + file_match_empty.return_value = _api_response(502) + + added, message = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert "Internal Server Error" in message + + +def test_add_file_db_put_is_not_checked(monkeypatch, file_match_empty): + """Overwrite (PUT): the file was in the database before, so file/match tells nothing.""" + monkeypatch.setattr( + "dds_cli.utils.requests.put", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + putter = _putter_with_one_file() + putter.filehandler.data["file.txt"]["overwrite"] = True + + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + file_match_empty.assert_not_called() From 91ece164d67e290b7838fbc027985fb018954810 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:28:11 +0100 Subject: [PATCH 4/9] Make the API retry rule explicit: no JSON body and 502/503 An answer without a JSON body is now raised as NonJsonResponseError (subclass of ApiResponseError, so existing callers are not affected). perform_request_with_retry retries only this error, and only for the status codes in API_NON_JSON_RETRY_STATUS_CODES (renamed from API_TRANSIENT_STATUS_CODES). Before, the rule depended on which exception type perform_request happened to raise: any ApiResponseError with status 502/503 would have been retried, while a 503 from the DDS API (maintenance) must never be. --- dds_cli/constants.py | 14 ++++++++------ dds_cli/exceptions.py | 7 +++++++ dds_cli/utils.py | 18 ++++++++++-------- tests/test_api_retry.py | 37 ++++++++++++++++++++++++++++++++++++- 4 files changed, 61 insertions(+), 15 deletions(-) diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 0cc5e2263..f7d708a1f 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -6,11 +6,13 @@ TODO: Move other constants here from __init__.py. """ -# Retry once on these API status codes, but only if the answer came from the proxy -# (Traefik, no JSON body). A 502 there usually means the backend closed an idle -# connection, i.e. the request did not reach the backend, so a retry is safe. -# A 503 from the DDS backend (maintenance) is never retried. -API_TRANSIENT_STATUS_CODES = (502, 503) +# perform_request_with_retry retries once on an answer with one of these status codes +# AND without a JSON body (NonJsonResponseError). Such an answer comes from the proxy +# (Traefik), not from the DDS API: a 502 there usually means the backend closed an idle +# connection, i.e. the request did not reach the backend. +# The status code alone is not enough: a 503 WITH a JSON body comes from the DDS API +# (maintenance, ServiceUnavailableError) and must never be retried. +API_NON_JSON_RETRY_STATUS_CODES = (502, 503) API_RETRY_WAIT = 1 # seconds # Timeout settings for upload and download @@ -24,7 +26,7 @@ # Import these constants when using '*' __all__ = [ - "API_TRANSIENT_STATUS_CODES", + "API_NON_JSON_RETRY_STATUS_CODES", "API_RETRY_WAIT", "READ_TIMEOUT", "CONNECT_TIMEOUT", diff --git a/dds_cli/exceptions.py b/dds_cli/exceptions.py index b53d8ad82..b195ed35c 100644 --- a/dds_cli/exceptions.py +++ b/dds_cli/exceptions.py @@ -106,6 +106,13 @@ def __init__(self, message, status_code=None): super().__init__(message) +class NonJsonResponseError(ApiResponseError): + """The answer has no valid JSON body, so it did not come from the DDS API. + + Usually an error page from the proxy (Traefik), e.g. 502 Bad Gateway. + """ + + class UploadError(Exception): """Errors relating to file uploads.""" diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 336a42696..9ec51cfec 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -243,7 +243,7 @@ def transform_paths(json_input): ) response_json = response.json() except simplejson.JSONDecodeError as err: - raise dds_cli.exceptions.ApiResponseError( + raise dds_cli.exceptions.NonJsonResponseError( message=( f"Response code: {response.status_code}. " f"The request did not return a valid JSON response. Details: {err}" @@ -303,7 +303,7 @@ def transform_paths(json_input): ) # Handle 503 from the DDS backend itself, e.g. maintenance. - # (A 503 from the proxy has no JSON body and is raised as ApiResponseError above.) + # (A 503 from the proxy has no JSON body and is raised as NonJsonResponseError above.) if response.status_code == http.HTTPStatus.SERVICE_UNAVAILABLE: raise dds_cli.exceptions.ServiceUnavailableError( message=f"{message}: {response_json.get('message', 'Service unavailable')}", @@ -319,22 +319,24 @@ def transform_paths(json_input): def perform_request_with_retry(*args, retries: int = 1, **kwargs): - """Same as perform_request, but retry on a transient error from the proxy (502, 503). + """Same as perform_request, but retry on a 502/503 from the proxy. A 502 from Traefik usually means that the backend closed an idle keep-alive connection just before the request was sent. The request did not reach the backend, so it is safe to send it again. - Only answers without a JSON body are retried (raised as ApiResponseError), i.e. - answers from the proxy. A 503 from the DDS backend (maintenance) has a JSON body, - is raised as ServiceUnavailableError and is not retried. + Both conditions are needed for a retry: + - the answer has no JSON body (NonJsonResponseError), i.e. it is from the proxy + - the status code is in API_NON_JSON_RETRY_STATUS_CODES + A 503 from the DDS API (maintenance) has a JSON body, is raised as + ServiceUnavailableError and is never retried. """ for attempt in range(retries + 1): try: return perform_request(*args, **kwargs) - except dds_cli.exceptions.ApiResponseError as err: + except dds_cli.exceptions.NonJsonResponseError as err: status_code = getattr(err, "status_code", None) - if status_code not in constants.API_TRANSIENT_STATUS_CODES or attempt >= retries: + if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES or attempt >= retries: raise LOG.warning( "API request failed with status %s, retrying in %ss: %s", diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 636129f5f..27f43668f 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -174,7 +174,7 @@ def test_add_file_db_no_retry_on_400(monkeypatch): def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): """The last error is raised when all attempts fail.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) - err = dds_cli.exceptions.ApiResponseError("Bad Gateway", status_code=502) + err = dds_cli.exceptions.NonJsonResponseError("Bad Gateway", status_code=502) mock_request = MagicMock(side_effect=err) monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) @@ -477,3 +477,38 @@ def test_add_file_db_put_is_not_checked(monkeypatch, file_match_empty): assert added is False file_match_empty.assert_not_called() + + +# THE RETRY NEEDS BOTH: NO JSON BODY AND 502/503 ############################### + + +def test_no_json_body_is_non_json_response_error(monkeypatch): + """An answer without a JSON body is NonJsonResponseError (still an ApiResponseError).""" + monkeypatch.setattr("dds_cli.utils.requests.put", MagicMock(return_value=_api_response(502))) + with pytest.raises(dds_cli.exceptions.NonJsonResponseError) as err: + dds_cli.utils.perform_request("https://x/file/update", method="put", headers={}) + assert isinstance(err.value, dds_cli.exceptions.ApiResponseError) + assert err.value.status_code == 502 + + +def test_retry_skips_json_502(monkeypatch): + """A 502 WITH a JSON body comes from the DDS API: not retried.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(return_value=_api_response(502, {"message": "from the API"})) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + with pytest.raises(dds_cli.exceptions.DDSCLIException): + dds_cli.utils.perform_request_with_retry("https://x/file/update", method="put", headers={}) + assert mock_put.call_count == 1 + + +def test_retry_skips_api_response_error_with_502_status(monkeypatch): + """Only NonJsonResponseError is retried, not any ApiResponseError with status 502.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + err = dds_cli.exceptions.ApiResponseError("JSON error", status_code=502) + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr("dds_cli.utils.perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiResponseError): + dds_cli.utils.perform_request_with_retry("https://x", method="put", headers={}) + assert mock_request.call_count == 1 From c5b927e7aa930364c71df6e238cbd7b43eb4cef3 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:39:07 +0100 Subject: [PATCH 5/9] Skip the end-of-batch DB calls when maintenance stopped the upload If maintenance (backend 503) stopped the upload, put() no longer calls retry_add_file_db and touch_project_after_upload: the API is down and these calls only add more 503 errors. The path to the failed delivery log is still shown, then the maintenance error is raised. --- dds_cli/data_putter.py | 12 ++++++--- tests/test_api_retry.py | 59 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index b2d4b7069..a654d3cc8 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -169,6 +169,15 @@ def put( for x in [y.id for y in progress.tasks if y.fields.get("step") != "put"] ] + # Maintenance stopped the upload: the API is down, don't call it again. + if putter.service_unavailable is not None: + if putter.failed_delivery_log.is_file(): + LOG.warning( + "The files that failed are listed in: %s", + str(putter.failed_delivery_log), + ) + putter.raise_if_service_unavailable() + # Make a single database update for files that have failed # Json file for failed files should only be created if there has been an error if putter.failed_delivery_log.is_file(): @@ -191,9 +200,6 @@ def put( # Single project metadata refresh after batch (date_updated / last_updated_by) putter.touch_project_after_upload() - # Maintenance stopped the upload: exit with the error - putter.raise_if_service_unavailable() - ############################################################################### # CLASSES ########################################################### CLASSES # diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 27f43668f..71f3f7d1b 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -512,3 +512,62 @@ def test_retry_skips_api_response_error_with_502_status(monkeypatch): with pytest.raises(dds_cli.exceptions.ApiResponseError): dds_cli.utils.perform_request_with_retry("https://x", method="put", headers={}) assert mock_request.call_count == 1 + + +# END OF UPLOAD BATCH ########################################################## + + +def _run_put_with(monkeypatch, putter): + """Run data_putter.put() with a mocked DataPutter and no files to upload.""" + import dds_cli.data_putter + + putter_cm = MagicMock() + putter_cm.__enter__.return_value = putter + putter_cm.__exit__.return_value = False + monkeypatch.setattr(dds_cli.data_putter, "DataPutter", MagicMock(return_value=putter_cm)) + monkeypatch.setattr(dds_cli.data_putter, "Progress", MagicMock()) + dds_cli.data_putter.put( + project="proj00001", + source=(), + source_path_file=None, + break_on_fail=False, + overwrite=False, + num_threads=1, + silent=True, + no_prompt=True, + token_path=None, + destination=None, + staging_dir=None, + ) + + +def _batch_putter(service_unavailable): + putter = MagicMock() + putter.filehandler.data = {} + putter.failed_delivery_log.is_file.return_value = True + putter.service_unavailable = service_unavailable + putter.raise_if_service_unavailable.side_effect = ( + service_unavailable if service_unavailable else None + ) + return putter + + +def test_put_skips_db_retry_on_maintenance(monkeypatch): + """Known maintenance: no retry_add_file_db and no timestamp refresh, just the error.""" + putter = _batch_putter(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError): + _run_put_with(monkeypatch, putter) + + putter.retry_add_file_db.assert_not_called() + putter.touch_project_after_upload.assert_not_called() + + +def test_put_runs_db_retry_without_maintenance(monkeypatch): + """No maintenance: the end-of-batch retry and timestamp refresh run as before.""" + putter = _batch_putter(None) + + _run_put_with(monkeypatch, putter) + + putter.retry_add_file_db.assert_called_once() + putter.touch_project_after_upload.assert_called_once() From 6928dfc2ee63537a25ac133bc8d8f19fc46bdb70 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:21:49 +0100 Subject: [PATCH 6/9] Fix crash when maintenance cancels downloads not started yet Download file keys are pathlib.Path objects, and rich's escape() needs a str, so the cancel message in verify_proceed raised a TypeError. Also remove the double period in the maintenance log line. --- dds_cli/base.py | 2 +- dds_cli/custom_decorators.py | 4 ++-- tests/test_api_retry.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/dds_cli/base.py b/dds_cli/base.py index bb7b408ac..b236a62bb 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -132,7 +132,7 @@ def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: """ if self.service_unavailable is None: self.service_unavailable = err - LOG.error("%s. Stopping: files not started yet are cancelled.", err) + LOG.error("%s. Stopping: files not started yet are cancelled.", str(err).rstrip(".")) self.stop_doing = True def raise_if_service_unavailable(self) -> None: diff --git a/dds_cli/custom_decorators.py b/dds_cli/custom_decorators.py index e0556abc8..0b9f9f903 100644 --- a/dds_cli/custom_decorators.py +++ b/dds_cli/custom_decorators.py @@ -45,13 +45,13 @@ def wrapped(self, file, *args, **kwargs): if getattr(self, "service_unavailable", None) else "KeyboardInterrupt" ) - message = f"{reason} - cancelling file {escape(file)}" + message = f"{reason} - cancelling file {escape(str(file))}" LOG.warning(message) return False # Do not proceed # Return if file cancelled by another file if self.status[file]["cancel"]: - message = f"File already cancelled, stopping file {escape(file)}" + message = f"File already cancelled, stopping file {escape(str(file))}" LOG.warning(message) return False diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 71f3f7d1b..4a35cdce6 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -303,6 +303,39 @@ def work(self, file): assert "Service unavailable - cancelling file" in caplog.text +@pytest.mark.parametrize("already_cancelled", [False, True]) +def test_verify_proceed_cancels_download_file_with_path_key(caplog, already_cancelled): + """Download file keys are pathlib.Path objects: the cancel message must not crash.""" + from dds_cli.custom_decorators import verify_proceed + + called = MagicMock(return_value=(True, "")) + + @verify_proceed + def work(self, file): + return called(file) + + getter = _update_db_getter() + file = pathlib.Path("dir/file.bin") + getter.status = {file: {"cancel": already_cancelled, "started": False}} + if not already_cancelled: + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + assert work(getter, file) is False + called.assert_not_called() + assert "dir/file.bin" in caplog.text + + +def test_stop_for_maintenance_log_has_no_double_period(caplog): + """The API message ends with a period; the log line must not get two.""" + putter = _putter_with_one_file() + putter.stop_for_maintenance( + dds_cli.exceptions.ServiceUnavailableError("Maintenance of DDS is ongoing.") + ) + + assert "Maintenance of DDS is ongoing. Stopping:" in caplog.text + assert ".." not in caplog.text + + def test_stop_for_maintenance_keeps_first_error_and_raises_later(): """The error is raised once, from the main thread, after the workers are done.""" putter = _putter_with_one_file() From d09968b7cd1262156e75a30e7c78b958f1f0d1aa Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:11:01 +0100 Subject: [PATCH 7/9] Make the Path-key cancel test pass on Windows The test compared against "dir/file.bin", but str(Path) uses the OS separator, so on Windows the log shows "dir\file.bin". --- tests/test_api_retry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 4a35cdce6..7c73759fa 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -322,7 +322,7 @@ def work(self, file): assert work(getter, file) is False called.assert_not_called() - assert "dir/file.bin" in caplog.text + assert str(file) in caplog.text # dir\file.bin on Windows def test_stop_for_maintenance_log_has_no_double_period(caplog): From f3f25c9614ce371b0b205259791929a9e5b82135 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:21:31 +0100 Subject: [PATCH 8/9] Move the last API attempt out of the retry loop The raise after the loop could not be reached. Now the loop only runs the attempts that can be retried, and the last attempt runs after it, so its error goes to the caller. --- dds_cli/utils.py | 8 ++++---- tests/test_api_retry.py | 9 +++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 9ec51cfec..38633ac9a 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -331,12 +331,12 @@ def perform_request_with_retry(*args, retries: int = 1, **kwargs): A 503 from the DDS API (maintenance) has a JSON body, is raised as ServiceUnavailableError and is never retried. """ - for attempt in range(retries + 1): + for _ in range(retries): try: return perform_request(*args, **kwargs) except dds_cli.exceptions.NonJsonResponseError as err: status_code = getattr(err, "status_code", None) - if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES or attempt >= retries: + if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES: raise LOG.warning( "API request failed with status %s, retrying in %ss: %s", @@ -345,8 +345,8 @@ def perform_request_with_retry(*args, retries: int = 1, **kwargs): err, ) time.sleep(constants.API_RETRY_WAIT) - # Not reached: the last attempt either returns or raises. - raise RuntimeError("perform_request_with_retry: no attempts made") + # Last attempt: any error goes to the caller + return perform_request(*args, **kwargs) def parse_project_errors(errors): diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 7c73759fa..1e5f017ae 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -171,17 +171,18 @@ def test_add_file_db_no_retry_on_400(monkeypatch): assert mock_post.call_count == 1 -def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): - """The last error is raised when all attempts fail.""" +@pytest.mark.parametrize("retries", [0, 2]) +def test_perform_request_with_retry_gives_up_after_retries(monkeypatch, retries): + """The last error is raised when all attempts fail; retries=0 sends one request.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) err = dds_cli.exceptions.NonJsonResponseError("Bad Gateway", status_code=502) mock_request = MagicMock(side_effect=err) monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) with pytest.raises(dds_cli.exceptions.ApiResponseError): - dds_cli.utils.perform_request_with_retry("url", method="put", retries=2) + dds_cli.utils.perform_request_with_retry("url", method="put", retries=retries) - assert mock_request.call_count == 3 + assert mock_request.call_count == retries + 1 def test_perform_request_with_retry_no_retry_on_request_error(monkeypatch): From 9b8385fa0be34beffafe6c31f07654cb0ed0779a Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:26:49 +0100 Subject: [PATCH 9/9] sprintlog --- SPRINTLOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/SPRINTLOG.md b/SPRINTLOG.md index 5487c11ec..7d335a755 100644 --- a/SPRINTLOG.md +++ b/SPRINTLOG.md @@ -613,3 +613,4 @@ _Empty sprint_ - Fix --no-prompt silently skipping user activation and deactivation ([#1008](https://github.com/ScilifelabDataCentre/dds_cli/pull/1008)) - Remove resolved entries from dds_failed_delivery.json after retry ([#999](https://github.com/ScilifelabDataCentre/dds_cli/pull/999)) +- Retry API calls once on a 502/503 from the proxy, and stop uploads/downloads during maintenance ([#1009](https://github.com/ScilifelabDataCentre/dds_cli/pull/1009))