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/_constants.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
DEFAULT_BASE_URL = "https://api.bulkit.io"
|
|
4
|
+
API_PREFIX = "/public/v1"
|
|
5
|
+
|
|
6
|
+
DEFAULT_TIMEOUT = 60.0
|
|
7
|
+
DEFAULT_MAX_RETRIES = 2
|
|
8
|
+
|
|
9
|
+
INITIAL_RETRY_DELAY = 0.5
|
|
10
|
+
MAX_RETRY_DELAY = 8.0
|
|
11
|
+
MAX_RETRY_AFTER = 60.0
|
|
12
|
+
|
|
13
|
+
MAX_IDEMPOTENCY_KEY_LENGTH = 255
|
|
14
|
+
# Leaves room for the ":start" / ":complete" suffixes used by media.upload_multipart.
|
|
15
|
+
MAX_MULTIPART_IDEMPOTENCY_KEY_LENGTH = 246
|
bulkit/_exceptions.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from pydantic import ValidationError
|
|
9
|
+
|
|
10
|
+
from bulkit.types._errors import ApiErrorCode, ErrorDetail, FieldError
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"APIConnectionError",
|
|
14
|
+
"APIConnectionTimeoutError",
|
|
15
|
+
"APIError",
|
|
16
|
+
"APIResponseValidationError",
|
|
17
|
+
"APIUserAbortError",
|
|
18
|
+
"AuthenticationError",
|
|
19
|
+
"BadRequestError",
|
|
20
|
+
"BulkitError",
|
|
21
|
+
"ConflictError",
|
|
22
|
+
"InternalServerError",
|
|
23
|
+
"NotFoundError",
|
|
24
|
+
"PayloadTooLargeError",
|
|
25
|
+
"PermissionDeniedError",
|
|
26
|
+
"QuotaExceededError",
|
|
27
|
+
"RateLimitError",
|
|
28
|
+
"UnprocessableEntityError",
|
|
29
|
+
"UnsupportedMediaTypeError",
|
|
30
|
+
"WebhookVerificationError",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class BulkitError(Exception):
|
|
35
|
+
"""Base class for every error this SDK raises. ``except BulkitError`` catches them all."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class APIError(BulkitError):
|
|
39
|
+
"""The API answered with a non-2xx status.
|
|
40
|
+
|
|
41
|
+
Branch on ``code`` (stable within v1) rather than ``message`` (prose, may change).
|
|
42
|
+
New codes can appear at any time, so always keep a fallback branch.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
status_code: int
|
|
46
|
+
code: ApiErrorCode | None
|
|
47
|
+
message: str
|
|
48
|
+
field: str | None
|
|
49
|
+
details: list[FieldError] | None
|
|
50
|
+
request_id: str | None
|
|
51
|
+
headers: httpx.Headers
|
|
52
|
+
body: Any
|
|
53
|
+
error: ErrorDetail | None
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
message: str,
|
|
58
|
+
*,
|
|
59
|
+
status_code: int,
|
|
60
|
+
headers: httpx.Headers,
|
|
61
|
+
body: Any = None,
|
|
62
|
+
error: ErrorDetail | None = None,
|
|
63
|
+
code: ApiErrorCode | None = None,
|
|
64
|
+
field: str | None = None,
|
|
65
|
+
details: list[FieldError] | None = None,
|
|
66
|
+
request_id: str | None = None,
|
|
67
|
+
) -> None:
|
|
68
|
+
super().__init__(message)
|
|
69
|
+
self.message = message
|
|
70
|
+
self.status_code = status_code
|
|
71
|
+
self.headers = headers
|
|
72
|
+
self.body = body
|
|
73
|
+
self.error = error
|
|
74
|
+
self.code = code
|
|
75
|
+
self.field = field
|
|
76
|
+
self.details = details
|
|
77
|
+
self.request_id = request_id
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_response(cls, response: httpx.Response, body: Any) -> APIError:
|
|
81
|
+
"""Build the status-specific subclass from an error response and its decoded body."""
|
|
82
|
+
status = response.status_code
|
|
83
|
+
headers = response.headers
|
|
84
|
+
raw: object = None
|
|
85
|
+
if isinstance(body, Mapping):
|
|
86
|
+
body_map = cast("Mapping[str, Any]", body)
|
|
87
|
+
raw = body_map.get("error")
|
|
88
|
+
|
|
89
|
+
error: ErrorDetail | None = None
|
|
90
|
+
code: ApiErrorCode | None = None
|
|
91
|
+
message: str | None = None
|
|
92
|
+
field: str | None = None
|
|
93
|
+
details: list[FieldError] | None = None
|
|
94
|
+
request_id: str | None = None
|
|
95
|
+
|
|
96
|
+
if isinstance(raw, Mapping):
|
|
97
|
+
raw_map = cast("Mapping[str, Any]", raw)
|
|
98
|
+
try:
|
|
99
|
+
error = ErrorDetail.model_validate(raw_map)
|
|
100
|
+
except ValidationError:
|
|
101
|
+
error = None
|
|
102
|
+
if error is not None:
|
|
103
|
+
code = error.code
|
|
104
|
+
message = error.message
|
|
105
|
+
field = error.field
|
|
106
|
+
details = error.details
|
|
107
|
+
request_id = error.request_id
|
|
108
|
+
else:
|
|
109
|
+
code = _str_or_none(raw_map.get("code"))
|
|
110
|
+
message = _str_or_none(raw_map.get("message"))
|
|
111
|
+
field = _str_or_none(raw_map.get("field"))
|
|
112
|
+
request_id = _str_or_none(raw_map.get("requestId"))
|
|
113
|
+
details = _parse_details(raw_map.get("details"))
|
|
114
|
+
|
|
115
|
+
if not message:
|
|
116
|
+
message = f"Request failed with status {status}"
|
|
117
|
+
if request_id is None:
|
|
118
|
+
request_id = headers.get("x-request-id")
|
|
119
|
+
|
|
120
|
+
error_cls = _error_class_for(status)
|
|
121
|
+
return error_cls(
|
|
122
|
+
message,
|
|
123
|
+
status_code=status,
|
|
124
|
+
headers=headers,
|
|
125
|
+
body=body,
|
|
126
|
+
error=error,
|
|
127
|
+
code=code,
|
|
128
|
+
field=field,
|
|
129
|
+
details=details,
|
|
130
|
+
request_id=request_id,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def __str__(self) -> str:
|
|
134
|
+
parts = [f"Error code: {self.status_code}"]
|
|
135
|
+
if self.code is not None:
|
|
136
|
+
parts.append(f"[{self.code}]")
|
|
137
|
+
text = " ".join(parts) + f" - {self.message}"
|
|
138
|
+
if self.request_id is not None:
|
|
139
|
+
text += f" (request_id: {self.request_id})"
|
|
140
|
+
return text
|
|
141
|
+
|
|
142
|
+
def __repr__(self) -> str:
|
|
143
|
+
# Never include headers or body: they may echo credentials.
|
|
144
|
+
return (
|
|
145
|
+
f"{type(self).__name__}(status_code={self.status_code!r}, code={self.code!r}, "
|
|
146
|
+
f"message={self.message!r}, request_id={self.request_id!r})"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class BadRequestError(APIError):
|
|
151
|
+
"""400 — the request was malformed or failed schema validation."""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class AuthenticationError(APIError):
|
|
155
|
+
"""401 — the API key is missing, malformed, revoked or unknown."""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class QuotaExceededError(APIError):
|
|
159
|
+
"""402 — the plan's allowance for this period is spent. Never retried."""
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class PermissionDeniedError(APIError):
|
|
163
|
+
"""403 — the key lacks the scope for this call."""
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class NotFoundError(APIError):
|
|
167
|
+
"""404 — the resource does not exist in this workspace."""
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class ConflictError(APIError):
|
|
171
|
+
"""409 — the resource state forbids this, or a same-key request is still running."""
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class PayloadTooLargeError(APIError):
|
|
175
|
+
"""413 — the request body or uploaded file is too large."""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class UnsupportedMediaTypeError(APIError):
|
|
179
|
+
"""415 — the uploaded file's type is not accepted."""
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class UnprocessableEntityError(APIError):
|
|
183
|
+
"""422 — well-formed but refused (e.g. a platform rule or reused idempotency key)."""
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class RateLimitError(APIError):
|
|
187
|
+
"""429 — too many requests. Retried automatically, honouring ``Retry-After``."""
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def retry_after(self) -> float | None:
|
|
191
|
+
"""Seconds the API asked us to wait before retrying, if it said."""
|
|
192
|
+
raw = self.headers.get("retry-after")
|
|
193
|
+
if raw is None:
|
|
194
|
+
return None
|
|
195
|
+
try:
|
|
196
|
+
value = float(raw)
|
|
197
|
+
except ValueError:
|
|
198
|
+
return None
|
|
199
|
+
if math.isfinite(value) and value >= 0:
|
|
200
|
+
return value
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class InternalServerError(APIError):
|
|
205
|
+
"""5xx — a fault on Bulkit's side or an unreachable dependency."""
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class APIConnectionError(BulkitError):
|
|
209
|
+
"""The request never got an HTTP response (DNS, TLS, connection reset, ...)."""
|
|
210
|
+
|
|
211
|
+
cause: BaseException | None
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self, message: str = "Connection error.", *, cause: BaseException | None = None
|
|
215
|
+
) -> None:
|
|
216
|
+
super().__init__(message)
|
|
217
|
+
self.message = message
|
|
218
|
+
self.cause = cause
|
|
219
|
+
if cause is not None:
|
|
220
|
+
self.__cause__ = cause
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class APIConnectionTimeoutError(APIConnectionError):
|
|
224
|
+
"""The request exceeded the configured ``timeout``."""
|
|
225
|
+
|
|
226
|
+
def __init__(
|
|
227
|
+
self, message: str = "Request timed out.", *, cause: BaseException | None = None
|
|
228
|
+
) -> None:
|
|
229
|
+
super().__init__(message, cause=cause)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class APIUserAbortError(BulkitError):
|
|
233
|
+
"""The caller aborted the request."""
|
|
234
|
+
|
|
235
|
+
def __init__(self, message: str = "Request was aborted.") -> None:
|
|
236
|
+
super().__init__(message)
|
|
237
|
+
self.message = message
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class APIResponseValidationError(BulkitError):
|
|
241
|
+
"""A 2xx response body could not be decoded or did not match the expected schema."""
|
|
242
|
+
|
|
243
|
+
http_response: httpx.Response
|
|
244
|
+
cause: Exception | None
|
|
245
|
+
|
|
246
|
+
def __init__(
|
|
247
|
+
self,
|
|
248
|
+
message: str = "Data returned by the API is invalid for the expected schema.",
|
|
249
|
+
*,
|
|
250
|
+
http_response: httpx.Response,
|
|
251
|
+
cause: Exception | None = None,
|
|
252
|
+
) -> None:
|
|
253
|
+
super().__init__(message)
|
|
254
|
+
self.message = message
|
|
255
|
+
self.http_response = http_response
|
|
256
|
+
self.cause = cause
|
|
257
|
+
if cause is not None:
|
|
258
|
+
self.__cause__ = cause
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def status_code(self) -> int:
|
|
262
|
+
return self.http_response.status_code
|
|
263
|
+
|
|
264
|
+
def __repr__(self) -> str:
|
|
265
|
+
return f"{type(self).__name__}(status_code={self.status_code!r}, message={self.message!r})"
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
class WebhookVerificationError(BulkitError):
|
|
269
|
+
"""A webhook delivery failed signature or timestamp verification. Respond 400 and drop it."""
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
_STATUS_MAP: dict[int, type[APIError]] = {
|
|
273
|
+
400: BadRequestError,
|
|
274
|
+
401: AuthenticationError,
|
|
275
|
+
402: QuotaExceededError,
|
|
276
|
+
403: PermissionDeniedError,
|
|
277
|
+
404: NotFoundError,
|
|
278
|
+
409: ConflictError,
|
|
279
|
+
413: PayloadTooLargeError,
|
|
280
|
+
415: UnsupportedMediaTypeError,
|
|
281
|
+
422: UnprocessableEntityError,
|
|
282
|
+
429: RateLimitError,
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _error_class_for(status: int) -> type[APIError]:
|
|
287
|
+
mapped = _STATUS_MAP.get(status)
|
|
288
|
+
if mapped is not None:
|
|
289
|
+
return mapped
|
|
290
|
+
return InternalServerError if status >= 500 else APIError
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _str_or_none(value: object) -> str | None:
|
|
294
|
+
return value if isinstance(value, str) else None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _parse_details(value: object) -> list[FieldError] | None:
|
|
298
|
+
if not isinstance(value, list):
|
|
299
|
+
return None
|
|
300
|
+
parsed: list[FieldError] = []
|
|
301
|
+
for item in value: # pyright: ignore[reportUnknownVariableType]
|
|
302
|
+
try:
|
|
303
|
+
parsed.append(FieldError.model_validate(item))
|
|
304
|
+
except ValidationError:
|
|
305
|
+
continue
|
|
306
|
+
return parsed
|
bulkit/_pagination.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Generator, Iterator
|
|
4
|
+
from typing import Any, Generic, TypeVar
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from bulkit._exceptions import BulkitError
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"AsyncCursorPage",
|
|
12
|
+
"AsyncPaginator",
|
|
13
|
+
"SyncCursorPage",
|
|
14
|
+
"build_async_cursor_page",
|
|
15
|
+
"build_sync_cursor_page",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
T = TypeVar("T")
|
|
19
|
+
|
|
20
|
+
_NO_NEXT_PAGE = "No next page; check has_next_page() before calling get_next_page()."
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _split_page_body(
|
|
24
|
+
body: Any, http_response: httpx.Response
|
|
25
|
+
) -> tuple[list[Any], str | None, bool | None]:
|
|
26
|
+
"""Validate a ``{ data, nextCursor, hasMore? }`` body and return its raw parts.
|
|
27
|
+
|
|
28
|
+
A server that predates paging for an endpoint answers with a bare array (or some other
|
|
29
|
+
shape). Fail loudly rather than read a missing ``nextCursor`` as "another page" and
|
|
30
|
+
re-request page one forever.
|
|
31
|
+
"""
|
|
32
|
+
if not isinstance(body, dict) or not isinstance(body.get("data"), list): # pyright: ignore[reportUnknownMemberType]
|
|
33
|
+
url = _safe_url(http_response)
|
|
34
|
+
raise BulkitError(
|
|
35
|
+
f"Expected a paged response ({{ data, nextCursor }}) from {url}, but got something "
|
|
36
|
+
"else. The server may be running an older API version."
|
|
37
|
+
)
|
|
38
|
+
raw: dict[str, Any] = body # pyright: ignore[reportUnknownVariableType]
|
|
39
|
+
items: list[Any] = raw["data"]
|
|
40
|
+
next_cursor = raw.get("nextCursor")
|
|
41
|
+
has_more = raw.get("hasMore")
|
|
42
|
+
return (
|
|
43
|
+
items,
|
|
44
|
+
next_cursor if isinstance(next_cursor, str) else None,
|
|
45
|
+
has_more if isinstance(has_more, bool) else None,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _safe_url(http_response: httpx.Response) -> str:
|
|
50
|
+
try:
|
|
51
|
+
return str(http_response.request.url.copy_with(query=None))
|
|
52
|
+
except RuntimeError:
|
|
53
|
+
return "the API"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class SyncCursorPage(Generic[T]):
|
|
57
|
+
"""One page of a cursor-paginated list.
|
|
58
|
+
|
|
59
|
+
Iterate it to walk every item across every page, or page manually with
|
|
60
|
+
:meth:`has_next_page` / :meth:`get_next_page`.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
data: list[T]
|
|
64
|
+
next_cursor: str | None
|
|
65
|
+
"""Opaque. Pass it back as ``cursor``; never parse or construct one."""
|
|
66
|
+
has_more: bool | None
|
|
67
|
+
http_response: httpx.Response
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
*,
|
|
72
|
+
data: list[T],
|
|
73
|
+
next_cursor: str | None,
|
|
74
|
+
has_more: bool | None,
|
|
75
|
+
http_response: httpx.Response,
|
|
76
|
+
fetch_page: Callable[[str], SyncCursorPage[T]],
|
|
77
|
+
) -> None:
|
|
78
|
+
self.data = data
|
|
79
|
+
self.next_cursor = next_cursor
|
|
80
|
+
self.has_more = has_more
|
|
81
|
+
self.http_response = http_response
|
|
82
|
+
self._fetch_page = fetch_page
|
|
83
|
+
|
|
84
|
+
def has_next_page(self) -> bool:
|
|
85
|
+
"""A ``None`` ``next_cursor`` — not an empty ``data`` — is the end of the list."""
|
|
86
|
+
return self.next_cursor is not None
|
|
87
|
+
|
|
88
|
+
def get_next_page(self) -> SyncCursorPage[T]:
|
|
89
|
+
if self.next_cursor is None:
|
|
90
|
+
raise BulkitError(_NO_NEXT_PAGE)
|
|
91
|
+
return self._fetch_page(self.next_cursor)
|
|
92
|
+
|
|
93
|
+
def iter_pages(self) -> Iterator[SyncCursorPage[T]]:
|
|
94
|
+
"""Yield this page and every page after it."""
|
|
95
|
+
page = self
|
|
96
|
+
yield page
|
|
97
|
+
while page.has_next_page():
|
|
98
|
+
page = page.get_next_page()
|
|
99
|
+
yield page
|
|
100
|
+
|
|
101
|
+
def __iter__(self) -> Iterator[T]:
|
|
102
|
+
for page in self.iter_pages():
|
|
103
|
+
yield from page.data
|
|
104
|
+
|
|
105
|
+
def __repr__(self) -> str:
|
|
106
|
+
return (
|
|
107
|
+
f"{type(self).__name__}(data=<{len(self.data)} items>, "
|
|
108
|
+
f"next_cursor={self.next_cursor!r}, has_more={self.has_more!r})"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class AsyncCursorPage(Generic[T]):
|
|
113
|
+
"""One page of a cursor-paginated list (async).
|
|
114
|
+
|
|
115
|
+
``async for`` it to walk every item across every page, or page manually with
|
|
116
|
+
:meth:`has_next_page` / :meth:`get_next_page`.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
data: list[T]
|
|
120
|
+
next_cursor: str | None
|
|
121
|
+
"""Opaque. Pass it back as ``cursor``; never parse or construct one."""
|
|
122
|
+
has_more: bool | None
|
|
123
|
+
http_response: httpx.Response
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
data: list[T],
|
|
129
|
+
next_cursor: str | None,
|
|
130
|
+
has_more: bool | None,
|
|
131
|
+
http_response: httpx.Response,
|
|
132
|
+
fetch_page: Callable[[str], Awaitable[AsyncCursorPage[T]]],
|
|
133
|
+
) -> None:
|
|
134
|
+
self.data = data
|
|
135
|
+
self.next_cursor = next_cursor
|
|
136
|
+
self.has_more = has_more
|
|
137
|
+
self.http_response = http_response
|
|
138
|
+
self._fetch_page = fetch_page
|
|
139
|
+
|
|
140
|
+
def has_next_page(self) -> bool:
|
|
141
|
+
"""A ``None`` ``next_cursor`` — not an empty ``data`` — is the end of the list."""
|
|
142
|
+
return self.next_cursor is not None
|
|
143
|
+
|
|
144
|
+
async def get_next_page(self) -> AsyncCursorPage[T]:
|
|
145
|
+
if self.next_cursor is None:
|
|
146
|
+
raise BulkitError(_NO_NEXT_PAGE)
|
|
147
|
+
return await self._fetch_page(self.next_cursor)
|
|
148
|
+
|
|
149
|
+
async def iter_pages(self) -> AsyncIterator[AsyncCursorPage[T]]:
|
|
150
|
+
"""Yield this page and every page after it."""
|
|
151
|
+
page = self
|
|
152
|
+
yield page
|
|
153
|
+
while page.has_next_page():
|
|
154
|
+
page = await page.get_next_page()
|
|
155
|
+
yield page
|
|
156
|
+
|
|
157
|
+
async def __aiter__(self) -> AsyncIterator[T]:
|
|
158
|
+
async for page in self.iter_pages():
|
|
159
|
+
for item in page.data:
|
|
160
|
+
yield item
|
|
161
|
+
|
|
162
|
+
def __repr__(self) -> str:
|
|
163
|
+
return (
|
|
164
|
+
f"{type(self).__name__}(data=<{len(self.data)} items>, "
|
|
165
|
+
f"next_cursor={self.next_cursor!r}, has_more={self.has_more!r})"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class AsyncPaginator(Generic[T]):
|
|
170
|
+
"""Awaitable for the first page, and directly async-iterable over every item.
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
page = await client.posts.list() # AsyncCursorPage[Post]
|
|
174
|
+
async for post in client.posts.list(): # every Post, across every page
|
|
175
|
+
...
|
|
176
|
+
```
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self, fetch_first_page: Callable[[], Coroutine[Any, Any, AsyncCursorPage[T]]]
|
|
181
|
+
) -> None:
|
|
182
|
+
self._fetch_first_page = fetch_first_page
|
|
183
|
+
|
|
184
|
+
def __await__(self) -> Generator[Any, None, AsyncCursorPage[T]]:
|
|
185
|
+
return self._fetch_first_page().__await__()
|
|
186
|
+
|
|
187
|
+
async def __aiter__(self) -> AsyncIterator[T]:
|
|
188
|
+
page = await self._fetch_first_page()
|
|
189
|
+
async for item in page:
|
|
190
|
+
yield item
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_sync_cursor_page(
|
|
194
|
+
body: Any,
|
|
195
|
+
*,
|
|
196
|
+
http_response: httpx.Response,
|
|
197
|
+
parse_item: Callable[[Any], T],
|
|
198
|
+
fetch_page: Callable[[str], SyncCursorPage[T]],
|
|
199
|
+
) -> SyncCursorPage[T]:
|
|
200
|
+
"""Validate a decoded page body and build a :class:`SyncCursorPage` from it."""
|
|
201
|
+
items, next_cursor, has_more = _split_page_body(body, http_response)
|
|
202
|
+
return SyncCursorPage(
|
|
203
|
+
data=[parse_item(item) for item in items],
|
|
204
|
+
next_cursor=next_cursor,
|
|
205
|
+
has_more=has_more,
|
|
206
|
+
http_response=http_response,
|
|
207
|
+
fetch_page=fetch_page,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def build_async_cursor_page(
|
|
212
|
+
body: Any,
|
|
213
|
+
*,
|
|
214
|
+
http_response: httpx.Response,
|
|
215
|
+
parse_item: Callable[[Any], T],
|
|
216
|
+
fetch_page: Callable[[str], Awaitable[AsyncCursorPage[T]]],
|
|
217
|
+
) -> AsyncCursorPage[T]:
|
|
218
|
+
"""Validate a decoded page body and build an :class:`AsyncCursorPage` from it."""
|
|
219
|
+
items, next_cursor, has_more = _split_page_body(body, http_response)
|
|
220
|
+
return AsyncCursorPage(
|
|
221
|
+
data=[parse_item(item) for item in items],
|
|
222
|
+
next_cursor=next_cursor,
|
|
223
|
+
has_more=has_more,
|
|
224
|
+
http_response=http_response,
|
|
225
|
+
fetch_page=fetch_page,
|
|
226
|
+
)
|
bulkit/_resource.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from bulkit._base_client import AsyncAPIClient, SyncAPIClient
|
|
4
|
+
|
|
5
|
+
__all__ = ["AsyncAPIResource", "SyncAPIResource"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SyncAPIResource:
|
|
9
|
+
_client: SyncAPIClient
|
|
10
|
+
|
|
11
|
+
def __init__(self, client: SyncAPIClient) -> None:
|
|
12
|
+
self._client = client
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AsyncAPIResource:
|
|
16
|
+
_client: AsyncAPIClient
|
|
17
|
+
|
|
18
|
+
def __init__(self, client: AsyncAPIClient) -> None:
|
|
19
|
+
self._client = client
|
bulkit/_response.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Generic, TypeVar, cast
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
__all__ = ["APIResponse", "RateLimitInfo", "rate_limit_from_headers"]
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class RateLimitInfo:
|
|
17
|
+
"""Rate-limit state reported by the ``x-ratelimit-*`` response headers."""
|
|
18
|
+
|
|
19
|
+
limit: int | None
|
|
20
|
+
remaining: int | None
|
|
21
|
+
reset: float | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _parse_float(raw: str | None) -> float | None:
|
|
25
|
+
if raw is None:
|
|
26
|
+
return None
|
|
27
|
+
try:
|
|
28
|
+
value = float(raw.strip())
|
|
29
|
+
except ValueError:
|
|
30
|
+
return None
|
|
31
|
+
return value if math.isfinite(value) else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _parse_int(raw: str | None) -> int | None:
|
|
35
|
+
value = _parse_float(raw)
|
|
36
|
+
if value is None or not value.is_integer():
|
|
37
|
+
return None
|
|
38
|
+
return int(value)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def rate_limit_from_headers(headers: httpx.Headers) -> RateLimitInfo:
|
|
42
|
+
"""Parse ``x-ratelimit-limit``/``-remaining``/``-reset``; anything invalid becomes ``None``."""
|
|
43
|
+
return RateLimitInfo(
|
|
44
|
+
limit=_parse_int(headers.get("x-ratelimit-limit")),
|
|
45
|
+
remaining=_parse_int(headers.get("x-ratelimit-remaining")),
|
|
46
|
+
reset=_parse_float(headers.get("x-ratelimit-reset")),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class APIResponse(Generic[T]):
|
|
51
|
+
"""A raw HTTP response together with its lazily parsed, cached payload."""
|
|
52
|
+
|
|
53
|
+
http_response: httpx.Response
|
|
54
|
+
request_id: str | None
|
|
55
|
+
rate_limit: RateLimitInfo
|
|
56
|
+
|
|
57
|
+
def __init__(self, http_response: httpx.Response, parser: Callable[[], T]) -> None:
|
|
58
|
+
self.http_response = http_response
|
|
59
|
+
self.request_id = http_response.headers.get("x-request-id")
|
|
60
|
+
self.rate_limit = rate_limit_from_headers(http_response.headers)
|
|
61
|
+
self._parser = parser
|
|
62
|
+
self._parsed: T | None = None
|
|
63
|
+
self._is_parsed = False
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def status_code(self) -> int:
|
|
67
|
+
return self.http_response.status_code
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def headers(self) -> httpx.Headers:
|
|
71
|
+
return self.http_response.headers
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def data(self) -> T:
|
|
75
|
+
return self.parse()
|
|
76
|
+
|
|
77
|
+
def parse(self) -> T:
|
|
78
|
+
"""Return the parsed payload, parsing on first call and caching thereafter."""
|
|
79
|
+
if not self._is_parsed:
|
|
80
|
+
self._parsed = self._parser()
|
|
81
|
+
self._is_parsed = True
|
|
82
|
+
return cast(T, self._parsed)
|
|
83
|
+
|
|
84
|
+
def __repr__(self) -> str:
|
|
85
|
+
return f"<APIResponse [{self.status_code}] request_id={self.request_id!r}>"
|
bulkit/_types.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import BinaryIO, Literal, TypeVar, Union
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from typing_extensions import TypeAlias, TypedDict
|
|
9
|
+
|
|
10
|
+
T = TypeVar("T")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NotGiven:
|
|
14
|
+
"""Sentinel type indicating an optional argument was omitted by the caller.
|
|
15
|
+
|
|
16
|
+
Used instead of ``None`` so unset optional fields are stripped completely
|
|
17
|
+
from JSON payloads (required by Bulkit's strict ``forbidNonWhitelisted``
|
|
18
|
+
validation).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __bool__(self) -> Literal[False]:
|
|
22
|
+
return False
|
|
23
|
+
|
|
24
|
+
def __repr__(self) -> str:
|
|
25
|
+
return "NOT_GIVEN"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
NOT_GIVEN = NotGiven()
|
|
29
|
+
|
|
30
|
+
# Stainless-style aliases
|
|
31
|
+
Omit: TypeAlias = NotGiven
|
|
32
|
+
OMIT = NOT_GIVEN
|
|
33
|
+
|
|
34
|
+
NotGivenOr: TypeAlias = Union[T, NotGiven]
|
|
35
|
+
|
|
36
|
+
Headers: TypeAlias = Mapping[str, str]
|
|
37
|
+
QueryValue: TypeAlias = Union[str, int, float, bool, NotGiven, None]
|
|
38
|
+
Query: TypeAlias = Mapping[str, Union[QueryValue, Sequence[QueryValue]]]
|
|
39
|
+
Timeout: TypeAlias = Union[float, httpx.Timeout]
|
|
40
|
+
HTTPMethod: TypeAlias = Literal["GET", "POST", "PUT", "DELETE"]
|
|
41
|
+
|
|
42
|
+
FileContent: TypeAlias = Union[bytes, BinaryIO, Path, str]
|
|
43
|
+
FileTuple: TypeAlias = tuple[str, Union[bytes, BinaryIO], str]
|
|
44
|
+
FileTypes: TypeAlias = Union[FileContent, FileTuple]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RequestOptions(TypedDict, total=False):
|
|
48
|
+
extra_headers: Headers | None
|
|
49
|
+
extra_query: Query | None
|
|
50
|
+
timeout: NotGivenOr[Timeout]
|
|
51
|
+
max_retries: NotGivenOr[int]
|
|
52
|
+
idempotency_key: NotGivenOr[str]
|