infixspeed-cli 0.0.16__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.
- infix_cli/__init__.py +5 -0
- infix_cli/__main__.py +6 -0
- infix_cli/agent-guide.txt +71 -0
- infix_cli/cli_framework.py +96 -0
- infix_cli/command_contract.py +157 -0
- infix_cli/commands/__init__.py +1 -0
- infix_cli/commands/_artifacts.py +142 -0
- infix_cli/commands/_comparison.py +443 -0
- infix_cli/commands/_confirm.py +26 -0
- infix_cli/commands/_control.py +290 -0
- infix_cli/commands/_create.py +351 -0
- infix_cli/commands/_create_output.py +139 -0
- infix_cli/commands/_delete.py +288 -0
- infix_cli/commands/_download.py +459 -0
- infix_cli/commands/_fusion_common.py +191 -0
- infix_cli/commands/_fusion_config.py +394 -0
- infix_cli/commands/_fusion_feedback.py +319 -0
- infix_cli/commands/_fusion_tasks.py +507 -0
- infix_cli/commands/_fusion_tensorboard.py +132 -0
- infix_cli/commands/_jobs.py +312 -0
- infix_cli/commands/_logs.py +210 -0
- infix_cli/commands/_publish.py +123 -0
- infix_cli/commands/_register.py +600 -0
- infix_cli/commands/_register_output.py +231 -0
- infix_cli/commands/_storage_tree.py +62 -0
- infix_cli/commands/admin.py +668 -0
- infix_cli/commands/asset.py +2012 -0
- infix_cli/commands/auth.py +246 -0
- infix_cli/commands/deploy.py +850 -0
- infix_cli/commands/evaluation.py +360 -0
- infix_cli/commands/examples.py +138 -0
- infix_cli/commands/fusion.py +1842 -0
- infix_cli/commands/merge.py +709 -0
- infix_cli/commands/resource.py +127 -0
- infix_cli/commands/spark.py +347 -0
- infix_cli/commands/storage.py +329 -0
- infix_cli/commands/training.py +748 -0
- infix_cli/config.py +311 -0
- infix_cli/config_input.py +217 -0
- infix_cli/context.py +84 -0
- infix_cli/discovery.py +459 -0
- infix_cli/domain/__init__.py +1 -0
- infix_cli/domain/dto/__init__.py +6 -0
- infix_cli/domain/dto/admin.py +413 -0
- infix_cli/domain/dto/asset.py +390 -0
- infix_cli/domain/dto/common.py +136 -0
- infix_cli/domain/dto/evaluation.py +296 -0
- infix_cli/domain/dto/logs.py +98 -0
- infix_cli/domain/dto/resource.py +108 -0
- infix_cli/domain/dto/serving.py +156 -0
- infix_cli/domain/dto/spark.py +241 -0
- infix_cli/domain/dto/storage.py +75 -0
- infix_cli/domain/dto/training.py +272 -0
- infix_cli/domain/enums.py +359 -0
- infix_cli/domain/hyperparams.py +190 -0
- infix_cli/domain/refs.py +108 -0
- infix_cli/domain/resolve.py +619 -0
- infix_cli/errors.py +158 -0
- infix_cli/example_data/__init__.py +1 -0
- infix_cli/example_data/fusion/README.md +128 -0
- infix_cli/example_data/fusion/fusion.json +149 -0
- infix_cli/example_data/fusion/prompts/code.jsonl +16 -0
- infix_cli/example_data/fusion/prompts/math.jsonl +16 -0
- infix_cli/example_data/fusion.zip +0 -0
- infix_cli/example_data/merge/README.md +89 -0
- infix_cli/example_data/merge/merge.json +26 -0
- infix_cli/example_data/merge.zip +0 -0
- infix_cli/http/__init__.py +1 -0
- infix_cli/http/browser_auth.py +160 -0
- infix_cli/http/client.py +575 -0
- infix_cli/http/pagination.py +84 -0
- infix_cli/http/upload.py +254 -0
- infix_cli/main.py +432 -0
- infix_cli/pipeline_config_schema.py +122 -0
- infix_cli/render/__init__.py +79 -0
- infix_cli/render/json_out.py +123 -0
- infix_cli/render/progress.py +62 -0
- infix_cli/render/text.py +233 -0
- infix_cli/update_check.py +177 -0
- infix_cli/waiter.py +93 -0
- infix_cli/workspace.py +158 -0
- infixspeed_cli-0.0.16.dist-info/METADATA +58 -0
- infixspeed_cli-0.0.16.dist-info/RECORD +85 -0
- infixspeed_cli-0.0.16.dist-info/WHEEL +4 -0
- infixspeed_cli-0.0.16.dist-info/entry_points.txt +2 -0
infix_cli/http/client.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
"""Authenticated HTTP client: one place for auth headers, retries, and
|
|
2
|
+
translation of backend status codes into ``CliError`` subclasses.
|
|
3
|
+
|
|
4
|
+
Deliberately thin. Anything domain-shaped (name -> id, enum mapping,
|
|
5
|
+
pagination policy) belongs in ``domain/``, not here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any, Iterable, Mapping
|
|
13
|
+
|
|
14
|
+
from infix_cli.errors import (
|
|
15
|
+
ApiError,
|
|
16
|
+
AuthError,
|
|
17
|
+
CliError,
|
|
18
|
+
ConflictError,
|
|
19
|
+
ForbiddenError,
|
|
20
|
+
NotFoundError,
|
|
21
|
+
UsageError,
|
|
22
|
+
SubmissionUnknown,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
API_PREFIX = "/api/v1"
|
|
26
|
+
|
|
27
|
+
_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
28
|
+
_RETRYABLE_METHODS = frozenset({"GET", "HEAD"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ApiClient:
|
|
32
|
+
"""Thin httpx wrapper over the platform REST API."""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
base_url: str,
|
|
37
|
+
api_key: str,
|
|
38
|
+
workspace_id: str = "",
|
|
39
|
+
*,
|
|
40
|
+
timeout: float = 60.0,
|
|
41
|
+
max_retries: int = 3,
|
|
42
|
+
verbose: bool = False,
|
|
43
|
+
transport: Any = None,
|
|
44
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
import httpx # imported lazily: a top-level import costs every command ~40ms
|
|
47
|
+
|
|
48
|
+
self.base_url = base_url.rstrip("/")
|
|
49
|
+
self.workspace_id = workspace_id
|
|
50
|
+
self._max_retries = max_retries
|
|
51
|
+
self._verbose = verbose
|
|
52
|
+
headers = {
|
|
53
|
+
"Authorization": f"Bearer {api_key}",
|
|
54
|
+
"Accept": "application/json",
|
|
55
|
+
"User-Agent": _user_agent(),
|
|
56
|
+
}
|
|
57
|
+
if workspace_id:
|
|
58
|
+
headers["X-Workspace-Id"] = workspace_id
|
|
59
|
+
headers.update(extra_headers or {})
|
|
60
|
+
headers.update(_headers_from_environment())
|
|
61
|
+
self._client = httpx.Client(
|
|
62
|
+
base_url=self.base_url + API_PREFIX,
|
|
63
|
+
headers=headers,
|
|
64
|
+
timeout=timeout,
|
|
65
|
+
follow_redirects=True,
|
|
66
|
+
# Injected by tests (httpx.MockTransport); None keeps the default.
|
|
67
|
+
transport=transport,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# ── lifecycle ────────────────────────────────────────────────────────────
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
self._client.close()
|
|
74
|
+
|
|
75
|
+
def __enter__(self) -> "ApiClient":
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def __exit__(self, *_exc: object) -> None:
|
|
79
|
+
self.close()
|
|
80
|
+
|
|
81
|
+
# ── verbs ────────────────────────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
def get(self, path: str, *, params: Mapping[str, Any] | None = None) -> Any:
|
|
84
|
+
return self.request("GET", path, params=params)
|
|
85
|
+
|
|
86
|
+
def post(
|
|
87
|
+
self,
|
|
88
|
+
path: str,
|
|
89
|
+
*,
|
|
90
|
+
json: Any = None,
|
|
91
|
+
params: Mapping[str, Any] | None = None,
|
|
92
|
+
) -> Any:
|
|
93
|
+
return self.request("POST", path, json=json, params=params)
|
|
94
|
+
|
|
95
|
+
def post_if_supported(
|
|
96
|
+
self, path: str, *, params: Mapping[str, Any] | None = None,
|
|
97
|
+
) -> Any | None:
|
|
98
|
+
"""POST to an endpoint older backends may not have; None when they do not.
|
|
99
|
+
|
|
100
|
+
"Does not have" means the route itself is missing — FastAPI's bare 404
|
|
101
|
+
``Not Found`` or a 405 — or the backend says 501 (it has the route but
|
|
102
|
+
cannot serve this request that way). Any other failure, including a 404
|
|
103
|
+
about the thing asked for, is raised as usual. Not retried, like post().
|
|
104
|
+
"""
|
|
105
|
+
import httpx
|
|
106
|
+
|
|
107
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
108
|
+
started = time.monotonic()
|
|
109
|
+
try:
|
|
110
|
+
response = self._client.request("POST", path, params=clean)
|
|
111
|
+
except httpx.TransportError as exc:
|
|
112
|
+
self._trace("POST", path, clean, None, started, 1, error=exc)
|
|
113
|
+
raise ApiError(
|
|
114
|
+
f"Cannot reach {self.base_url}: {exc}",
|
|
115
|
+
"Check the API URL and your network, then retry.",
|
|
116
|
+
) from exc
|
|
117
|
+
self._trace("POST", path, clean, response, started, 1)
|
|
118
|
+
if response.status_code in (405, 501) or (
|
|
119
|
+
response.status_code == 404 and _detail_text(response) == "Not Found"
|
|
120
|
+
):
|
|
121
|
+
return None
|
|
122
|
+
if response.status_code >= 400:
|
|
123
|
+
raise _translate(response)
|
|
124
|
+
return _decode(response)
|
|
125
|
+
|
|
126
|
+
def patch(self, path: str, *, json: Any = None) -> Any:
|
|
127
|
+
return self.request("PATCH", path, json=json)
|
|
128
|
+
|
|
129
|
+
def delete(
|
|
130
|
+
self,
|
|
131
|
+
path: str,
|
|
132
|
+
*,
|
|
133
|
+
params: Mapping[str, Any] | None = None,
|
|
134
|
+
json: Any = None,
|
|
135
|
+
) -> Any:
|
|
136
|
+
# Some deletes carry a body (DELETE /storage/item, /storage/items).
|
|
137
|
+
return self.request("DELETE", path, params=params, json=json)
|
|
138
|
+
|
|
139
|
+
def put_bytes(self, path: str, payload: bytes, *, timeout: float = 300.0) -> Any:
|
|
140
|
+
"""PUT a raw byte range — one part of a chunked upload.
|
|
141
|
+
|
|
142
|
+
Not retried: the caller tracks which parts landed and resumes from
|
|
143
|
+
there, so a blind retry here would only duplicate that bookkeeping.
|
|
144
|
+
"""
|
|
145
|
+
import httpx
|
|
146
|
+
|
|
147
|
+
started = time.monotonic()
|
|
148
|
+
try:
|
|
149
|
+
response = self._client.put(
|
|
150
|
+
path, content=payload,
|
|
151
|
+
headers={"Content-Type": "application/octet-stream"},
|
|
152
|
+
timeout=timeout,
|
|
153
|
+
)
|
|
154
|
+
except httpx.TransportError as exc:
|
|
155
|
+
self._trace("PUT", path, {}, None, started, 1, error=exc)
|
|
156
|
+
raise ApiError(f"Upload to {self.base_url} failed: {exc}") from exc
|
|
157
|
+
# Traced like every other call: without it --verbose showed a chunked
|
|
158
|
+
# upload as just its session and complete calls, and a failure in the
|
|
159
|
+
# middle looked like the parts were never sent at all.
|
|
160
|
+
self._trace("PUT", path, {}, response, started, 1)
|
|
161
|
+
if response.status_code >= 400:
|
|
162
|
+
raise _translate(response)
|
|
163
|
+
return _decode(response)
|
|
164
|
+
|
|
165
|
+
def post_multipart(
|
|
166
|
+
self,
|
|
167
|
+
path: str,
|
|
168
|
+
*,
|
|
169
|
+
files: Mapping[str, Any],
|
|
170
|
+
data: Mapping[str, Any] | None = None,
|
|
171
|
+
params: Mapping[str, Any] | None = None,
|
|
172
|
+
timeout: float = 300.0,
|
|
173
|
+
) -> Any:
|
|
174
|
+
"""Multipart upload. Never retried, and given its own longer timeout.
|
|
175
|
+
|
|
176
|
+
Used by the endpoints that take a file directly rather than through the
|
|
177
|
+
chunked upload protocol (dataset upload-local).
|
|
178
|
+
"""
|
|
179
|
+
import httpx
|
|
180
|
+
|
|
181
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
182
|
+
try:
|
|
183
|
+
response = self._client.post(
|
|
184
|
+
path, files=dict(files), data=dict(data or {}), params=clean, timeout=timeout,
|
|
185
|
+
)
|
|
186
|
+
except httpx.TransportError as exc:
|
|
187
|
+
raise ApiError(f"Upload to {self.base_url} failed: {exc}") from exc
|
|
188
|
+
if response.status_code >= 400:
|
|
189
|
+
raise _translate(response)
|
|
190
|
+
return _decode(response)
|
|
191
|
+
|
|
192
|
+
def request(
|
|
193
|
+
self,
|
|
194
|
+
method: str,
|
|
195
|
+
path: str,
|
|
196
|
+
*,
|
|
197
|
+
params: Mapping[str, Any] | None = None,
|
|
198
|
+
json: Any = None,
|
|
199
|
+
headers: Mapping[str,str] | None = None,
|
|
200
|
+
) -> Any:
|
|
201
|
+
"""Send one request, retrying only where a retry cannot duplicate work.
|
|
202
|
+
|
|
203
|
+
POST is never retried automatically: a timed-out create may well have
|
|
204
|
+
reached the backend, and a second attempt would submit a second job.
|
|
205
|
+
"""
|
|
206
|
+
import httpx
|
|
207
|
+
|
|
208
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
209
|
+
retryable = method.upper() in _RETRYABLE_METHODS
|
|
210
|
+
attempt = 0
|
|
211
|
+
while True:
|
|
212
|
+
attempt += 1
|
|
213
|
+
started = time.monotonic()
|
|
214
|
+
try:
|
|
215
|
+
response = self._client.request(method, path, params=clean, json=json,headers=headers)
|
|
216
|
+
except httpx.TransportError as exc:
|
|
217
|
+
self._trace(method, path, clean, None, started, attempt, error=exc)
|
|
218
|
+
if retryable and attempt <= self._max_retries:
|
|
219
|
+
self._sleep(attempt)
|
|
220
|
+
continue
|
|
221
|
+
if not retryable:
|
|
222
|
+
raise SubmissionUnknown(
|
|
223
|
+
"The write request did not receive a response; its outcome is unknown.",
|
|
224
|
+
"Query the resource before submitting again.",
|
|
225
|
+
details={"method": method.upper(), "path": path},
|
|
226
|
+
) from exc
|
|
227
|
+
raise ApiError(
|
|
228
|
+
f"Cannot reach {self.base_url}.",
|
|
229
|
+
"Check the API URL and your network, then retry.", retryable=True,
|
|
230
|
+
) from exc
|
|
231
|
+
|
|
232
|
+
self._trace(method, path, clean, response, started, attempt)
|
|
233
|
+
if response.status_code in _RETRY_STATUSES and retryable and attempt <= self._max_retries:
|
|
234
|
+
self._sleep(attempt)
|
|
235
|
+
continue
|
|
236
|
+
if response.status_code >= 400:
|
|
237
|
+
err = _translate(response)
|
|
238
|
+
err.retryable = retryable and response.status_code in _RETRY_STATUSES
|
|
239
|
+
raise err
|
|
240
|
+
return _decode(response)
|
|
241
|
+
|
|
242
|
+
def stream_lines(
|
|
243
|
+
self,
|
|
244
|
+
method: str,
|
|
245
|
+
path: str,
|
|
246
|
+
*,
|
|
247
|
+
params: Mapping[str, Any] | None = None,
|
|
248
|
+
) -> Iterable[str]:
|
|
249
|
+
"""Yield raw response lines (used by log streaming)."""
|
|
250
|
+
import httpx
|
|
251
|
+
|
|
252
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
253
|
+
try:
|
|
254
|
+
with self._client.stream(method, path, params=clean) as response:
|
|
255
|
+
if response.status_code >= 400:
|
|
256
|
+
response.read()
|
|
257
|
+
raise _translate(response)
|
|
258
|
+
yield from response.iter_lines()
|
|
259
|
+
except httpx.TransportError as exc:
|
|
260
|
+
raise ApiError(f"Stream to {self.base_url} failed: {exc}") from exc
|
|
261
|
+
|
|
262
|
+
def download(
|
|
263
|
+
self,
|
|
264
|
+
path: str,
|
|
265
|
+
target: Any,
|
|
266
|
+
*,
|
|
267
|
+
params: Mapping[str, Any] | None = None,
|
|
268
|
+
on_chunk: Any = None,
|
|
269
|
+
on_etag: Any = None,
|
|
270
|
+
offset: int = 0,
|
|
271
|
+
if_range: str | None = None,
|
|
272
|
+
timeout: float = 300.0,
|
|
273
|
+
) -> int:
|
|
274
|
+
"""Stream a GET response body into ``target`` (a binary file object).
|
|
275
|
+
|
|
276
|
+
``if_range`` 将断点绑定到已确认的远端 ETag。响应与断点不匹配时,
|
|
277
|
+
从头下载。``on_etag`` 可以在读响应体前确认本地完整文件仍可复用。
|
|
278
|
+
|
|
279
|
+
Not retried. A dropped connection raises ``TransferInterrupted`` so the
|
|
280
|
+
caller can keep what arrived and resume from it.
|
|
281
|
+
"""
|
|
282
|
+
import httpx
|
|
283
|
+
|
|
284
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
285
|
+
headers = {"Accept-Encoding": "identity"}
|
|
286
|
+
if offset:
|
|
287
|
+
headers["Range"] = f"bytes={offset}-"
|
|
288
|
+
if if_range:
|
|
289
|
+
headers["If-Range"] = if_range
|
|
290
|
+
started = time.monotonic()
|
|
291
|
+
size = offset
|
|
292
|
+
try:
|
|
293
|
+
with self._client.stream(
|
|
294
|
+
"GET", path, params=clean, headers=headers, timeout=timeout,
|
|
295
|
+
) as response:
|
|
296
|
+
self._trace("GET", path, clean, response, started, 1)
|
|
297
|
+
invalid_range = response.status_code == 206 and (
|
|
298
|
+
not response.headers.get("content-range", "").startswith(f"bytes {offset}-")
|
|
299
|
+
or (if_range and response.headers.get("etag") != if_range)
|
|
300
|
+
)
|
|
301
|
+
if offset and (response.status_code == 416 or invalid_range):
|
|
302
|
+
response.close()
|
|
303
|
+
target.seek(0)
|
|
304
|
+
target.truncate()
|
|
305
|
+
return self.download(
|
|
306
|
+
path, target, params=params, on_chunk=on_chunk, on_etag=on_etag,
|
|
307
|
+
timeout=timeout,
|
|
308
|
+
)
|
|
309
|
+
if response.status_code >= 400:
|
|
310
|
+
response.read()
|
|
311
|
+
raise _translate(response)
|
|
312
|
+
if not offset and response.status_code == 206:
|
|
313
|
+
raise ApiError("Download returned a partial response without a Range request.")
|
|
314
|
+
if offset and response.status_code != 206:
|
|
315
|
+
target.seek(0)
|
|
316
|
+
target.truncate()
|
|
317
|
+
size = 0
|
|
318
|
+
if on_etag is not None and not on_etag(response.headers.get("etag")):
|
|
319
|
+
return size
|
|
320
|
+
for chunk in response.iter_bytes(1024 * 1024):
|
|
321
|
+
target.write(chunk)
|
|
322
|
+
size += len(chunk)
|
|
323
|
+
if on_chunk is not None:
|
|
324
|
+
on_chunk(len(chunk))
|
|
325
|
+
except httpx.TransportError as exc:
|
|
326
|
+
self._trace("GET", path, clean, None, started, 1, error=exc)
|
|
327
|
+
raise TransferInterrupted(f"Download from {self.base_url} failed: {exc}") from exc
|
|
328
|
+
return size
|
|
329
|
+
|
|
330
|
+
def _sleep(self, attempt: int) -> None:
|
|
331
|
+
time.sleep(min(0.5 * (2 ** (attempt - 1)), 4.0))
|
|
332
|
+
|
|
333
|
+
def _trace(
|
|
334
|
+
self,
|
|
335
|
+
method: str,
|
|
336
|
+
path: str,
|
|
337
|
+
params: Mapping[str, Any],
|
|
338
|
+
response: Any,
|
|
339
|
+
started: float,
|
|
340
|
+
attempt: int,
|
|
341
|
+
*,
|
|
342
|
+
error: Exception | None = None,
|
|
343
|
+
) -> None:
|
|
344
|
+
"""One line per request, for ``--verbose``.
|
|
345
|
+
|
|
346
|
+
Written to stderr so it never contaminates ``-o json``, and carrying
|
|
347
|
+
what actually helps when a command misbehaves: which call, how it ended,
|
|
348
|
+
how long it took, and whether it was a retry. Never the request body —
|
|
349
|
+
registrations carry HuggingFace and git tokens.
|
|
350
|
+
"""
|
|
351
|
+
if not self._verbose:
|
|
352
|
+
return
|
|
353
|
+
import sys
|
|
354
|
+
|
|
355
|
+
elapsed = (time.monotonic() - started) * 1000
|
|
356
|
+
outcome = f"ERR {type(error).__name__}" if error is not None else str(
|
|
357
|
+
getattr(response, "status_code", "?"),
|
|
358
|
+
)
|
|
359
|
+
retry = f" (attempt {attempt})" if attempt > 1 else ""
|
|
360
|
+
print(
|
|
361
|
+
f" → {method.upper()} {_trace_target(path)}{_query_text(params)} "
|
|
362
|
+
f"{outcome} {elapsed:.0f}ms{retry}",
|
|
363
|
+
file=sys.stderr,
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
class TransferInterrupted(ApiError):
|
|
368
|
+
"""A download whose connection dropped part-way; what arrived is usable."""
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _trace_target(path: str) -> str:
|
|
372
|
+
"""What --verbose shows for a request: the site path, never a download ticket.
|
|
373
|
+
|
|
374
|
+
API calls are relative to /api/v1; download-service URLs are absolute and
|
|
375
|
+
carry a ticket that, while it lasts, lets anyone holding it fetch the file.
|
|
376
|
+
Verbose output gets pasted into chats and issues, so the ticket is elided.
|
|
377
|
+
"""
|
|
378
|
+
if "://" not in path:
|
|
379
|
+
return f"{API_PREFIX}{path}"
|
|
380
|
+
from urllib.parse import urlsplit
|
|
381
|
+
|
|
382
|
+
site_path = urlsplit(path).path
|
|
383
|
+
head, sep, rest = site_path.partition("/dl/")
|
|
384
|
+
if sep and not head:
|
|
385
|
+
_ticket, _, name = rest.partition("/")
|
|
386
|
+
return f"/dl/<ticket>/{name}"
|
|
387
|
+
return site_path
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _headers_from_environment() -> dict[str, str]:
|
|
391
|
+
"""Tracing headers the deployment environment asks us to forward.
|
|
392
|
+
|
|
393
|
+
Two variables, both ``Name=value`` pairs separated by commas:
|
|
394
|
+
|
|
395
|
+
* ``INFIX_EXTRA_HEADERS`` — literal values, fixed for the process.
|
|
396
|
+
* ``INFIX_EXTRA_HEADER_FILES`` — values read from a file, for anything the
|
|
397
|
+
environment republishes while the process could be running.
|
|
398
|
+
|
|
399
|
+
Deliberately generic. Callers that need a header (a CI system tagging its
|
|
400
|
+
runs, an agent runtime attributing backend time to the turn that waited on
|
|
401
|
+
it) declare it from outside, so no caller's concepts leak into the client.
|
|
402
|
+
Read once at construction: a command that outlives the state a file
|
|
403
|
+
describes keeps reporting the state it started under, which attributes its
|
|
404
|
+
later requests to the thing that caused them.
|
|
405
|
+
"""
|
|
406
|
+
headers: dict[str, str] = {}
|
|
407
|
+
for name, value in _parse_pairs(os.environ.get("INFIX_EXTRA_HEADERS", "")):
|
|
408
|
+
headers[name] = value
|
|
409
|
+
for name, path in _parse_pairs(os.environ.get("INFIX_EXTRA_HEADER_FILES", "")):
|
|
410
|
+
try:
|
|
411
|
+
with open(path, encoding="utf-8") as handle:
|
|
412
|
+
content = handle.read().strip()
|
|
413
|
+
except OSError:
|
|
414
|
+
# Instrumentation must never break a command: an unreadable or
|
|
415
|
+
# not-yet-written file simply means the header is omitted.
|
|
416
|
+
continue
|
|
417
|
+
if content:
|
|
418
|
+
headers[name] = content
|
|
419
|
+
return headers
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _parse_pairs(raw: str) -> list[tuple[str, str]]:
|
|
423
|
+
pairs = []
|
|
424
|
+
for chunk in raw.split(","):
|
|
425
|
+
name, sep, value = chunk.partition("=")
|
|
426
|
+
name, value = name.strip(), value.strip()
|
|
427
|
+
if sep and name and value:
|
|
428
|
+
pairs.append((name, value))
|
|
429
|
+
return pairs
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _user_agent() -> str:
|
|
433
|
+
from infix_cli import __version__
|
|
434
|
+
|
|
435
|
+
return f"infix-cli/{__version__}"
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _decode(response: Any) -> Any:
|
|
439
|
+
if response.status_code == 204 or not response.content:
|
|
440
|
+
return None
|
|
441
|
+
try:
|
|
442
|
+
return response.json()
|
|
443
|
+
except ValueError:
|
|
444
|
+
return response.text
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _query_text(params: Mapping[str, Any]) -> str:
|
|
448
|
+
if not params:
|
|
449
|
+
return ""
|
|
450
|
+
return "?" + "&".join(f"{key}={value}" for key, value in params.items())
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _translate(response: Any) -> CliError:
|
|
454
|
+
error = _response_error(response)
|
|
455
|
+
error.http = {
|
|
456
|
+
"status": response.status_code,
|
|
457
|
+
"method": response.request.method,
|
|
458
|
+
"path": _trace_target(str(response.request.url)),
|
|
459
|
+
}
|
|
460
|
+
return error
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _response_error(response: Any) -> CliError:
|
|
464
|
+
"""Map an HTTP failure onto the CLI's error hierarchy.
|
|
465
|
+
|
|
466
|
+
The backend's ``detail`` is used verbatim as the reason — it is closer to
|
|
467
|
+
the truth than anything the CLI could paraphrase (tech-design §3.10 rule 4).
|
|
468
|
+
"""
|
|
469
|
+
status = response.status_code
|
|
470
|
+
detail = _detail_text(response)
|
|
471
|
+
if status == 401:
|
|
472
|
+
return AuthError(
|
|
473
|
+
detail or "Authentication failed.",
|
|
474
|
+
'Run "infix auth login --api-key sk-..." to refresh your credentials.',
|
|
475
|
+
)
|
|
476
|
+
if status == 403:
|
|
477
|
+
return ForbiddenError(detail or "Permission denied.")
|
|
478
|
+
if status == 404:
|
|
479
|
+
return NotFoundError(detail or "Not found.")
|
|
480
|
+
if status == 409:
|
|
481
|
+
return ConflictError(detail or "Conflict.", _conflict_hint(detail))
|
|
482
|
+
if status == 503:
|
|
483
|
+
# The asset pipeline is the one place a 503 is routine rather than an
|
|
484
|
+
# outage: HuggingFace imports, git clones and large directory copies all
|
|
485
|
+
# run as K8s jobs, and the endpoint refuses them outright when that
|
|
486
|
+
# pipeline is not up. "HTTP 503" alone reads as "try again later", which
|
|
487
|
+
# is wrong — nothing the caller waits for will fix it.
|
|
488
|
+
return ApiError(
|
|
489
|
+
detail or "The platform is temporarily unavailable.",
|
|
490
|
+
"Registering from HuggingFace or git needs the platform's copy "
|
|
491
|
+
"pipeline. Ask an administrator, or register from Workspace Storage "
|
|
492
|
+
"instead."
|
|
493
|
+
if "copy" in (detail or "").lower() else None,
|
|
494
|
+
)
|
|
495
|
+
if status in (400, 422):
|
|
496
|
+
# A validation error names the field but not the call it came from, and
|
|
497
|
+
# one command can fan out to half a dozen endpoints — `admin resource
|
|
498
|
+
# jobs <name> --detail` alone hits the running-jobs list, up to three
|
|
499
|
+
# module listings, a workers endpoint and a metrics endpoint. "status:
|
|
500
|
+
# Field required" with no path sends the reader through all of them.
|
|
501
|
+
fields = []
|
|
502
|
+
try:
|
|
503
|
+
body = response.json()
|
|
504
|
+
validation = body.get("detail") if isinstance(body, dict) else None
|
|
505
|
+
if isinstance(validation, list):
|
|
506
|
+
for item in validation:
|
|
507
|
+
if isinstance(item, dict):
|
|
508
|
+
fields.append({
|
|
509
|
+
"field": ".".join(str(part) for part in item.get("loc", []) if part not in {"body", "query"}),
|
|
510
|
+
"reason": item.get("msg", "Invalid value"),
|
|
511
|
+
})
|
|
512
|
+
except ValueError:
|
|
513
|
+
pass
|
|
514
|
+
return UsageError(detail or "Invalid request.", _request_hint(response), details=fields or None)
|
|
515
|
+
return ApiError(f"Backend returned HTTP {status}: {detail or 'no detail'}")
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _conflict_hint(detail: str) -> str | None:
|
|
519
|
+
"""Point at the wait, for the one 409 that resolves by itself.
|
|
520
|
+
|
|
521
|
+
A version's files cannot be listed or previewed while its copy is still
|
|
522
|
+
running. That is a "not yet", not a "no", and the backend's own wording does
|
|
523
|
+
not say how to get past it.
|
|
524
|
+
"""
|
|
525
|
+
if "still in progress" in (detail or "").lower():
|
|
526
|
+
return 'Wait for the version to become available, or watch it with "--wait".'
|
|
527
|
+
return None
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _request_hint(response: Any) -> str | None:
|
|
531
|
+
"""Which call failed, for errors whose text does not say.
|
|
532
|
+
|
|
533
|
+
Path only: the query string carries search terms and ids that make the line
|
|
534
|
+
long without making it clearer.
|
|
535
|
+
"""
|
|
536
|
+
request = getattr(response, "request", None)
|
|
537
|
+
if request is None:
|
|
538
|
+
return None
|
|
539
|
+
method = getattr(request, "method", "")
|
|
540
|
+
url = getattr(request, "url", None)
|
|
541
|
+
path = getattr(url, "path", "") if url is not None else ""
|
|
542
|
+
if not method or not path:
|
|
543
|
+
return None
|
|
544
|
+
return f"Failed request: {method} {_trace_target(str(url))}"
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _detail_text(response: Any) -> str:
|
|
548
|
+
"""Flatten the several shapes ``detail`` takes across backend handlers."""
|
|
549
|
+
try:
|
|
550
|
+
body = response.json()
|
|
551
|
+
except ValueError:
|
|
552
|
+
return (response.text or "").strip()[:500]
|
|
553
|
+
if not isinstance(body, dict):
|
|
554
|
+
return str(body)[:500]
|
|
555
|
+
detail = body.get("detail", body.get("message"))
|
|
556
|
+
if isinstance(detail, str):
|
|
557
|
+
return detail
|
|
558
|
+
if isinstance(detail, dict):
|
|
559
|
+
errors = detail.get("errors")
|
|
560
|
+
if isinstance(errors, list) and errors:
|
|
561
|
+
# upload-local's JSONL validation: one entry per offending line.
|
|
562
|
+
# Printed as the dict itself this read "{'errors': ['Line 1: …']}".
|
|
563
|
+
listed = "\n".join(f" {e}" for e in errors)
|
|
564
|
+
return f"{detail.get('message') or 'Validation failed'}:\n{listed}"
|
|
565
|
+
return str(detail.get("message") or detail.get("error_code") or detail)
|
|
566
|
+
if isinstance(detail, list): # FastAPI validation errors
|
|
567
|
+
parts = []
|
|
568
|
+
for item in detail:
|
|
569
|
+
if isinstance(item, dict):
|
|
570
|
+
loc = ".".join(str(p) for p in item.get("loc", []) if p not in ("body", "query"))
|
|
571
|
+
parts.append(f"{loc}: {item.get('msg', '')}".strip(": "))
|
|
572
|
+
else:
|
|
573
|
+
parts.append(str(item))
|
|
574
|
+
return "; ".join(parts)
|
|
575
|
+
return ""
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Page-walking helpers.
|
|
2
|
+
|
|
3
|
+
User-facing ``list`` commands page explicitly (``--page`` / ``--page-size``,
|
|
4
|
+
decision 15) — these helpers exist for *internal* lookups, above all
|
|
5
|
+
name -> id resolution, where the CLI must see every candidate before it can
|
|
6
|
+
say "no such asset".
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Iterator, Mapping
|
|
12
|
+
|
|
13
|
+
MAX_PAGE_SIZE = 100
|
|
14
|
+
_PAGE_LIMIT = 100 # 10k rows; a lookup needing more is a bug, not a big workspace
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def iter_items(
|
|
18
|
+
client: Any,
|
|
19
|
+
path: str,
|
|
20
|
+
*,
|
|
21
|
+
params: Mapping[str, Any] | None = None,
|
|
22
|
+
page_size: int = MAX_PAGE_SIZE,
|
|
23
|
+
) -> Iterator[dict]:
|
|
24
|
+
"""Yield every item across pages of a ``{items, total, page, ...}`` response.
|
|
25
|
+
|
|
26
|
+
Tolerates endpoints that return a bare list (``GET /tags``) by yielding it
|
|
27
|
+
once and stopping.
|
|
28
|
+
"""
|
|
29
|
+
page = 1
|
|
30
|
+
seen = 0
|
|
31
|
+
while page <= _PAGE_LIMIT:
|
|
32
|
+
payload = client.get(path, params={**(params or {}), "page": page, "page_size": page_size})
|
|
33
|
+
if isinstance(payload, list):
|
|
34
|
+
yield from payload
|
|
35
|
+
return
|
|
36
|
+
if not isinstance(payload, dict):
|
|
37
|
+
return
|
|
38
|
+
items = payload.get("items") or []
|
|
39
|
+
yield from items
|
|
40
|
+
seen += len(items)
|
|
41
|
+
total = payload.get("total")
|
|
42
|
+
if not items:
|
|
43
|
+
return
|
|
44
|
+
if isinstance(total, int) and seen >= total:
|
|
45
|
+
return
|
|
46
|
+
pages = payload.get("total_pages")
|
|
47
|
+
if isinstance(pages, int) and page >= pages:
|
|
48
|
+
return
|
|
49
|
+
page += 1
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def fetch_page(
|
|
53
|
+
client: Any,
|
|
54
|
+
path: str,
|
|
55
|
+
*,
|
|
56
|
+
params: Mapping[str, Any] | None = None,
|
|
57
|
+
page: int = 1,
|
|
58
|
+
page_size: int = 10,
|
|
59
|
+
) -> tuple[list[dict], int, int, int]:
|
|
60
|
+
"""Fetch exactly one page. Returns ``(items, page, page_size, total)``.
|
|
61
|
+
|
|
62
|
+
Endpoints that ignore pagination (``GET /tags``, ``GET /storage/list``)
|
|
63
|
+
return a bare list; the caller slices locally and still reports the full
|
|
64
|
+
total, so ``Showing 1-10 of 42`` stays honest.
|
|
65
|
+
"""
|
|
66
|
+
payload = client.get(path, params={**(params or {}), "page": page, "page_size": page_size})
|
|
67
|
+
if isinstance(payload, list):
|
|
68
|
+
return list(payload), page, page_size, len(payload)
|
|
69
|
+
if not isinstance(payload, dict):
|
|
70
|
+
return [], page, page_size, 0
|
|
71
|
+
items = list(payload.get("items") or [])
|
|
72
|
+
total = payload.get("total")
|
|
73
|
+
return (
|
|
74
|
+
items,
|
|
75
|
+
int(payload.get("page") or page),
|
|
76
|
+
int(payload.get("page_size") or page_size),
|
|
77
|
+
int(total) if isinstance(total, int) else len(items),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def slice_page(items: list, page: int, page_size: int) -> list:
|
|
82
|
+
"""Local pagination for endpoints the backend does not paginate."""
|
|
83
|
+
start = (page - 1) * page_size
|
|
84
|
+
return items[start : start + page_size]
|