cloudsprite 0.11.0__py3-none-any.whl
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.
- cloudsprite/__init__.py +451 -0
- cloudsprite/_antenna.py +83 -0
- cloudsprite/_auth.py +295 -0
- cloudsprite/_client.py +502 -0
- cloudsprite/_config.py +203 -0
- cloudsprite/_consent.py +104 -0
- cloudsprite/_context.py +945 -0
- cloudsprite/_exceptions.py +136 -0
- cloudsprite/_figure_models.py +158 -0
- cloudsprite/_figure_validation.py +168 -0
- cloudsprite/_filter_foster.py +165 -0
- cloudsprite/_filter_synthesis.py +400 -0
- cloudsprite/_filtering.py +134 -0
- cloudsprite/_impedance_matching.py +262 -0
- cloudsprite/_interpolation.py +47 -0
- cloudsprite/_lineage.py +775 -0
- cloudsprite/_link_budget.py +99 -0
- cloudsprite/_logging.py +53 -0
- cloudsprite/_mixed_mode.py +49 -0
- cloudsprite/_monte_carlo.py +193 -0
- cloudsprite/_noise_figure.py +44 -0
- cloudsprite/_pagination.py +130 -0
- cloudsprite/_parsers.py +75 -0
- cloudsprite/_publish.py +162 -0
- cloudsprite/_redact.py +179 -0
- cloudsprite/_response.py +63 -0
- cloudsprite/_resultset.py +65 -0
- cloudsprite/_rf_network.py +111 -0
- cloudsprite/_run_config.py +46 -0
- cloudsprite/_script_runner.py +217 -0
- cloudsprite/_script_workspace.py +271 -0
- cloudsprite/_sparameter_metrics.py +75 -0
- cloudsprite/_tdr.py +283 -0
- cloudsprite/_trace.py +112 -0
- cloudsprite/_version.py +23 -0
- cloudsprite/_visualizer.py +380 -0
- cloudsprite/_visualizer_cli.py +412 -0
- cloudsprite/_visualizer_preview.py +864 -0
- cloudsprite/_work_context.py +116 -0
- cloudsprite/_ws.py +577 -0
- cloudsprite/cli.py +300 -0
- cloudsprite/py.typed +0 -0
- cloudsprite/resources/__init__.py +1 -0
- cloudsprite/resources/_base.py +293 -0
- cloudsprite/resources/_models.py +50 -0
- cloudsprite/resources/cloudscripts.py +173 -0
- cloudsprite/resources/datasets.py +431 -0
- cloudsprite/resources/figures.py +282 -0
- cloudsprite/resources/instruments.py +295 -0
- cloudsprite/resources/notebooks.py +183 -0
- cloudsprite/resources/orbs.py +99 -0
- cloudsprite/resources/parameters.py +77 -0
- cloudsprite/resources/projects.py +182 -0
- cloudsprite/resources/related.py +125 -0
- cloudsprite/resources/reports.py +992 -0
- cloudsprite/resources/search.py +245 -0
- cloudsprite/resources/shares.py +229 -0
- cloudsprite/resources/sprites.py +15 -0
- cloudsprite/resources/tags.py +107 -0
- cloudsprite/resources/teams.py +86 -0
- cloudsprite/resources/traces.py +147 -0
- cloudsprite/resources/usage.py +152 -0
- cloudsprite/resources/visualizer_templates.py +466 -0
- cloudsprite/resources/workflows.py +59 -0
- cloudsprite-0.11.0.dist-info/METADATA +358 -0
- cloudsprite-0.11.0.dist-info/RECORD +70 -0
- cloudsprite-0.11.0.dist-info/WHEEL +5 -0
- cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
- cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
- cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
cloudsprite/_client.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""HTTP client with auth headers, retries, error mapping, and audit logging."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import weakref
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
import requests as req
|
|
11
|
+
from requests.adapters import HTTPAdapter
|
|
12
|
+
from urllib3.util.retry import Retry
|
|
13
|
+
|
|
14
|
+
from cloudsprite._auth import AuthManager
|
|
15
|
+
from cloudsprite._config import Config
|
|
16
|
+
from cloudsprite._exceptions import (
|
|
17
|
+
APIError,
|
|
18
|
+
AuthError,
|
|
19
|
+
CloudSpriteError,
|
|
20
|
+
NotFoundError,
|
|
21
|
+
QuotaExceededError,
|
|
22
|
+
ValidationError,
|
|
23
|
+
)
|
|
24
|
+
from cloudsprite._logging import log_mutation
|
|
25
|
+
from cloudsprite._response import HTML_BASE_URL_HINT, looks_like_html, parse_json_response
|
|
26
|
+
from cloudsprite._version import sdk_version
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from cloudsprite._context import Client
|
|
30
|
+
|
|
31
|
+
# Default (connect, read) timeout in seconds. Override with CLOUDSPRITE_TIMEOUT
|
|
32
|
+
# (single float, or "connect,read") or a future Config.timeout field.
|
|
33
|
+
DEFAULT_TIMEOUT: tuple[float, float] = (5.0, 60.0)
|
|
34
|
+
|
|
35
|
+
# Methods eligible for urllib3 retries. POST/PATCH included deliberately so
|
|
36
|
+
# transient 429/5xx on mutations are retried; callers should still design
|
|
37
|
+
# create endpoints to be safe under at-least-once delivery where possible.
|
|
38
|
+
_RETRY_METHODS = frozenset({"HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE", "POST", "PATCH"})
|
|
39
|
+
_RETRY_STATUS = frozenset({429, 502, 503, 504})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def resolve_timeout(config: Config | None = None) -> float | tuple[float, float]:
|
|
43
|
+
"""Resolve request timeout: env → config.timeout → default.
|
|
44
|
+
|
|
45
|
+
``CLOUDSPRITE_TIMEOUT`` accepts a single float (both connect and read) or
|
|
46
|
+
``connect,read`` (e.g. ``3.05,30``). Config may expose ``timeout`` later
|
|
47
|
+
without requiring a change here.
|
|
48
|
+
"""
|
|
49
|
+
env = os.environ.get("CLOUDSPRITE_TIMEOUT")
|
|
50
|
+
if env:
|
|
51
|
+
env = env.strip()
|
|
52
|
+
if "," in env:
|
|
53
|
+
connect_s, read_s = env.split(",", 1)
|
|
54
|
+
return (float(connect_s.strip()), float(read_s.strip()))
|
|
55
|
+
return float(env)
|
|
56
|
+
if config is not None:
|
|
57
|
+
configured = getattr(config, "timeout", None)
|
|
58
|
+
if configured is not None:
|
|
59
|
+
return configured # type: ignore[no-any-return]
|
|
60
|
+
return DEFAULT_TIMEOUT
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def extract_error_detail(body: Any) -> str:
|
|
64
|
+
"""Render a useful message from JSON error bodies of various shapes.
|
|
65
|
+
|
|
66
|
+
Ninja/DRF may return ``{"detail": "..."}``, a bare list, or field errors
|
|
67
|
+
like ``{"field": ["msg"]}``. Never assume ``body`` is a dict.
|
|
68
|
+
"""
|
|
69
|
+
if isinstance(body, list):
|
|
70
|
+
if not body:
|
|
71
|
+
return "Unknown error"
|
|
72
|
+
parts = []
|
|
73
|
+
for item in body:
|
|
74
|
+
if isinstance(item, dict):
|
|
75
|
+
parts.append(str(item.get("msg") or item.get("detail") or item.get("message") or item))
|
|
76
|
+
else:
|
|
77
|
+
parts.append(str(item))
|
|
78
|
+
return "; ".join(parts)
|
|
79
|
+
if isinstance(body, dict):
|
|
80
|
+
detail = body.get("detail", body.get("message"))
|
|
81
|
+
if detail is not None:
|
|
82
|
+
if isinstance(detail, list):
|
|
83
|
+
return extract_error_detail(detail)
|
|
84
|
+
return str(detail)
|
|
85
|
+
# Field-keyed validation errors: {"name": ["required"], ...}
|
|
86
|
+
field_parts = []
|
|
87
|
+
for key, value in body.items():
|
|
88
|
+
if key in ("limit", "code", "type", "status"):
|
|
89
|
+
continue
|
|
90
|
+
if isinstance(value, list):
|
|
91
|
+
field_parts.append(f"{key}: {'; '.join(str(v) for v in value)}")
|
|
92
|
+
else:
|
|
93
|
+
field_parts.append(f"{key}: {value}")
|
|
94
|
+
if field_parts:
|
|
95
|
+
return "; ".join(field_parts)
|
|
96
|
+
return "Unknown error"
|
|
97
|
+
if body is None:
|
|
98
|
+
return "Unknown error"
|
|
99
|
+
return str(body)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def raise_for_response(resp: req.Response, path: str = "") -> None:
|
|
103
|
+
"""Map an HTTP error response to a typed SDK exception.
|
|
104
|
+
|
|
105
|
+
Public code paths must use this (or ``HTTPClient._handle_error``) instead of
|
|
106
|
+
``Response.raise_for_status()`` so callers never see raw ``requests`` errors.
|
|
107
|
+
"""
|
|
108
|
+
if resp.status_code < 400:
|
|
109
|
+
return
|
|
110
|
+
if looks_like_html(resp):
|
|
111
|
+
# An HTML body on a >=400 is far more likely an intermediary answering
|
|
112
|
+
# — an ALB 502, an nginx 504, a CDN error page — than a base_url aimed
|
|
113
|
+
# at the frontend, which answers 200. Blaming base_url here would send
|
|
114
|
+
# users to edit their config while the API is simply down. Truncate:
|
|
115
|
+
# the body is a full HTML document.
|
|
116
|
+
body: Any = {"detail": f"Non-JSON error body (HTML document, HTTP {resp.status_code})"}
|
|
117
|
+
else:
|
|
118
|
+
try:
|
|
119
|
+
body = resp.json()
|
|
120
|
+
except ValueError:
|
|
121
|
+
body = {"detail": resp.text}
|
|
122
|
+
detail = extract_error_detail(body)
|
|
123
|
+
body_dict = body if isinstance(body, dict) else {"detail": detail, "errors": body}
|
|
124
|
+
|
|
125
|
+
if resp.status_code in (401, 403):
|
|
126
|
+
raise AuthError(detail, status_code=resp.status_code, response_body=body_dict)
|
|
127
|
+
if resp.status_code == 404:
|
|
128
|
+
raise NotFoundError("resource", path or resp.url or "", status_code=resp.status_code, response_body=body_dict)
|
|
129
|
+
if resp.status_code == 413:
|
|
130
|
+
limit = body_dict.get("limit") if isinstance(body_dict, dict) else None
|
|
131
|
+
raise QuotaExceededError(
|
|
132
|
+
"Upload size exceeds your plan's limit.",
|
|
133
|
+
limit=str(limit) if limit is not None else None,
|
|
134
|
+
)
|
|
135
|
+
if resp.status_code == 429:
|
|
136
|
+
raise QuotaExceededError(
|
|
137
|
+
detail if detail != "Unknown error" else "Rate limit exceeded. Retry later.",
|
|
138
|
+
limit=None,
|
|
139
|
+
)
|
|
140
|
+
if resp.status_code == 400 and "No tenant context" in detail:
|
|
141
|
+
raise ValidationError(
|
|
142
|
+
"No org selected. Run `cloudsprite init` or cs.set_org('your-org-slug').",
|
|
143
|
+
status_code=resp.status_code,
|
|
144
|
+
response_body=body_dict,
|
|
145
|
+
)
|
|
146
|
+
if resp.status_code == 400 and "No team selected" in detail:
|
|
147
|
+
raise ValidationError(
|
|
148
|
+
"No team selected. Run `cloudsprite init` or cs.set_team('your-team-slug').",
|
|
149
|
+
status_code=resp.status_code,
|
|
150
|
+
response_body=body_dict,
|
|
151
|
+
)
|
|
152
|
+
raise APIError(resp.status_code, detail, body_dict)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class HTTPClient:
|
|
156
|
+
"""Manages HTTP sessions with automatic auth, retries, and error handling."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, config: Config, auth: AuthManager):
|
|
159
|
+
self._config = config
|
|
160
|
+
self._auth = auth
|
|
161
|
+
self._timeout = resolve_timeout(config)
|
|
162
|
+
self._header_provider: Callable[[], dict[str, str] | None] | None = None
|
|
163
|
+
self._owner_ref: weakref.ref[Client] | None = None
|
|
164
|
+
self._closed = False
|
|
165
|
+
self._session = self._build_session()
|
|
166
|
+
|
|
167
|
+
def set_header_provider(self, provider: Callable[[], dict[str, str] | None] | None) -> None:
|
|
168
|
+
"""Register a callable that returns headers merged into every request.
|
|
169
|
+
|
|
170
|
+
Used by Client to inject ``X-Team-ID`` centrally so individual
|
|
171
|
+
collections cannot forget it.
|
|
172
|
+
"""
|
|
173
|
+
self._header_provider = provider
|
|
174
|
+
|
|
175
|
+
def set_owner(self, client: Client) -> None:
|
|
176
|
+
"""Register the owning ``Client`` as a weak back-link.
|
|
177
|
+
|
|
178
|
+
Internal modules (ws, publish, lineage, resources) resolve team,
|
|
179
|
+
lineage and the publish pool from here rather than importing the
|
|
180
|
+
process-default client. Weak, so the owner stays collectable.
|
|
181
|
+
"""
|
|
182
|
+
self._owner_ref = weakref.ref(client)
|
|
183
|
+
|
|
184
|
+
def owner(self) -> Client | None:
|
|
185
|
+
"""The owning ``Client``, or None if unset or already collected."""
|
|
186
|
+
ref = self._owner_ref
|
|
187
|
+
return ref() if ref is not None else None
|
|
188
|
+
|
|
189
|
+
def close(self) -> None:
|
|
190
|
+
"""Close the session; subsequent requests raise. Idempotent.
|
|
191
|
+
|
|
192
|
+
The guard has to live here rather than on ``Client``: a
|
|
193
|
+
``ResourceCollection`` captured before the close holds this transport
|
|
194
|
+
directly and never consults the owning client, so it would otherwise
|
|
195
|
+
keep issuing live requests after ``Client.close()``.
|
|
196
|
+
"""
|
|
197
|
+
self._closed = True
|
|
198
|
+
try:
|
|
199
|
+
self._session.close()
|
|
200
|
+
except Exception: # pragma: no cover - defensive
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
def _build_session(self) -> req.Session:
|
|
204
|
+
session = req.Session()
|
|
205
|
+
retry = Retry(
|
|
206
|
+
total=3,
|
|
207
|
+
backoff_factor=0.5,
|
|
208
|
+
status_forcelist=list(_RETRY_STATUS),
|
|
209
|
+
allowed_methods=_RETRY_METHODS,
|
|
210
|
+
respect_retry_after_header=True,
|
|
211
|
+
# Return the final response after retries so we can map 429 → QuotaExceededError
|
|
212
|
+
# instead of leaking urllib3 MaxRetryError as a transport failure.
|
|
213
|
+
raise_on_status=False,
|
|
214
|
+
)
|
|
215
|
+
adapter = HTTPAdapter(max_retries=retry)
|
|
216
|
+
session.mount("https://", adapter)
|
|
217
|
+
# Only mount http:// for local dev (when allow_insecure is set)
|
|
218
|
+
if getattr(self._config, "_allow_insecure", False):
|
|
219
|
+
session.mount("http://", adapter)
|
|
220
|
+
return session
|
|
221
|
+
|
|
222
|
+
def _url(self, path: str) -> str:
|
|
223
|
+
return f"{self._config.base_url}{path}"
|
|
224
|
+
|
|
225
|
+
def _merge_headers(
|
|
226
|
+
self,
|
|
227
|
+
extra: dict[str, str] | None = None,
|
|
228
|
+
*,
|
|
229
|
+
content_type: str | None = "application/json",
|
|
230
|
+
) -> dict[str, str]:
|
|
231
|
+
"""Build request headers: UA → auth → Content-Type → team provider → caller extra."""
|
|
232
|
+
headers: dict[str, str] = {"User-Agent": f"cloudsprite-python/{sdk_version()}"}
|
|
233
|
+
headers.update(self._auth.get_auth_header())
|
|
234
|
+
if content_type:
|
|
235
|
+
headers["Content-Type"] = content_type
|
|
236
|
+
if self._header_provider is not None:
|
|
237
|
+
provided = self._header_provider()
|
|
238
|
+
if provided:
|
|
239
|
+
headers.update(provided)
|
|
240
|
+
if extra:
|
|
241
|
+
headers.update(extra)
|
|
242
|
+
return headers
|
|
243
|
+
|
|
244
|
+
def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
245
|
+
return self._merge_headers(extra)
|
|
246
|
+
|
|
247
|
+
def _handle_error(self, resp: req.Response, path: str) -> None:
|
|
248
|
+
raise_for_response(resp, path)
|
|
249
|
+
|
|
250
|
+
def _request(self, method: str, url: str, **kwargs: Any) -> req.Response:
|
|
251
|
+
"""Issue a session request with timeout; map transport errors to APIError."""
|
|
252
|
+
if self._closed:
|
|
253
|
+
raise CloudSpriteError(
|
|
254
|
+
"This client has been closed. Handles obtained before close() are no "
|
|
255
|
+
"longer usable — create a new Client() to continue."
|
|
256
|
+
)
|
|
257
|
+
kwargs.setdefault("timeout", self._timeout)
|
|
258
|
+
try:
|
|
259
|
+
return self._session.request(method, url, **kwargs)
|
|
260
|
+
except req.RequestException as exc:
|
|
261
|
+
raise APIError(0, f"Request failed: {exc}", None) from exc
|
|
262
|
+
|
|
263
|
+
def get(
|
|
264
|
+
self,
|
|
265
|
+
path: str,
|
|
266
|
+
params: dict[str, Any] | None = None,
|
|
267
|
+
headers: dict[str, str] | None = None,
|
|
268
|
+
) -> Any:
|
|
269
|
+
resp = self._request(
|
|
270
|
+
"GET",
|
|
271
|
+
self._url(path),
|
|
272
|
+
headers=self._headers(headers),
|
|
273
|
+
params=params,
|
|
274
|
+
)
|
|
275
|
+
self._handle_error(resp, path)
|
|
276
|
+
return parse_json_response(resp, path)
|
|
277
|
+
|
|
278
|
+
def post(
|
|
279
|
+
self,
|
|
280
|
+
path: str,
|
|
281
|
+
json: dict[str, Any] | None = None,
|
|
282
|
+
files: dict[str, Any] | None = None,
|
|
283
|
+
headers: dict[str, str] | None = None,
|
|
284
|
+
) -> Any:
|
|
285
|
+
if files:
|
|
286
|
+
base_headers = self._merge_headers(headers, content_type=None)
|
|
287
|
+
resp = self._request("POST", self._url(path), headers=base_headers, data=json, files=files)
|
|
288
|
+
else:
|
|
289
|
+
base_headers = self._merge_headers(headers)
|
|
290
|
+
resp = self._request("POST", self._url(path), headers=base_headers, json=json)
|
|
291
|
+
self._handle_error(resp, path)
|
|
292
|
+
log_mutation("api", "post", resource_id=path)
|
|
293
|
+
# Handle empty/non-JSON responses (204, plain-text action endpoints).
|
|
294
|
+
# HTML is never a valid success body for API calls — that usually means
|
|
295
|
+
# base_url points at the frontend SPA catch-all.
|
|
296
|
+
if resp.status_code == 204 or not resp.content:
|
|
297
|
+
return {}
|
|
298
|
+
# Must precede the non-JSON early return below: an HTML 200 has a
|
|
299
|
+
# text/html content-type, so without this it would be handed back as a
|
|
300
|
+
# successful {"status": 200, "message": "<!doctype html..."}.
|
|
301
|
+
if looks_like_html(resp):
|
|
302
|
+
raise APIError(resp.status_code, HTML_BASE_URL_HINT, None)
|
|
303
|
+
content_type = resp.headers.get("content-type", "")
|
|
304
|
+
if "json" not in content_type:
|
|
305
|
+
return {"status": resp.status_code, "message": resp.text.strip() or "OK"}
|
|
306
|
+
return parse_json_response(resp, path)
|
|
307
|
+
|
|
308
|
+
def put(
|
|
309
|
+
self,
|
|
310
|
+
path: str,
|
|
311
|
+
json: dict[str, Any] | None = None,
|
|
312
|
+
headers: dict[str, str] | None = None,
|
|
313
|
+
) -> Any:
|
|
314
|
+
"""Send a PUT request with JSON body. Returns parsed response."""
|
|
315
|
+
resp = self._request(
|
|
316
|
+
"PUT",
|
|
317
|
+
self._url(path),
|
|
318
|
+
headers=self._headers(headers),
|
|
319
|
+
json=json,
|
|
320
|
+
)
|
|
321
|
+
self._handle_error(resp, path)
|
|
322
|
+
log_mutation("api", "put", resource_id=path)
|
|
323
|
+
return parse_json_response(resp, path)
|
|
324
|
+
|
|
325
|
+
def patch(
|
|
326
|
+
self,
|
|
327
|
+
path: str,
|
|
328
|
+
json: dict[str, Any] | None = None,
|
|
329
|
+
headers: dict[str, str] | None = None,
|
|
330
|
+
) -> Any:
|
|
331
|
+
"""Send a PATCH request with JSON body. Returns parsed response."""
|
|
332
|
+
resp = self._request(
|
|
333
|
+
"PATCH",
|
|
334
|
+
self._url(path),
|
|
335
|
+
headers=self._headers(headers),
|
|
336
|
+
json=json,
|
|
337
|
+
)
|
|
338
|
+
self._handle_error(resp, path)
|
|
339
|
+
log_mutation("api", "patch", resource_id=path)
|
|
340
|
+
return parse_json_response(resp, path)
|
|
341
|
+
|
|
342
|
+
def delete(self, path: str, headers: dict[str, str] | None = None) -> Any:
|
|
343
|
+
"""Send DELETE; return a JSON response when present, or None for 204."""
|
|
344
|
+
resp = self._request(
|
|
345
|
+
"DELETE",
|
|
346
|
+
self._url(path),
|
|
347
|
+
headers=self._headers(headers),
|
|
348
|
+
)
|
|
349
|
+
self._handle_error(resp, path)
|
|
350
|
+
log_mutation("api", "delete", resource_id=path)
|
|
351
|
+
if resp.status_code != 204 and resp.content:
|
|
352
|
+
return parse_json_response(resp, path)
|
|
353
|
+
return None
|
|
354
|
+
|
|
355
|
+
def download_presigned(self, url: str, dest: str | os.PathLike[str], *, chunk_size: int = 1024 * 1024) -> int:
|
|
356
|
+
"""Stream a presigned URL to ``dest`` and return the byte count.
|
|
357
|
+
|
|
358
|
+
Sends no CloudSprite credentials (the URL carries its own) and never puts
|
|
359
|
+
the URL or the storage error body in an error message or log line. Writes to a temporary sibling and
|
|
360
|
+
renames on success, so a failed download leaves no partial ``dest``.
|
|
361
|
+
"""
|
|
362
|
+
if self._closed:
|
|
363
|
+
raise CloudSpriteError("This client has been closed. Create a new Client() to continue.")
|
|
364
|
+
target = os.fspath(dest)
|
|
365
|
+
partial = f"{target}.part"
|
|
366
|
+
try:
|
|
367
|
+
resp = self._session.request("GET", url, stream=True, timeout=self._timeout)
|
|
368
|
+
except req.RequestException as exc:
|
|
369
|
+
raise APIError(0, f"Download failed: {type(exc).__name__}", None) from None
|
|
370
|
+
try:
|
|
371
|
+
if resp.status_code >= 400:
|
|
372
|
+
# Never surface the storage error body: a signature error can echo the
|
|
373
|
+
# canonical request, including X-Amz-Credential and the security token.
|
|
374
|
+
message = f"Download failed (HTTP {resp.status_code})"
|
|
375
|
+
if resp.status_code in (401, 403):
|
|
376
|
+
raise AuthError(message, status_code=resp.status_code)
|
|
377
|
+
raise APIError(resp.status_code, message, None)
|
|
378
|
+
written = 0
|
|
379
|
+
try:
|
|
380
|
+
with open(partial, "wb") as fh:
|
|
381
|
+
for chunk in resp.iter_content(chunk_size=chunk_size):
|
|
382
|
+
fh.write(chunk)
|
|
383
|
+
written += len(chunk)
|
|
384
|
+
except req.RequestException as exc:
|
|
385
|
+
raise APIError(0, f"Download failed: {type(exc).__name__}", None) from None
|
|
386
|
+
os.replace(partial, target)
|
|
387
|
+
return written
|
|
388
|
+
finally:
|
|
389
|
+
resp.close()
|
|
390
|
+
if os.path.exists(partial):
|
|
391
|
+
os.remove(partial)
|
|
392
|
+
|
|
393
|
+
def post_file(
|
|
394
|
+
self,
|
|
395
|
+
path: str,
|
|
396
|
+
file_name: str,
|
|
397
|
+
file_data: bytes,
|
|
398
|
+
extra_fields: dict[str, Any] | None = None,
|
|
399
|
+
headers: dict[str, str] | None = None,
|
|
400
|
+
) -> Any:
|
|
401
|
+
"""Upload a file using multipart/form-data."""
|
|
402
|
+
base_headers = self._merge_headers(headers, content_type=None)
|
|
403
|
+
files = {"file": (file_name, file_data)}
|
|
404
|
+
resp = self._request(
|
|
405
|
+
"POST",
|
|
406
|
+
self._url(path),
|
|
407
|
+
headers=base_headers,
|
|
408
|
+
files=files,
|
|
409
|
+
data=extra_fields,
|
|
410
|
+
)
|
|
411
|
+
self._handle_error(resp, path)
|
|
412
|
+
log_mutation("file", "upload", resource_id=path, filename=file_name)
|
|
413
|
+
return parse_json_response(resp, path)
|
|
414
|
+
|
|
415
|
+
def upload_file(self, path: str, file_path: str, headers: dict[str, str] | None = None) -> Any:
|
|
416
|
+
"""Upload a file from disk using multipart/form-data.
|
|
417
|
+
|
|
418
|
+
Args:
|
|
419
|
+
path: API endpoint path.
|
|
420
|
+
file_path: Local filesystem path to the file.
|
|
421
|
+
headers: Optional additional headers.
|
|
422
|
+
|
|
423
|
+
Returns:
|
|
424
|
+
Parsed JSON response from the server.
|
|
425
|
+
|
|
426
|
+
Raises:
|
|
427
|
+
FileNotFoundError: If file_path does not exist.
|
|
428
|
+
APIError: If the server rejects the upload.
|
|
429
|
+
"""
|
|
430
|
+
from pathlib import Path as FilePath
|
|
431
|
+
|
|
432
|
+
p = FilePath(file_path)
|
|
433
|
+
if not p.exists():
|
|
434
|
+
raise FileNotFoundError(f"File not found: {file_path}")
|
|
435
|
+
base_headers = self._merge_headers(headers, content_type=None)
|
|
436
|
+
with open(p, "rb") as f:
|
|
437
|
+
files = {"file": (p.name, f)}
|
|
438
|
+
resp = self._request(
|
|
439
|
+
"POST",
|
|
440
|
+
self._url(path),
|
|
441
|
+
headers=base_headers,
|
|
442
|
+
files=files,
|
|
443
|
+
)
|
|
444
|
+
self._handle_error(resp, path)
|
|
445
|
+
log_mutation("file", "upload", resource_id=path, filename=p.name)
|
|
446
|
+
return parse_json_response(resp, path)
|
|
447
|
+
|
|
448
|
+
def upload_multipart(self, path: str, file_path: str, chunk_size: int = 50 * 1024 * 1024) -> Any:
|
|
449
|
+
"""Upload a large file using chunked multipart upload.
|
|
450
|
+
|
|
451
|
+
For files >50MB, uses the backend's multipart upload protocol:
|
|
452
|
+
1. Initiate → get upload_id
|
|
453
|
+
2. Sign + upload each chunk
|
|
454
|
+
3. Complete upload
|
|
455
|
+
|
|
456
|
+
Args:
|
|
457
|
+
path: Dataset datafiles endpoint (e.g. "/api/datasets/{id}/datafiles/")
|
|
458
|
+
file_path: Local filesystem path.
|
|
459
|
+
chunk_size: Bytes per chunk (default: 50MB).
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
Parsed JSON response from completed upload.
|
|
463
|
+
"""
|
|
464
|
+
from pathlib import Path as FilePath
|
|
465
|
+
|
|
466
|
+
p = FilePath(file_path)
|
|
467
|
+
if not p.exists():
|
|
468
|
+
raise FileNotFoundError(f"File not found: {file_path}")
|
|
469
|
+
|
|
470
|
+
file_size = p.stat().st_size
|
|
471
|
+
if file_size <= chunk_size:
|
|
472
|
+
return self.upload_file(path, file_path)
|
|
473
|
+
|
|
474
|
+
# Initiate multipart
|
|
475
|
+
multipart_base = path.rstrip("/").rsplit("/datafiles", 1)[0] + "/datafiles/multipart"
|
|
476
|
+
init_resp = self.post(
|
|
477
|
+
f"{multipart_base}/initiate",
|
|
478
|
+
json={"filename": p.name, "file_size": file_size, "content_type": "application/octet-stream"},
|
|
479
|
+
)
|
|
480
|
+
upload_id = init_resp["upload_id"]
|
|
481
|
+
|
|
482
|
+
# Upload chunks via the session (retries + timeout). No auth headers —
|
|
483
|
+
# signed URLs carry their own credentials.
|
|
484
|
+
parts = []
|
|
485
|
+
part_number = 1
|
|
486
|
+
with open(p, "rb") as f:
|
|
487
|
+
while True:
|
|
488
|
+
chunk = f.read(chunk_size)
|
|
489
|
+
if not chunk:
|
|
490
|
+
break
|
|
491
|
+
sign_resp = self.post(f"{multipart_base}/{upload_id}/sign", json={"part_number": part_number})
|
|
492
|
+
signed_url = sign_resp["signed_url"]
|
|
493
|
+
upload_resp = self._request("PUT", signed_url, data=chunk)
|
|
494
|
+
self._handle_error(upload_resp, signed_url)
|
|
495
|
+
etag = upload_resp.headers.get("ETag", "").strip('"')
|
|
496
|
+
parts.append({"part_number": part_number, "etag": etag})
|
|
497
|
+
part_number += 1
|
|
498
|
+
|
|
499
|
+
# Complete
|
|
500
|
+
complete_resp = self.post(f"{multipart_base}/{upload_id}/complete", json={"parts": parts})
|
|
501
|
+
log_mutation("file", "multipart_upload", resource_id=path, filename=p.name, size=str(file_size))
|
|
502
|
+
return complete_resp
|