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,140 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+ from urllib.parse import quote
5
+
6
+ from . import _generated
7
+ from ._http import NOT_GIVEN, AsyncClientBase, SyncClientBase, Timeout
8
+
9
+ if TYPE_CHECKING:
10
+ import builtins
11
+
12
+ ServiceClass = _generated.ServiceClass
13
+ """The order of magnitude of a service's processing time: `immediate` (under 1 s), `short` (under 10 s) or `long`
14
+ (up to 5 min). It caps the `wait` of `TaskClient.create`: 10 s, 30 s, and ignored for `long`.
15
+
16
+ Example:
17
+ >>> wait = 10 if summary.get("class") == "immediate" else None
18
+ """
19
+
20
+ ServiceSummary = _generated.ServiceSummary
21
+ """A service of the catalogue, as listed by `ServicesClient.list`: its `name`, `title`, descriptions, `class`, and
22
+ whether it takes files (`files_enabled`, `max_file_size_mib`); without its schemas. Read `class` with
23
+ `summary.get("class")` (`class` is a Python keyword).
24
+
25
+ Example:
26
+ >>> for summary in services.list():
27
+ ... print(summary["name"], summary.get("title"), summary.get("class"))
28
+ """
29
+
30
+ ServiceDetail = _generated.ServiceDetail
31
+ """A service's live contract, as answered by `ServicesClient.get`: the fields of `ServiceSummary`, plus the JSON
32
+ Schemas of its input (`input_schema`) and result (`output_schema`), and its `file_fields`, the input fields that
33
+ take a file.
34
+
35
+ Example:
36
+ >>> detail = services.get("generation-render")
37
+ >>> detail.get("file_fields", [])
38
+ ['file_id']
39
+ """
40
+
41
+ __all__ = ["AsyncServicesClient", "ServiceClass", "ServiceDetail", "ServiceSummary", "ServicesClient"]
42
+
43
+
44
+ def path_segment(value: str, what: str) -> str:
45
+ """`value` escaped as one URL path segment; `what` names it in the error.
46
+
47
+ Raises:
48
+ ValueError: an empty, `.` or `..` value. Those survive percent-encoding and are resolved as dot-segments by
49
+ URL parsers, so they would reach another route (`/v1/services/..` is `/v1`); none names a resource.
50
+ """
51
+ if value in ("", ".", ".."):
52
+ raise ValueError(f"Invalid {what}: {value!r}")
53
+ return quote(value, safe="")
54
+
55
+
56
+ def service_path(service: str) -> str:
57
+ return f"/v1/services/{path_segment(service, 'service name')}"
58
+
59
+
60
+ class ServicesClient(SyncClientBase):
61
+ """Raw client of the service catalogue (`/v1/services`).
62
+
63
+ Services are added to AsyncTaskAPI dynamically and the SDK knows none of them: this client discovers them and
64
+ reads their current contract at runtime.
65
+
66
+ Example:
67
+ >>> with ServicesClient(base_url=base_url, token=token) as services:
68
+ ... for service in services.list():
69
+ ... print(service["name"], service.get("class"))
70
+ ... render = services.get("generation-render")
71
+ >>> render.get("input_schema") # JSON Schema of the input
72
+ """
73
+
74
+ def list(self, *, timeout: Timeout = NOT_GIVEN) -> builtins.list[ServiceSummary]:
75
+ """The service catalogue, without schemas (`GET /v1/services`).
76
+
77
+ Args:
78
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
79
+
80
+ Raises:
81
+ AuthenticationError: the token is refused.
82
+ ApiError: any other error answered by the API.
83
+
84
+ Example:
85
+ >>> names = [summary["name"] for summary in services.list()]
86
+ """
87
+ return self._http.get("/v1/services", timeout=timeout)
88
+
89
+ def get(self, service: str, *, timeout: Timeout = NOT_GIVEN) -> ServiceDetail:
90
+ """One service with its input/result JSON Schemas and file fields (`GET /v1/services/{service}`).
91
+
92
+ Args:
93
+ service: the service's name, as listed by `list()`.
94
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
95
+
96
+ Raises:
97
+ ApiError: `SERVICE_NOT_FOUND` (404) for an unknown service.
98
+ AuthenticationError: the token is refused.
99
+ ValueError: an empty, `.` or `..` service name, which no service bears; no request is sent.
100
+
101
+ Example:
102
+ >>> detail = services.get("generation-render")
103
+ >>> schema = detail.get("input_schema") # JSON Schema of the input, or None
104
+ """
105
+ return self._http.get(service_path(service), timeout=timeout)
106
+
107
+
108
+ class AsyncServicesClient(AsyncClientBase):
109
+ """Asynchronous twin of `ServicesClient`.
110
+
111
+ Example:
112
+ >>> async with AsyncServicesClient(base_url=base_url, token=token) as services:
113
+ ... catalogue = await services.list()
114
+ """
115
+
116
+ async def list(self, *, timeout: Timeout = NOT_GIVEN) -> builtins.list[ServiceSummary]:
117
+ """The service catalogue, without schemas (`GET /v1/services`). See `ServicesClient.list`.
118
+
119
+ Raises:
120
+ AuthenticationError: the token is refused.
121
+ ApiError: any other error answered by the API.
122
+
123
+ Example:
124
+ >>> names = [summary["name"] for summary in await services.list()]
125
+ """
126
+ return await self._http.get("/v1/services", timeout=timeout)
127
+
128
+ async def get(self, service: str, *, timeout: Timeout = NOT_GIVEN) -> ServiceDetail:
129
+ """One service with its input/result JSON Schemas and file fields (`GET /v1/services/{service}`). See
130
+ `ServicesClient.get`.
131
+
132
+ Raises:
133
+ ApiError: `SERVICE_NOT_FOUND` (404) for an unknown service.
134
+ AuthenticationError: the token is refused.
135
+ ValueError: an empty, `.` or `..` service name, which no service bears; no request is sent.
136
+
137
+ Example:
138
+ >>> detail = await services.get("generation-render")
139
+ """
140
+ return await self._http.get(service_path(service), timeout=timeout)
@@ -0,0 +1,527 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import stat
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any, overload
7
+
8
+ from . import _generated
9
+ from ._files import FileContent, FilePath, file_name, mime_type_of, open_file, unreadable_error
10
+ from ._http import (
11
+ NOT_GIVEN,
12
+ AsyncClientBase,
13
+ AsyncTransport,
14
+ HttpMethod,
15
+ SyncClientBase,
16
+ SyncTransport,
17
+ Timeout,
18
+ in_thread,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from ._generated import PresignedDownloadRequest, PresignedDownloadResponse, PresignedUploadResponse
23
+
24
+ __all__ = [
25
+ "AsyncPresignedDownload",
26
+ "AsyncPresignedFileUpload",
27
+ "AsyncPresignedUpload",
28
+ "AsyncStorageClient",
29
+ "PresignedDownload",
30
+ "PresignedFileUpload",
31
+ "PresignedUpload",
32
+ "PresignedUploadRequest",
33
+ "StorageClient",
34
+ ]
35
+
36
+
37
+ PresignedUploadRequest = _generated.PresignedUploadRequest
38
+ """The description of a file to reserve with `StorageClient.presigned_upload`, when the file is not on disk yet or
39
+ to impose its name or type: its `filename`, `mime_type` and exact `size_bytes`, all signed into the upload.
40
+
41
+ Example:
42
+ >>> upload = storage.presigned_upload({"filename": "scan.pdf", "mime_type": "application/pdf", "size_bytes": size})
43
+ """
44
+
45
+
46
+ def _describe(path: FilePath) -> PresignedUploadRequest:
47
+ """The reservation of a file on disk: its name, its MIME type from its extension, and its size. A path that is
48
+ not a regular file (a directory, a pipe, a device), or cannot be read, raises an `SdkError` naming it; the file
49
+ is opened (to check it can be read) but not read."""
50
+ try:
51
+ status = Path(path).stat()
52
+ except OSError as error:
53
+ raise unreadable_error(path) from error
54
+ # Checked before opening: a pipe would block until written to, and its size, like a device's, means nothing.
55
+ if not stat.S_ISREG(status.st_mode):
56
+ raise unreadable_error(path, reason="not a regular file")
57
+ open_file(path).close()
58
+ name = file_name(path)
59
+ return {"filename": name, "mime_type": mime_type_of(name), "size_bytes": status.st_size}
60
+
61
+
62
+ _RESERVATION_FIELDS = tuple(sorted(_generated.PresignedUploadResponse.__required_keys__))
63
+ """The fields a presigned upload must have, read from its generated type; `method`, optional, defaults to `PUT`."""
64
+
65
+ _DOWNLOAD_FIELDS = tuple(sorted(_generated.PresignedDownloadResponse.__required_keys__))
66
+ """The fields a presigned download must have, read from its generated type."""
67
+
68
+
69
+ def _download_request(file_id: str, expires_in_seconds: int | None) -> PresignedDownloadRequest:
70
+ """The body of a presigned download: `expires_in_seconds` only when given, the API applying its default else."""
71
+ request: PresignedDownloadRequest = {"file_id": file_id}
72
+ if expires_in_seconds is not None:
73
+ request["expires_in_seconds"] = expires_in_seconds
74
+ return request
75
+
76
+
77
+ class _Presigned:
78
+ """The fields every presigned transfer has, as answered by the API. Its `repr` leaves the URL out: it grants the
79
+ transfer by itself."""
80
+
81
+ def __init__(self, presigned: PresignedUploadResponse | PresignedDownloadResponse) -> None:
82
+ self.file_id: str = presigned["file_id"]
83
+ """The file: for an upload, the reserved id (`f_<hex>`) to put in a task's input once uploaded, single-use."""
84
+ self.url: str = presigned["url"]
85
+ """The presigned S3 URL; it grants the transfer by itself, keep it private."""
86
+ self.expires_in_seconds: int = presigned["expires_in_seconds"]
87
+ """Validity of the presigned URL, in seconds from the API's answer."""
88
+
89
+ def _shown(self) -> str:
90
+ """The fields `repr` shows after `file_id`."""
91
+ return f"expires_in_seconds={self.expires_in_seconds!r}"
92
+
93
+ def __repr__(self) -> str:
94
+ return f"{type(self).__name__}(file_id={self.file_id!r}, {self._shown()})"
95
+
96
+
97
+ class _Reservation(_Presigned):
98
+ """The fields of a presigned upload, as answered by the API."""
99
+
100
+ def __init__(self, reserved: PresignedUploadResponse) -> None:
101
+ super().__init__(reserved)
102
+ self.method: str = reserved.get("method", HttpMethod.PUT)
103
+ """The HTTP method of the upload: always `PUT`."""
104
+ self.headers: dict[str, str] = dict(reserved["headers"])
105
+ """The signed headers (`Content-Type`, `Content-Length`), sent exactly as given."""
106
+ self.expires_at: str = reserved["expires_at"]
107
+ """Until when the reserved file id can be submitted (ISO 8601); unclaimed, the upload is purged after."""
108
+
109
+ def _shown(self) -> str:
110
+ return f"expires_at={self.expires_at!r}"
111
+
112
+
113
+ class PresignedUpload(_Reservation):
114
+ """A reserved file id and its presigned upload to S3, returned by `StorageClient.presigned_upload` from a
115
+ description: `upload(file)` sends the file.
116
+
117
+ Upload before `expires_at`, then submit `file_id` in a task's input.
118
+
119
+ Example:
120
+ >>> request: PresignedUploadRequest = {"filename": "a.pdf", "mime_type": "application/pdf", "size_bytes": n}
121
+ >>> upload = storage.presigned_upload(request)
122
+ >>> upload.upload(pdf)
123
+ >>> task = ocr.create({"file_id": upload.file_id})
124
+ """
125
+
126
+ def __init__(self, http: SyncTransport, reserved: PresignedUploadResponse) -> None:
127
+ super().__init__(reserved)
128
+ self._http = http
129
+
130
+ def upload(self, file: FilePath | FileContent, *, timeout: Timeout = NOT_GIVEN) -> None:
131
+ """Sends the file to S3: one `PUT` to `url` with the signed headers, without the API token.
132
+
133
+ Args:
134
+ file: the path of a file on disk (streamed from disk, never read whole in memory), `bytes`, or a binary
135
+ stream, left open. A seekable stream is sent from its start, wherever its position (as
136
+ `TaskClient.create` sends `files`), so calling `upload` again after a failure sends the whole file; a
137
+ stream that cannot seek (a pipe) is sent from its current position. It must be exactly `size_bytes`
138
+ long, with the reserved MIME type. A relative path is resolved against the working directory.
139
+ timeout: as on every method.
140
+
141
+ Raises:
142
+ StorageTransferError: S3 refused the upload (expired URL, size or type not matching).
143
+ SdkError: the path cannot be read; the message names it, resolved against the working directory.
144
+ Nothing is sent.
145
+
146
+ Example:
147
+ >>> with open("./report.pdf", "rb") as report:
148
+ ... upload.upload(report)
149
+ """
150
+ self._http.upload(self.method, self.url, file, headers=self.headers, timeout=timeout)
151
+
152
+
153
+ class PresignedFileUpload(PresignedUpload):
154
+ """A presigned upload reserved from a file on disk, returned by `StorageClient.presigned_upload` from a path:
155
+ `upload()` sends that file.
156
+
157
+ Example:
158
+ >>> upload = storage.presigned_upload("./scans/scan.pdf")
159
+ >>> upload.upload() # streamed from disk
160
+ >>> task = ocr.create({"file_id": upload.file_id})
161
+ """
162
+
163
+ def __init__(self, http: SyncTransport, reserved: PresignedUploadResponse, path: FilePath) -> None:
164
+ super().__init__(http, reserved)
165
+ self.path = path
166
+ """The file the reservation was made from, sent by `upload()`."""
167
+
168
+ def upload(self, file: FilePath | FileContent | None = None, *, timeout: Timeout = NOT_GIVEN) -> None:
169
+ """Sends the file the reservation was made from (or `file`, when given) to S3: one `PUT` to `url` with the
170
+ signed headers, without the API token.
171
+
172
+ The path is read again, streamed: if the file changed since the reservation (its size above all), S3 refuses
173
+ it; reserve again.
174
+
175
+ Args:
176
+ file: another file to send instead, as for `PresignedUpload.upload`.
177
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
178
+
179
+ Raises:
180
+ StorageTransferError: S3 refused the upload (expired URL, size or type not matching).
181
+ SdkError: the path cannot be read anymore; nothing is sent.
182
+
183
+ Example:
184
+ >>> upload = storage.presigned_upload("./scans/scan.pdf")
185
+ >>> upload.upload(timeout=600)
186
+ """
187
+ super().upload(self.path if file is None else file, timeout=timeout)
188
+
189
+
190
+ class PresignedDownload(_Presigned):
191
+ """A short-lived presigned URL to fetch a file from S3, returned by `StorageClient.presigned_download`.
192
+
193
+ Download within `expires_in_seconds`; ask `presigned_download` again for a new URL.
194
+
195
+ Example:
196
+ >>> download = storage.presigned_download(file_id)
197
+ >>> download.save_to("./out/report.pdf")
198
+ """
199
+
200
+ def __init__(self, http: SyncTransport, presigned: PresignedDownloadResponse) -> None:
201
+ super().__init__(presigned)
202
+ self._http = http
203
+
204
+ def download(self, *, timeout: Timeout = NOT_GIVEN) -> bytes:
205
+ """The file's content, fetched from S3 into memory: one `GET` to `url`, without the API token. For a large
206
+ file, prefer `save_to`, which streams it to disk.
207
+
208
+ Args:
209
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
210
+
211
+ Raises:
212
+ StorageTransferError: S3 refused the download (for instance an expired URL).
213
+
214
+ Example:
215
+ >>> content = storage.presigned_download(file_id).download()
216
+ >>> text = content.decode()
217
+ """
218
+ return self._http.fetch(self.url, timeout=timeout)
219
+
220
+ def save_to(self, path: FilePath, *, timeout: Timeout = NOT_GIVEN) -> None:
221
+ """Streams the file from S3 to disk, never holding it whole in memory: one `GET` to `url`, without the API
222
+ token. The directory must exist. The file is written whole or not at all: streamed to a temporary file next to
223
+ it (created only once S3 accepted the download), then renamed over it, replacing an existing file. On failure
224
+ or cancellation, `path` is either untouched or the complete file, never a partial one, and no temporary file
225
+ remains.
226
+
227
+ Args:
228
+ path: where to write the file; a relative path is resolved against the working directory.
229
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
230
+
231
+ Raises:
232
+ StorageTransferError: S3 refused the download; `path` is left untouched.
233
+ SdkError: `path` cannot be written (a missing directory, a full disk...); the message names it, resolved
234
+ against the working directory, with the `OSError` as `__cause__`. `path` is left untouched.
235
+
236
+ Example:
237
+ >>> storage.presigned_download(file["file_id"]).save_to(Path("out") / file["name"])
238
+ """
239
+ self._http.save(self.url, path, timeout=timeout)
240
+
241
+
242
+ class StorageClient(SyncClientBase):
243
+ """Raw client of the file storage (`/storage`): presigned URLs from the API, and single-request transfers to and
244
+ from S3 through them, sent without the API token.
245
+
246
+ Files are referenced by their `file_id` (`f_<hex>`) only, and this client is the only way to send one: reserve it,
247
+ upload it (up to 500 MiB), then pass its `file_id` to `TaskClient.create`. It also fetches output files. Files are
248
+ kept 72 hours once attached to a task, and a file id is single-use.
249
+
250
+ Takes the options of every client (`base_url`, `token`, `http_client`, `timeout`, see `__init__`). Transfers go
251
+ through the same HTTP client (its transport, proxy and event hooks), but carry exactly the presigned URL and its
252
+ signed headers: none of the HTTP client's default headers, query parameters, cookies or `auth`.
253
+
254
+ Example:
255
+ >>> with StorageClient(base_url=base_url, token=token) as storage:
256
+ ... upload = storage.presigned_upload("./scans/scan.pdf") # name, type and size from the file
257
+ ... upload.upload() # streamed from disk
258
+ ... task = ocr.create({"file_id": upload.file_id})
259
+ ... # later, an output file of a succeeded task:
260
+ ... storage.presigned_download(output["file_id"]).save_to(f"./out/{output['name']}")
261
+ """
262
+
263
+ @overload
264
+ def presigned_upload(self, file: FilePath, *, timeout: Timeout = NOT_GIVEN) -> PresignedFileUpload: ...
265
+ @overload
266
+ def presigned_upload(self, file: PresignedUploadRequest, *, timeout: Timeout = NOT_GIVEN) -> PresignedUpload: ...
267
+ def presigned_upload(
268
+ self,
269
+ file: FilePath | PresignedUploadRequest,
270
+ *,
271
+ timeout: Timeout = NOT_GIVEN,
272
+ ) -> PresignedUpload:
273
+ """Reserves a file, up to 500 MiB, and returns its presigned upload (`POST /storage/presigned-upload`).
274
+ Nothing is uploaded yet: call `upload()` on the result.
275
+
276
+ Args:
277
+ file: the path of a file on disk, described by the SDK (its name, its MIME type from its extension, its
278
+ size on disk; not read here, `upload()` streams it), so that `upload()` needs no argument; or the
279
+ description of a file (`filename`, `mime_type`, `size_bytes`) when it is not at hand yet, or to
280
+ impose its name or type: `upload(file)` then takes the file. A relative path is resolved against the
281
+ working directory.
282
+ timeout: as on every method.
283
+
284
+ Raises:
285
+ SdkError: the path cannot be read; the message names it, resolved against the working directory.
286
+ Nothing is reserved.
287
+ ApiError: `UPLOAD_TOO_LARGE` (413) above 500 MiB, `REQUEST_VALIDATION_ERROR` (422) for an invalid
288
+ description.
289
+ AuthenticationError: the token is refused.
290
+
291
+ Example:
292
+ >>> upload = storage.presigned_upload("./scans/big-scan.pdf")
293
+ >>> upload.upload()
294
+ >>> task = ocr.create({"file_id": upload.file_id})
295
+ """
296
+ if not isinstance(file, (str, os.PathLike)):
297
+ return PresignedUpload(self._http, self._reserve(file, timeout))
298
+ self._http.ensure_open() # before opening the file
299
+ return PresignedFileUpload(self._http, self._reserve(_describe(file), timeout), file)
300
+
301
+ def presigned_download(
302
+ self,
303
+ file_id: str,
304
+ *,
305
+ expires_in_seconds: int | None = None,
306
+ timeout: Timeout = NOT_GIVEN,
307
+ ) -> PresignedDownload:
308
+ """A short-lived URL to download a file you uploaded or an output file of your tasks
309
+ (`POST /storage/presigned-download`). Nothing is downloaded yet: call `download()` or `save_to(path)` on
310
+ the result.
311
+
312
+ Args:
313
+ file_id: the file's id (`f_<hex>`), e.g. from the `files` of a succeeded task.
314
+ expires_in_seconds: the URL's validity, for one shorter-lived than the default (handing it to a third
315
+ party, for instance). The bounds are the API's, not checked here: from 60 s up to the default
316
+ validity (3600 s), unless the instance is configured otherwise. `None`: the default validity.
317
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
318
+
319
+ Raises:
320
+ ApiError: `FILE_NOT_FOUND` (404) for an unknown file or one of another consumer, `FILE_EXPIRED` (410)
321
+ past its 72-hour retention, `PRESIGNED_TTL_OUT_OF_RANGE` (422) for an `expires_in_seconds` out of
322
+ bounds.
323
+ AuthenticationError: the token is refused.
324
+
325
+ Example:
326
+ >>> download = storage.presigned_download("f_0123456789abcdef")
327
+ >>> content = download.download()
328
+ >>> url = storage.presigned_download("f_0123456789abcdef", expires_in_seconds=300).url # five minutes
329
+ """
330
+ request = _download_request(file_id, expires_in_seconds)
331
+ presigned = self._http.send(
332
+ HttpMethod.POST,
333
+ "/storage/presigned-download",
334
+ json=request,
335
+ required=_DOWNLOAD_FIELDS,
336
+ timeout=timeout,
337
+ )
338
+ return PresignedDownload(self._http, presigned)
339
+
340
+ def _reserve(self, request: PresignedUploadRequest, timeout: Timeout) -> Any:
341
+ return self._http.send(
342
+ HttpMethod.POST,
343
+ "/storage/presigned-upload",
344
+ json=request,
345
+ required=_RESERVATION_FIELDS,
346
+ timeout=timeout,
347
+ )
348
+
349
+
350
+ class AsyncPresignedUpload(_Reservation):
351
+ """Asynchronous twin of `PresignedUpload`, returned by `AsyncStorageClient.presigned_upload` from a
352
+ description: `await upload(file)` sends the file.
353
+
354
+ Example:
355
+ >>> request: PresignedUploadRequest = {"filename": "a.pdf", "mime_type": "application/pdf", "size_bytes": n}
356
+ >>> upload = await storage.presigned_upload(request)
357
+ >>> await upload.upload(pdf_bytes)
358
+ """
359
+
360
+ def __init__(self, http: AsyncTransport, reserved: PresignedUploadResponse) -> None:
361
+ super().__init__(reserved)
362
+ self._http = http
363
+
364
+ async def upload(self, file: FilePath | FileContent, *, timeout: Timeout = NOT_GIVEN) -> None:
365
+ """Sends the file to S3: one `PUT` to `url` with the signed headers, without the API token. See
366
+ `PresignedUpload.upload`; files are read chunk by chunk in a worker thread, off the event loop.
367
+
368
+ Raises:
369
+ StorageTransferError: S3 refused the upload (expired URL, size or type not matching).
370
+ SdkError: the path cannot be read; nothing is sent.
371
+
372
+ Example:
373
+ >>> await upload.upload("./report.pdf")
374
+ """
375
+ await self._http.upload(self.method, self.url, file, headers=self.headers, timeout=timeout)
376
+
377
+
378
+ class AsyncPresignedFileUpload(AsyncPresignedUpload):
379
+ """Asynchronous twin of `PresignedFileUpload`: `await upload()` sends the file the reservation was made from.
380
+
381
+ Example:
382
+ >>> upload = await storage.presigned_upload("./scans/scan.pdf")
383
+ >>> await upload.upload()
384
+ """
385
+
386
+ def __init__(self, http: AsyncTransport, reserved: PresignedUploadResponse, path: FilePath) -> None:
387
+ super().__init__(http, reserved)
388
+ self.path = path
389
+ """The file the reservation was made from, sent by `upload()`."""
390
+
391
+ async def upload(self, file: FilePath | FileContent | None = None, *, timeout: Timeout = NOT_GIVEN) -> None:
392
+ """Sends the file the reservation was made from (or `file`, when given) to S3. See
393
+ `PresignedFileUpload.upload`.
394
+
395
+ Raises:
396
+ StorageTransferError: S3 refused the upload (expired URL, size or type not matching).
397
+ SdkError: the path cannot be read anymore; nothing is sent.
398
+
399
+ Example:
400
+ >>> await upload.upload(timeout=600)
401
+ """
402
+ await super().upload(self.path if file is None else file, timeout=timeout)
403
+
404
+
405
+ class AsyncPresignedDownload(_Presigned):
406
+ """Asynchronous twin of `PresignedDownload`, returned by `AsyncStorageClient.presigned_download`.
407
+
408
+ Example:
409
+ >>> download = await storage.presigned_download(file_id)
410
+ >>> await download.save_to("./out/report.pdf")
411
+ """
412
+
413
+ def __init__(self, http: AsyncTransport, presigned: PresignedDownloadResponse) -> None:
414
+ super().__init__(presigned)
415
+ self._http = http
416
+
417
+ async def download(self, *, timeout: Timeout = NOT_GIVEN) -> bytes:
418
+ """The file's content, fetched from S3 into memory, without the API token. See `PresignedDownload.download`.
419
+
420
+ Raises:
421
+ StorageTransferError: S3 refused the download (for instance an expired URL).
422
+
423
+ Example:
424
+ >>> content = await (await storage.presigned_download(file_id)).download()
425
+ """
426
+ return await self._http.fetch(self.url, timeout=timeout)
427
+
428
+ async def save_to(self, path: FilePath, *, timeout: Timeout = NOT_GIVEN) -> None:
429
+ """Streams the file from S3 to disk, replacing it once complete; see `PresignedDownload.save_to`. Written
430
+ chunk by chunk in a worker thread, off the event loop.
431
+
432
+ On failure or cancellation, `path` is either untouched or the complete file, never a partial one, and no
433
+ temporary file remains. A thread cannot be stopped: a cancellation waits for the write under way to end, then
434
+ removes the temporary file; one landing during the final rename lets it finish (`path` is then the complete
435
+ file), and still propagates.
436
+
437
+ Raises:
438
+ StorageTransferError: S3 refused the download; `path` is left untouched.
439
+ SdkError: `path` cannot be written.
440
+
441
+ Example:
442
+ >>> await (await storage.presigned_download(file_id)).save_to("./out/report.pdf")
443
+ """
444
+ await self._http.save(self.url, path, timeout=timeout)
445
+
446
+
447
+ class AsyncStorageClient(AsyncClientBase):
448
+ """Asynchronous twin of `StorageClient`; the methods' documentation is there.
449
+
450
+ Example:
451
+ >>> async with AsyncStorageClient(base_url=base_url, token=token) as storage:
452
+ ... upload = await storage.presigned_upload("./scans/big-scan.pdf")
453
+ ... await upload.upload()
454
+ """
455
+
456
+ @overload
457
+ async def presigned_upload(self, file: FilePath, *, timeout: Timeout = NOT_GIVEN) -> AsyncPresignedFileUpload: ...
458
+ @overload
459
+ async def presigned_upload(
460
+ self,
461
+ file: PresignedUploadRequest,
462
+ *,
463
+ timeout: Timeout = NOT_GIVEN,
464
+ ) -> AsyncPresignedUpload: ...
465
+ async def presigned_upload(
466
+ self,
467
+ file: FilePath | PresignedUploadRequest,
468
+ *,
469
+ timeout: Timeout = NOT_GIVEN,
470
+ ) -> AsyncPresignedUpload:
471
+ """Reserves a file, up to 500 MiB, from its path or its description, and returns its presigned upload
472
+ (`POST /storage/presigned-upload`). See `StorageClient.presigned_upload`.
473
+
474
+ Raises:
475
+ SdkError: the path cannot be read; nothing is reserved.
476
+ ApiError: `UPLOAD_TOO_LARGE` (413) above 500 MiB, `REQUEST_VALIDATION_ERROR` (422).
477
+ AuthenticationError: the token is refused.
478
+
479
+ Example:
480
+ >>> upload = await storage.presigned_upload("./scans/big-scan.pdf")
481
+ >>> await upload.upload()
482
+ """
483
+ if not isinstance(file, (str, os.PathLike)):
484
+ return AsyncPresignedUpload(self._http, await self._reserve(file, timeout))
485
+ self._http.ensure_open() # before opening the file
486
+ return AsyncPresignedFileUpload(
487
+ self._http,
488
+ await self._reserve(await in_thread(_describe, file), timeout),
489
+ file,
490
+ )
491
+
492
+ async def presigned_download(
493
+ self,
494
+ file_id: str,
495
+ *,
496
+ expires_in_seconds: int | None = None,
497
+ timeout: Timeout = NOT_GIVEN,
498
+ ) -> AsyncPresignedDownload:
499
+ """A short-lived URL to download a file (`POST /storage/presigned-download`). See
500
+ `StorageClient.presigned_download`.
501
+
502
+ Raises:
503
+ ApiError: `FILE_NOT_FOUND` (404), `FILE_EXPIRED` (410), `PRESIGNED_TTL_OUT_OF_RANGE` (422).
504
+ AuthenticationError: the token is refused.
505
+
506
+ Example:
507
+ >>> download = await storage.presigned_download("f_0123456789abcdef")
508
+ >>> short = await storage.presigned_download("f_0123456789abcdef", expires_in_seconds=300)
509
+ """
510
+ request = _download_request(file_id, expires_in_seconds)
511
+ presigned = await self._http.send(
512
+ HttpMethod.POST,
513
+ "/storage/presigned-download",
514
+ json=request,
515
+ required=_DOWNLOAD_FIELDS,
516
+ timeout=timeout,
517
+ )
518
+ return AsyncPresignedDownload(self._http, presigned)
519
+
520
+ async def _reserve(self, request: PresignedUploadRequest, timeout: Timeout) -> Any:
521
+ return await self._http.send(
522
+ HttpMethod.POST,
523
+ "/storage/presigned-upload",
524
+ json=request,
525
+ required=_RESERVATION_FIELDS,
526
+ timeout=timeout,
527
+ )