das-cli 1.6.0__tar.gz → 1.6.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {das_cli-1.6.0/das_cli.egg-info → das_cli-1.6.5}/PKG-INFO +1 -1
- {das_cli-1.6.0 → das_cli-1.6.5}/das/common/api.py +23 -8
- das_cli-1.6.5/das/common/errors.py +165 -0
- das_cli-1.6.5/das/common/exceptions.py +191 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/digital_objects.py +52 -9
- {das_cli-1.6.0 → das_cli-1.6.5/das_cli.egg-info}/PKG-INFO +1 -1
- {das_cli-1.6.0 → das_cli-1.6.5}/das_cli.egg-info/SOURCES.txt +1 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/pyproject.toml +1 -1
- das_cli-1.6.0/das/common/errors.py +0 -93
- {das_cli-1.6.0 → das_cli-1.6.5}/LICENSE +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/MANIFEST.in +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/README.md +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/__init__.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/ai/plugins/dasai.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/ai/plugins/entries/entries_plugin.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/app.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/authentication/auth.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/authentication/oauth.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/authentication/secure_input.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/cli.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/common/config.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/common/entry_fields_constants.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/common/enums.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/common/file_utils.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/managers/__init__.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/managers/digital_objects_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/managers/download_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/managers/entries_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/managers/search_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/attributes.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/cache.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/das_elastic_search.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/downloads.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/entries.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/entry_fields.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/hangfire.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/search.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/service_base.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das/services/users.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das_cli.egg-info/dependency_links.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das_cli.egg-info/entry_points.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das_cli.egg-info/requires.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/das_cli.egg-info/top_level.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.5}/setup.cfg +0 -0
|
@@ -24,6 +24,10 @@ def _process_response(response, action: str):
|
|
|
24
24
|
# behaviour does not depend on ``.ok`` being populated.
|
|
25
25
|
is_http_error = response.status_code >= 400
|
|
26
26
|
|
|
27
|
+
# The server tags every response with a correlation id; carry it along so
|
|
28
|
+
# error messages can quote it (invaluable for tracing 5xx server-side).
|
|
29
|
+
correlation_id = response.headers.get("X-Correlation-ID")
|
|
30
|
+
|
|
27
31
|
try:
|
|
28
32
|
data = response.json()
|
|
29
33
|
except json.JSONDecodeError as json_err:
|
|
@@ -33,26 +37,37 @@ def _process_response(response, action: str):
|
|
|
33
37
|
f"The server returned HTTP {response.status_code} "
|
|
34
38
|
f"({response.reason}) while trying to {action}."
|
|
35
39
|
)
|
|
36
|
-
logger.error(
|
|
40
|
+
logger.error(
|
|
41
|
+
"%s Response body: %s [correlationId: %s]",
|
|
42
|
+
message, response.text[:500], correlation_id,
|
|
43
|
+
)
|
|
37
44
|
return {
|
|
38
45
|
"error": message,
|
|
39
46
|
"status_code": response.status_code,
|
|
47
|
+
"correlation_id": correlation_id,
|
|
40
48
|
"raw_content": response.text[:500],
|
|
41
49
|
}
|
|
42
50
|
logger.error("Error decoding JSON response: %s", json_err)
|
|
43
51
|
return {
|
|
44
52
|
"error": f"Invalid JSON response: {json_err}",
|
|
45
53
|
"status_code": response.status_code,
|
|
54
|
+
"correlation_id": correlation_id,
|
|
46
55
|
"raw_content": response.text[:500],
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
if isinstance(data, dict)
|
|
50
|
-
# ABP usually returns 200 even for logical errors,
|
|
51
|
-
#
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
)
|
|
58
|
+
if isinstance(data, dict):
|
|
59
|
+
# ABP usually returns 200 even for logical errors, so attach the status
|
|
60
|
+
# code when the HTTP layer itself signalled an error, and the
|
|
61
|
+
# correlation id whenever the call failed by either signal.
|
|
62
|
+
if is_http_error:
|
|
63
|
+
data.setdefault("status_code", response.status_code)
|
|
64
|
+
if correlation_id and (is_http_error or data.get("success") is False):
|
|
65
|
+
data.setdefault("correlation_id", correlation_id)
|
|
66
|
+
if is_http_error:
|
|
67
|
+
logger.debug(
|
|
68
|
+
"%s returned HTTP %s: %s [correlationId: %s]",
|
|
69
|
+
action, response.status_code, data.get("error"), correlation_id,
|
|
70
|
+
)
|
|
56
71
|
return data
|
|
57
72
|
|
|
58
73
|
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Shared helpers for turning HTTP/API failures into clear, human-readable messages.
|
|
2
|
+
|
|
3
|
+
The goal is to never surface a raw stack trace or a raw Python dict/JSON blob to
|
|
4
|
+
the user. Instead we extract the message the API actually returned (ABP wraps it
|
|
5
|
+
in an ``error`` object), classify it by HTTP status (4xx vs 5xx) and add an
|
|
6
|
+
actionable hint plus the server correlation id so users and developers can tell
|
|
7
|
+
at a glance *why* a call failed and what to do next.
|
|
8
|
+
|
|
9
|
+
Two entry points:
|
|
10
|
+
|
|
11
|
+
* :func:`build_api_error` returns a typed :class:`~das.common.exceptions.DasApiError`
|
|
12
|
+
(``DasAuthenticationError``, ``DasValidationError``, ``DasServerError`` …) that
|
|
13
|
+
callers can raise and, if they wish, catch by type.
|
|
14
|
+
* :func:`extract_api_error` returns the same information as a ready-to-print
|
|
15
|
+
string. It is kept for the many call sites that do
|
|
16
|
+
``raise ValueError(extract_api_error(response))``.
|
|
17
|
+
"""
|
|
18
|
+
import logging
|
|
19
|
+
|
|
20
|
+
import requests
|
|
21
|
+
|
|
22
|
+
from das.common.exceptions import DasApiError, DasConnectionError, DasServerError, for_status
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger("das")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def describe_request_exception(exc: Exception, url: str = None) -> str:
|
|
28
|
+
"""Return a friendly message for a ``requests`` exception.
|
|
29
|
+
|
|
30
|
+
Distinguishes the common connection-level failures (bad/self-signed TLS
|
|
31
|
+
certificate, host unreachable, timeout) so the user gets an actionable hint
|
|
32
|
+
instead of an opaque traceback.
|
|
33
|
+
"""
|
|
34
|
+
where = f" ({url})" if url else ""
|
|
35
|
+
|
|
36
|
+
if isinstance(exc, requests.exceptions.SSLError):
|
|
37
|
+
return (
|
|
38
|
+
"SSL certificate verification failed for the server"
|
|
39
|
+
f"{where}. The host may be using a self-signed or otherwise "
|
|
40
|
+
"untrusted certificate. If you trust this host, disable "
|
|
41
|
+
"verification with 'das config ssl-verify false'. "
|
|
42
|
+
f"Details: {exc}"
|
|
43
|
+
)
|
|
44
|
+
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
|
45
|
+
return f"Timed out while connecting to the server{where}. Details: {exc}"
|
|
46
|
+
if isinstance(exc, requests.exceptions.ReadTimeout):
|
|
47
|
+
return f"The server{where} took too long to respond. Details: {exc}"
|
|
48
|
+
if isinstance(exc, requests.exceptions.Timeout):
|
|
49
|
+
return f"The request timed out{where}. Details: {exc}"
|
|
50
|
+
if isinstance(exc, requests.exceptions.ConnectionError):
|
|
51
|
+
return (
|
|
52
|
+
f"Could not connect to the server{where}. Check that the API URL is "
|
|
53
|
+
"correct and that the host is reachable. "
|
|
54
|
+
f"Details: {exc}"
|
|
55
|
+
)
|
|
56
|
+
return str(exc)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def connection_error(exc: Exception, url: str = None) -> DasConnectionError:
|
|
60
|
+
"""Wrap a ``requests`` transport exception as a typed connection error.
|
|
61
|
+
|
|
62
|
+
Unlike responses routed through :mod:`das.common.api` (which log their own
|
|
63
|
+
transport failures), callers that issue requests directly — e.g. the chunked
|
|
64
|
+
file upload — rely on this helper, so log here to keep coverage uniform.
|
|
65
|
+
"""
|
|
66
|
+
error = DasConnectionError(describe_request_exception(exc, url))
|
|
67
|
+
logger.debug("Connection error: %s", str(error).replace("\n", " | "))
|
|
68
|
+
return error
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse_response(response, default: str):
|
|
72
|
+
"""Pull message / details / validation errors / status / correlation id out
|
|
73
|
+
of a parsed API response dict.
|
|
74
|
+
|
|
75
|
+
Returns a tuple ``(message, details, validation_errors, status_code,
|
|
76
|
+
correlation_id)``.
|
|
77
|
+
"""
|
|
78
|
+
if not isinstance(response, dict):
|
|
79
|
+
text = str(response).strip()
|
|
80
|
+
return (text or default, None, [], None, None)
|
|
81
|
+
|
|
82
|
+
status_code = response.get("status_code")
|
|
83
|
+
correlation_id = response.get("correlation_id")
|
|
84
|
+
|
|
85
|
+
error = response.get("error")
|
|
86
|
+
|
|
87
|
+
message = ""
|
|
88
|
+
details = None
|
|
89
|
+
validation_errors = []
|
|
90
|
+
|
|
91
|
+
if isinstance(error, dict):
|
|
92
|
+
message = (error.get("message") or "").strip()
|
|
93
|
+
details = (error.get("details") or "").strip() or None
|
|
94
|
+
|
|
95
|
+
raw_validation = error.get("validationErrors")
|
|
96
|
+
if isinstance(raw_validation, list):
|
|
97
|
+
for item in raw_validation:
|
|
98
|
+
if isinstance(item, dict) and item.get("message"):
|
|
99
|
+
validation_errors.append(str(item["message"]).strip())
|
|
100
|
+
elif isinstance(item, str) and item.strip():
|
|
101
|
+
validation_errors.append(item.strip())
|
|
102
|
+
|
|
103
|
+
# The error object may carry the correlation id too (fallback middleware).
|
|
104
|
+
correlation_id = correlation_id or error.get("correlationId")
|
|
105
|
+
elif isinstance(error, str) and error.strip():
|
|
106
|
+
message = error.strip()
|
|
107
|
+
|
|
108
|
+
if not message:
|
|
109
|
+
# No structured message but the call still failed (e.g. a non-JSON body
|
|
110
|
+
# surfaced by das.common.api).
|
|
111
|
+
raw = response.get("raw_content")
|
|
112
|
+
message = str(raw).strip() if raw else ""
|
|
113
|
+
|
|
114
|
+
return (message or default, details, validation_errors, status_code, correlation_id)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def build_api_error(response, default: str = "Unknown error occurred") -> DasApiError:
|
|
118
|
+
"""Build a typed :class:`DasApiError` from a parsed API response.
|
|
119
|
+
|
|
120
|
+
The concrete subclass is chosen from the HTTP status code (and the presence
|
|
121
|
+
of validation errors), so callers can distinguish 4xx from 5xx by type as
|
|
122
|
+
well as by the rendered message.
|
|
123
|
+
"""
|
|
124
|
+
message, details, validation_errors, status_code, correlation_id = _parse_response(
|
|
125
|
+
response, default
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
error_cls = for_status(status_code, has_validation_errors=bool(validation_errors))
|
|
129
|
+
error = error_cls(
|
|
130
|
+
message,
|
|
131
|
+
status_code=status_code,
|
|
132
|
+
correlation_id=correlation_id,
|
|
133
|
+
details=details,
|
|
134
|
+
validation_errors=validation_errors,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Log every surfaced API error here — the single choke point all callers go
|
|
138
|
+
# through — so the full categorised message and correlation id land in the
|
|
139
|
+
# log (invaluable for tracing a 5xx). Logged at DEBUG on purpose: the CLI
|
|
140
|
+
# already prints a friendly message to the console, so logging louder would
|
|
141
|
+
# double-print it (the ``das`` logger propagates to the default WARNING
|
|
142
|
+
# console handler). Enable capture with ``das config log-level debug`` or a
|
|
143
|
+
# debug-level log file. ``severity`` records the true level for readers.
|
|
144
|
+
severity = "ERROR" if isinstance(error, DasServerError) else "WARNING"
|
|
145
|
+
logger.debug(
|
|
146
|
+
"API error [severity=%s status=%s correlationId=%s]: %s",
|
|
147
|
+
severity,
|
|
148
|
+
error.status_code,
|
|
149
|
+
error.correlation_id,
|
|
150
|
+
str(error).replace("\n", " | "),
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
return error
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def extract_api_error(response, default: str = "Unknown error occurred") -> str:
|
|
157
|
+
"""Extract a human-readable, category-aware error message from a response.
|
|
158
|
+
|
|
159
|
+
Backward-compatible string form of :func:`build_api_error`. Handles the ABP
|
|
160
|
+
envelope as well as the plain-string errors produced by :mod:`das.common.api`.
|
|
161
|
+
The returned message is prefixed with the HTTP status and an error category
|
|
162
|
+
(e.g. ``HTTP 404 — Not found: ...``) and, for server errors, includes the
|
|
163
|
+
correlation id to quote to support.
|
|
164
|
+
"""
|
|
165
|
+
return str(build_api_error(response, default))
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Typed exceptions for DAS API failures.
|
|
2
|
+
|
|
3
|
+
The DAS backend returns errors in ABP's envelope
|
|
4
|
+
(``{"success": false, "error": {"message", "details", "validationErrors"}}``)
|
|
5
|
+
together with an HTTP status code and an ``X-Correlation-ID`` header. These
|
|
6
|
+
classes turn that raw data into clear, category-specific messages so both end
|
|
7
|
+
users and developers can immediately tell *why* a call failed and what to do
|
|
8
|
+
about it — in particular whether it is a 4xx (fix your request) or a 5xx
|
|
9
|
+
(server-side fault, quote the reference).
|
|
10
|
+
|
|
11
|
+
All classes derive from :class:`ValueError` so that existing ``except
|
|
12
|
+
ValueError`` / ``except Exception`` handlers throughout the CLI keep working;
|
|
13
|
+
they simply receive a richer message (and, when caught by type, the HTTP
|
|
14
|
+
status code and correlation id as attributes).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DasApiError(ValueError):
|
|
19
|
+
"""Base class for an error returned by the DAS API.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
api_message: The raw message extracted from the API response.
|
|
23
|
+
status_code: The HTTP status code, if known.
|
|
24
|
+
correlation_id: The server correlation id (``X-Correlation-ID``), if any.
|
|
25
|
+
details: Extra detail text returned alongside the message.
|
|
26
|
+
validation_errors: List of field-level validation messages.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
#: Short human label used in the rendered message.
|
|
30
|
+
category = "API error"
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
message,
|
|
35
|
+
*,
|
|
36
|
+
status_code=None,
|
|
37
|
+
correlation_id=None,
|
|
38
|
+
details=None,
|
|
39
|
+
validation_errors=None,
|
|
40
|
+
):
|
|
41
|
+
self.api_message = (message or "").strip() or "Unknown error occurred"
|
|
42
|
+
self.status_code = status_code
|
|
43
|
+
self.correlation_id = correlation_id
|
|
44
|
+
self.details = (details or "").strip() or None
|
|
45
|
+
self.validation_errors = [v for v in (validation_errors or []) if v]
|
|
46
|
+
super().__init__(self._render())
|
|
47
|
+
|
|
48
|
+
# -- rendering ---------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def guidance(self):
|
|
51
|
+
"""Return an actionable hint for this error class, or None."""
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
def _render(self):
|
|
55
|
+
# Only decorate with the category when we actually have something to
|
|
56
|
+
# categorise by — a status code, or a specific (non-base) error type.
|
|
57
|
+
# Otherwise (e.g. an ABP logical error returned with HTTP 200 and no
|
|
58
|
+
# status) show the bare message so it stays clean.
|
|
59
|
+
if self.status_code:
|
|
60
|
+
header = f"HTTP {self.status_code} — {self.category}: {self.api_message}"
|
|
61
|
+
elif type(self) is not DasApiError:
|
|
62
|
+
header = f"{self.category}: {self.api_message}"
|
|
63
|
+
else:
|
|
64
|
+
header = self.api_message
|
|
65
|
+
|
|
66
|
+
lines = [header]
|
|
67
|
+
|
|
68
|
+
if self.details and self.details != self.api_message:
|
|
69
|
+
lines.append(self.details)
|
|
70
|
+
|
|
71
|
+
for item in self.validation_errors:
|
|
72
|
+
lines.append(f" • {item}")
|
|
73
|
+
|
|
74
|
+
hint = self.guidance()
|
|
75
|
+
if hint:
|
|
76
|
+
lines.append(hint)
|
|
77
|
+
|
|
78
|
+
if self.correlation_id:
|
|
79
|
+
lines.append(f"Reference: {self.correlation_id}")
|
|
80
|
+
|
|
81
|
+
return "\n".join(lines)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class DasAuthenticationError(DasApiError):
|
|
85
|
+
"""401 — the caller is not authenticated (missing/expired credentials)."""
|
|
86
|
+
|
|
87
|
+
category = "Authentication error"
|
|
88
|
+
|
|
89
|
+
def guidance(self):
|
|
90
|
+
return (
|
|
91
|
+
"Your credentials are missing or have expired. Re-authenticate with "
|
|
92
|
+
"'das auth login', or verify the API key you configured."
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class DasPermissionError(DasApiError):
|
|
97
|
+
"""403 — authenticated but not authorized for this action."""
|
|
98
|
+
|
|
99
|
+
category = "Permission error"
|
|
100
|
+
|
|
101
|
+
def guidance(self):
|
|
102
|
+
return (
|
|
103
|
+
"You are signed in but lack permission for this action. Check your "
|
|
104
|
+
"role/permissions, or that your API key is scoped for it."
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class DasNotFoundError(DasApiError):
|
|
109
|
+
"""404 — the requested resource does not exist."""
|
|
110
|
+
|
|
111
|
+
category = "Not found"
|
|
112
|
+
|
|
113
|
+
def guidance(self):
|
|
114
|
+
return "Check the id/code is correct and that the resource still exists."
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class DasValidationError(DasApiError):
|
|
118
|
+
"""400/422 — the request was rejected as invalid."""
|
|
119
|
+
|
|
120
|
+
category = "Validation error"
|
|
121
|
+
|
|
122
|
+
def guidance(self):
|
|
123
|
+
return "Correct the field(s) above and try again."
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class DasConflictError(DasApiError):
|
|
127
|
+
"""409 — the request conflicts with the current server state."""
|
|
128
|
+
|
|
129
|
+
category = "Conflict"
|
|
130
|
+
|
|
131
|
+
def guidance(self):
|
|
132
|
+
return (
|
|
133
|
+
"This conflicts with existing data (e.g. a duplicate key) or a "
|
|
134
|
+
"concurrent change. Reload the current state and retry."
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class DasClientError(DasApiError):
|
|
139
|
+
"""Other 4xx — a client-side problem not covered by a more specific class."""
|
|
140
|
+
|
|
141
|
+
category = "Request error"
|
|
142
|
+
|
|
143
|
+
def guidance(self):
|
|
144
|
+
return "The server rejected the request. Review the parameters and retry."
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class DasServerError(DasApiError):
|
|
148
|
+
"""5xx — a server-side fault, not caused by the caller's input."""
|
|
149
|
+
|
|
150
|
+
category = "Server error"
|
|
151
|
+
|
|
152
|
+
def guidance(self):
|
|
153
|
+
base = (
|
|
154
|
+
"This is a server-side problem, not caused by your request. Wait a "
|
|
155
|
+
"moment and retry."
|
|
156
|
+
)
|
|
157
|
+
if self.correlation_id:
|
|
158
|
+
return base + " If it persists, contact support and quote the reference below."
|
|
159
|
+
return base + " If it persists, contact support with the time of the request."
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class DasConnectionError(DasApiError):
|
|
163
|
+
"""The request never reached the server (DNS/TLS/timeout/connection refused)."""
|
|
164
|
+
|
|
165
|
+
category = "Connection error"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# Status code -> exception class. 400 is resolved dynamically (validation vs
|
|
169
|
+
# generic) in :func:`for_status`.
|
|
170
|
+
_STATUS_MAP = {
|
|
171
|
+
401: DasAuthenticationError,
|
|
172
|
+
403: DasPermissionError,
|
|
173
|
+
404: DasNotFoundError,
|
|
174
|
+
409: DasConflictError,
|
|
175
|
+
422: DasValidationError,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def for_status(status_code, has_validation_errors=False):
|
|
180
|
+
"""Return the most specific :class:`DasApiError` subclass for a status code."""
|
|
181
|
+
if status_code in _STATUS_MAP:
|
|
182
|
+
return _STATUS_MAP[status_code]
|
|
183
|
+
if status_code == 400:
|
|
184
|
+
return DasValidationError if has_validation_errors else DasClientError
|
|
185
|
+
if isinstance(status_code, int):
|
|
186
|
+
if status_code >= 500:
|
|
187
|
+
return DasServerError
|
|
188
|
+
if status_code >= 400:
|
|
189
|
+
return DasClientError
|
|
190
|
+
# Unknown / no status (e.g. ABP logical error returned with HTTP 200).
|
|
191
|
+
return DasValidationError if has_validation_errors else DasApiError
|
|
@@ -3,9 +3,10 @@ from math import ceil
|
|
|
3
3
|
from os.path import exists
|
|
4
4
|
import json
|
|
5
5
|
from base64 import b64encode, b64decode
|
|
6
|
-
from das.common.api import post_data
|
|
6
|
+
from das.common.api import post_data, DEFAULT_TIMEOUT
|
|
7
7
|
from das.common.config import load_verify_ssl
|
|
8
|
-
from das.common.errors import extract_api_error
|
|
8
|
+
from das.common.errors import extract_api_error, build_api_error, connection_error
|
|
9
|
+
from das.common.exceptions import DasApiError
|
|
9
10
|
from das.services.service_base import ServiceBase
|
|
10
11
|
import uuid
|
|
11
12
|
import requests
|
|
@@ -122,6 +123,10 @@ class DigitalObjectsService(ServiceBase):
|
|
|
122
123
|
f"Upload failed for '{file_path}': no digital object returned on final chunk"
|
|
123
124
|
)
|
|
124
125
|
|
|
126
|
+
except DasApiError:
|
|
127
|
+
# Already a clear, categorised API error — let it propagate so
|
|
128
|
+
# callers can distinguish 4xx from 5xx (and keep the reference id).
|
|
129
|
+
raise
|
|
125
130
|
except Exception as e:
|
|
126
131
|
raise ValueError(f"Error uploading file '{file_path}': {str(e)}")
|
|
127
132
|
|
|
@@ -144,14 +149,52 @@ class DigitalObjectsService(ServiceBase):
|
|
|
144
149
|
}
|
|
145
150
|
|
|
146
151
|
try:
|
|
147
|
-
response = requests.post(
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
152
|
+
response = requests.post(
|
|
153
|
+
self.upload_digital_object_url,
|
|
154
|
+
headers=headers,
|
|
155
|
+
files=files,
|
|
156
|
+
verify=load_verify_ssl(),
|
|
157
|
+
timeout=DEFAULT_TIMEOUT,
|
|
158
|
+
)
|
|
153
159
|
except requests.RequestException as e:
|
|
154
|
-
|
|
160
|
+
# Transport-level failure (DNS/TLS/timeout/connection refused).
|
|
161
|
+
raise connection_error(e, self.upload_digital_object_url)
|
|
162
|
+
|
|
163
|
+
correlation_id = response.headers.get("X-Correlation-ID")
|
|
164
|
+
|
|
165
|
+
# Parse the JSON body regardless of status so we can surface the ABP
|
|
166
|
+
# envelope (message/details/validationErrors) instead of a raw dump.
|
|
167
|
+
try:
|
|
168
|
+
data = response.json()
|
|
169
|
+
except ValueError:
|
|
170
|
+
data = None
|
|
171
|
+
|
|
172
|
+
failed = response.status_code >= 400 or (
|
|
173
|
+
isinstance(data, dict) and data.get("success") is False
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if failed:
|
|
177
|
+
if isinstance(data, dict):
|
|
178
|
+
data.setdefault("status_code", response.status_code)
|
|
179
|
+
if correlation_id:
|
|
180
|
+
data.setdefault("correlation_id", correlation_id)
|
|
181
|
+
raise build_api_error(data, default="File upload failed")
|
|
182
|
+
|
|
183
|
+
# Non-JSON error body (e.g. an HTML 500 page from a proxy).
|
|
184
|
+
raise build_api_error(
|
|
185
|
+
{
|
|
186
|
+
"error": (
|
|
187
|
+
f"The server returned HTTP {response.status_code} "
|
|
188
|
+
f"({response.reason}) during file upload."
|
|
189
|
+
),
|
|
190
|
+
"status_code": response.status_code,
|
|
191
|
+
"correlation_id": correlation_id,
|
|
192
|
+
"raw_content": (response.text or "")[:500],
|
|
193
|
+
},
|
|
194
|
+
default="File upload failed",
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
return data
|
|
155
198
|
|
|
156
199
|
def download_digital_object(self, output_path: str, digital_object_id: str = None, digital_object_code: str = None):
|
|
157
200
|
"""Download a digital object from the digital object service."""
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
"""Shared helpers for turning HTTP/API failures into clear, human-readable messages.
|
|
2
|
-
|
|
3
|
-
The goal is to never surface a raw stack trace or a raw Python dict/JSON blob to
|
|
4
|
-
the user. Instead we extract the message the API actually returned (ABP wraps it
|
|
5
|
-
in an ``error`` object) and add the HTTP status code when we have one.
|
|
6
|
-
"""
|
|
7
|
-
import requests
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def describe_request_exception(exc: Exception, url: str = None) -> str:
|
|
11
|
-
"""Return a friendly message for a ``requests`` exception.
|
|
12
|
-
|
|
13
|
-
Distinguishes the common connection-level failures (bad/self-signed TLS
|
|
14
|
-
certificate, host unreachable, timeout) so the user gets an actionable hint
|
|
15
|
-
instead of an opaque traceback.
|
|
16
|
-
"""
|
|
17
|
-
where = f" ({url})" if url else ""
|
|
18
|
-
|
|
19
|
-
if isinstance(exc, requests.exceptions.SSLError):
|
|
20
|
-
return (
|
|
21
|
-
"SSL certificate verification failed for the server"
|
|
22
|
-
f"{where}. The host may be using a self-signed or otherwise "
|
|
23
|
-
"untrusted certificate. If you trust this host, disable "
|
|
24
|
-
"verification with 'das config ssl-verify false'. "
|
|
25
|
-
f"Details: {exc}"
|
|
26
|
-
)
|
|
27
|
-
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
|
28
|
-
return f"Timed out while connecting to the server{where}. Details: {exc}"
|
|
29
|
-
if isinstance(exc, requests.exceptions.ReadTimeout):
|
|
30
|
-
return f"The server{where} took too long to respond. Details: {exc}"
|
|
31
|
-
if isinstance(exc, requests.exceptions.Timeout):
|
|
32
|
-
return f"The request timed out{where}. Details: {exc}"
|
|
33
|
-
if isinstance(exc, requests.exceptions.ConnectionError):
|
|
34
|
-
return (
|
|
35
|
-
f"Could not connect to the server{where}. Check that the API URL is "
|
|
36
|
-
"correct and that the host is reachable. "
|
|
37
|
-
f"Details: {exc}"
|
|
38
|
-
)
|
|
39
|
-
return str(exc)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def extract_api_error(response, default: str = "Unknown error occurred") -> str:
|
|
43
|
-
"""Extract a human-readable error message from a parsed API response.
|
|
44
|
-
|
|
45
|
-
Handles the ABP envelope (``{"error": {"message": ..., "details": ...,
|
|
46
|
-
"validationErrors": [...]}}``) as well as plain-string errors produced by
|
|
47
|
-
:mod:`das.common.api`. When a status code is available it is prefixed so the
|
|
48
|
-
caller can tell a 404 from a 500.
|
|
49
|
-
"""
|
|
50
|
-
if not isinstance(response, dict):
|
|
51
|
-
text = str(response).strip()
|
|
52
|
-
return text or default
|
|
53
|
-
|
|
54
|
-
status_code = response.get("status_code")
|
|
55
|
-
|
|
56
|
-
def _with_status(message: str) -> str:
|
|
57
|
-
message = (message or "").strip()
|
|
58
|
-
if status_code and message:
|
|
59
|
-
return f"HTTP {status_code}: {message}"
|
|
60
|
-
if status_code:
|
|
61
|
-
return f"HTTP {status_code}"
|
|
62
|
-
return message or default
|
|
63
|
-
|
|
64
|
-
error = response.get("error")
|
|
65
|
-
|
|
66
|
-
if isinstance(error, dict):
|
|
67
|
-
parts = []
|
|
68
|
-
message = (error.get("message") or "").strip()
|
|
69
|
-
details = (error.get("details") or "").strip()
|
|
70
|
-
if message:
|
|
71
|
-
parts.append(message)
|
|
72
|
-
if details and details != message:
|
|
73
|
-
parts.append(details)
|
|
74
|
-
|
|
75
|
-
validation_errors = error.get("validationErrors")
|
|
76
|
-
if isinstance(validation_errors, list):
|
|
77
|
-
for item in validation_errors:
|
|
78
|
-
if isinstance(item, dict) and item.get("message"):
|
|
79
|
-
parts.append(str(item["message"]).strip())
|
|
80
|
-
|
|
81
|
-
if parts:
|
|
82
|
-
return _with_status(" - ".join(parts))
|
|
83
|
-
return _with_status("")
|
|
84
|
-
|
|
85
|
-
if isinstance(error, str) and error.strip():
|
|
86
|
-
return _with_status(error)
|
|
87
|
-
|
|
88
|
-
# No structured error but the response still failed (e.g. non-JSON body).
|
|
89
|
-
raw = response.get("raw_content")
|
|
90
|
-
if raw:
|
|
91
|
-
return _with_status(str(raw))
|
|
92
|
-
|
|
93
|
-
return _with_status("")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|