bulkit 0.1.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.
- bulkit/__init__.py +307 -0
- bulkit/_base_client.py +1147 -0
- bulkit/_constants.py +15 -0
- bulkit/_exceptions.py +306 -0
- bulkit/_pagination.py +226 -0
- bulkit/_resource.py +19 -0
- bulkit/_response.py +85 -0
- bulkit/_types.py +52 -0
- bulkit/_version.py +3 -0
- bulkit/client.py +146 -0
- bulkit/py.typed +0 -0
- bulkit/resources/__init__.py +85 -0
- bulkit/resources/channels.py +305 -0
- bulkit/resources/media.py +1319 -0
- bulkit/resources/platforms.py +122 -0
- bulkit/resources/posts.py +1186 -0
- bulkit/resources/stats.py +267 -0
- bulkit/resources/tags.py +107 -0
- bulkit/resources/usage.py +108 -0
- bulkit/resources/webhooks.py +823 -0
- bulkit/types/__init__.py +233 -0
- bulkit/types/_base.py +10 -0
- bulkit/types/_errors.py +113 -0
- bulkit/types/channel.py +52 -0
- bulkit/types/comment.py +35 -0
- bulkit/types/media.py +48 -0
- bulkit/types/platform.py +105 -0
- bulkit/types/post.py +250 -0
- bulkit/types/shared.py +123 -0
- bulkit/types/stats.py +112 -0
- bulkit/types/tag.py +10 -0
- bulkit/types/usage.py +29 -0
- bulkit/types/webhook.py +145 -0
- bulkit/webhooks.py +141 -0
- bulkit-0.1.0.dist-info/METADATA +346 -0
- bulkit-0.1.0.dist-info/RECORD +38 -0
- bulkit-0.1.0.dist-info/WHEEL +4 -0
- bulkit-0.1.0.dist-info/licenses/LICENSE +21 -0
bulkit/_base_client.py
ADDED
|
@@ -0,0 +1,1147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import random
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
11
|
+
from typing import Any, Generic, TypeVar, cast, overload
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
from pydantic import BaseModel, TypeAdapter, ValidationError
|
|
16
|
+
from typing_extensions import Self, TypeAlias
|
|
17
|
+
|
|
18
|
+
from bulkit._constants import (
|
|
19
|
+
API_PREFIX,
|
|
20
|
+
DEFAULT_BASE_URL,
|
|
21
|
+
DEFAULT_MAX_RETRIES,
|
|
22
|
+
DEFAULT_TIMEOUT,
|
|
23
|
+
INITIAL_RETRY_DELAY,
|
|
24
|
+
MAX_IDEMPOTENCY_KEY_LENGTH,
|
|
25
|
+
MAX_RETRY_AFTER,
|
|
26
|
+
MAX_RETRY_DELAY,
|
|
27
|
+
)
|
|
28
|
+
from bulkit._exceptions import (
|
|
29
|
+
APIConnectionError,
|
|
30
|
+
APIConnectionTimeoutError,
|
|
31
|
+
APIError,
|
|
32
|
+
APIResponseValidationError,
|
|
33
|
+
BulkitError,
|
|
34
|
+
RateLimitError,
|
|
35
|
+
)
|
|
36
|
+
from bulkit._pagination import (
|
|
37
|
+
AsyncCursorPage,
|
|
38
|
+
AsyncPaginator,
|
|
39
|
+
SyncCursorPage,
|
|
40
|
+
build_async_cursor_page,
|
|
41
|
+
build_sync_cursor_page,
|
|
42
|
+
)
|
|
43
|
+
from bulkit._response import APIResponse
|
|
44
|
+
from bulkit._types import (
|
|
45
|
+
NOT_GIVEN,
|
|
46
|
+
Headers,
|
|
47
|
+
HTTPMethod,
|
|
48
|
+
NotGiven,
|
|
49
|
+
NotGivenOr,
|
|
50
|
+
Query,
|
|
51
|
+
RequestOptions,
|
|
52
|
+
Timeout,
|
|
53
|
+
)
|
|
54
|
+
from bulkit._version import __version__
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"AsyncAPIClient",
|
|
58
|
+
"SyncAPIClient",
|
|
59
|
+
"encode_path_param",
|
|
60
|
+
"encode_query",
|
|
61
|
+
"strip_not_given",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
T = TypeVar("T")
|
|
65
|
+
_HttpxClientT = TypeVar("_HttpxClientT", httpx.Client, httpx.AsyncClient)
|
|
66
|
+
|
|
67
|
+
_WRITE_METHODS = frozenset({"POST", "PUT"})
|
|
68
|
+
_READ_METHODS = frozenset({"GET", "DELETE"})
|
|
69
|
+
_ALWAYS_RETRY_STATUSES = frozenset({408, 429, 502, 503, 504})
|
|
70
|
+
|
|
71
|
+
FilesParam: TypeAlias = Mapping[str, tuple[str, bytes, str]]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------------------------------------------------------------------------
|
|
75
|
+
# Encoding helpers
|
|
76
|
+
# ---------------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def encode_path_param(value: str, name: str = "param") -> str:
|
|
80
|
+
"""Percent-encode a single path segment; ``/`` becomes ``%2F``. Rejects empty strings."""
|
|
81
|
+
if value == "":
|
|
82
|
+
raise ValueError(f"Path parameter '{name}' must not be empty.")
|
|
83
|
+
return quote(value, safe="")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _encode_query_value(value: object) -> str:
|
|
87
|
+
# bool before int: bool is a subclass of int.
|
|
88
|
+
if isinstance(value, bool):
|
|
89
|
+
return "true" if value else "false"
|
|
90
|
+
return str(value)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def encode_query(query: Query | None, extra_query: Query | None = None) -> list[tuple[str, str]]:
|
|
94
|
+
"""Flatten query params into ordered pairs.
|
|
95
|
+
|
|
96
|
+
``extra_query`` overrides ``query`` key-by-key. ``None``/``NOT_GIVEN`` values are skipped,
|
|
97
|
+
sequences expand into repeated keys, and booleans serialize as ``"true"``/``"false"``.
|
|
98
|
+
"""
|
|
99
|
+
merged: dict[str, object] = {}
|
|
100
|
+
if query:
|
|
101
|
+
merged.update(query)
|
|
102
|
+
if extra_query:
|
|
103
|
+
merged.update(extra_query)
|
|
104
|
+
|
|
105
|
+
pairs: list[tuple[str, str]] = []
|
|
106
|
+
for key, value in merged.items():
|
|
107
|
+
if value is None or isinstance(value, NotGiven):
|
|
108
|
+
continue
|
|
109
|
+
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
|
110
|
+
for item in cast("Sequence[object]", value):
|
|
111
|
+
if item is None or isinstance(item, NotGiven):
|
|
112
|
+
continue
|
|
113
|
+
pairs.append((key, _encode_query_value(item)))
|
|
114
|
+
else:
|
|
115
|
+
pairs.append((key, _encode_query_value(value)))
|
|
116
|
+
return pairs
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def strip_not_given(obj: Any) -> Any:
|
|
120
|
+
"""Recursively drop ``NOT_GIVEN`` from dicts and lists, keeping key order and explicit ``None``."""
|
|
121
|
+
if isinstance(obj, Mapping):
|
|
122
|
+
mapping = cast("Mapping[object, object]", obj)
|
|
123
|
+
return {k: strip_not_given(v) for k, v in mapping.items() if not isinstance(v, NotGiven)}
|
|
124
|
+
if isinstance(obj, (list, tuple)):
|
|
125
|
+
seq = cast("Sequence[object]", obj)
|
|
126
|
+
return [strip_not_given(v) for v in seq if not isinstance(v, NotGiven)]
|
|
127
|
+
return obj
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _serialize_json_body(json_body: object | None) -> bytes | None:
|
|
131
|
+
if json_body is None or isinstance(json_body, NotGiven):
|
|
132
|
+
return None
|
|
133
|
+
cleaned = strip_not_given(json_body)
|
|
134
|
+
return json.dumps(
|
|
135
|
+
cleaned,
|
|
136
|
+
separators=(",", ":"),
|
|
137
|
+
ensure_ascii=False,
|
|
138
|
+
allow_nan=False,
|
|
139
|
+
).encode("utf-8")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ---------------------------------------------------------------------------
|
|
143
|
+
# Response decoding
|
|
144
|
+
# ---------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _decode_error_body(response: httpx.Response) -> Any:
|
|
148
|
+
if not response.content:
|
|
149
|
+
return None
|
|
150
|
+
try:
|
|
151
|
+
return json.loads(response.content)
|
|
152
|
+
except ValueError:
|
|
153
|
+
return response.text
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _decode_success_body(response: httpx.Response) -> Any:
|
|
157
|
+
if response.status_code == 204 or not response.content:
|
|
158
|
+
return None
|
|
159
|
+
content_type = response.headers.get("content-type", "")
|
|
160
|
+
if "json" not in content_type.lower():
|
|
161
|
+
return response.text
|
|
162
|
+
try:
|
|
163
|
+
return json.loads(response.content)
|
|
164
|
+
except ValueError as exc:
|
|
165
|
+
raise APIResponseValidationError(
|
|
166
|
+
"The API returned a response that is not valid JSON.",
|
|
167
|
+
http_response=response,
|
|
168
|
+
cause=exc,
|
|
169
|
+
) from exc
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _validate(value: Any, cast_to: type[T] | TypeAdapter[T]) -> T:
|
|
173
|
+
if isinstance(cast_to, TypeAdapter):
|
|
174
|
+
adapter: TypeAdapter[T] = cast_to
|
|
175
|
+
return adapter.validate_python(value)
|
|
176
|
+
if issubclass(cast_to, BaseModel):
|
|
177
|
+
return cast(T, cast_to.model_validate(value))
|
|
178
|
+
return TypeAdapter(cast_to).validate_python(value)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _parse_response(response: httpx.Response, cast_to: type[T] | TypeAdapter[T] | None) -> Any:
|
|
182
|
+
if cast_to is type(None):
|
|
183
|
+
return None
|
|
184
|
+
decoded = _decode_success_body(response)
|
|
185
|
+
if cast_to is None:
|
|
186
|
+
return decoded
|
|
187
|
+
if decoded is None:
|
|
188
|
+
raise APIResponseValidationError(
|
|
189
|
+
"Expected a JSON response body, got an empty response.",
|
|
190
|
+
http_response=response,
|
|
191
|
+
)
|
|
192
|
+
try:
|
|
193
|
+
return _validate(decoded, cast_to)
|
|
194
|
+
except ValidationError as exc:
|
|
195
|
+
raise APIResponseValidationError(
|
|
196
|
+
"Data returned by the API is invalid for the expected schema.",
|
|
197
|
+
http_response=response,
|
|
198
|
+
cause=exc,
|
|
199
|
+
) from exc
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _item_parser(item_type: type[T]) -> Callable[[Any], T]:
|
|
203
|
+
if issubclass(item_type, BaseModel):
|
|
204
|
+
model = item_type
|
|
205
|
+
|
|
206
|
+
def parse_model(item: Any) -> T:
|
|
207
|
+
return cast(T, model.model_validate(item))
|
|
208
|
+
|
|
209
|
+
return parse_model
|
|
210
|
+
adapter = TypeAdapter(item_type)
|
|
211
|
+
return adapter.validate_python
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------------------
|
|
215
|
+
# Shared client machinery
|
|
216
|
+
# ---------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
_API_KEY_RE = re.compile(r"[\x21-\x7e]+")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _resolve_api_key(api_key: str | None) -> str:
|
|
223
|
+
resolved = api_key if api_key is not None else os.environ.get("BULKIT_API_KEY")
|
|
224
|
+
resolved = resolved.strip() if resolved is not None else ""
|
|
225
|
+
if not resolved:
|
|
226
|
+
raise BulkitError(
|
|
227
|
+
"Missing API key. Pass `api_key` or set the BULKIT_API_KEY environment variable."
|
|
228
|
+
)
|
|
229
|
+
if not _API_KEY_RE.fullmatch(resolved):
|
|
230
|
+
# Never echo the key itself: it may be a real credential with a stray character.
|
|
231
|
+
raise BulkitError("API key contains invalid characters.")
|
|
232
|
+
return resolved
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _resolve_base_url(base_url: str | None) -> str:
|
|
236
|
+
resolved = base_url.strip() if base_url is not None else ""
|
|
237
|
+
if not resolved:
|
|
238
|
+
env = os.environ.get("BULKIT_BASE_URL")
|
|
239
|
+
resolved = env.strip() if env is not None else ""
|
|
240
|
+
if not resolved:
|
|
241
|
+
resolved = DEFAULT_BASE_URL
|
|
242
|
+
return resolved.rstrip("/")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _find_header(headers: Headers | None, name: str) -> str | None:
|
|
246
|
+
if not headers:
|
|
247
|
+
return None
|
|
248
|
+
lowered = name.lower()
|
|
249
|
+
for key, value in headers.items():
|
|
250
|
+
if key.lower() == lowered:
|
|
251
|
+
return value
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _should_retry(error: APIError, method: str) -> bool:
|
|
256
|
+
"""What is worth retrying, per the API's contract.
|
|
257
|
+
|
|
258
|
+
- 408/429/502/503/504: transient on any method.
|
|
259
|
+
- 409 only for ``request_in_progress``.
|
|
260
|
+
- 500 only on reads: a write's idempotency key is kept on a 500, so a retry would replay it.
|
|
261
|
+
- 402 ``quota_exceeded`` and every other 4xx: retrying can never succeed.
|
|
262
|
+
"""
|
|
263
|
+
status = error.status_code
|
|
264
|
+
if status in _ALWAYS_RETRY_STATUSES:
|
|
265
|
+
return True
|
|
266
|
+
if status == 409:
|
|
267
|
+
return error.code == "request_in_progress"
|
|
268
|
+
if status == 500:
|
|
269
|
+
return method in _READ_METHODS
|
|
270
|
+
return False
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _retry_delay(attempt: int, error: BulkitError | None) -> float:
|
|
274
|
+
if isinstance(error, RateLimitError):
|
|
275
|
+
retry_after = error.retry_after
|
|
276
|
+
if retry_after is not None:
|
|
277
|
+
return min(retry_after, MAX_RETRY_AFTER)
|
|
278
|
+
backoff = min(INITIAL_RETRY_DELAY * (2.0**attempt), MAX_RETRY_DELAY)
|
|
279
|
+
# Jitter between 75% and 100% so clients do not retry in lockstep.
|
|
280
|
+
return backoff * random.uniform(0.75, 1.0)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _build_options(
|
|
284
|
+
*,
|
|
285
|
+
extra_headers: Headers | None,
|
|
286
|
+
extra_query: Query | None,
|
|
287
|
+
timeout: NotGivenOr[Timeout],
|
|
288
|
+
max_retries: NotGivenOr[int],
|
|
289
|
+
idempotency_key: NotGivenOr[str],
|
|
290
|
+
) -> RequestOptions:
|
|
291
|
+
options: RequestOptions = {}
|
|
292
|
+
if extra_headers is not None:
|
|
293
|
+
options["extra_headers"] = extra_headers
|
|
294
|
+
if extra_query is not None:
|
|
295
|
+
options["extra_query"] = extra_query
|
|
296
|
+
if not isinstance(timeout, NotGiven):
|
|
297
|
+
options["timeout"] = timeout
|
|
298
|
+
if not isinstance(max_retries, NotGiven):
|
|
299
|
+
options["max_retries"] = max_retries
|
|
300
|
+
if not isinstance(idempotency_key, NotGiven):
|
|
301
|
+
options["idempotency_key"] = idempotency_key
|
|
302
|
+
return options
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _next_page_options(options: RequestOptions | None) -> RequestOptions | None:
|
|
306
|
+
"""Drop any ``cursor`` from ``extra_query`` so it cannot pin every page to the same cursor."""
|
|
307
|
+
if not options:
|
|
308
|
+
return options
|
|
309
|
+
extra_query = options.get("extra_query")
|
|
310
|
+
if not extra_query or "cursor" not in extra_query:
|
|
311
|
+
return options
|
|
312
|
+
copied: RequestOptions = {**options}
|
|
313
|
+
copied["extra_query"] = {k: v for k, v in extra_query.items() if k != "cursor"}
|
|
314
|
+
return copied
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class _BaseClient(Generic[_HttpxClientT]):
|
|
318
|
+
_client: _HttpxClientT
|
|
319
|
+
_owns_client: bool
|
|
320
|
+
|
|
321
|
+
def __init__(
|
|
322
|
+
self,
|
|
323
|
+
*,
|
|
324
|
+
api_key: str | None,
|
|
325
|
+
base_url: str | None,
|
|
326
|
+
timeout: Timeout,
|
|
327
|
+
max_retries: int,
|
|
328
|
+
default_headers: Mapping[str, str] | None,
|
|
329
|
+
) -> None:
|
|
330
|
+
if max_retries < 0:
|
|
331
|
+
raise ValueError("max_retries must be >= 0.")
|
|
332
|
+
self._api_key = _resolve_api_key(api_key)
|
|
333
|
+
self._base_url = _resolve_base_url(base_url)
|
|
334
|
+
self._timeout: Timeout = timeout
|
|
335
|
+
self._max_retries = max_retries
|
|
336
|
+
self._default_headers: dict[str, str] = dict(default_headers) if default_headers else {}
|
|
337
|
+
|
|
338
|
+
@property
|
|
339
|
+
def is_test_mode(self) -> bool:
|
|
340
|
+
return self._api_key.startswith("bk_test_")
|
|
341
|
+
|
|
342
|
+
@property
|
|
343
|
+
def base_url(self) -> str:
|
|
344
|
+
return self._base_url
|
|
345
|
+
|
|
346
|
+
@property
|
|
347
|
+
def timeout(self) -> Timeout:
|
|
348
|
+
return self._timeout
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def max_retries(self) -> int:
|
|
352
|
+
return self._max_retries
|
|
353
|
+
|
|
354
|
+
def __repr__(self) -> str:
|
|
355
|
+
return (
|
|
356
|
+
f"{type(self).__name__}(base_url={self._base_url!r}, "
|
|
357
|
+
f"is_test_mode={self.is_test_mode!r}, timeout={self._timeout!r}, "
|
|
358
|
+
f"max_retries={self._max_retries!r})"
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
# -- request preparation -------------------------------------------------
|
|
362
|
+
|
|
363
|
+
def _build_url(self, path: str) -> str:
|
|
364
|
+
if not path.startswith("/"):
|
|
365
|
+
path = "/" + path
|
|
366
|
+
return f"{self._base_url}{API_PREFIX}{path}"
|
|
367
|
+
|
|
368
|
+
def _resolve_timeout(self, options: RequestOptions) -> Timeout:
|
|
369
|
+
timeout = options.get("timeout", NOT_GIVEN)
|
|
370
|
+
return self._timeout if isinstance(timeout, NotGiven) else timeout
|
|
371
|
+
|
|
372
|
+
def _resolve_max_retries(self, options: RequestOptions) -> int:
|
|
373
|
+
max_retries = options.get("max_retries", NOT_GIVEN)
|
|
374
|
+
return self._max_retries if isinstance(max_retries, NotGiven) else max(0, max_retries)
|
|
375
|
+
|
|
376
|
+
def _resolve_idempotency_key(self, method: str, options: RequestOptions) -> str | None:
|
|
377
|
+
if method not in _WRITE_METHODS:
|
|
378
|
+
return None
|
|
379
|
+
explicit = options.get("idempotency_key", NOT_GIVEN)
|
|
380
|
+
key: str | None
|
|
381
|
+
if isinstance(explicit, str):
|
|
382
|
+
key = explicit
|
|
383
|
+
else:
|
|
384
|
+
key = _find_header(options.get("extra_headers"), "Idempotency-Key")
|
|
385
|
+
if key is None:
|
|
386
|
+
key = str(uuid.uuid4())
|
|
387
|
+
elif not key:
|
|
388
|
+
raise ValueError("idempotency_key must not be empty.")
|
|
389
|
+
if len(key) > MAX_IDEMPOTENCY_KEY_LENGTH:
|
|
390
|
+
raise ValueError(
|
|
391
|
+
f"idempotency_key must be at most {MAX_IDEMPOTENCY_KEY_LENGTH} characters "
|
|
392
|
+
f"(got {len(key)})."
|
|
393
|
+
)
|
|
394
|
+
return key
|
|
395
|
+
|
|
396
|
+
def _build_headers(
|
|
397
|
+
self,
|
|
398
|
+
*,
|
|
399
|
+
method: str,
|
|
400
|
+
options: RequestOptions,
|
|
401
|
+
has_json_body: bool,
|
|
402
|
+
has_files: bool,
|
|
403
|
+
idempotency_key: str | None,
|
|
404
|
+
) -> httpx.Headers:
|
|
405
|
+
headers = httpx.Headers(
|
|
406
|
+
{"Accept": "application/json", "User-Agent": f"bulkit-python/{__version__}"}
|
|
407
|
+
)
|
|
408
|
+
headers.update(self._default_headers)
|
|
409
|
+
extra_headers = options.get("extra_headers")
|
|
410
|
+
if extra_headers:
|
|
411
|
+
headers.update(extra_headers)
|
|
412
|
+
if has_json_body:
|
|
413
|
+
headers["Content-Type"] = "application/json"
|
|
414
|
+
elif has_files and "content-type" in headers:
|
|
415
|
+
# Let httpx set multipart/form-data with its boundary.
|
|
416
|
+
del headers["content-type"]
|
|
417
|
+
if idempotency_key is not None and method in _WRITE_METHODS:
|
|
418
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
419
|
+
elif "idempotency-key" in headers:
|
|
420
|
+
del headers["idempotency-key"]
|
|
421
|
+
# Always last, so it overrides any caller-supplied authorization header in any casing.
|
|
422
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
423
|
+
return headers
|
|
424
|
+
|
|
425
|
+
def _build_request(
|
|
426
|
+
self,
|
|
427
|
+
method: HTTPMethod,
|
|
428
|
+
path: str,
|
|
429
|
+
*,
|
|
430
|
+
query: Query | None,
|
|
431
|
+
body_bytes: bytes | None,
|
|
432
|
+
files: FilesParam | None,
|
|
433
|
+
options: RequestOptions,
|
|
434
|
+
idempotency_key: str | None,
|
|
435
|
+
) -> httpx.Request:
|
|
436
|
+
headers = self._build_headers(
|
|
437
|
+
method=method,
|
|
438
|
+
options=options,
|
|
439
|
+
has_json_body=body_bytes is not None,
|
|
440
|
+
has_files=bool(files),
|
|
441
|
+
idempotency_key=idempotency_key,
|
|
442
|
+
)
|
|
443
|
+
params = encode_query(query, options.get("extra_query"))
|
|
444
|
+
try:
|
|
445
|
+
return self._client.build_request(
|
|
446
|
+
method,
|
|
447
|
+
self._build_url(path),
|
|
448
|
+
params=tuple(params),
|
|
449
|
+
headers=headers,
|
|
450
|
+
content=body_bytes,
|
|
451
|
+
files=dict(files) if files else None,
|
|
452
|
+
timeout=self._resolve_timeout(options),
|
|
453
|
+
)
|
|
454
|
+
except httpx.InvalidURL as exc:
|
|
455
|
+
raise BulkitError(f"Invalid request URL: {exc}") from exc
|
|
456
|
+
|
|
457
|
+
def _external_put_request(
|
|
458
|
+
self, url: str, content: bytes, timeout: NotGivenOr[Timeout]
|
|
459
|
+
) -> httpx.Request:
|
|
460
|
+
resolved = self._timeout if isinstance(timeout, NotGiven) else timeout
|
|
461
|
+
try:
|
|
462
|
+
return httpx.Request(
|
|
463
|
+
"PUT",
|
|
464
|
+
url,
|
|
465
|
+
content=content,
|
|
466
|
+
extensions={"timeout": httpx.Timeout(resolved).as_dict()},
|
|
467
|
+
)
|
|
468
|
+
except httpx.InvalidURL as exc:
|
|
469
|
+
raise BulkitError(f"Invalid upload URL: {exc}") from exc
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _map_transport_error(exc: httpx.TransportError) -> BulkitError:
|
|
473
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
474
|
+
return APIConnectionTimeoutError(cause=exc)
|
|
475
|
+
if isinstance(exc, httpx.UnsupportedProtocol):
|
|
476
|
+
return BulkitError(f"Unsupported protocol in request URL: {exc}")
|
|
477
|
+
return APIConnectionError(cause=exc)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
# ---------------------------------------------------------------------------
|
|
481
|
+
# Sync client
|
|
482
|
+
# ---------------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class SyncAPIClient(_BaseClient[httpx.Client]):
|
|
486
|
+
def __init__(
|
|
487
|
+
self,
|
|
488
|
+
*,
|
|
489
|
+
api_key: str | None = None,
|
|
490
|
+
base_url: str | None = None,
|
|
491
|
+
timeout: Timeout = DEFAULT_TIMEOUT,
|
|
492
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
493
|
+
default_headers: Mapping[str, str] | None = None,
|
|
494
|
+
http_client: httpx.Client | None = None,
|
|
495
|
+
) -> None:
|
|
496
|
+
super().__init__(
|
|
497
|
+
api_key=api_key,
|
|
498
|
+
base_url=base_url,
|
|
499
|
+
timeout=timeout,
|
|
500
|
+
max_retries=max_retries,
|
|
501
|
+
default_headers=default_headers,
|
|
502
|
+
)
|
|
503
|
+
if http_client is not None:
|
|
504
|
+
self._client = http_client
|
|
505
|
+
self._owns_client = False
|
|
506
|
+
else:
|
|
507
|
+
self._client = httpx.Client(timeout=timeout)
|
|
508
|
+
self._owns_client = True
|
|
509
|
+
|
|
510
|
+
# -- lifecycle -----------------------------------------------------------
|
|
511
|
+
|
|
512
|
+
def close(self) -> None:
|
|
513
|
+
"""Close the underlying HTTP client, unless it was supplied by the caller."""
|
|
514
|
+
if self._owns_client:
|
|
515
|
+
self._client.close()
|
|
516
|
+
|
|
517
|
+
def __enter__(self) -> Self:
|
|
518
|
+
return self
|
|
519
|
+
|
|
520
|
+
def __exit__(self, *_exc_info: object) -> None:
|
|
521
|
+
self.close()
|
|
522
|
+
|
|
523
|
+
def _sleep(self, seconds: float) -> None:
|
|
524
|
+
time.sleep(seconds)
|
|
525
|
+
|
|
526
|
+
# -- core request --------------------------------------------------------
|
|
527
|
+
|
|
528
|
+
def _send_with_retries(
|
|
529
|
+
self,
|
|
530
|
+
method: HTTPMethod,
|
|
531
|
+
path: str,
|
|
532
|
+
*,
|
|
533
|
+
query: Query | None,
|
|
534
|
+
json_body: object | None,
|
|
535
|
+
files: FilesParam | None,
|
|
536
|
+
options: RequestOptions | None,
|
|
537
|
+
) -> httpx.Response:
|
|
538
|
+
opts: RequestOptions = options or {}
|
|
539
|
+
idempotency_key = self._resolve_idempotency_key(method, opts)
|
|
540
|
+
body_bytes = _serialize_json_body(json_body)
|
|
541
|
+
max_retries = self._resolve_max_retries(opts)
|
|
542
|
+
|
|
543
|
+
attempt = 0
|
|
544
|
+
while True:
|
|
545
|
+
request = self._build_request(
|
|
546
|
+
method,
|
|
547
|
+
path,
|
|
548
|
+
query=query,
|
|
549
|
+
body_bytes=body_bytes,
|
|
550
|
+
files=files,
|
|
551
|
+
options=opts,
|
|
552
|
+
idempotency_key=idempotency_key,
|
|
553
|
+
)
|
|
554
|
+
try:
|
|
555
|
+
response = self._client.send(request)
|
|
556
|
+
except httpx.TransportError as exc:
|
|
557
|
+
error = _map_transport_error(exc)
|
|
558
|
+
if attempt < max_retries and isinstance(error, APIConnectionError):
|
|
559
|
+
self._sleep(_retry_delay(attempt, error))
|
|
560
|
+
attempt += 1
|
|
561
|
+
continue
|
|
562
|
+
raise error from exc
|
|
563
|
+
|
|
564
|
+
if response.is_success:
|
|
565
|
+
return response
|
|
566
|
+
|
|
567
|
+
api_error = APIError.from_response(response, _decode_error_body(response))
|
|
568
|
+
if attempt < max_retries and _should_retry(api_error, method):
|
|
569
|
+
response.close()
|
|
570
|
+
self._sleep(_retry_delay(attempt, api_error))
|
|
571
|
+
attempt += 1
|
|
572
|
+
continue
|
|
573
|
+
raise api_error
|
|
574
|
+
|
|
575
|
+
@overload
|
|
576
|
+
def _request(
|
|
577
|
+
self,
|
|
578
|
+
method: HTTPMethod,
|
|
579
|
+
path: str,
|
|
580
|
+
*,
|
|
581
|
+
cast_to: type[None],
|
|
582
|
+
query: Query | None = None,
|
|
583
|
+
json_body: object | None = None,
|
|
584
|
+
files: FilesParam | None = None,
|
|
585
|
+
options: RequestOptions | None = None,
|
|
586
|
+
) -> APIResponse[None]: ...
|
|
587
|
+
|
|
588
|
+
@overload
|
|
589
|
+
def _request(
|
|
590
|
+
self,
|
|
591
|
+
method: HTTPMethod,
|
|
592
|
+
path: str,
|
|
593
|
+
*,
|
|
594
|
+
cast_to: type[T] | TypeAdapter[T],
|
|
595
|
+
query: Query | None = None,
|
|
596
|
+
json_body: object | None = None,
|
|
597
|
+
files: FilesParam | None = None,
|
|
598
|
+
options: RequestOptions | None = None,
|
|
599
|
+
) -> APIResponse[T]: ...
|
|
600
|
+
|
|
601
|
+
@overload
|
|
602
|
+
def _request(
|
|
603
|
+
self,
|
|
604
|
+
method: HTTPMethod,
|
|
605
|
+
path: str,
|
|
606
|
+
*,
|
|
607
|
+
cast_to: None,
|
|
608
|
+
query: Query | None = None,
|
|
609
|
+
json_body: object | None = None,
|
|
610
|
+
files: FilesParam | None = None,
|
|
611
|
+
options: RequestOptions | None = None,
|
|
612
|
+
) -> APIResponse[Any]: ...
|
|
613
|
+
|
|
614
|
+
def _request(
|
|
615
|
+
self,
|
|
616
|
+
method: HTTPMethod,
|
|
617
|
+
path: str,
|
|
618
|
+
*,
|
|
619
|
+
cast_to: type[T] | TypeAdapter[T] | None,
|
|
620
|
+
query: Query | None = None,
|
|
621
|
+
json_body: object | None = None,
|
|
622
|
+
files: FilesParam | None = None,
|
|
623
|
+
options: RequestOptions | None = None,
|
|
624
|
+
) -> APIResponse[Any]:
|
|
625
|
+
response = self._send_with_retries(
|
|
626
|
+
method, path, query=query, json_body=json_body, files=files, options=options
|
|
627
|
+
)
|
|
628
|
+
return APIResponse(response, lambda: _parse_response(response, cast_to))
|
|
629
|
+
|
|
630
|
+
# -- pagination ----------------------------------------------------------
|
|
631
|
+
|
|
632
|
+
def _get_api_list(
|
|
633
|
+
self,
|
|
634
|
+
path: str,
|
|
635
|
+
*,
|
|
636
|
+
item_type: type[T],
|
|
637
|
+
query: Query | None = None,
|
|
638
|
+
options: RequestOptions | None = None,
|
|
639
|
+
) -> SyncCursorPage[T]:
|
|
640
|
+
return self._get_api_list_raw(
|
|
641
|
+
path, item_type=item_type, query=query, options=options
|
|
642
|
+
).parse()
|
|
643
|
+
|
|
644
|
+
def _get_api_list_raw(
|
|
645
|
+
self,
|
|
646
|
+
path: str,
|
|
647
|
+
*,
|
|
648
|
+
item_type: type[T],
|
|
649
|
+
query: Query | None = None,
|
|
650
|
+
options: RequestOptions | None = None,
|
|
651
|
+
) -> APIResponse[SyncCursorPage[T]]:
|
|
652
|
+
parse_item = _item_parser(item_type)
|
|
653
|
+
|
|
654
|
+
def fetch_page(cursor: str) -> SyncCursorPage[T]:
|
|
655
|
+
next_query: dict[str, Any] = {**(query or {}), "cursor": cursor}
|
|
656
|
+
return self._get_api_list(
|
|
657
|
+
path, item_type=item_type, query=next_query, options=_next_page_options(options)
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
response = self._send_with_retries(
|
|
661
|
+
"GET", path, query=query, json_body=None, files=None, options=options
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
def parse() -> SyncCursorPage[T]:
|
|
665
|
+
body = _decode_success_body(response)
|
|
666
|
+
try:
|
|
667
|
+
return build_sync_cursor_page(
|
|
668
|
+
body, http_response=response, parse_item=parse_item, fetch_page=fetch_page
|
|
669
|
+
)
|
|
670
|
+
except ValidationError as exc:
|
|
671
|
+
raise APIResponseValidationError(
|
|
672
|
+
"Data returned by the API is invalid for the expected schema.",
|
|
673
|
+
http_response=response,
|
|
674
|
+
cause=exc,
|
|
675
|
+
) from exc
|
|
676
|
+
|
|
677
|
+
return APIResponse(response, parse)
|
|
678
|
+
|
|
679
|
+
# -- external uploads ----------------------------------------------------
|
|
680
|
+
|
|
681
|
+
def _send_external_put(
|
|
682
|
+
self, url: str, *, content: bytes, timeout: NotGivenOr[Timeout] = NOT_GIVEN
|
|
683
|
+
) -> httpx.Response:
|
|
684
|
+
"""PUT raw bytes to a presigned URL with zero SDK/auth headers.
|
|
685
|
+
|
|
686
|
+
Sent through the configured ``httpx.Client`` so injected transports, proxies and TLS
|
|
687
|
+
settings still apply, but bypassing ``build_request`` so no client default headers
|
|
688
|
+
or auth are merged in.
|
|
689
|
+
"""
|
|
690
|
+
request = self._external_put_request(url, content, timeout)
|
|
691
|
+
try:
|
|
692
|
+
return self._client.send(request, auth=None)
|
|
693
|
+
except httpx.TransportError as exc:
|
|
694
|
+
raise _map_transport_error(exc) from exc
|
|
695
|
+
|
|
696
|
+
# -- low-level escape hatches --------------------------------------------
|
|
697
|
+
|
|
698
|
+
def request(
|
|
699
|
+
self,
|
|
700
|
+
method: HTTPMethod,
|
|
701
|
+
path: str,
|
|
702
|
+
*,
|
|
703
|
+
body: object | None = None,
|
|
704
|
+
query: Query | None = None,
|
|
705
|
+
extra_headers: Headers | None = None,
|
|
706
|
+
extra_query: Query | None = None,
|
|
707
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
708
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
709
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
710
|
+
) -> Any:
|
|
711
|
+
"""Send a request to any ``/public/v1`` path and return the decoded JSON (or text)."""
|
|
712
|
+
options = _build_options(
|
|
713
|
+
extra_headers=extra_headers,
|
|
714
|
+
extra_query=extra_query,
|
|
715
|
+
timeout=timeout,
|
|
716
|
+
max_retries=max_retries,
|
|
717
|
+
idempotency_key=idempotency_key,
|
|
718
|
+
)
|
|
719
|
+
return self._request(
|
|
720
|
+
method, path, cast_to=None, query=query, json_body=body, options=options
|
|
721
|
+
).parse()
|
|
722
|
+
|
|
723
|
+
def get(
|
|
724
|
+
self,
|
|
725
|
+
path: str,
|
|
726
|
+
*,
|
|
727
|
+
query: Query | None = None,
|
|
728
|
+
extra_headers: Headers | None = None,
|
|
729
|
+
extra_query: Query | None = None,
|
|
730
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
731
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
732
|
+
) -> Any:
|
|
733
|
+
return self.request(
|
|
734
|
+
"GET",
|
|
735
|
+
path,
|
|
736
|
+
query=query,
|
|
737
|
+
extra_headers=extra_headers,
|
|
738
|
+
extra_query=extra_query,
|
|
739
|
+
timeout=timeout,
|
|
740
|
+
max_retries=max_retries,
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
def post(
|
|
744
|
+
self,
|
|
745
|
+
path: str,
|
|
746
|
+
*,
|
|
747
|
+
body: object | None = None,
|
|
748
|
+
query: Query | None = None,
|
|
749
|
+
extra_headers: Headers | None = None,
|
|
750
|
+
extra_query: Query | None = None,
|
|
751
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
752
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
753
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
754
|
+
) -> Any:
|
|
755
|
+
return self.request(
|
|
756
|
+
"POST",
|
|
757
|
+
path,
|
|
758
|
+
body=body,
|
|
759
|
+
query=query,
|
|
760
|
+
extra_headers=extra_headers,
|
|
761
|
+
extra_query=extra_query,
|
|
762
|
+
timeout=timeout,
|
|
763
|
+
max_retries=max_retries,
|
|
764
|
+
idempotency_key=idempotency_key,
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
def put(
|
|
768
|
+
self,
|
|
769
|
+
path: str,
|
|
770
|
+
*,
|
|
771
|
+
body: object | None = None,
|
|
772
|
+
query: Query | None = None,
|
|
773
|
+
extra_headers: Headers | None = None,
|
|
774
|
+
extra_query: Query | None = None,
|
|
775
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
776
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
777
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
778
|
+
) -> Any:
|
|
779
|
+
return self.request(
|
|
780
|
+
"PUT",
|
|
781
|
+
path,
|
|
782
|
+
body=body,
|
|
783
|
+
query=query,
|
|
784
|
+
extra_headers=extra_headers,
|
|
785
|
+
extra_query=extra_query,
|
|
786
|
+
timeout=timeout,
|
|
787
|
+
max_retries=max_retries,
|
|
788
|
+
idempotency_key=idempotency_key,
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
def delete(
|
|
792
|
+
self,
|
|
793
|
+
path: str,
|
|
794
|
+
*,
|
|
795
|
+
query: Query | None = None,
|
|
796
|
+
extra_headers: Headers | None = None,
|
|
797
|
+
extra_query: Query | None = None,
|
|
798
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
799
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
800
|
+
) -> Any:
|
|
801
|
+
return self.request(
|
|
802
|
+
"DELETE",
|
|
803
|
+
path,
|
|
804
|
+
query=query,
|
|
805
|
+
extra_headers=extra_headers,
|
|
806
|
+
extra_query=extra_query,
|
|
807
|
+
timeout=timeout,
|
|
808
|
+
max_retries=max_retries,
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
# ---------------------------------------------------------------------------
|
|
813
|
+
# Async client
|
|
814
|
+
# ---------------------------------------------------------------------------
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
class AsyncAPIClient(_BaseClient[httpx.AsyncClient]):
|
|
818
|
+
def __init__(
|
|
819
|
+
self,
|
|
820
|
+
*,
|
|
821
|
+
api_key: str | None = None,
|
|
822
|
+
base_url: str | None = None,
|
|
823
|
+
timeout: Timeout = DEFAULT_TIMEOUT,
|
|
824
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
825
|
+
default_headers: Mapping[str, str] | None = None,
|
|
826
|
+
http_client: httpx.AsyncClient | None = None,
|
|
827
|
+
) -> None:
|
|
828
|
+
super().__init__(
|
|
829
|
+
api_key=api_key,
|
|
830
|
+
base_url=base_url,
|
|
831
|
+
timeout=timeout,
|
|
832
|
+
max_retries=max_retries,
|
|
833
|
+
default_headers=default_headers,
|
|
834
|
+
)
|
|
835
|
+
if http_client is not None:
|
|
836
|
+
self._client = http_client
|
|
837
|
+
self._owns_client = False
|
|
838
|
+
else:
|
|
839
|
+
self._client = httpx.AsyncClient(timeout=timeout)
|
|
840
|
+
self._owns_client = True
|
|
841
|
+
|
|
842
|
+
# -- lifecycle -----------------------------------------------------------
|
|
843
|
+
|
|
844
|
+
async def aclose(self) -> None:
|
|
845
|
+
"""Close the underlying HTTP client, unless it was supplied by the caller."""
|
|
846
|
+
if self._owns_client:
|
|
847
|
+
await self._client.aclose()
|
|
848
|
+
|
|
849
|
+
async def __aenter__(self) -> Self:
|
|
850
|
+
return self
|
|
851
|
+
|
|
852
|
+
async def __aexit__(self, *_exc_info: object) -> None:
|
|
853
|
+
await self.aclose()
|
|
854
|
+
|
|
855
|
+
async def _asleep(self, seconds: float) -> None:
|
|
856
|
+
await asyncio.sleep(seconds)
|
|
857
|
+
|
|
858
|
+
# -- core request --------------------------------------------------------
|
|
859
|
+
|
|
860
|
+
async def _send_with_retries(
|
|
861
|
+
self,
|
|
862
|
+
method: HTTPMethod,
|
|
863
|
+
path: str,
|
|
864
|
+
*,
|
|
865
|
+
query: Query | None,
|
|
866
|
+
json_body: object | None,
|
|
867
|
+
files: FilesParam | None,
|
|
868
|
+
options: RequestOptions | None,
|
|
869
|
+
) -> httpx.Response:
|
|
870
|
+
opts: RequestOptions = options or {}
|
|
871
|
+
idempotency_key = self._resolve_idempotency_key(method, opts)
|
|
872
|
+
body_bytes = _serialize_json_body(json_body)
|
|
873
|
+
max_retries = self._resolve_max_retries(opts)
|
|
874
|
+
|
|
875
|
+
attempt = 0
|
|
876
|
+
while True:
|
|
877
|
+
request = self._build_request(
|
|
878
|
+
method,
|
|
879
|
+
path,
|
|
880
|
+
query=query,
|
|
881
|
+
body_bytes=body_bytes,
|
|
882
|
+
files=files,
|
|
883
|
+
options=opts,
|
|
884
|
+
idempotency_key=idempotency_key,
|
|
885
|
+
)
|
|
886
|
+
try:
|
|
887
|
+
response = await self._client.send(request)
|
|
888
|
+
except httpx.TransportError as exc:
|
|
889
|
+
error = _map_transport_error(exc)
|
|
890
|
+
if attempt < max_retries and isinstance(error, APIConnectionError):
|
|
891
|
+
await self._asleep(_retry_delay(attempt, error))
|
|
892
|
+
attempt += 1
|
|
893
|
+
continue
|
|
894
|
+
raise error from exc
|
|
895
|
+
|
|
896
|
+
if response.is_success:
|
|
897
|
+
return response
|
|
898
|
+
|
|
899
|
+
api_error = APIError.from_response(response, _decode_error_body(response))
|
|
900
|
+
if attempt < max_retries and _should_retry(api_error, method):
|
|
901
|
+
await response.aclose()
|
|
902
|
+
await self._asleep(_retry_delay(attempt, api_error))
|
|
903
|
+
attempt += 1
|
|
904
|
+
continue
|
|
905
|
+
raise api_error
|
|
906
|
+
|
|
907
|
+
@overload
|
|
908
|
+
async def _request(
|
|
909
|
+
self,
|
|
910
|
+
method: HTTPMethod,
|
|
911
|
+
path: str,
|
|
912
|
+
*,
|
|
913
|
+
cast_to: type[None],
|
|
914
|
+
query: Query | None = None,
|
|
915
|
+
json_body: object | None = None,
|
|
916
|
+
files: FilesParam | None = None,
|
|
917
|
+
options: RequestOptions | None = None,
|
|
918
|
+
) -> APIResponse[None]: ...
|
|
919
|
+
|
|
920
|
+
@overload
|
|
921
|
+
async def _request(
|
|
922
|
+
self,
|
|
923
|
+
method: HTTPMethod,
|
|
924
|
+
path: str,
|
|
925
|
+
*,
|
|
926
|
+
cast_to: type[T] | TypeAdapter[T],
|
|
927
|
+
query: Query | None = None,
|
|
928
|
+
json_body: object | None = None,
|
|
929
|
+
files: FilesParam | None = None,
|
|
930
|
+
options: RequestOptions | None = None,
|
|
931
|
+
) -> APIResponse[T]: ...
|
|
932
|
+
|
|
933
|
+
@overload
|
|
934
|
+
async def _request(
|
|
935
|
+
self,
|
|
936
|
+
method: HTTPMethod,
|
|
937
|
+
path: str,
|
|
938
|
+
*,
|
|
939
|
+
cast_to: None,
|
|
940
|
+
query: Query | None = None,
|
|
941
|
+
json_body: object | None = None,
|
|
942
|
+
files: FilesParam | None = None,
|
|
943
|
+
options: RequestOptions | None = None,
|
|
944
|
+
) -> APIResponse[Any]: ...
|
|
945
|
+
|
|
946
|
+
async def _request(
|
|
947
|
+
self,
|
|
948
|
+
method: HTTPMethod,
|
|
949
|
+
path: str,
|
|
950
|
+
*,
|
|
951
|
+
cast_to: type[T] | TypeAdapter[T] | None,
|
|
952
|
+
query: Query | None = None,
|
|
953
|
+
json_body: object | None = None,
|
|
954
|
+
files: FilesParam | None = None,
|
|
955
|
+
options: RequestOptions | None = None,
|
|
956
|
+
) -> APIResponse[Any]:
|
|
957
|
+
response = await self._send_with_retries(
|
|
958
|
+
method, path, query=query, json_body=json_body, files=files, options=options
|
|
959
|
+
)
|
|
960
|
+
return APIResponse(response, lambda: _parse_response(response, cast_to))
|
|
961
|
+
|
|
962
|
+
# -- pagination ----------------------------------------------------------
|
|
963
|
+
|
|
964
|
+
def _get_api_list(
|
|
965
|
+
self,
|
|
966
|
+
path: str,
|
|
967
|
+
*,
|
|
968
|
+
item_type: type[T],
|
|
969
|
+
query: Query | None = None,
|
|
970
|
+
options: RequestOptions | None = None,
|
|
971
|
+
) -> AsyncPaginator[T]:
|
|
972
|
+
async def fetch_first_page() -> AsyncCursorPage[T]:
|
|
973
|
+
raw = await self._get_api_list_raw(
|
|
974
|
+
path, item_type=item_type, query=query, options=options
|
|
975
|
+
)
|
|
976
|
+
return raw.parse()
|
|
977
|
+
|
|
978
|
+
return AsyncPaginator(fetch_first_page)
|
|
979
|
+
|
|
980
|
+
async def _get_api_list_raw(
|
|
981
|
+
self,
|
|
982
|
+
path: str,
|
|
983
|
+
*,
|
|
984
|
+
item_type: type[T],
|
|
985
|
+
query: Query | None = None,
|
|
986
|
+
options: RequestOptions | None = None,
|
|
987
|
+
) -> APIResponse[AsyncCursorPage[T]]:
|
|
988
|
+
parse_item = _item_parser(item_type)
|
|
989
|
+
|
|
990
|
+
async def fetch_page(cursor: str) -> AsyncCursorPage[T]:
|
|
991
|
+
next_query: dict[str, Any] = {**(query or {}), "cursor": cursor}
|
|
992
|
+
raw = await self._get_api_list_raw(
|
|
993
|
+
path, item_type=item_type, query=next_query, options=_next_page_options(options)
|
|
994
|
+
)
|
|
995
|
+
return raw.parse()
|
|
996
|
+
|
|
997
|
+
response = await self._send_with_retries(
|
|
998
|
+
"GET", path, query=query, json_body=None, files=None, options=options
|
|
999
|
+
)
|
|
1000
|
+
|
|
1001
|
+
def parse() -> AsyncCursorPage[T]:
|
|
1002
|
+
body = _decode_success_body(response)
|
|
1003
|
+
try:
|
|
1004
|
+
return build_async_cursor_page(
|
|
1005
|
+
body, http_response=response, parse_item=parse_item, fetch_page=fetch_page
|
|
1006
|
+
)
|
|
1007
|
+
except ValidationError as exc:
|
|
1008
|
+
raise APIResponseValidationError(
|
|
1009
|
+
"Data returned by the API is invalid for the expected schema.",
|
|
1010
|
+
http_response=response,
|
|
1011
|
+
cause=exc,
|
|
1012
|
+
) from exc
|
|
1013
|
+
|
|
1014
|
+
return APIResponse(response, parse)
|
|
1015
|
+
|
|
1016
|
+
# -- external uploads ----------------------------------------------------
|
|
1017
|
+
|
|
1018
|
+
async def _send_external_put(
|
|
1019
|
+
self, url: str, *, content: bytes, timeout: NotGivenOr[Timeout] = NOT_GIVEN
|
|
1020
|
+
) -> httpx.Response:
|
|
1021
|
+
"""PUT raw bytes to a presigned URL with zero SDK/auth headers.
|
|
1022
|
+
|
|
1023
|
+
Sent through the configured ``httpx.AsyncClient`` so injected transports, proxies and
|
|
1024
|
+
TLS settings still apply, but bypassing ``build_request`` so no client default headers
|
|
1025
|
+
or auth are merged in.
|
|
1026
|
+
"""
|
|
1027
|
+
request = self._external_put_request(url, content, timeout)
|
|
1028
|
+
try:
|
|
1029
|
+
return await self._client.send(request, auth=None)
|
|
1030
|
+
except httpx.TransportError as exc:
|
|
1031
|
+
raise _map_transport_error(exc) from exc
|
|
1032
|
+
|
|
1033
|
+
# -- low-level escape hatches --------------------------------------------
|
|
1034
|
+
|
|
1035
|
+
async def request(
|
|
1036
|
+
self,
|
|
1037
|
+
method: HTTPMethod,
|
|
1038
|
+
path: str,
|
|
1039
|
+
*,
|
|
1040
|
+
body: object | None = None,
|
|
1041
|
+
query: Query | None = None,
|
|
1042
|
+
extra_headers: Headers | None = None,
|
|
1043
|
+
extra_query: Query | None = None,
|
|
1044
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
1045
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
1046
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
1047
|
+
) -> Any:
|
|
1048
|
+
"""Send a request to any ``/public/v1`` path and return the decoded JSON (or text)."""
|
|
1049
|
+
options = _build_options(
|
|
1050
|
+
extra_headers=extra_headers,
|
|
1051
|
+
extra_query=extra_query,
|
|
1052
|
+
timeout=timeout,
|
|
1053
|
+
max_retries=max_retries,
|
|
1054
|
+
idempotency_key=idempotency_key,
|
|
1055
|
+
)
|
|
1056
|
+
raw = await self._request(
|
|
1057
|
+
method, path, cast_to=None, query=query, json_body=body, options=options
|
|
1058
|
+
)
|
|
1059
|
+
return raw.parse()
|
|
1060
|
+
|
|
1061
|
+
async def get(
|
|
1062
|
+
self,
|
|
1063
|
+
path: str,
|
|
1064
|
+
*,
|
|
1065
|
+
query: Query | None = None,
|
|
1066
|
+
extra_headers: Headers | None = None,
|
|
1067
|
+
extra_query: Query | None = None,
|
|
1068
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
1069
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
1070
|
+
) -> Any:
|
|
1071
|
+
return await self.request(
|
|
1072
|
+
"GET",
|
|
1073
|
+
path,
|
|
1074
|
+
query=query,
|
|
1075
|
+
extra_headers=extra_headers,
|
|
1076
|
+
extra_query=extra_query,
|
|
1077
|
+
timeout=timeout,
|
|
1078
|
+
max_retries=max_retries,
|
|
1079
|
+
)
|
|
1080
|
+
|
|
1081
|
+
async def post(
|
|
1082
|
+
self,
|
|
1083
|
+
path: str,
|
|
1084
|
+
*,
|
|
1085
|
+
body: object | None = None,
|
|
1086
|
+
query: Query | None = None,
|
|
1087
|
+
extra_headers: Headers | None = None,
|
|
1088
|
+
extra_query: Query | None = None,
|
|
1089
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
1090
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
1091
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
1092
|
+
) -> Any:
|
|
1093
|
+
return await self.request(
|
|
1094
|
+
"POST",
|
|
1095
|
+
path,
|
|
1096
|
+
body=body,
|
|
1097
|
+
query=query,
|
|
1098
|
+
extra_headers=extra_headers,
|
|
1099
|
+
extra_query=extra_query,
|
|
1100
|
+
timeout=timeout,
|
|
1101
|
+
max_retries=max_retries,
|
|
1102
|
+
idempotency_key=idempotency_key,
|
|
1103
|
+
)
|
|
1104
|
+
|
|
1105
|
+
async def put(
|
|
1106
|
+
self,
|
|
1107
|
+
path: str,
|
|
1108
|
+
*,
|
|
1109
|
+
body: object | None = None,
|
|
1110
|
+
query: Query | None = None,
|
|
1111
|
+
extra_headers: Headers | None = None,
|
|
1112
|
+
extra_query: Query | None = None,
|
|
1113
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
1114
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
1115
|
+
idempotency_key: NotGivenOr[str] = NOT_GIVEN,
|
|
1116
|
+
) -> Any:
|
|
1117
|
+
return await self.request(
|
|
1118
|
+
"PUT",
|
|
1119
|
+
path,
|
|
1120
|
+
body=body,
|
|
1121
|
+
query=query,
|
|
1122
|
+
extra_headers=extra_headers,
|
|
1123
|
+
extra_query=extra_query,
|
|
1124
|
+
timeout=timeout,
|
|
1125
|
+
max_retries=max_retries,
|
|
1126
|
+
idempotency_key=idempotency_key,
|
|
1127
|
+
)
|
|
1128
|
+
|
|
1129
|
+
async def delete(
|
|
1130
|
+
self,
|
|
1131
|
+
path: str,
|
|
1132
|
+
*,
|
|
1133
|
+
query: Query | None = None,
|
|
1134
|
+
extra_headers: Headers | None = None,
|
|
1135
|
+
extra_query: Query | None = None,
|
|
1136
|
+
timeout: NotGivenOr[Timeout] = NOT_GIVEN,
|
|
1137
|
+
max_retries: NotGivenOr[int] = NOT_GIVEN,
|
|
1138
|
+
) -> Any:
|
|
1139
|
+
return await self.request(
|
|
1140
|
+
"DELETE",
|
|
1141
|
+
path,
|
|
1142
|
+
query=query,
|
|
1143
|
+
extra_headers=extra_headers,
|
|
1144
|
+
extra_query=extra_query,
|
|
1145
|
+
timeout=timeout,
|
|
1146
|
+
max_retries=max_retries,
|
|
1147
|
+
)
|