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,596 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Final, Generic, Literal, TypeAlias, TypeGuard, Union, cast
4
+
5
+ from typing_extensions import NotRequired, TypedDict, TypeVar
6
+
7
+ from . import _generated
8
+ from ._errors import SdkError, TaskFailedError
9
+ from ._http import NOT_GIVEN, AsyncClientBase, HttpMethod, Params, SyncClientBase, Timeout
10
+ from ._services import path_segment, service_path
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Sequence
14
+
15
+ import httpx
16
+
17
+ __all__ = [
18
+ "AsyncTaskClient",
19
+ "Callback",
20
+ "FailedTask",
21
+ "FinishedTask",
22
+ "InProgressTask",
23
+ "PendingTask",
24
+ "SucceededTask",
25
+ "Task",
26
+ "TaskClient",
27
+ "TaskError",
28
+ "TaskFile",
29
+ "TaskPage",
30
+ "TaskStatus",
31
+ "TaskSummary",
32
+ "ensure_succeeded",
33
+ "is_finished",
34
+ ]
35
+
36
+ InputT = TypeVar("InputT", default=dict[str, Any])
37
+ """The service's parameters, sent as the submission's `body`: the caller's own type, never checked by the SDK."""
38
+
39
+ ResultT = TypeVar("ResultT", default=Any)
40
+ """The `result` of a succeeded task: the caller's own type, never checked by the SDK."""
41
+
42
+ Callback = _generated.Callback
43
+ """Where the API sends the final state of a task, given to `TaskClient.create`: an HTTP URL, or an AMQP DSN and a
44
+ queue. The SDK only passes it on; it provides no receiver.
45
+
46
+ Example:
47
+ >>> task = render.create(input, callback={"type": "http", "url": "https://my-app.example.org/hooks/async-task"})
48
+ >>> task = render.create(input, callback={"type": "amqp", "url": amqp_dsn, "queue": "render-results"})
49
+ """
50
+
51
+ TaskStatus = _generated.TaskStatus
52
+ """The status of a task: `pending`, `in_progress`, `success` or `failure`; the last two are final.
53
+
54
+ Example:
55
+ >>> page = render.list(status=["pending", "in_progress"])
56
+ """
57
+
58
+ TaskError = _generated.TaskError
59
+ """Why a task failed, in `FailedTask["error"]`: a stable `code` to match on, and a human-readable `message`.
60
+
61
+ Example:
62
+ >>> if task["status"] == "failure" and (error := task.get("error")):
63
+ ... print(error["code"], error["message"])
64
+ """
65
+
66
+ TaskSummary = _generated.TaskSummary
67
+ """One line of the task list (`TaskClient.list`): the task's id, `status`, session label (`session_id`), `progress`
68
+ and dates, without its input nor result (use `TaskClient.get` for those).
69
+
70
+ Example:
71
+ >>> for summary in render.list(session_id="case-42")["tasks"]:
72
+ ... print(summary["task_id"], summary["status"], summary.get("progress"))
73
+ """
74
+
75
+ TaskFile = _generated.TaskFileInfo
76
+ """A file of a task: an input it was given or an output it produced (`role`), with its `file_id`, `name`,
77
+ `content_type`, `size_bytes`, and `expires_at`, the end of its retention.
78
+
79
+ Example:
80
+ >>> outputs = [file for file in ensure_succeeded(task).get("files", []) if file["role"] == "output"]
81
+ >>> storage.presigned_download(outputs[0]["file_id"]).save_to(outputs[0]["name"])
82
+ """
83
+
84
+ TaskPage = _generated.TaskListData
85
+ """One page of the task list: the `tasks` (`TaskSummary`, most recent first), with the `count`, `limit` and `offset`
86
+ applied.
87
+
88
+ Example:
89
+ >>> page = render.list(limit=50, offset=100)
90
+ >>> maybe_more = page["count"] == page["limit"]
91
+ """
92
+
93
+
94
+ class PendingTask(TypedDict):
95
+ """A task waiting in the queue; `task_position` is its place in it.
96
+
97
+ Example:
98
+ >>> if task["status"] == "pending":
99
+ ... print("queued at", task.get("task_position"))
100
+ """
101
+
102
+ task_id: str
103
+ status: Literal["pending"]
104
+ task_position: NotRequired[int | None]
105
+ submission_date: NotRequired[str | None]
106
+
107
+
108
+ class InProgressTask(TypedDict):
109
+ """A task being processed; `progress` goes from 0.0 to 1.0 when the service reports it.
110
+
111
+ Example:
112
+ >>> if task["status"] == "in_progress":
113
+ ... print(f"{task.get('progress') or 0:.0%}")
114
+ """
115
+
116
+ task_id: str
117
+ status: Literal["in_progress"]
118
+ progress: NotRequired[float | None]
119
+ submission_date: NotRequired[str | None]
120
+ start_date: NotRequired[str | None]
121
+
122
+
123
+ class SucceededTask(TypedDict, Generic[ResultT]):
124
+ """A task that ended with a result, typed `ResultT` (the caller's own type, never checked by the SDK).
125
+
126
+ `files` lists the task's input and output files (`role`), absent when it has none.
127
+
128
+ Example:
129
+ >>> if task["status"] == "success":
130
+ ... print(task["result"], len(task.get("files", [])))
131
+ """
132
+
133
+ task_id: str
134
+ status: Literal["success"]
135
+ result: ResultT
136
+ submission_date: NotRequired[str | None]
137
+ start_date: NotRequired[str | None]
138
+ end_date: NotRequired[str | None]
139
+ files: NotRequired[list[TaskFile]]
140
+
141
+
142
+ class FailedTask(TypedDict):
143
+ """A task that ended with an error: a business outcome, returned as data, never raised by the raw clients.
144
+
145
+ Match on `error["code"]` (stable), not on the message nor on the legacy `error_message`. `error` is `None` when
146
+ no error was recorded.
147
+
148
+ Example:
149
+ >>> if task["status"] == "failure":
150
+ ... error = task.get("error")
151
+ ... code = error["code"] if error else None
152
+ """
153
+
154
+ task_id: str
155
+ status: Literal["failure"]
156
+ error_message: str | None
157
+ error: NotRequired[TaskError | None]
158
+ submission_date: NotRequired[str | None]
159
+ start_date: NotRequired[str | None]
160
+ end_date: NotRequired[str | None]
161
+
162
+
163
+ Task: TypeAlias = Union[PendingTask, InProgressTask, SucceededTask[ResultT], FailedTask] # noqa: UP007
164
+ """The state of a task, discriminated on `status`: narrow on `task["status"]` to reach the fields of each state.
165
+
166
+ Example:
167
+ >>> task = render.get(task_id)
168
+ >>> if task["status"] == "success":
169
+ ... print(task["result"])
170
+ ... elif task["status"] == "failure":
171
+ ... print(task.get("error"))
172
+ """
173
+
174
+ FinishedTask: TypeAlias = Union[SucceededTask[ResultT], FailedTask] # noqa: UP007
175
+ """A task in a final state: succeeded or failed. `is_finished` narrows a `Task` to it.
176
+
177
+ Example:
178
+ >>> def report(task: FinishedTask[RenderOutput]) -> str:
179
+ ... return task["result"]["text"] if task["status"] == "success" else "failed"
180
+ """
181
+
182
+
183
+ def is_finished(task: Task[ResultT]) -> TypeGuard[FinishedTask[ResultT]]:
184
+ """Whether a task is in a final state, `success` or `failure`; narrows it to a `FinishedTask` when it is.
185
+
186
+ A `TypeGuard`, not a `TypeIs`: type checkers narrow `TypedDict` unions poorly through `TypeIs`, so the `else`
187
+ branch keeps the `Task` type. Narrow on `task["status"]` to reach the fields of a running task.
188
+
189
+ Example:
190
+ >>> task = render.create(input, wait=10)
191
+ >>> if is_finished(task):
192
+ ... handle(task) # FinishedTask: "success" or "failure"
193
+ ... else:
194
+ ... remember(task["task_id"]) # still running: poll `get`, or rely on a callback
195
+ """
196
+ # `.get`: a task answered without `status` (out of contract) is not finished, rather than a `KeyError`.
197
+ return task.get("status") in _FINISHED_STATUSES
198
+
199
+
200
+ def ensure_succeeded(task: Task[ResultT]) -> SucceededTask[ResultT]:
201
+ """Returns a task as succeeded, its `result` typed, or raises: use it where a failure is an error for you;
202
+ otherwise narrow on `task["status"]` yourself. The task is returned as is, not copied.
203
+
204
+ Raises:
205
+ TaskFailedError: the task failed; it carries the task id, the error code and the failed task.
206
+ SdkError: the task is still `pending` or `in_progress`: wait for it to finish first. Also raised, rather
207
+ than a `KeyError`, for a task without `status` (out of the API's contract).
208
+
209
+ The `result` of a succeeded task is not checked: the API always sends it, `None` when the service returned
210
+ none, although the OpenAPI spec leaves it optional (it has a default). A task without it is returned as is.
211
+
212
+ Example:
213
+ >>> text = ensure_succeeded(render.get(task_id))["result"]["text"]
214
+ """
215
+ if "status" not in task:
216
+ raise SdkError(f"Task {task.get('task_id')} has no status")
217
+ if task["status"] == _FAILURE:
218
+ raise TaskFailedError(task)
219
+ if task["status"] != _SUCCESS:
220
+ raise SdkError(f"Task {task['task_id']} is not finished: {task['status']}")
221
+ return task
222
+
223
+
224
+ _SUCCESS: Final = "success"
225
+ _FAILURE: Final = "failure"
226
+ _FINISHED_STATUSES: Final[frozenset[str]] = frozenset({_SUCCESS, _FAILURE})
227
+ """The final states of a task: it will not change any more."""
228
+
229
+ _PREFER_HEADER: Final = "prefer"
230
+ _WAIT_PREFERENCE: Final = "wait"
231
+ """The `Prefer` preference (RFC 7240) that lets the API hold its answer until the task ends."""
232
+
233
+ _MAX_WAIT = 60
234
+ """The longest `wait` the API accepts, in seconds, before its cap by service class."""
235
+
236
+
237
+ _WAIT_MARGIN = 5
238
+ """Seconds added to `wait` for the read timeout `create` derives when the caller gave the SDK none."""
239
+
240
+
241
+ class _TaskSubmission(TypedDict):
242
+ """The JSON body of a submission (`POST /v1/services/{service}/tasks`)."""
243
+
244
+ body: object
245
+ callback: NotRequired[Callback]
246
+ session_id: NotRequired[str]
247
+
248
+
249
+ class _TaskListQuery(TypedDict, total=False):
250
+ """The query of the task list (`GET /v1/services/{service}/tasks`): only the filters given."""
251
+
252
+ session_id: str
253
+ status: list[TaskStatus]
254
+ limit: int
255
+ offset: int
256
+
257
+
258
+ class _Submission(TypedDict):
259
+ json: _TaskSubmission | None
260
+ headers: dict[str, str]
261
+ min_read_timeout: float | None
262
+
263
+
264
+ def _submission(
265
+ input: object,
266
+ callback: Callback | None,
267
+ session_id: str | None,
268
+ wait: int | None,
269
+ ) -> _Submission:
270
+ """The task as JSON (`body`, then `callback` and `session_id` when given), with the headers and the read timeout
271
+ that `wait` needs."""
272
+ # The API takes a whole number of seconds from 0 to 60 (`bool` is an `int`, but `wait=True` is a mistake).
273
+ if wait is not None and (type(wait) is not int or not 0 <= wait <= _MAX_WAIT):
274
+ raise ValueError(f"wait must be a whole number of seconds from 0 to {_MAX_WAIT}, got {wait!r}")
275
+ task: _TaskSubmission = {"body": input}
276
+ if callback is not None:
277
+ task["callback"] = callback
278
+ if session_id is not None:
279
+ task["session_id"] = session_id
280
+ submission: _Submission = {"json": task, "headers": {}, "min_read_timeout": None}
281
+ if wait is not None:
282
+ # Lets the API hold the answer `wait` seconds, with a margin for the network.
283
+ submission.update(headers={_PREFER_HEADER: f"{_WAIT_PREFERENCE}={wait}"}, min_read_timeout=wait + _WAIT_MARGIN)
284
+ return submission
285
+
286
+
287
+ def _list_params(
288
+ session_id: str | None,
289
+ status: TaskStatus | Sequence[TaskStatus] | None,
290
+ limit: int | None,
291
+ offset: int | None,
292
+ ) -> Params:
293
+ """The query of the task list: only the filters given, so that the API applies its own paging defaults."""
294
+ params: _TaskListQuery = {}
295
+ if session_id is not None:
296
+ params["session_id"] = session_id
297
+ if status is not None:
298
+ # A `str` is one status (a `Literal`), never a sequence of them: the checker cannot rule that out alone.
299
+ params["status"] = [cast("TaskStatus", status)] if isinstance(status, str) else list(status)
300
+ if limit is not None:
301
+ params["limit"] = limit
302
+ if offset is not None:
303
+ params["offset"] = offset
304
+ return params
305
+
306
+
307
+ class _ServiceTasks:
308
+ """The binding to one service shared by the task client twins: its routes, independent of the I/O."""
309
+
310
+ service: str
311
+ """The service this client is bound to."""
312
+
313
+ def _bind(self, service: str) -> None:
314
+ """Binds the client to `service`; raises `ValueError` for an empty, `.` or `..` name."""
315
+ self._path = f"{service_path(service)}/tasks"
316
+ self.service = service
317
+
318
+ def _task_path(self, task_id: str) -> str:
319
+ return f"{self._path}/{path_segment(task_id, 'task id')}"
320
+
321
+
322
+ class TaskClient(_ServiceTasks, SyncClientBase, Generic[InputT, ResultT]):
323
+ """Raw client of the tasks of ONE service (`/v1/services/{service}/tasks`): each call is one HTTP request, with
324
+ no retry and no polling.
325
+
326
+ Services are added dynamically and the SDK knows none of them: `InputT` (the service's parameters) and `ResultT`
327
+ (the `result` of a succeeded task) are the caller's own types, never checked by the SDK. Unparametrized, the
328
+ input is a `dict[str, Any]` and the result `Any`. A service's live contract is given by `ServicesClient.get`.
329
+
330
+ Takes the options of every client (`base_url`, `token`, `http_client`, `timeout`), plus `service`, the name of
331
+ the service it is bound to (see `__init__`).
332
+
333
+ To bind your types with `with`, parametrize the class (`with TaskClient[In, Out](...) as render`): annotating the
334
+ variable (`render: TaskClient[In, Out]`) then `with TaskClient(...) as render` is refused by type checkers, the
335
+ types not flowing through `__enter__`.
336
+
337
+ Example:
338
+ >>> class RenderInput(TypedDict):
339
+ ... template: str
340
+ ... data: dict[str, str]
341
+ >>> class RenderOutput(TypedDict):
342
+ ... text: str
343
+ >>> with TaskClient[RenderInput, RenderOutput](
344
+ ... base_url=base_url, token=token, service="generation-render"
345
+ ... ) as render:
346
+ ... # No timeout given: the read timeout becomes 15 seconds, so that the API can hold the answer 10.
347
+ ... task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
348
+ ... while not is_finished(task): # the raw level does not poll for you
349
+ ... time.sleep(1)
350
+ ... task = render.get(task["task_id"])
351
+ >>> ensure_succeeded(task)["result"]["text"]
352
+ 'Hello Dupont'
353
+ """
354
+
355
+ def __init__(
356
+ self,
357
+ *,
358
+ base_url: str,
359
+ token: str,
360
+ service: str,
361
+ http_client: httpx.Client | None = None,
362
+ timeout: Timeout = NOT_GIVEN,
363
+ ) -> None:
364
+ """Creates a client bound to one service; with no `http_client`, it creates its own, to close with `close()`
365
+ or `with`.
366
+
367
+ Args:
368
+ base_url: base URL of the AsyncTaskAPI instance, e.g. `https://<host>`. A trailing slash is ignored.
369
+ token: personal access token of the consumer, sent as `Authorization: Bearer <token>` on each request.
370
+ service: the name of the service, as listed by `ServicesClient.list`.
371
+ http_client: the `httpx.Client` to send requests with; the SDK never modifies nor closes it.
372
+ timeout: default timeout of every call, in seconds; `None` disables it. When omitted, the HTTP client's
373
+ own timeout applies, its read timeout raised for a `create` with `wait`.
374
+
375
+ Raises:
376
+ ValueError: an empty, `.` or `..` service name; no HTTP client is created.
377
+
378
+ Example:
379
+ >>> render = TaskClient[RenderInput, RenderOutput](
380
+ ... base_url=base_url, token=token, service="generation-render"
381
+ ... )
382
+ >>> untyped = TaskClient(base_url=base_url, token=token, service="core-ocr") # dict input, Any result
383
+ """
384
+ self._bind(service) # first: a refused service name must not leave an HTTP client behind
385
+ super().__init__(base_url=base_url, token=token, http_client=http_client, timeout=timeout)
386
+
387
+ def create(
388
+ self,
389
+ input: InputT,
390
+ *,
391
+ callback: Callback | None = None,
392
+ session_id: str | None = None,
393
+ wait: int | None = None,
394
+ timeout: Timeout = NOT_GIVEN,
395
+ ) -> Task[ResultT]:
396
+ """Submits a task (`POST /v1/services/{service}/tasks`) and returns it.
397
+
398
+ Args:
399
+ input: the service's parameters, sent as the submission's `body`.
400
+ callback: where the API sends the final state of the task: `{"type": "http", "url": ...}` or
401
+ `{"type": "amqp", "url": <dsn>, "queue": ...}`.
402
+ session_id: a free label (up to 128 characters) to group tasks and find them with `list()`; it grants
403
+ no right.
404
+ wait: seconds the API may hold the answer until the task ends, a whole number from 0 to 60, sent as
405
+ `Prefer: wait=N`. The API caps it by the service class (`immediate` 10 s, `short` 30 s) and ignores it
406
+ for `long` services.
407
+ timeout: as on every method; see below how it interacts with `wait`.
408
+
409
+ A file is sent beforehand, never with the task: reserve it with `StorageClient.presigned_upload`, upload it,
410
+ then put its `file_id` in the service's file field of `input` (`file_fields` of `ServicesClient.get`).
411
+
412
+ Returns:
413
+ The task, whether the API answered `201` (created, still running) or `200` (finished within `wait`):
414
+ check it with `is_finished` or narrow on `task["status"]`. A failed task is returned, not raised.
415
+
416
+ How `wait` and `timeout` interact: when no timeout was given to the SDK (neither this call's `timeout` nor
417
+ the client's default), a `wait` of `N` seconds raises the read timeout of the HTTP client's own timeout to
418
+ `N + 5` seconds when it is shorter (5 seconds with httpx's default client), so that the API can hold the
419
+ answer; its connect, write and pool timeouts are kept, and a disabled read timeout stays disabled. A timeout
420
+ given to the SDK, `None` included, is never changed: give one above `N`, e.g.
421
+ `create(input, wait=10, timeout=15)`, or the call may time out before the API answers.
422
+
423
+ On `RequestTimeoutError` the SDK cannot tell whether the task was created. A read timeout, after the request
424
+ was sent, may leave a created task: it can be found again with `list(session_id=...)` only if a `session_id`
425
+ was given. A connect, write or pool timeout means the submission never reached the API.
426
+
427
+ Raises:
428
+ ApiError: the API refused the submission: `REQUEST_VALIDATION_ERROR` (422), `SERVICE_NOT_FOUND` (404),
429
+ `SERVICE_FORBIDDEN` (403), `FILE_NOT_FOUND` (404), `FILE_ALREADY_BOUND` (409), `FILE_EXPIRED` (410),
430
+ `FILE_TOO_LARGE` (413), `CLIENT_SERVICE_QUOTA_EXCEEDED` (429)... Never retried.
431
+ AuthenticationError: the token is refused.
432
+ ValueError: a `wait` that is not a whole number from 0 to 60; no request is sent.
433
+
434
+ Example:
435
+ >>> task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
436
+ >>> upload = storage.presigned_upload("./templates/contract.docx")
437
+ >>> upload.upload()
438
+ >>> task = render.create({"file_id": upload.file_id, "data": {"name": "Dupont"}})
439
+ """
440
+ submission = _submission(input, callback, session_id, wait)
441
+ return self._http.send(HttpMethod.POST, self._path, timeout=timeout, unwrap=True, **submission)
442
+
443
+ def get(self, task_id: str, *, timeout: Timeout = NOT_GIVEN) -> Task[ResultT]:
444
+ """The current state of a task (`GET /v1/services/{service}/tasks/{task_id}`), discriminated on `status`.
445
+
446
+ A failed task is returned as data, not raised: narrow on `task["status"]`, or call `ensure_succeeded`. Each
447
+ call is one request: to wait for the end of a task, call it again (or rely on a callback).
448
+
449
+ Args:
450
+ task_id: the task's id, as returned by `create` or `list`.
451
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
452
+
453
+ Raises:
454
+ ApiError: `TASK_NOT_FOUND` (404) for an unknown task, or one of another consumer.
455
+ AuthenticationError: the token is refused.
456
+ ValueError: an empty, `.` or `..` task id; no request is sent.
457
+
458
+ Example:
459
+ >>> task = render.get(task_id)
460
+ >>> while not is_finished(task):
461
+ ... time.sleep(2)
462
+ ... task = render.get(task_id)
463
+ """
464
+ return self._http.get(self._task_path(task_id), timeout=timeout, unwrap=True)
465
+
466
+ def list(
467
+ self,
468
+ *,
469
+ session_id: str | None = None,
470
+ status: TaskStatus | Sequence[TaskStatus] | None = None,
471
+ limit: int | None = None,
472
+ offset: int | None = None,
473
+ timeout: Timeout = NOT_GIVEN,
474
+ ) -> TaskPage:
475
+ """One page of the consumer's tasks on the service, most recent first (`GET /v1/services/{service}/tasks`).
476
+
477
+ Only the calling consumer's tasks are listed, without their input nor result (use `get` for those). Useful
478
+ to find what was still running after a restart. Only the filters given are sent.
479
+
480
+ Args:
481
+ session_id: only the tasks submitted with this session label.
482
+ status: only the tasks in this status, or in one of these statuses.
483
+ limit: page size, from 1 to 200; the API's default is 50.
484
+ offset: number of tasks to skip; the API's default is 0.
485
+ timeout: seconds before giving up, overriding the client's default; `None` disables it.
486
+
487
+ Raises:
488
+ ApiError: an invalid filter (`REQUEST_VALIDATION_ERROR`, 422) or an unknown service (404).
489
+ AuthenticationError: the token is refused.
490
+
491
+ Example:
492
+ >>> page = render.list(session_id="case-42", status=["pending", "in_progress"])
493
+ >>> running = [summary["task_id"] for summary in page["tasks"]]
494
+ """
495
+ params = _list_params(session_id, status, limit, offset)
496
+ return self._http.get(self._path, timeout=timeout, params=params, unwrap=True)
497
+
498
+
499
+ class AsyncTaskClient(_ServiceTasks, AsyncClientBase, Generic[InputT, ResultT]):
500
+ """Asynchronous twin of `TaskClient`; the methods' documentation is there.
501
+
502
+ Example:
503
+ >>> async with AsyncTaskClient[RenderInput, RenderOutput](
504
+ ... base_url=base_url, token=token, service="generation-render"
505
+ ... ) as render:
506
+ ... task = await render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
507
+ """
508
+
509
+ def __init__(
510
+ self,
511
+ *,
512
+ base_url: str,
513
+ token: str,
514
+ service: str,
515
+ http_client: httpx.AsyncClient | None = None,
516
+ timeout: Timeout = NOT_GIVEN,
517
+ ) -> None:
518
+ """Creates a client bound to one service; with no `http_client`, it creates its own, to close with `aclose()`
519
+ or `async with`. See `TaskClient.__init__`.
520
+
521
+ Example:
522
+ >>> render = AsyncTaskClient[RenderInput, RenderOutput](
523
+ ... base_url=base_url, token=token, service="generation-render"
524
+ ... )
525
+ """
526
+ self._bind(service) # first: a refused service name must not leave an HTTP client behind
527
+ super().__init__(base_url=base_url, token=token, http_client=http_client, timeout=timeout)
528
+
529
+ async def create(
530
+ self,
531
+ input: InputT,
532
+ *,
533
+ callback: Callback | None = None,
534
+ session_id: str | None = None,
535
+ wait: int | None = None,
536
+ timeout: Timeout = NOT_GIVEN,
537
+ ) -> Task[ResultT]:
538
+ """Submits a task (`POST /v1/services/{service}/tasks`) and returns it, `201` or `200` alike.
539
+
540
+ Without a timeout given to the SDK, a `wait` of `N` raises the HTTP client's read timeout to `N + 5` seconds
541
+ when shorter; a timeout given to the SDK is never changed: give one above `wait` (see `TaskClient.create`).
542
+
543
+ Raises:
544
+ ApiError: the API refused the submission (422, 404, 403, 409, 410, 413, 429...). Never retried.
545
+ AuthenticationError: the token is refused.
546
+ ValueError: a `wait` that is not a whole number from 0 to 60; no request is sent.
547
+
548
+ A file is sent beforehand with `AsyncStorageClient.presigned_upload`, then referenced by its `file_id`.
549
+
550
+ Example:
551
+ >>> task = await render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
552
+ >>> upload = await storage.presigned_upload("./contract.docx")
553
+ >>> await upload.upload()
554
+ >>> task = await render.create({"file_id": upload.file_id, "data": {"name": "Dupont"}})
555
+ """
556
+ submission = _submission(input, callback, session_id, wait)
557
+ return await self._http.send(HttpMethod.POST, self._path, timeout=timeout, unwrap=True, **submission)
558
+
559
+ async def get(self, task_id: str, *, timeout: Timeout = NOT_GIVEN) -> Task[ResultT]:
560
+ """The current state of a task (`GET /v1/services/{service}/tasks/{task_id}`); a failure is returned. See
561
+ `TaskClient.get`.
562
+
563
+ Raises:
564
+ ApiError: `TASK_NOT_FOUND` (404) for an unknown task, or one of another consumer.
565
+ AuthenticationError: the token is refused.
566
+ ValueError: an empty, `.` or `..` task id; no request is sent.
567
+
568
+ Example:
569
+ >>> task = await render.get(task_id)
570
+ >>> while not is_finished(task):
571
+ ... await asyncio.sleep(2)
572
+ ... task = await render.get(task_id)
573
+ """
574
+ return await self._http.get(self._task_path(task_id), timeout=timeout, unwrap=True)
575
+
576
+ async def list(
577
+ self,
578
+ *,
579
+ session_id: str | None = None,
580
+ status: TaskStatus | Sequence[TaskStatus] | None = None,
581
+ limit: int | None = None,
582
+ offset: int | None = None,
583
+ timeout: Timeout = NOT_GIVEN,
584
+ ) -> TaskPage:
585
+ """One page of the consumer's tasks on the service, most recent first (`GET /v1/services/{service}/tasks`).
586
+ See `TaskClient.list`.
587
+
588
+ Raises:
589
+ ApiError: an invalid filter (`REQUEST_VALIDATION_ERROR`, 422) or an unknown service (404).
590
+ AuthenticationError: the token is refused.
591
+
592
+ Example:
593
+ >>> page = await render.list(session_id="case-42", status="pending")
594
+ """
595
+ params = _list_params(session_id, status, limit, offset)
596
+ return await self._http.get(self._path, timeout=timeout, params=params, unwrap=True)
File without changes
@@ -0,0 +1,97 @@
1
+ """The raw level of the SDK: one client per resource, each call is one HTTP request.
2
+
3
+ No orchestration: no retries, no polling, no file strategy.
4
+ """
5
+
6
+ from ._errors import (
7
+ ApiError,
8
+ AuthenticationError,
9
+ ClientClosedError,
10
+ Issue,
11
+ ReadyComponent,
12
+ RequestTimeoutError,
13
+ SdkError,
14
+ StorageTransferError,
15
+ TaskFailedError,
16
+ TransportError,
17
+ UnexpectedResponseError,
18
+ )
19
+ from ._me import AsyncMeClient, Authorization, Me, MeClient
20
+ from ._services import AsyncServicesClient, ServiceClass, ServiceDetail, ServicesClient, ServiceSummary
21
+ from ._storage import (
22
+ AsyncPresignedDownload,
23
+ AsyncPresignedFileUpload,
24
+ AsyncPresignedUpload,
25
+ AsyncStorageClient,
26
+ PresignedDownload,
27
+ PresignedFileUpload,
28
+ PresignedUpload,
29
+ PresignedUploadRequest,
30
+ StorageClient,
31
+ )
32
+ from ._tasks import (
33
+ AsyncTaskClient,
34
+ Callback,
35
+ FailedTask,
36
+ FinishedTask,
37
+ InProgressTask,
38
+ PendingTask,
39
+ SucceededTask,
40
+ Task,
41
+ TaskClient,
42
+ TaskError,
43
+ TaskFile,
44
+ TaskPage,
45
+ TaskStatus,
46
+ TaskSummary,
47
+ ensure_succeeded,
48
+ is_finished,
49
+ )
50
+
51
+ __all__ = [
52
+ "ApiError",
53
+ "AsyncMeClient",
54
+ "AsyncPresignedDownload",
55
+ "AsyncPresignedFileUpload",
56
+ "AsyncPresignedUpload",
57
+ "AsyncServicesClient",
58
+ "AsyncStorageClient",
59
+ "AsyncTaskClient",
60
+ "AuthenticationError",
61
+ "Authorization",
62
+ "Callback",
63
+ "ClientClosedError",
64
+ "FailedTask",
65
+ "FinishedTask",
66
+ "InProgressTask",
67
+ "Issue",
68
+ "Me",
69
+ "MeClient",
70
+ "PendingTask",
71
+ "PresignedDownload",
72
+ "PresignedFileUpload",
73
+ "PresignedUpload",
74
+ "PresignedUploadRequest",
75
+ "ReadyComponent",
76
+ "RequestTimeoutError",
77
+ "SdkError",
78
+ "ServiceClass",
79
+ "ServiceDetail",
80
+ "ServiceSummary",
81
+ "ServicesClient",
82
+ "StorageClient",
83
+ "StorageTransferError",
84
+ "SucceededTask",
85
+ "Task",
86
+ "TaskClient",
87
+ "TaskError",
88
+ "TaskFailedError",
89
+ "TaskFile",
90
+ "TaskPage",
91
+ "TaskStatus",
92
+ "TaskSummary",
93
+ "TransportError",
94
+ "UnexpectedResponseError",
95
+ "ensure_succeeded",
96
+ "is_finished",
97
+ ]