async-task-api-client 0.1.0rc1__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.
- async_task_api_client/__init__.py +4 -0
- async_task_api_client/_errors.py +294 -0
- async_task_api_client/_files.py +162 -0
- async_task_api_client/_generated.py +488 -0
- async_task_api_client/_http.py +617 -0
- async_task_api_client/_me.py +79 -0
- async_task_api_client/_services.py +140 -0
- async_task_api_client/_storage.py +527 -0
- async_task_api_client/_tasks.py +596 -0
- async_task_api_client/py.typed +0 -0
- async_task_api_client/raw.py +97 -0
- async_task_api_client-0.1.0rc1.dist-info/METADATA +465 -0
- async_task_api_client-0.1.0rc1.dist-info/RECORD +15 -0
- async_task_api_client-0.1.0rc1.dist-info/WHEEL +4 -0
- async_task_api_client-0.1.0rc1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
"""Internal: the HTTP transport shared by every raw client, in a sync and an async twin.
|
|
2
|
+
|
|
3
|
+
Both twins share request building and response parsing; they differ only by the I/O call.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import abc
|
|
9
|
+
import asyncio
|
|
10
|
+
import enum
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from contextlib import ExitStack, aclosing, asynccontextmanager, contextmanager, suppress
|
|
14
|
+
from typing import IO, TYPE_CHECKING, Any, Final, Generic, TypeAlias, TypeVar, cast
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from typing_extensions import Self, TypedDict
|
|
18
|
+
|
|
19
|
+
from ._errors import (
|
|
20
|
+
ClientClosedError,
|
|
21
|
+
RequestTimeoutError,
|
|
22
|
+
SdkError,
|
|
23
|
+
StorageTransferError,
|
|
24
|
+
TransportError,
|
|
25
|
+
UnexpectedResponseError,
|
|
26
|
+
error_from_response,
|
|
27
|
+
json_from_response,
|
|
28
|
+
)
|
|
29
|
+
from ._files import Destination, FileContent, FilePath, open_content
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator, Iterator, Mapping
|
|
33
|
+
from types import TracebackType
|
|
34
|
+
|
|
35
|
+
from httpx._client import UseClientDefault # httpx exports the value `USE_CLIENT_DEFAULT`, not its type
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NotGiven(enum.Enum):
|
|
39
|
+
"""Type of `NOT_GIVEN`, the default of every `timeout` parameter: it tells "not given" apart from `None`."""
|
|
40
|
+
|
|
41
|
+
NOT_GIVEN = "NOT_GIVEN"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
NOT_GIVEN = NotGiven.NOT_GIVEN
|
|
45
|
+
|
|
46
|
+
Timeout: TypeAlias = float | NotGiven | None
|
|
47
|
+
"""A timeout in seconds; `None` disables it; `NOT_GIVEN` (the default) defers to the next level."""
|
|
48
|
+
|
|
49
|
+
Params: TypeAlias = "Mapping[str, object]"
|
|
50
|
+
"""Query parameters; a list value is repeated in the query string."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_ClientT = TypeVar("_ClientT", httpx.Client, httpx.AsyncClient)
|
|
54
|
+
|
|
55
|
+
# What httpx may raise while building or sending a request; `InvalidURL` (an unusable `base_url`) is no `HTTPError`.
|
|
56
|
+
_SEND_FAILURES = (httpx.HTTPError, httpx.InvalidURL, RuntimeError)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def encode_json(value: object) -> bytes:
|
|
60
|
+
"""A JSON request body, encoded by the SDK rather than by httpx, whose encoding varies across versions: compact,
|
|
61
|
+
UTF-8. A value that is not valid JSON (`NaN`, infinity) raises `ValueError`, before anything is sent."""
|
|
62
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_T = TypeVar("_T")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def in_thread(function: Callable[..., _T], *args: Any) -> _T:
|
|
69
|
+
"""Runs blocking I/O in a worker thread, off the event loop, and returns its result.
|
|
70
|
+
|
|
71
|
+
A thread cannot be stopped: a cancellation landing meanwhile waits for the function to end (its outcome dropped)
|
|
72
|
+
before propagating, so that nothing it touches is closed or removed under it. The caller cleans up, then."""
|
|
73
|
+
work = asyncio.ensure_future(asyncio.to_thread(function, *args))
|
|
74
|
+
try:
|
|
75
|
+
return await asyncio.shield(work)
|
|
76
|
+
except asyncio.CancelledError:
|
|
77
|
+
while not work.done():
|
|
78
|
+
# `asyncio.wait` never cancels `work`; a cancellation repeated meanwhile is the one re-raised below.
|
|
79
|
+
with suppress(asyncio.CancelledError):
|
|
80
|
+
await asyncio.wait({work})
|
|
81
|
+
if not work.cancelled():
|
|
82
|
+
work.exception() # retrieved, so that asyncio does not log it as never retrieved
|
|
83
|
+
raise
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class HttpMethod(str, enum.Enum):
|
|
87
|
+
"""The HTTP methods the SDK sends; a presigned upload's own comes from the API (`PUT` when it names none)."""
|
|
88
|
+
|
|
89
|
+
GET = "GET"
|
|
90
|
+
POST = "POST"
|
|
91
|
+
PUT = "PUT"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_AUTHORIZATION_HEADER: Final = "authorization"
|
|
95
|
+
_BEARER_SCHEME: Final = "Bearer"
|
|
96
|
+
_CONTENT_TYPE_HEADER: Final = "content-type"
|
|
97
|
+
_JSON_MEDIA_TYPE: Final = "application/json"
|
|
98
|
+
_TIMEOUT_EXTENSION: Final = "timeout"
|
|
99
|
+
"""The httpx request extension that carries a request's timeouts."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _Envelope(TypedDict, total=False):
|
|
103
|
+
"""The wrapper of the task routes' answers: `{"status": "success", "data": {...}}`."""
|
|
104
|
+
|
|
105
|
+
data: object
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_CLIENT_CLOSED_MESSAGE: Final = "Cannot send a request: the client has been closed"
|
|
109
|
+
|
|
110
|
+
_CHUNK_SIZE = 64 * 1024
|
|
111
|
+
"""Bytes read from a file at a time, when streaming it to S3."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _rewind(file: IO[bytes]) -> None:
|
|
115
|
+
"""Moves a stream back to its start, so that an upload sent again (a retry after a failure midway) sends the
|
|
116
|
+
whole file; a stream that cannot seek is left at its position."""
|
|
117
|
+
if file.seekable():
|
|
118
|
+
file.seek(0)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _chunks(file: IO[bytes]) -> Iterator[bytes]:
|
|
122
|
+
"""The chunks of a file, from its start (see `_rewind`)."""
|
|
123
|
+
_rewind(file)
|
|
124
|
+
while chunk := file.read(_CHUNK_SIZE):
|
|
125
|
+
yield chunk
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def _async_chunks(file: IO[bytes]) -> AsyncGenerator[bytes, None]:
|
|
129
|
+
"""The chunks of a file, from its start (see `_rewind`), read in a worker thread so as not to block the event
|
|
130
|
+
loop."""
|
|
131
|
+
await in_thread(_rewind, file)
|
|
132
|
+
while chunk := await in_thread(file.read, _CHUNK_SIZE):
|
|
133
|
+
yield chunk
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class _Transport(abc.ABC, Generic[_ClientT]):
|
|
137
|
+
def __init__(self, *, base_url: str, token: str, http_client: _ClientT | None, timeout: Timeout) -> None:
|
|
138
|
+
self._base_url = base_url.rstrip("/")
|
|
139
|
+
self._token = token
|
|
140
|
+
self._timeout = timeout
|
|
141
|
+
self._client: _ClientT = http_client if http_client is not None else self._new_client()
|
|
142
|
+
# Only the HTTP client the transport created is closed with it; an injected one is the caller's.
|
|
143
|
+
self._owned_client: _ClientT | None = None if http_client is not None else self._client
|
|
144
|
+
|
|
145
|
+
@abc.abstractmethod
|
|
146
|
+
def _new_client(self) -> _ClientT:
|
|
147
|
+
"""The HTTP client to use when none is injected; the transport owns it, and closes it."""
|
|
148
|
+
|
|
149
|
+
def _request(
|
|
150
|
+
self,
|
|
151
|
+
method: str,
|
|
152
|
+
path: str,
|
|
153
|
+
timeout: Timeout,
|
|
154
|
+
*,
|
|
155
|
+
json: object = None,
|
|
156
|
+
params: Params | None = None,
|
|
157
|
+
headers: dict[str, str] | None = None,
|
|
158
|
+
min_read_timeout: float | None = None,
|
|
159
|
+
) -> httpx.Request:
|
|
160
|
+
headers = {**(headers or {}), _AUTHORIZATION_HEADER: f"{_BEARER_SCHEME} {self._token}"}
|
|
161
|
+
content = None
|
|
162
|
+
if json is not None:
|
|
163
|
+
content = encode_json(json)
|
|
164
|
+
headers[_CONTENT_TYPE_HEADER] = _JSON_MEDIA_TYPE
|
|
165
|
+
# httpx 0.23 types `build_request` partially (an unparametrized `dict`); later versions fully. The query
|
|
166
|
+
# values are strings, integers or lists of strings (see the clients): httpx's own parameter type.
|
|
167
|
+
return self._client.build_request(
|
|
168
|
+
method,
|
|
169
|
+
f"{self._base_url}{path}",
|
|
170
|
+
headers=headers,
|
|
171
|
+
content=content,
|
|
172
|
+
params=cast("Any", params),
|
|
173
|
+
timeout=self._resolve(timeout, min_read_timeout),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def _transfer_request(
|
|
177
|
+
self,
|
|
178
|
+
method: str,
|
|
179
|
+
url: str,
|
|
180
|
+
timeout: Timeout,
|
|
181
|
+
*,
|
|
182
|
+
content: bytes | Iterator[bytes] | AsyncIterator[bytes] | None = None,
|
|
183
|
+
headers: dict[str, str] | None = None,
|
|
184
|
+
) -> httpx.Request:
|
|
185
|
+
"""A request to S3 through a presigned URL: the URL and the headers exactly as given, never the API token.
|
|
186
|
+
|
|
187
|
+
Built apart from the HTTP client (`client.build_request` would merge its default headers, query parameters
|
|
188
|
+
and cookies), and sent with `auth=None`: nothing of the caller's credentials for the
|
|
189
|
+
API reaches S3, nor breaks the signature. The client's event hooks still see it (logging)."""
|
|
190
|
+
resolved = self._resolve(timeout)
|
|
191
|
+
# Anything else is httpx's `USE_CLIENT_DEFAULT`; an `int` is a valid timeout in seconds too.
|
|
192
|
+
given = resolved is None or isinstance(resolved, (int, float, httpx.Timeout))
|
|
193
|
+
timeout_config = httpx.Timeout(resolved) if given else self._client.timeout
|
|
194
|
+
return httpx.Request(
|
|
195
|
+
method,
|
|
196
|
+
url,
|
|
197
|
+
headers=headers,
|
|
198
|
+
content=content,
|
|
199
|
+
extensions={_TIMEOUT_EXTENSION: timeout_config.as_dict()},
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def _resolve(
|
|
203
|
+
self,
|
|
204
|
+
timeout: Timeout,
|
|
205
|
+
min_read_timeout: float | None = None,
|
|
206
|
+
) -> float | httpx.Timeout | UseClientDefault | None:
|
|
207
|
+
"""The timeout of a request: per call, else the client's default, else the HTTP client's own (httpx's
|
|
208
|
+
`USE_CLIENT_DEFAULT`), its read timeout raised to `min_read_timeout` when given."""
|
|
209
|
+
resolved: Timeout | httpx.Timeout = self._timeout if timeout is NOT_GIVEN else timeout
|
|
210
|
+
if resolved is NOT_GIVEN and min_read_timeout is not None:
|
|
211
|
+
resolved = self._http_client_timeout(min_read_timeout)
|
|
212
|
+
return httpx.USE_CLIENT_DEFAULT if resolved is NOT_GIVEN else resolved
|
|
213
|
+
|
|
214
|
+
def _http_client_timeout(self, min_read_timeout: float) -> httpx.Timeout | NotGiven:
|
|
215
|
+
"""The HTTP client's own timeout, its read timeout raised to `min_read_timeout` when shorter (not when
|
|
216
|
+
disabled); `NOT_GIVEN` when it needs no change."""
|
|
217
|
+
own = self._client.timeout
|
|
218
|
+
if own.read is None or own.read >= min_read_timeout:
|
|
219
|
+
return NOT_GIVEN
|
|
220
|
+
return httpx.Timeout(connect=own.connect, read=min_read_timeout, write=own.write, pool=own.pool)
|
|
221
|
+
|
|
222
|
+
def ensure_open(self) -> None:
|
|
223
|
+
"""Raises `ClientClosedError` once the HTTP client is closed; called before any file is opened."""
|
|
224
|
+
if self._client.is_closed:
|
|
225
|
+
raise ClientClosedError(_CLIENT_CLOSED_MESSAGE)
|
|
226
|
+
|
|
227
|
+
def _failure(self, error: Exception) -> SdkError | None:
|
|
228
|
+
"""The SDK error for one of `_SEND_FAILURES`, to raise from it; `None` to let it propagate as is."""
|
|
229
|
+
if isinstance(error, httpx.TimeoutException):
|
|
230
|
+
return RequestTimeoutError(str(error) or type(error).__name__)
|
|
231
|
+
# httpx's stream errors are `RuntimeError`s, not `HTTPError`s: a streamed body it cannot send again (a redirect
|
|
232
|
+
# followed with `follow_redirects=True`, an auth flow of the injected client), a stream already closed...
|
|
233
|
+
if isinstance(error, (httpx.HTTPError, httpx.InvalidURL, httpx.StreamError)):
|
|
234
|
+
return TransportError(str(error) or type(error).__name__)
|
|
235
|
+
# Closed after the `is_closed` check (by another task or thread): httpx raises a bare `RuntimeError`.
|
|
236
|
+
if self._client.is_closed:
|
|
237
|
+
return ClientClosedError(_CLIENT_CLOSED_MESSAGE)
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
def _refused(self, response: httpx.Response) -> StorageTransferError:
|
|
241
|
+
"""The error for a transfer S3 refused; its body must have been read."""
|
|
242
|
+
return StorageTransferError(response.status_code, response.text)
|
|
243
|
+
|
|
244
|
+
def _parse(self, response: httpx.Response, *, unwrap: bool, required: tuple[str, ...]) -> Any:
|
|
245
|
+
if not response.is_success:
|
|
246
|
+
raise error_from_response(response)
|
|
247
|
+
body: object = json_from_response(response)
|
|
248
|
+
if unwrap:
|
|
249
|
+
# The task routes wrap their answer, always an object, in `{"status": "success", "data": {...}}`.
|
|
250
|
+
body = cast("_Envelope", body).get("data") if isinstance(body, dict) else None
|
|
251
|
+
if not isinstance(body, dict):
|
|
252
|
+
raise UnexpectedResponseError(response.status_code, response.text)
|
|
253
|
+
if required and not (
|
|
254
|
+
isinstance(body, dict) and all(name in cast("dict[str, object]", body) for name in required)
|
|
255
|
+
):
|
|
256
|
+
raise UnexpectedResponseError(response.status_code, response.text)
|
|
257
|
+
return cast("Any", body)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class SyncTransport(_Transport[httpx.Client]):
|
|
261
|
+
def _new_client(self) -> httpx.Client:
|
|
262
|
+
return httpx.Client()
|
|
263
|
+
|
|
264
|
+
def close(self) -> None:
|
|
265
|
+
if self._owned_client is not None:
|
|
266
|
+
self._owned_client.close()
|
|
267
|
+
|
|
268
|
+
def get(self, path: str, *, timeout: Timeout, params: Params | None = None, unwrap: bool = False) -> Any:
|
|
269
|
+
return self.send(HttpMethod.GET, path, timeout=timeout, params=params, unwrap=unwrap)
|
|
270
|
+
|
|
271
|
+
def send(
|
|
272
|
+
self,
|
|
273
|
+
method: str,
|
|
274
|
+
path: str,
|
|
275
|
+
*,
|
|
276
|
+
timeout: Timeout,
|
|
277
|
+
json: object = None,
|
|
278
|
+
params: Params | None = None,
|
|
279
|
+
headers: dict[str, str] | None = None,
|
|
280
|
+
unwrap: bool = False,
|
|
281
|
+
required: tuple[str, ...] = (),
|
|
282
|
+
min_read_timeout: float | None = None,
|
|
283
|
+
) -> Any:
|
|
284
|
+
"""Sends one request and returns its JSON body, or the body's `data` with `unwrap`.
|
|
285
|
+
|
|
286
|
+
`required` lists the fields the answer must have, an object, else it raises `UnexpectedResponseError`.
|
|
287
|
+
|
|
288
|
+
`min_read_timeout` raises the read timeout of the HTTP client's own timeout, used only when no timeout was
|
|
289
|
+
given to the SDK (per call nor per client).
|
|
290
|
+
"""
|
|
291
|
+
self.ensure_open()
|
|
292
|
+
try:
|
|
293
|
+
request = self._request(
|
|
294
|
+
method,
|
|
295
|
+
path,
|
|
296
|
+
timeout,
|
|
297
|
+
json=json,
|
|
298
|
+
params=params,
|
|
299
|
+
headers=headers,
|
|
300
|
+
min_read_timeout=min_read_timeout,
|
|
301
|
+
)
|
|
302
|
+
response = self._client.send(request)
|
|
303
|
+
except _SEND_FAILURES as error:
|
|
304
|
+
if (failure := self._failure(error)) is None:
|
|
305
|
+
raise
|
|
306
|
+
raise failure from error
|
|
307
|
+
return self._parse(response, unwrap=unwrap, required=required)
|
|
308
|
+
|
|
309
|
+
def upload(
|
|
310
|
+
self,
|
|
311
|
+
method: str,
|
|
312
|
+
url: str,
|
|
313
|
+
file: FilePath | FileContent,
|
|
314
|
+
*,
|
|
315
|
+
headers: dict[str, str],
|
|
316
|
+
timeout: Timeout,
|
|
317
|
+
) -> None:
|
|
318
|
+
"""Sends a file to a presigned URL, a path or a stream read chunk by chunk; raises `StorageTransferError`
|
|
319
|
+
when S3 refuses it, an `SdkError` (before sending) for an unreadable path."""
|
|
320
|
+
self.ensure_open()
|
|
321
|
+
with ExitStack() as stack:
|
|
322
|
+
content = open_content(file, stack)
|
|
323
|
+
body = content if isinstance(content, bytes) else _chunks(content)
|
|
324
|
+
with self._transfer(method, url, timeout, content=body, headers=headers):
|
|
325
|
+
pass
|
|
326
|
+
|
|
327
|
+
def fetch(self, url: str, *, timeout: Timeout) -> bytes:
|
|
328
|
+
"""Fetches a file from a presigned URL into memory; raises `StorageTransferError` when S3 refuses it."""
|
|
329
|
+
self.ensure_open()
|
|
330
|
+
with self._transfer(HttpMethod.GET, url, timeout) as response:
|
|
331
|
+
return response.read()
|
|
332
|
+
|
|
333
|
+
def save(self, url: str, path: FilePath, *, timeout: Timeout) -> None:
|
|
334
|
+
"""Streams a file from a presigned URL to `path`; raises `StorageTransferError` when S3 refuses it."""
|
|
335
|
+
self.ensure_open()
|
|
336
|
+
with self._transfer(HttpMethod.GET, url, timeout) as response:
|
|
337
|
+
destination = Destination(path)
|
|
338
|
+
try:
|
|
339
|
+
destination.create() # only once S3 accepted
|
|
340
|
+
for chunk in response.iter_bytes():
|
|
341
|
+
destination.write(chunk)
|
|
342
|
+
destination.commit()
|
|
343
|
+
except BaseException:
|
|
344
|
+
destination.discard()
|
|
345
|
+
raise
|
|
346
|
+
|
|
347
|
+
@contextmanager
|
|
348
|
+
def _transfer(
|
|
349
|
+
self,
|
|
350
|
+
method: str,
|
|
351
|
+
url: str,
|
|
352
|
+
timeout: Timeout,
|
|
353
|
+
*,
|
|
354
|
+
content: bytes | Iterator[bytes] | None = None,
|
|
355
|
+
headers: dict[str, str] | None = None,
|
|
356
|
+
) -> Generator[httpx.Response, None, None]:
|
|
357
|
+
"""Sends a request to S3 and yields its response, accepted, its body not read yet; failures to send or to
|
|
358
|
+
read it within the block are raised as SDK errors."""
|
|
359
|
+
try:
|
|
360
|
+
request = self._transfer_request(method, url, timeout, content=content, headers=headers)
|
|
361
|
+
response = self._client.send(request, stream=True, auth=None)
|
|
362
|
+
try:
|
|
363
|
+
if not response.is_success:
|
|
364
|
+
response.read()
|
|
365
|
+
raise self._refused(response)
|
|
366
|
+
yield response
|
|
367
|
+
finally:
|
|
368
|
+
response.close()
|
|
369
|
+
except _SEND_FAILURES as error:
|
|
370
|
+
if (failure := self._failure(error)) is None:
|
|
371
|
+
raise
|
|
372
|
+
raise failure from error
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class AsyncTransport(_Transport[httpx.AsyncClient]):
|
|
376
|
+
def _new_client(self) -> httpx.AsyncClient:
|
|
377
|
+
return httpx.AsyncClient()
|
|
378
|
+
|
|
379
|
+
async def aclose(self) -> None:
|
|
380
|
+
if self._owned_client is not None:
|
|
381
|
+
await self._owned_client.aclose()
|
|
382
|
+
|
|
383
|
+
async def get(self, path: str, *, timeout: Timeout, params: Params | None = None, unwrap: bool = False) -> Any:
|
|
384
|
+
return await self.send(HttpMethod.GET, path, timeout=timeout, params=params, unwrap=unwrap)
|
|
385
|
+
|
|
386
|
+
async def send(
|
|
387
|
+
self,
|
|
388
|
+
method: str,
|
|
389
|
+
path: str,
|
|
390
|
+
*,
|
|
391
|
+
timeout: Timeout,
|
|
392
|
+
json: object = None,
|
|
393
|
+
params: Params | None = None,
|
|
394
|
+
headers: dict[str, str] | None = None,
|
|
395
|
+
unwrap: bool = False,
|
|
396
|
+
required: tuple[str, ...] = (),
|
|
397
|
+
min_read_timeout: float | None = None,
|
|
398
|
+
) -> Any:
|
|
399
|
+
"""Sends one request and returns its JSON body, or the body's `data` with `unwrap`.
|
|
400
|
+
|
|
401
|
+
`required` lists the fields the answer must have, an object, else it raises `UnexpectedResponseError`.
|
|
402
|
+
|
|
403
|
+
`min_read_timeout` raises the read timeout of the HTTP client's own timeout, used only when no timeout was
|
|
404
|
+
given to the SDK (per call nor per client).
|
|
405
|
+
"""
|
|
406
|
+
self.ensure_open()
|
|
407
|
+
try:
|
|
408
|
+
request = self._request(
|
|
409
|
+
method,
|
|
410
|
+
path,
|
|
411
|
+
timeout,
|
|
412
|
+
json=json,
|
|
413
|
+
params=params,
|
|
414
|
+
headers=headers,
|
|
415
|
+
min_read_timeout=min_read_timeout,
|
|
416
|
+
)
|
|
417
|
+
response = await self._client.send(request)
|
|
418
|
+
except _SEND_FAILURES as error:
|
|
419
|
+
if (failure := self._failure(error)) is None:
|
|
420
|
+
raise
|
|
421
|
+
raise failure from error
|
|
422
|
+
return self._parse(response, unwrap=unwrap, required=required)
|
|
423
|
+
|
|
424
|
+
async def upload(
|
|
425
|
+
self,
|
|
426
|
+
method: str,
|
|
427
|
+
url: str,
|
|
428
|
+
file: FilePath | FileContent,
|
|
429
|
+
*,
|
|
430
|
+
headers: dict[str, str],
|
|
431
|
+
timeout: Timeout,
|
|
432
|
+
) -> None:
|
|
433
|
+
"""Sends a file to a presigned URL, a path or a stream read chunk by chunk; raises `StorageTransferError`
|
|
434
|
+
when S3 refuses it, an `SdkError` (before sending) for an unreadable path."""
|
|
435
|
+
self.ensure_open()
|
|
436
|
+
with ExitStack() as stack:
|
|
437
|
+
# A path is opened in a worker thread, off the event loop (closed with `stack`, even when cancelled).
|
|
438
|
+
content = await in_thread(open_content, file, stack) if isinstance(file, (str, os.PathLike)) else file
|
|
439
|
+
if isinstance(content, bytes):
|
|
440
|
+
async with self._transfer(method, url, timeout, content=content, headers=headers):
|
|
441
|
+
pass
|
|
442
|
+
return
|
|
443
|
+
# The chunks are closed before the file, once a read under way when cancelled has ended (see `in_thread`).
|
|
444
|
+
async with (
|
|
445
|
+
aclosing(_async_chunks(content)) as chunks,
|
|
446
|
+
self._transfer(method, url, timeout, content=chunks, headers=headers),
|
|
447
|
+
):
|
|
448
|
+
pass
|
|
449
|
+
|
|
450
|
+
async def fetch(self, url: str, *, timeout: Timeout) -> bytes:
|
|
451
|
+
"""Fetches a file from a presigned URL into memory; raises `StorageTransferError` when S3 refuses it."""
|
|
452
|
+
self.ensure_open()
|
|
453
|
+
async with self._transfer(HttpMethod.GET, url, timeout) as response:
|
|
454
|
+
return await response.aread()
|
|
455
|
+
|
|
456
|
+
async def save(self, url: str, path: FilePath, *, timeout: Timeout) -> None:
|
|
457
|
+
"""Streams a file from a presigned URL to `path`; raises `StorageTransferError` when S3 refuses it."""
|
|
458
|
+
self.ensure_open()
|
|
459
|
+
async with self._transfer(HttpMethod.GET, url, timeout) as response:
|
|
460
|
+
# The file is written in worker threads, off the event loop. On a cancellation, `in_thread` lets the
|
|
461
|
+
# file operation under way end first: a write, then the temporary file is removed; the rename (atomic),
|
|
462
|
+
# then `path` is the complete file. Either way, the cancellation propagates.
|
|
463
|
+
destination = Destination(path)
|
|
464
|
+
try:
|
|
465
|
+
await in_thread(destination.create) # only once S3 accepted
|
|
466
|
+
async for chunk in response.aiter_bytes():
|
|
467
|
+
await in_thread(destination.write, chunk)
|
|
468
|
+
await in_thread(destination.commit)
|
|
469
|
+
except BaseException: # cancellation included
|
|
470
|
+
await in_thread(destination.discard) # nothing to do once committed
|
|
471
|
+
raise
|
|
472
|
+
|
|
473
|
+
@asynccontextmanager
|
|
474
|
+
async def _transfer(
|
|
475
|
+
self,
|
|
476
|
+
method: str,
|
|
477
|
+
url: str,
|
|
478
|
+
timeout: Timeout,
|
|
479
|
+
*,
|
|
480
|
+
content: bytes | AsyncIterator[bytes] | None = None,
|
|
481
|
+
headers: dict[str, str] | None = None,
|
|
482
|
+
) -> AsyncGenerator[httpx.Response, None]:
|
|
483
|
+
"""Sends a request to S3 and yields its response, accepted, its body not read yet; failures to send or to
|
|
484
|
+
read it within the block are raised as SDK errors."""
|
|
485
|
+
try:
|
|
486
|
+
request = self._transfer_request(method, url, timeout, content=content, headers=headers)
|
|
487
|
+
response = await self._client.send(request, stream=True, auth=None)
|
|
488
|
+
try:
|
|
489
|
+
if not response.is_success:
|
|
490
|
+
await response.aread()
|
|
491
|
+
raise self._refused(response)
|
|
492
|
+
yield response
|
|
493
|
+
finally:
|
|
494
|
+
await response.aclose()
|
|
495
|
+
except _SEND_FAILURES as error:
|
|
496
|
+
if (failure := self._failure(error)) is None:
|
|
497
|
+
raise
|
|
498
|
+
raise failure from error
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class SyncClientBase:
|
|
502
|
+
"""Options and lifecycle shared by every synchronous raw client."""
|
|
503
|
+
|
|
504
|
+
def __init__(
|
|
505
|
+
self,
|
|
506
|
+
*,
|
|
507
|
+
base_url: str,
|
|
508
|
+
token: str,
|
|
509
|
+
http_client: httpx.Client | None = None,
|
|
510
|
+
timeout: Timeout = NOT_GIVEN,
|
|
511
|
+
) -> None:
|
|
512
|
+
"""Creates a client; with no `http_client`, it creates its own, to close with `close()` or `with`.
|
|
513
|
+
|
|
514
|
+
Args:
|
|
515
|
+
base_url: base URL of the AsyncTaskAPI instance, e.g. `https://<host>`. A trailing slash is ignored.
|
|
516
|
+
token: personal access token of the consumer, sent as `Authorization: Bearer <token>` on each request. It is
|
|
517
|
+
never set on the HTTP client, so it never reaches another host.
|
|
518
|
+
http_client: the `httpx.Client` to send requests with (proxy, logging, shared pool, test double). The SDK
|
|
519
|
+
never modifies nor closes it. When omitted, the client creates its own, closed by `close()` or at the
|
|
520
|
+
end of a `with` block.
|
|
521
|
+
timeout: default timeout of every call, in seconds; `None` disables it, as in httpx. When omitted, the HTTP
|
|
522
|
+
client's own timeout applies (5 seconds for httpx's default), its read timeout raised for a task
|
|
523
|
+
`create` with `wait`. Each method also takes a `timeout` keyword, which overrides it, `None` included.
|
|
524
|
+
|
|
525
|
+
Example:
|
|
526
|
+
>>> client = MeClient(base_url="https://async-task-api.example.org", token=os.environ["TOKEN"], timeout=30)
|
|
527
|
+
>>> with httpx.Client(event_hooks={"request": [log_request]}) as http_client:
|
|
528
|
+
... me = MeClient(base_url=base_url, token=token, http_client=http_client).get()
|
|
529
|
+
"""
|
|
530
|
+
self._http = SyncTransport(base_url=base_url, token=token, http_client=http_client, timeout=timeout)
|
|
531
|
+
|
|
532
|
+
def close(self) -> None:
|
|
533
|
+
"""Closes the HTTP client this client created; an injected one is left open. Calling it again does nothing.
|
|
534
|
+
|
|
535
|
+
Once closed, a client that created its own HTTP client raises `ClientClosedError` on any call. A `with` block
|
|
536
|
+
closes the client on exit.
|
|
537
|
+
|
|
538
|
+
Example:
|
|
539
|
+
>>> client = MeClient(base_url=base_url, token=token)
|
|
540
|
+
>>> try:
|
|
541
|
+
... me = client.get()
|
|
542
|
+
... finally:
|
|
543
|
+
... client.close()
|
|
544
|
+
"""
|
|
545
|
+
self._http.close()
|
|
546
|
+
|
|
547
|
+
def __enter__(self) -> Self:
|
|
548
|
+
return self
|
|
549
|
+
|
|
550
|
+
def __exit__(
|
|
551
|
+
self,
|
|
552
|
+
exc_type: type[BaseException] | None,
|
|
553
|
+
exc: BaseException | None,
|
|
554
|
+
tb: TracebackType | None,
|
|
555
|
+
) -> None:
|
|
556
|
+
self.close()
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
class AsyncClientBase:
|
|
560
|
+
"""Options and lifecycle shared by every asynchronous raw client.
|
|
561
|
+
|
|
562
|
+
Calls are cancelled with asyncio's own tools (`task.cancel()`, `asyncio.timeout()`); the SDK never wraps
|
|
563
|
+
`asyncio.CancelledError`.
|
|
564
|
+
"""
|
|
565
|
+
|
|
566
|
+
def __init__(
|
|
567
|
+
self,
|
|
568
|
+
*,
|
|
569
|
+
base_url: str,
|
|
570
|
+
token: str,
|
|
571
|
+
http_client: httpx.AsyncClient | None = None,
|
|
572
|
+
timeout: Timeout = NOT_GIVEN,
|
|
573
|
+
) -> None:
|
|
574
|
+
"""Creates a client; with no `http_client`, it creates its own, to close with `aclose()` or `async with`.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
base_url: base URL of the AsyncTaskAPI instance, e.g. `https://<host>`. A trailing slash is ignored.
|
|
578
|
+
token: personal access token of the consumer, sent as `Authorization: Bearer <token>` on each request. It is
|
|
579
|
+
never set on the HTTP client, so it never reaches another host.
|
|
580
|
+
http_client: the `httpx.AsyncClient` to send requests with (proxy, logging, shared pool, test double). The
|
|
581
|
+
SDK never modifies nor closes it. When omitted, the client creates its own, closed by `aclose()` or at
|
|
582
|
+
the end of an `async with` block.
|
|
583
|
+
timeout: default timeout of every call, in seconds; `None` disables it, as in httpx. When omitted, the HTTP
|
|
584
|
+
client's own timeout applies (5 seconds for httpx's default), its read timeout raised for a task
|
|
585
|
+
`create` with `wait`. Each method also takes a `timeout` keyword, which overrides it, `None` included.
|
|
586
|
+
|
|
587
|
+
Example:
|
|
588
|
+
>>> async with httpx.AsyncClient(event_hooks={"request": [log_request]}) as http_client:
|
|
589
|
+
... me = await AsyncMeClient(base_url=base_url, token=token, http_client=http_client).get()
|
|
590
|
+
"""
|
|
591
|
+
self._http = AsyncTransport(base_url=base_url, token=token, http_client=http_client, timeout=timeout)
|
|
592
|
+
|
|
593
|
+
async def aclose(self) -> None:
|
|
594
|
+
"""Closes the HTTP client this client created; an injected one is left open. Calling it again does nothing.
|
|
595
|
+
|
|
596
|
+
Once closed, a client that created its own HTTP client raises `ClientClosedError` on any call. An
|
|
597
|
+
`async with` block closes the client on exit.
|
|
598
|
+
|
|
599
|
+
Example:
|
|
600
|
+
>>> client = AsyncMeClient(base_url=base_url, token=token)
|
|
601
|
+
>>> try:
|
|
602
|
+
... me = await client.get()
|
|
603
|
+
... finally:
|
|
604
|
+
... await client.aclose()
|
|
605
|
+
"""
|
|
606
|
+
await self._http.aclose()
|
|
607
|
+
|
|
608
|
+
async def __aenter__(self) -> Self:
|
|
609
|
+
return self
|
|
610
|
+
|
|
611
|
+
async def __aexit__(
|
|
612
|
+
self,
|
|
613
|
+
exc_type: type[BaseException] | None,
|
|
614
|
+
exc: BaseException | None,
|
|
615
|
+
tb: TracebackType | None,
|
|
616
|
+
) -> None:
|
|
617
|
+
await self.aclose()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ._generated import AuthorizationResponse, MeResponse
|
|
4
|
+
from ._http import NOT_GIVEN, AsyncClientBase, SyncClientBase, Timeout
|
|
5
|
+
|
|
6
|
+
Authorization = AuthorizationResponse
|
|
7
|
+
"""A service the consumer may call, with its quota of concurrent tasks if any.
|
|
8
|
+
|
|
9
|
+
`service: "all"` is returned literally and means every service.
|
|
10
|
+
|
|
11
|
+
Example:
|
|
12
|
+
>>> authorization = me["authorizations"][0]
|
|
13
|
+
>>> authorization["service"], authorization.get("quotas")
|
|
14
|
+
('generation-render', 5)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
Me = MeResponse
|
|
18
|
+
"""Identity of the authenticated consumer (`client_id`) and the services it may call (`authorizations`, empty if
|
|
19
|
+
none).
|
|
20
|
+
|
|
21
|
+
Example:
|
|
22
|
+
>>> me = client.get()
|
|
23
|
+
>>> me["client_id"], [authorization["service"] for authorization in me["authorizations"]]
|
|
24
|
+
('my-app', ['all'])
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class MeClient(SyncClientBase):
|
|
29
|
+
"""Raw client of the consumer's identity (`/v1/me`): who the token belongs to, and which services it may call.
|
|
30
|
+
|
|
31
|
+
Example:
|
|
32
|
+
>>> with MeClient(base_url=base_url, token=token) as client:
|
|
33
|
+
... me = client.get()
|
|
34
|
+
>>> allowed = {authorization["service"] for authorization in me["authorizations"]}
|
|
35
|
+
>>> can_render = "all" in allowed or "generation-render" in allowed
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def get(self, *, timeout: Timeout = NOT_GIVEN) -> Me:
|
|
39
|
+
"""Identity of the authenticated consumer and the services it may call (`GET /v1/me`).
|
|
40
|
+
|
|
41
|
+
Read-only, it is the cheapest way to validate a token.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
timeout: seconds before giving up, overriding the client's default; `None` disables it.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
AuthenticationError: the token is missing or invalid, or the consumer unknown or inactive.
|
|
48
|
+
ApiError: any other error answered by the API.
|
|
49
|
+
|
|
50
|
+
Example:
|
|
51
|
+
>>> try:
|
|
52
|
+
... me = client.get(timeout=5)
|
|
53
|
+
... except AuthenticationError:
|
|
54
|
+
... print("Invalid token")
|
|
55
|
+
"""
|
|
56
|
+
return self._http.get("/v1/me", timeout=timeout)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AsyncMeClient(AsyncClientBase):
|
|
60
|
+
"""Asynchronous twin of `MeClient`.
|
|
61
|
+
|
|
62
|
+
Example:
|
|
63
|
+
>>> async with AsyncMeClient(base_url=base_url, token=token) as client:
|
|
64
|
+
... me = await client.get()
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
async def get(self, *, timeout: Timeout = NOT_GIVEN) -> Me:
|
|
68
|
+
"""Identity of the authenticated consumer and the services it may call (`GET /v1/me`).
|
|
69
|
+
|
|
70
|
+
See `MeClient.get`.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
AuthenticationError: the token is missing or invalid, or the consumer unknown or inactive.
|
|
74
|
+
ApiError: any other error answered by the API.
|
|
75
|
+
|
|
76
|
+
Example:
|
|
77
|
+
>>> me = await client.get(timeout=5)
|
|
78
|
+
"""
|
|
79
|
+
return await self._http.get("/v1/me", timeout=timeout)
|