wherobots-python-sdk 0.7.1__py3-none-any.whl → 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wherobots/__init__.py CHANGED
@@ -26,6 +26,8 @@ from wherobots.exceptions import (
26
26
  WherobotsJobError,
27
27
  WherobotsNotAuthenticatedError,
28
28
  WherobotsS3Error,
29
+ WherobotsTaskRunError,
30
+ WherobotsTaskRunTimeoutError,
29
31
  WherobotsTimeoutError,
30
32
  WherobotsValidationError,
31
33
  )
@@ -94,6 +96,8 @@ __all__ = [
94
96
  "WherobotsValidationError",
95
97
  "WherobotsS3Error",
96
98
  "WherobotsConfigError",
99
+ "WherobotsTaskRunError",
100
+ "WherobotsTaskRunTimeoutError",
97
101
  "WherobotsTimeoutError",
98
102
  "WherobotsNotAuthenticatedError",
99
103
  "WherobotsFilesNotEnabledError",
wherobots/__version__.py CHANGED
@@ -1,5 +1,5 @@
1
1
  """Version information."""
2
2
 
3
- __version__ = "0.7.1"
3
+ __version__ = "0.9.0"
4
4
  __author__ = "Wherobots"
5
5
  __email__ = "support@wherobots.com"
wherobots/_wire.py ADDED
@@ -0,0 +1,212 @@
1
+ """JSON conversion for the generated models, driven by each field's annotation.
2
+
3
+ Decoding keeps the SDK honest about the API contract. An unknown field or enum value
4
+ is tolerated, so a newer server keeps working. A missing required field or a value of
5
+ the wrong shape raises ``WherobotsAPIError``. Those messages name fields, never values,
6
+ because a body may hold credentials.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses as dc
12
+ import functools
13
+ import math
14
+ import types
15
+ import typing
16
+ from datetime import UTC, datetime
17
+ from decimal import Decimal, InvalidOperation
18
+ from enum import Enum, StrEnum
19
+ from typing import TYPE_CHECKING, Literal, Self, get_args, get_origin
20
+
21
+ from wherobots.exceptions import WherobotsAPIError
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Callable, Mapping
25
+
26
+ _UNIONS: tuple[object, ...] = (types.UnionType, typing.Union)
27
+
28
+
29
+ def _contract_error(where: str, expected: str, value: object) -> WherobotsAPIError:
30
+ return WherobotsAPIError(
31
+ f"Unexpected API response at {where}: expected {expected}, got {type(value).__name__}"
32
+ )
33
+
34
+
35
+ class OpenEnum(StrEnum):
36
+ """A server enum. A value this SDK predates decodes to a member holding that value."""
37
+
38
+ @classmethod
39
+ def _missing_(cls, value: object) -> Self | None:
40
+ if not isinstance(value, str):
41
+ return None
42
+ member = str.__new__(cls, value)
43
+ member._name_ = value
44
+ member._value_ = value
45
+ return member
46
+
47
+
48
+ @functools.cache
49
+ def _field_types(model: type) -> dict[str, object]:
50
+ return typing.get_type_hints(model)
51
+
52
+
53
+ def _shared_keys(option: object, value: object) -> int:
54
+ """How many of a union member's fields ``value`` carries; ties keep spec order."""
55
+ if not (isinstance(option, type) and issubclass(option, WireModel) and isinstance(value, dict)):
56
+ return 0
57
+ return sum(field.metadata.get("wire") in value for field in dc.fields(option))
58
+
59
+
60
+ def _decode_union(options: tuple[object, ...], value: object, where: str) -> object:
61
+ for option in sorted(options, key=lambda option: _shared_keys(option, value), reverse=True):
62
+ try:
63
+ return _decode(option, value, where)
64
+ except WherobotsAPIError:
65
+ continue
66
+ raise _contract_error(where, "a member of the declared union", value)
67
+
68
+
69
+ def _decode_datetime(value: object, where: str) -> datetime:
70
+ if not isinstance(value, str):
71
+ raise _contract_error(where, "an ISO 8601 string", value)
72
+ try:
73
+ parsed = datetime.fromisoformat(value)
74
+ except ValueError:
75
+ raise _contract_error(where, "an ISO 8601 string", value) from None
76
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
77
+
78
+
79
+ def _decode_decimal(value: object, where: str) -> Decimal:
80
+ if isinstance(value, bool) or not isinstance(value, (str, int, float)):
81
+ raise _contract_error(where, "a decimal", value)
82
+ try:
83
+ parsed = Decimal(str(value))
84
+ except InvalidOperation:
85
+ raise _contract_error(where, "a decimal", value) from None
86
+ if not parsed.is_finite():
87
+ raise _contract_error(where, "a finite decimal", value)
88
+ return parsed
89
+
90
+
91
+ def _decode_float(value: object, where: str) -> float:
92
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
93
+ raise _contract_error(where, "a finite number", value)
94
+ try:
95
+ number = float(value)
96
+ except OverflowError:
97
+ number = math.inf
98
+ if not math.isfinite(number):
99
+ raise _contract_error(where, "a finite number", value)
100
+ return number
101
+
102
+
103
+ def _decode_plain(hint: type, value: object, where: str) -> object:
104
+ if hint is object:
105
+ return value
106
+ if issubclass(hint, WireModel):
107
+ if not isinstance(value, dict):
108
+ raise _contract_error(where, hint.__name__, value)
109
+ return hint.from_dict(value)
110
+ if issubclass(hint, OpenEnum):
111
+ if not isinstance(value, str):
112
+ raise _contract_error(where, hint.__name__, value)
113
+ return hint(value)
114
+ readers: dict[type, Callable[[object, str], object]] = {
115
+ datetime: _decode_datetime,
116
+ Decimal: _decode_decimal,
117
+ float: _decode_float,
118
+ }
119
+ if hint in readers:
120
+ return readers[hint](value, where)
121
+ # bool is an int in Python and is not one on the wire.
122
+ if not isinstance(value, hint) or (hint is int and isinstance(value, bool)):
123
+ raise _contract_error(where, hint.__name__, value)
124
+ return value
125
+
126
+
127
+ def _decode_generic(
128
+ origin: object, arguments: tuple[object, ...], value: object, where: str
129
+ ) -> object:
130
+ if origin in _UNIONS:
131
+ return _decode_union(arguments, value, where)
132
+ if origin is Literal:
133
+ if value not in arguments:
134
+ raise _contract_error(where, f"one of {arguments}", value)
135
+ return value
136
+ if origin is list:
137
+ if not isinstance(value, list):
138
+ raise _contract_error(where, "a list", value)
139
+ return [_decode(arguments[0], item, f"{where}[]") for item in value]
140
+ if not isinstance(value, dict):
141
+ raise _contract_error(where, "an object", value)
142
+ return {key: _decode(arguments[1], item, f"{where}{{}}") for key, item in value.items()}
143
+
144
+
145
+ def _decode(hint: object, value: object, where: str) -> object:
146
+ origin = get_origin(hint)
147
+ if origin is not None:
148
+ return _decode_generic(origin, get_args(hint), value, where)
149
+ if isinstance(hint, type):
150
+ return _decode_plain(hint, value, where)
151
+ raise _contract_error(where, str(hint), value)
152
+
153
+
154
+ def encode(value: object) -> object:
155
+ """Convert a model, enum or plain value to its JSON form."""
156
+ if isinstance(value, list):
157
+ return [encode(item) for item in value]
158
+ if isinstance(value, dict):
159
+ return {key: encode(item) for key, item in value.items()}
160
+ if isinstance(value, Enum):
161
+ return value.value
162
+ if isinstance(value, (datetime, Decimal)):
163
+ return value.isoformat() if isinstance(value, datetime) else str(value)
164
+ return value.to_dict() if isinstance(value, WireModel) else value
165
+
166
+
167
+ @dc.dataclass(frozen=True, kw_only=True)
168
+ class WireModel:
169
+ """Base of the generated models: fields say which wire key they map to."""
170
+
171
+ @classmethod
172
+ def from_dict(cls, data: Mapping[str, object]) -> Self:
173
+ """Build the model from a JSON object.
174
+
175
+ Args:
176
+ data: The JSON object.
177
+
178
+ Returns:
179
+ The decoded model.
180
+
181
+ Raises:
182
+ WherobotsAPIError: If a required field is missing or a value has the wrong shape.
183
+ """
184
+ hints = _field_types(cls)
185
+ values: dict[str, object] = {}
186
+ for field in dc.fields(cls):
187
+ wire = field.metadata.get("wire")
188
+ if wire is None:
189
+ values[field.name] = dict(data)
190
+ elif wire in data:
191
+ where = f"{cls.__name__}.{wire}"
192
+ values[field.name] = _decode(hints[field.name], data[wire], where)
193
+ elif field.default is dc.MISSING and field.default_factory is dc.MISSING:
194
+ raise WherobotsAPIError(
195
+ f"Unexpected API response: {cls.__name__} has no required field {wire}"
196
+ )
197
+ build: Callable[..., Self] = cls
198
+ return build(**values)
199
+
200
+ def to_dict(self) -> dict[str, object]:
201
+ """Return the model as the API's JSON object, leaving out unset fields.
202
+
203
+ Returns:
204
+ The JSON object.
205
+ """
206
+ body: dict[str, object] = {}
207
+ for field in dc.fields(self):
208
+ wire = field.metadata.get("wire")
209
+ value = getattr(self, field.name)
210
+ if wire is not None and value is not None:
211
+ body[wire] = encode(value)
212
+ return body
@@ -0,0 +1,317 @@
1
+ # Generated by scripts/generate_sdk.py from openapi/wherobots-api.json. Do not edit.
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from urllib.parse import quote
7
+
8
+ from wherobots.api.base import BaseClient, json_array, json_object
9
+ from wherobots.enums import JobStatus, RunSource, TaskKind, TaskRunState
10
+ from wherobots.models import (
11
+ CreateRunPayload,
12
+ CreateTaskRunPayload,
13
+ DirectoryPage,
14
+ DownloadUrlResponse,
15
+ FileUploadUrl,
16
+ LogsResponse,
17
+ RunListPage,
18
+ RunMetricsResponse,
19
+ RunView,
20
+ StorageCredentialsRequest,
21
+ StorageCredentialsResponse,
22
+ StorageIntegration,
23
+ Task,
24
+ TaskRun,
25
+ TaskRunCost,
26
+ TaskRunLogs,
27
+ TaskRunSummary,
28
+ TaskRunSummaryPage,
29
+ TaskSummaryPage,
30
+ )
31
+
32
+
33
+ def list_job_runs(
34
+ client: BaseClient,
35
+ *,
36
+ name: str | None = None,
37
+ created_after: datetime | None = None,
38
+ status: list[JobStatus] | None = None,
39
+ region: str | None = None,
40
+ cursor: str | None = None,
41
+ size: int | None = None,
42
+ ) -> RunListPage:
43
+ """List job runs (``GET /runs``)."""
44
+ return RunListPage.from_dict(
45
+ json_object(
46
+ client.request(
47
+ "GET",
48
+ "/runs",
49
+ params={
50
+ "name": name,
51
+ "created_after": created_after,
52
+ "status": status,
53
+ "region": region,
54
+ "cursor": cursor,
55
+ "size": size,
56
+ },
57
+ )
58
+ )
59
+ )
60
+
61
+
62
+ def create_job_run(
63
+ client: BaseClient, body: CreateRunPayload, *, region: str | None = None
64
+ ) -> RunView:
65
+ """Create a job run (``POST /runs``)."""
66
+ return RunView.from_dict(
67
+ json_object(
68
+ client.request("POST", "/runs", json_body=body.to_dict(), params={"region": region})
69
+ )
70
+ )
71
+
72
+
73
+ def get_job_run(client: BaseClient, run_id: str) -> RunView:
74
+ """Get a job run (``GET /runs/{run_id}``)."""
75
+ return RunView.from_dict(json_object(client.request("GET", f"/runs/{quote(run_id, safe='')}")))
76
+
77
+
78
+ def cancel_job_run(client: BaseClient, run_id: str) -> RunView:
79
+ """Cancel a job run (``POST /runs/{run_id}/cancel``)."""
80
+ return RunView.from_dict(
81
+ json_object(client.request("POST", f"/runs/{quote(run_id, safe='')}/cancel"))
82
+ )
83
+
84
+
85
+ def get_job_run_logs(
86
+ client: BaseClient, run_id: str, *, size: int | None = None, cursor: str | None = None
87
+ ) -> LogsResponse:
88
+ """Get job run logs (``GET /runs/{run_id}/logs``)."""
89
+ return LogsResponse.from_dict(
90
+ json_object(
91
+ client.request(
92
+ "GET",
93
+ f"/runs/{quote(run_id, safe='')}/logs",
94
+ params={"size": size, "cursor": cursor},
95
+ )
96
+ )
97
+ )
98
+
99
+
100
+ def get_job_run_metrics(client: BaseClient, run_id: str) -> RunMetricsResponse:
101
+ """Get job run metrics (``GET /runs/{run_id}/metrics``)."""
102
+ return RunMetricsResponse.from_dict(
103
+ json_object(client.request("GET", f"/runs/{quote(run_id, safe='')}/metrics"))
104
+ )
105
+
106
+
107
+ def list_integration(
108
+ client: BaseClient, *, include_external_providers: bool | None = None
109
+ ) -> list[StorageIntegration]:
110
+ """List storage integrations (``GET /storage``)."""
111
+ return [
112
+ StorageIntegration.from_dict(row)
113
+ for row in json_array(
114
+ client.request(
115
+ "GET", "/storage", params={"include_external_providers": include_external_providers}
116
+ )
117
+ )
118
+ ]
119
+
120
+
121
+ def get_storage_credentials(
122
+ client: BaseClient, body: StorageCredentialsRequest
123
+ ) -> StorageCredentialsResponse:
124
+ """Get Storage Credentials (``POST /storage/credentials``)."""
125
+ return StorageCredentialsResponse.from_dict(
126
+ json_object(client.request("POST", "/storage/credentials", json_body=body.to_dict()))
127
+ )
128
+
129
+
130
+ def delete_directory(client: BaseClient, storage_id: str, path: str) -> None:
131
+ """Delete a directory from storage (``DELETE
132
+ /storage/{storage_id}/directories/{path}``).
133
+ """
134
+ client.request(
135
+ "DELETE", f"/storage/{quote(storage_id, safe='')}/directories/{quote(path, safe='/')}"
136
+ )
137
+
138
+
139
+ def list_directory_contents(
140
+ client: BaseClient,
141
+ storage_id: str,
142
+ path: str,
143
+ *,
144
+ cursor: str | None = None,
145
+ limit: int | None = None,
146
+ ) -> DirectoryPage:
147
+ """List directory contents (``GET /storage/{storage_id}/directories/{path}``)."""
148
+ return DirectoryPage.from_dict(
149
+ json_object(
150
+ client.request(
151
+ "GET",
152
+ f"/storage/{quote(storage_id, safe='')}/directories/{quote(path, safe='/')}",
153
+ params={"cursor": cursor, "limit": limit},
154
+ )
155
+ )
156
+ )
157
+
158
+
159
+ def create_directory(client: BaseClient, storage_id: str, path: str) -> None:
160
+ """Create a directory in storage (``PUT /storage/{storage_id}/directories/{path}``)."""
161
+ client.request(
162
+ "PUT", f"/storage/{quote(storage_id, safe='')}/directories/{quote(path, safe='/')}"
163
+ )
164
+
165
+
166
+ def get_file_download_url(client: BaseClient, storage_id: str, path: str) -> DownloadUrlResponse:
167
+ """Get a safe file download URL (``GET /storage/{storage_id}/file-download-
168
+ url/{path}``).
169
+ """
170
+ return DownloadUrlResponse.from_dict(
171
+ json_object(
172
+ client.request(
173
+ "GET",
174
+ f"/storage/{quote(storage_id, safe='')}/file-download-url/{quote(path, safe='/')}",
175
+ )
176
+ )
177
+ )
178
+
179
+
180
+ def rename_file_in_storage(
181
+ client: BaseClient, storage_id: str, path: str, *, new_name: str
182
+ ) -> None:
183
+ """Rename a file in storage (``POST /storage/{storage_id}/file-rename/{path}``)."""
184
+ client.request(
185
+ "POST",
186
+ f"/storage/{quote(storage_id, safe='')}/file-rename/{quote(path, safe='/')}",
187
+ params={"new_name": new_name},
188
+ )
189
+
190
+
191
+ def create_file_upload_url(client: BaseClient, storage_id: str, path: str) -> FileUploadUrl:
192
+ """Create a presigned file upload URL (``POST /storage/{storage_id}/file-upload-
193
+ url/{path}``).
194
+ """
195
+ return FileUploadUrl.from_dict(
196
+ json_object(
197
+ client.request(
198
+ "POST",
199
+ f"/storage/{quote(storage_id, safe='')}/file-upload-url/{quote(path, safe='/')}",
200
+ )
201
+ )
202
+ )
203
+
204
+
205
+ def delete_file_from_storage(client: BaseClient, storage_id: str, path: str) -> None:
206
+ """Delete a file from storage (``DELETE /storage/{storage_id}/files/{path}``)."""
207
+ client.request("DELETE", f"/storage/{quote(storage_id, safe='')}/files/{quote(path, safe='/')}")
208
+
209
+
210
+ def list_task_runs(
211
+ client: BaseClient,
212
+ *,
213
+ task_name: str | None = None,
214
+ type: TaskKind | None = None,
215
+ state: list[TaskRunState] | None = None,
216
+ created_after: datetime | None = None,
217
+ task_id: str | None = None,
218
+ task_trigger_id: str | None = None,
219
+ run_source: RunSource | None = None,
220
+ batch_time_from: datetime | None = None,
221
+ batch_time_to: datetime | None = None,
222
+ user_id: str | None = None,
223
+ region: str | None = None,
224
+ limit: int | None = None,
225
+ offset: int | None = None,
226
+ ) -> TaskRunSummaryPage:
227
+ """List task runs (``GET /task-runs``)."""
228
+ return TaskRunSummaryPage.from_dict(
229
+ json_object(
230
+ client.request(
231
+ "GET",
232
+ "/task-runs",
233
+ params={
234
+ "taskName": task_name,
235
+ "type": type,
236
+ "state": state,
237
+ "createdAfter": created_after,
238
+ "taskId": task_id,
239
+ "taskTriggerId": task_trigger_id,
240
+ "runSource": run_source,
241
+ "batchTimeFrom": batch_time_from,
242
+ "batchTimeTo": batch_time_to,
243
+ "userId": user_id,
244
+ "region": region,
245
+ "limit": limit,
246
+ "offset": offset,
247
+ },
248
+ )
249
+ )
250
+ )
251
+
252
+
253
+ def get_task_run(client: BaseClient, task_run_id: str) -> TaskRun:
254
+ """Get a task run (``GET /task-runs/{taskRunId}``)."""
255
+ return TaskRun.from_dict(
256
+ json_object(client.request("GET", f"/task-runs/{quote(task_run_id, safe='')}"))
257
+ )
258
+
259
+
260
+ def cancel_task_run(client: BaseClient, task_run_id: str) -> None:
261
+ """Cancel a task run (``POST /task-runs/{taskRunId}/cancel``)."""
262
+ client.request("POST", f"/task-runs/{quote(task_run_id, safe='')}/cancel")
263
+
264
+
265
+ def get_task_run_cost(client: BaseClient, task_run_id: str) -> TaskRunCost:
266
+ """Get task run cost (``GET /task-runs/{taskRunId}/cost``)."""
267
+ return TaskRunCost.from_dict(
268
+ json_object(client.request("GET", f"/task-runs/{quote(task_run_id, safe='')}/cost"))
269
+ )
270
+
271
+
272
+ def get_task_run_logs(
273
+ client: BaseClient, task_run_id: str, *, since: str | None = None
274
+ ) -> TaskRunLogs:
275
+ """Get task run logs (``GET /task-runs/{taskRunId}/logs``)."""
276
+ return TaskRunLogs.from_dict(
277
+ json_object(
278
+ client.request(
279
+ "GET", f"/task-runs/{quote(task_run_id, safe='')}/logs", params={"since": since}
280
+ )
281
+ )
282
+ )
283
+
284
+
285
+ def list_tasks(
286
+ client: BaseClient,
287
+ *,
288
+ regions: list[str] | None = None,
289
+ limit: int | None = None,
290
+ offset: int | None = None,
291
+ ) -> TaskSummaryPage:
292
+ """List tasks (``GET /tasks``)."""
293
+ return TaskSummaryPage.from_dict(
294
+ json_object(
295
+ client.request(
296
+ "GET", "/tasks", params={"regions": regions, "limit": limit, "offset": offset}
297
+ )
298
+ )
299
+ )
300
+
301
+
302
+ def get_task(client: BaseClient, task_name: str) -> Task:
303
+ """Get a task (``GET /tasks/{taskName}``)."""
304
+ return Task.from_dict(json_object(client.request("GET", f"/tasks/{quote(task_name, safe='')}")))
305
+
306
+
307
+ def create_task_run(
308
+ client: BaseClient, task_name: str, body: CreateTaskRunPayload
309
+ ) -> TaskRunSummary:
310
+ """Run a task (``POST /tasks/{taskName}/runs``)."""
311
+ return TaskRunSummary.from_dict(
312
+ json_object(
313
+ client.request(
314
+ "POST", f"/tasks/{quote(task_name, safe='')}/runs", json_body=body.to_dict()
315
+ )
316
+ )
317
+ )