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.
@@ -0,0 +1,4 @@
1
+ """Python SDK for AsyncTaskAPI. Exposes the same names as `async_task_api_client.raw`."""
2
+
3
+ from .raw import * # noqa: F403
4
+ from .raw import __all__ as __all__
@@ -0,0 +1,294 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from http import HTTPStatus
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from . import _generated
8
+
9
+ if TYPE_CHECKING:
10
+ import httpx
11
+
12
+ from ._tasks import FailedTask
13
+
14
+ Issue = _generated.Issue
15
+ """One invalid field of a rejected request, in `ApiError.issues` (`422`): its path `loc`, its message `msg` and the
16
+ validator's `type`.
17
+
18
+ Example:
19
+ >>> for issue in error.issues or []:
20
+ ... print(".".join(str(part) for part in issue["loc"]), issue["msg"])
21
+ body.template Field required
22
+ """
23
+
24
+ ReadyComponent = _generated.ReadyComponent
25
+ """The state of one dependency of the API, in `ApiError.components` (`503`, `DEPENDENCIES_NOT_READY`): its `status`
26
+ (`ok` or `error`), and `details` when it is not ready.
27
+
28
+ Example:
29
+ >>> down = [name for name, component in (error.components or {}).items() if component["status"] != "ok"]
30
+ """
31
+
32
+ __all__ = [
33
+ "ApiError",
34
+ "AuthenticationError",
35
+ "ClientClosedError",
36
+ "Issue",
37
+ "ReadyComponent",
38
+ "RequestTimeoutError",
39
+ "SdkError",
40
+ "StorageTransferError",
41
+ "TaskFailedError",
42
+ "TransportError",
43
+ "UnexpectedResponseError",
44
+ ]
45
+
46
+
47
+ class SdkError(Exception):
48
+ """Base class of every error raised by the SDK: catch it to handle them all.
49
+
50
+ Example:
51
+ >>> try:
52
+ ... me = client.get()
53
+ ... except AuthenticationError:
54
+ ... print("Check ASYNC_TASK_API_TOKEN")
55
+ ... except ApiError as error:
56
+ ... print(error.code, error.message)
57
+ ... except SdkError as error:
58
+ ... print("AsyncTaskAPI call failed:", error)
59
+ """
60
+
61
+ def __init__(self, message: str) -> None:
62
+ super().__init__(message)
63
+ self.message = message
64
+ """Human-readable description of the error."""
65
+
66
+ def __reduce__(self) -> tuple[Any, ...]:
67
+ # `BaseException.__reduce__` calls `type(self)(*self.args)`, which a subclass `__init__` with another
68
+ # signature rejects: rebuild without `__init__`, then restore the arguments and the attributes.
69
+ return (_restore_error, (type(self), self.args, self.__dict__))
70
+
71
+
72
+ def _restore_error(cls: type[SdkError], args: tuple[Any, ...], state: dict[str, Any]) -> SdkError:
73
+ error = cls.__new__(cls, *args)
74
+ error.args = args # `OSError.__new__` (for `TimeoutError`) leaves `args` to `__init__`.
75
+ error.__dict__.update(state)
76
+ return error
77
+
78
+
79
+ class ApiError(SdkError):
80
+ """An error answered by the API in its `ErrorResponse` format.
81
+
82
+ Match on `code`: it is stable and unique, whereas the message and even the HTTP status may change. Common codes:
83
+ `SERVICE_NOT_FOUND`, `TASK_NOT_FOUND`, `FILE_NOT_FOUND` (404), `FILE_ALREADY_BOUND` (409), `FILE_EXPIRED` (410),
84
+ `UPLOAD_TOO_LARGE` / `FILE_TOO_LARGE` (413), `REQUEST_VALIDATION_ERROR` (422),
85
+ `CLIENT_SERVICE_QUOTA_EXCEEDED` (429), `DEPENDENCIES_NOT_READY` (503).
86
+
87
+ Example:
88
+ >>> try:
89
+ ... detail = services.get("generation-render")
90
+ ... except ApiError as error:
91
+ ... if error.code != "SERVICE_NOT_FOUND":
92
+ ... raise
93
+ ... detail = None
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ *,
99
+ code: str,
100
+ status: int,
101
+ message: str,
102
+ issues: list[Issue] | None = None,
103
+ components: dict[str, ReadyComponent] | None = None,
104
+ ) -> None:
105
+ super().__init__(message)
106
+ self.code = code
107
+ """Stable SCREAMING_SNAKE_CASE identifier of the error."""
108
+ self.status = status
109
+ """HTTP status of the response."""
110
+ self.issues = issues
111
+ """Field-level detail, on validation errors (`422`)."""
112
+ self.components = components
113
+ """State of each dependency, on `DEPENDENCIES_NOT_READY` (`503`)."""
114
+
115
+
116
+ class AuthenticationError(SdkError):
117
+ """The token is missing, invalid, or its consumer is unknown or inactive (`401`).
118
+
119
+ Usually answered by the API gateway, whose body is not the API's error format: `code` is then `None`. It is set
120
+ when the API itself refused the consumer.
121
+
122
+ Example:
123
+ >>> try:
124
+ ... me = client.get()
125
+ ... except AuthenticationError as error:
126
+ ... sys.exit(f"Invalid AsyncTaskAPI token: {error.message}")
127
+ """
128
+
129
+ status = int(HTTPStatus.UNAUTHORIZED)
130
+ """Always `401`."""
131
+
132
+ def __init__(self, message: str, code: str | None = None) -> None:
133
+ super().__init__(message)
134
+ self.code = code
135
+ """The API's error code, when the API itself (not the gateway) refused the consumer."""
136
+
137
+
138
+ class UnexpectedResponseError(SdkError):
139
+ """An answer the SDK cannot read: an error body in no known format (for instance an HTML page from a proxy in
140
+ front of the API), or a success that is not JSON.
141
+
142
+ Example:
143
+ >>> try:
144
+ ... me = client.get()
145
+ ... except UnexpectedResponseError as error:
146
+ ... log.error("Unreadable answer, HTTP %s: %.200s", error.status, error.body)
147
+ ... raise
148
+ """
149
+
150
+ def __init__(self, status: int, body: str) -> None:
151
+ super().__init__(f"Unexpected HTTP {status} response")
152
+ self.status = status
153
+ """HTTP status of the response."""
154
+ self.body = body
155
+ """The raw response body, as text."""
156
+
157
+
158
+ class StorageTransferError(SdkError):
159
+ """S3 refused a presigned transfer (`upload()`, `download()`, `save_to()`): an expired URL, a file whose size or
160
+ type does not match the reservation... The API was not involved: the error is S3's own, in `body`.
161
+
162
+ Example:
163
+ >>> try:
164
+ ... upload.upload()
165
+ ... except StorageTransferError as error:
166
+ ... print(error.status, error.body) # e.g. 403 and S3's <Error><Code>AccessDenied</Code>...
167
+ ... upload = storage.presigned_upload("./scans/big-scan.pdf") # reserve again
168
+ """
169
+
170
+ def __init__(self, status: int, body: str) -> None:
171
+ super().__init__(f"S3 refused the transfer: HTTP {status}")
172
+ self.status = status
173
+ """HTTP status of S3's response."""
174
+ self.body = body
175
+ """S3's response body, as text (usually an XML `<Error>` document)."""
176
+
177
+
178
+ class ClientClosedError(SdkError, RuntimeError):
179
+ """A call on a closed client: its HTTP client was closed (by `close()`, the end of a `with` block, or the
180
+ caller for an injected one). No request is sent. Also catchable as the builtin `RuntimeError`, as httpx raises.
181
+
182
+ Example:
183
+ >>> with MeClient(base_url=base_url, token=token) as client:
184
+ ... me = client.get()
185
+ >>> client.get()
186
+ Traceback (most recent call last):
187
+ ClientClosedError: ...
188
+ """
189
+
190
+
191
+ class TaskFailedError(SdkError):
192
+ """A task ended in failure, raised by `ensure_succeeded` only.
193
+
194
+ The raw clients never raise it: a failed task is a normal state, returned as data by `create` and `get`. Call
195
+ `ensure_succeeded` where a failure is an error for you.
196
+
197
+ Example:
198
+ >>> try:
199
+ ... text = ensure_succeeded(render.get(task_id))["result"]["text"]
200
+ ... except TaskFailedError as error:
201
+ ... if error.code != "TEMPLATE_SYNTAX_ERROR":
202
+ ... raise
203
+ ... print(error.message, error.task.get("end_date"))
204
+ """
205
+
206
+ def __init__(self, task: FailedTask) -> None:
207
+ # Read defensively: an off-spec failure (no `error_message`, an incomplete `error`) still gets a message.
208
+ error = task.get("error") or {}
209
+ code, message = error.get("code"), error.get("message")
210
+ if code and message:
211
+ reason = f"{code}: {message}"
212
+ else:
213
+ reason = task.get("error_message") or code or message or "no error recorded"
214
+ super().__init__(f"Task {task['task_id']} failed: {reason}")
215
+ self.task_id = task["task_id"]
216
+ """Id of the failed task."""
217
+ self.code = code or None
218
+ """The service's error code (`error["code"]`), stable: match on it. `None` when no structured error was
219
+ recorded."""
220
+ self.task = task
221
+ """The failed task, as answered by the API."""
222
+
223
+
224
+ class TransportError(SdkError):
225
+ """The request got no answer: a network failure (DNS, refused connection, broken connection...), a request
226
+ that could not even be built, such as one to an invalid `base_url`, or a streamed body httpx could not send
227
+ again (a redirect followed by an injected client with `follow_redirects=True`).
228
+
229
+ The underlying httpx exception is kept as `__cause__`. Nothing is retried: retry yourself if the call is safe to
230
+ repeat (a `get` or a `list`; a `create` may have created a task).
231
+
232
+ Example:
233
+ >>> try:
234
+ ... services = client.list()
235
+ ... except TransportError as error:
236
+ ... print("AsyncTaskAPI unreachable:", error.__cause__)
237
+ """
238
+
239
+
240
+ class RequestTimeoutError(TransportError, TimeoutError):
241
+ """The request timed out, also catchable as the builtin `TimeoutError`.
242
+
243
+ The underlying httpx exception is kept as `__cause__`. After a read timeout on `TaskClient.create`, the task may
244
+ have been created: find it with `list(session_id=...)` if you gave a session label.
245
+
246
+ Example:
247
+ >>> try:
248
+ ... task = render.create(input, wait=10, session_id="case-42", timeout=15)
249
+ ... except RequestTimeoutError:
250
+ ... page = render.list(session_id="case-42")
251
+ """
252
+
253
+
254
+ def error_from_response(response: httpx.Response) -> SdkError:
255
+ """Turns a non-2xx response into the matching SDK error."""
256
+ # The gateway's 401 is JSON sent as text/plain: parse the text whatever the content type.
257
+ text = response.text
258
+ parsed = _parse_json(text)
259
+ # Read defensively: the body is the API's `ErrorResponse` only when it says so (a gateway, a proxy...).
260
+ detail: object = cast("_generated.ErrorResponse", parsed).get("error") if isinstance(parsed, dict) else None
261
+ api_error = cast("_generated.ErrorDetail", detail if isinstance(detail, dict) else {})
262
+ raw_code: object = api_error.get("code")
263
+ raw_message: object = api_error.get("message")
264
+ code = raw_code if isinstance(raw_code, str) else None
265
+ message = raw_message if isinstance(raw_message, str) else None
266
+
267
+ if response.status_code == HTTPStatus.UNAUTHORIZED:
268
+ if message is None:
269
+ message = detail if isinstance(detail, str) else "Authentication failed"
270
+ return AuthenticationError(message, code)
271
+ if code is not None and message is not None:
272
+ return ApiError(
273
+ code=code,
274
+ status=response.status_code,
275
+ message=message,
276
+ issues=api_error.get("issues"),
277
+ components=api_error.get("components"),
278
+ )
279
+ return UnexpectedResponseError(response.status_code, text)
280
+
281
+
282
+ def json_from_response(response: httpx.Response) -> Any:
283
+ """The JSON body of a 2xx response."""
284
+ try:
285
+ return json.loads(response.content)
286
+ except ValueError:
287
+ raise UnexpectedResponseError(response.status_code, response.text) from None
288
+
289
+
290
+ def _parse_json(text: str) -> Any:
291
+ try:
292
+ return json.loads(text)
293
+ except ValueError:
294
+ return None
@@ -0,0 +1,162 @@
1
+ """Internal: files on disk, named and typed after their path, opened to be streamed (never read whole in memory)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import secrets
7
+ from contextlib import ExitStack, suppress
8
+ from pathlib import Path
9
+ from typing import IO, TypeAlias, Union
10
+
11
+ from ._errors import SdkError
12
+
13
+ FilePath: TypeAlias = Union[str, "os.PathLike[str]"]
14
+ """The path of a file on disk; a relative path is resolved against the working directory."""
15
+
16
+ FileContent: TypeAlias = Union[bytes, IO[bytes]] # noqa: UP007
17
+ """A file's content: `bytes`, or a binary stream (a file opened with `"rb"`, an `io.BytesIO`...)."""
18
+
19
+ # Common document, image, audio and video types, as in the TypeScript SDK; anything else is
20
+ # `application/octet-stream`. A fixed table rather than `mimetypes`, which reads the system's files and so varies.
21
+ _MIME_TYPES = {
22
+ ".pdf": "application/pdf",
23
+ ".doc": "application/msword",
24
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
25
+ ".xls": "application/vnd.ms-excel",
26
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
27
+ ".ppt": "application/vnd.ms-powerpoint",
28
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
29
+ ".odt": "application/vnd.oasis.opendocument.text",
30
+ ".ods": "application/vnd.oasis.opendocument.spreadsheet",
31
+ ".odp": "application/vnd.oasis.opendocument.presentation",
32
+ ".rtf": "application/rtf",
33
+ ".txt": "text/plain",
34
+ ".md": "text/markdown",
35
+ ".csv": "text/csv",
36
+ ".html": "text/html",
37
+ ".htm": "text/html",
38
+ ".xml": "application/xml",
39
+ ".json": "application/json",
40
+ ".zip": "application/zip",
41
+ ".png": "image/png",
42
+ ".jpg": "image/jpeg",
43
+ ".jpeg": "image/jpeg",
44
+ ".gif": "image/gif",
45
+ ".webp": "image/webp",
46
+ ".tif": "image/tiff",
47
+ ".tiff": "image/tiff",
48
+ ".bmp": "image/bmp",
49
+ ".svg": "image/svg+xml",
50
+ ".mp3": "audio/mpeg",
51
+ ".wav": "audio/wav",
52
+ ".ogg": "audio/ogg",
53
+ ".m4a": "audio/mp4",
54
+ ".flac": "audio/flac",
55
+ ".mp4": "video/mp4",
56
+ ".webm": "video/webm",
57
+ ".mov": "video/quicktime",
58
+ }
59
+
60
+
61
+ def mime_type_of(name: str) -> str:
62
+ """The MIME type of a file name, from its extension (case-insensitive), or `application/octet-stream`."""
63
+ return _MIME_TYPES.get(Path(name).suffix.lower(), "application/octet-stream")
64
+
65
+
66
+ def file_name(path: FilePath) -> str:
67
+ """The name of a file on disk, without its directory."""
68
+ return Path(path).name
69
+
70
+
71
+ def open_content(file: FilePath | FileContent, stack: ExitStack) -> FileContent:
72
+ """The content of a file to send: a path opened for reading (see `open_file`, closed with `stack`), else `bytes`
73
+ or a stream as is."""
74
+ if isinstance(file, (str, os.PathLike)):
75
+ return stack.enter_context(open_file(file))
76
+ return file
77
+
78
+
79
+ def open_file(path: FilePath) -> IO[bytes]:
80
+ """Opens a file on disk for reading, to be streamed. An unreadable path raises an `SdkError` naming it, resolved
81
+ against the working directory, with the `OSError` as `__cause__`."""
82
+ try:
83
+ return Path(path).open("rb") # closed by the caller, once sent
84
+ except OSError as error:
85
+ raise unreadable_error(path) from error
86
+
87
+
88
+ def unreadable_error(path: FilePath, reason: str | None = None) -> SdkError:
89
+ """The error for a file that cannot be read, naming its path resolved against the working directory, and why,
90
+ when given."""
91
+ because = "" if reason is None else f": {reason}"
92
+ return SdkError(f'Cannot read the file "{os.fspath(path)}" (resolved to {Path(path).absolute()}){because}')
93
+
94
+
95
+ class Destination:
96
+ """A file on disk written whole or not at all: written to a temporary file next to it, created by `create()`,
97
+ renamed over it by `commit()`, removed by `discard()`. An existing file is replaced only once the new one is
98
+ complete.
99
+
100
+ Any `OSError` (a missing directory, a full disk...) raises an `SdkError` naming the path, resolved against the
101
+ working directory, with the `OSError` as `__cause__`; the temporary file is then removed.
102
+ """
103
+
104
+ def __init__(self, path: FilePath) -> None:
105
+ """Names the temporary file; nothing is created on disk yet."""
106
+ self._path = path
107
+ absolute = Path(path).absolute()
108
+ self._temporary = absolute.with_name(f".{absolute.name}.{secrets.token_hex(4)}.part")
109
+ self._file: IO[bytes] | None = None
110
+ """The temporary file, from its creation until it is committed or discarded."""
111
+
112
+ def create(self) -> None:
113
+ """Creates the temporary file."""
114
+ try:
115
+ # Created as `open` would (the umask applies), never over an existing file.
116
+ descriptor = os.open(self._temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_BINARY, 0o666)
117
+ except OSError as error:
118
+ raise self._unwritable() from error
119
+ self._file = os.fdopen(descriptor, "wb", buffering=_WRITE_BUFFER_BYTES)
120
+
121
+ def write(self, chunk: bytes) -> None:
122
+ try:
123
+ self._created().write(chunk)
124
+ except OSError as error:
125
+ self.discard()
126
+ raise self._unwritable() from error
127
+
128
+ def commit(self) -> None:
129
+ """Closes the file and renames it over the path."""
130
+ try:
131
+ self._created().close()
132
+ self._temporary.replace(self._path)
133
+ except OSError as error:
134
+ self.discard()
135
+ raise self._unwritable() from error
136
+ self._file = None
137
+
138
+ def discard(self) -> None:
139
+ """Closes and removes the temporary file, leaving the path untouched; does nothing when no temporary file
140
+ remains (never created, committed, or already discarded)."""
141
+ if self._file is None:
142
+ return
143
+ with suppress(OSError):
144
+ self._file.close()
145
+ with suppress(OSError):
146
+ self._temporary.unlink()
147
+ self._file = None
148
+
149
+ def _created(self) -> IO[bytes]:
150
+ assert self._file is not None, "create() first"
151
+ return self._file
152
+
153
+ def _unwritable(self) -> SdkError:
154
+ return SdkError(f'Cannot write the file "{os.fspath(self._path)}" (resolved to {Path(self._path).absolute()})')
155
+
156
+
157
+ _O_BINARY: int = getattr(os, "O_BINARY", 0)
158
+ """No newline translation on Windows; 0 elsewhere."""
159
+
160
+ _WRITE_BUFFER_BYTES = 8 * 1024
161
+ """The most of a download held in memory before it is written to disk. Fixed rather than `io.DEFAULT_BUFFER_SIZE`,
162
+ which Python 3.14 raised from 8 KiB to 128 KiB: a download reaches the disk the same way on every Python version."""