atonode-sdk 0.3.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.
- atonode/__init__.py +48 -0
- atonode/py.typed +0 -0
- atonode_sdk-0.3.0.dist-info/METADATA +183 -0
- atonode_sdk-0.3.0.dist-info/RECORD +22 -0
- atonode_sdk-0.3.0.dist-info/WHEEL +5 -0
- atonode_sdk-0.3.0.dist-info/licenses/LICENSE +202 -0
- atonode_sdk-0.3.0.dist-info/top_level.txt +2 -0
- exprts_ai/__init__.py +44 -0
- exprts_ai/_types.py +31 -0
- exprts_ai/client.py +334 -0
- exprts_ai/config.py +77 -0
- exprts_ai/data.py +115 -0
- exprts_ai/datasets.py +104 -0
- exprts_ai/errors.py +34 -0
- exprts_ai/experiences.py +83 -0
- exprts_ai/models.py +54 -0
- exprts_ai/py.typed +0 -0
- exprts_ai/realtime.py +87 -0
- exprts_ai/recording.py +247 -0
- exprts_ai/storage.py +162 -0
- exprts_ai/sync.py +506 -0
- exprts_ai/transport.py +97 -0
exprts_ai/client.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Background connectivity never touches robot control or framework objects."""
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any
|
|
4
|
+
|
|
5
|
+
from ._types import Identifier, JSONDict
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .recording import StreamRecorder
|
|
9
|
+
|
|
10
|
+
import platform
|
|
11
|
+
import random
|
|
12
|
+
import threading
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from enum import Enum
|
|
15
|
+
|
|
16
|
+
from .config import Config
|
|
17
|
+
from .errors import (
|
|
18
|
+
APIError,
|
|
19
|
+
AuthenticationError,
|
|
20
|
+
ConfigurationError,
|
|
21
|
+
ExprtsError,
|
|
22
|
+
ProtocolError,
|
|
23
|
+
TransportError,
|
|
24
|
+
)
|
|
25
|
+
from .models import DeviceInfo
|
|
26
|
+
from .transport import HTTPTransport
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConnectionState(str, Enum):
|
|
30
|
+
STOPPED = "stopped"
|
|
31
|
+
CONNECTING = "connecting"
|
|
32
|
+
CONNECTED = "connected"
|
|
33
|
+
RETRYING = "retrying"
|
|
34
|
+
AUTHENTICATION_FAILED = "authentication_failed"
|
|
35
|
+
FAILED = "failed"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ConnectionStatus:
|
|
40
|
+
state: ConnectionState
|
|
41
|
+
device: DeviceInfo | None
|
|
42
|
+
error: str | None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ExprtsClient:
|
|
46
|
+
"""Robot device client. ``start`` is nonblocking; direct requests are blocking.
|
|
47
|
+
|
|
48
|
+
Credentials identify the robot on the server. No project or robot IDs are sent.
|
|
49
|
+
Instances own one background worker and serialize their HTTP requests.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
*,
|
|
55
|
+
api_url: str | None = None,
|
|
56
|
+
device_token: str | None = None,
|
|
57
|
+
timeout: float = 3.0,
|
|
58
|
+
max_backoff: float = 30.0,
|
|
59
|
+
max_retry_after: float = 300.0,
|
|
60
|
+
integration: str = "python",
|
|
61
|
+
runtime: str | None = None,
|
|
62
|
+
):
|
|
63
|
+
self._config = Config.from_env(
|
|
64
|
+
api_url=api_url,
|
|
65
|
+
device_token=device_token,
|
|
66
|
+
timeout=timeout,
|
|
67
|
+
max_backoff=max_backoff,
|
|
68
|
+
max_retry_after=max_retry_after,
|
|
69
|
+
)
|
|
70
|
+
self._payload: JSONDict = {
|
|
71
|
+
"integration": integration,
|
|
72
|
+
"runtime": runtime if runtime is not None else "python-" + platform.python_version(),
|
|
73
|
+
"client_version": "0.2.0",
|
|
74
|
+
}
|
|
75
|
+
for value in self._payload.values():
|
|
76
|
+
if (
|
|
77
|
+
not isinstance(value, str)
|
|
78
|
+
or not 1 <= len(value.strip()) <= 100
|
|
79
|
+
or any(ord(c) < 32 for c in value)
|
|
80
|
+
or "exprts_dev_" in value
|
|
81
|
+
or "exprts_sk_" in value
|
|
82
|
+
):
|
|
83
|
+
raise ConfigurationError(
|
|
84
|
+
"Client metadata must be 1–100 characters "
|
|
85
|
+
"without credentials or control characters"
|
|
86
|
+
)
|
|
87
|
+
self._transport = HTTPTransport(self._config)
|
|
88
|
+
self._http_lock = threading.Lock()
|
|
89
|
+
self._lock = threading.RLock()
|
|
90
|
+
self._stop = threading.Event()
|
|
91
|
+
self._connected = threading.Event()
|
|
92
|
+
self._thread: threading.Thread | None = None
|
|
93
|
+
self._status = ConnectionStatus(ConnectionState.STOPPED, None, None)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def status(self) -> ConnectionStatus:
|
|
97
|
+
with self._lock:
|
|
98
|
+
return self._status
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def is_connected(self) -> bool:
|
|
102
|
+
return self._connected.is_set()
|
|
103
|
+
|
|
104
|
+
def _set_status(
|
|
105
|
+
self, state: ConnectionState, device: DeviceInfo | None = None, error: str | None = None
|
|
106
|
+
) -> None:
|
|
107
|
+
with self._lock:
|
|
108
|
+
self._status = ConnectionStatus(state, device or self._status.device, error)
|
|
109
|
+
if state == ConnectionState.CONNECTED:
|
|
110
|
+
self._connected.set()
|
|
111
|
+
else:
|
|
112
|
+
self._connected.clear()
|
|
113
|
+
|
|
114
|
+
def set_location(
|
|
115
|
+
self, latitude: float | None, longitude: float | None = None, *, source: str = "configured"
|
|
116
|
+
) -> None:
|
|
117
|
+
"""Cache a fix for subsequent heartbeats; no network or GPS discovery.
|
|
118
|
+
|
|
119
|
+
Pass None to stop sending fixes. The server retains the last reported position.
|
|
120
|
+
Call from your GPS integration when a fix changes, outside the control loop.
|
|
121
|
+
"""
|
|
122
|
+
import math
|
|
123
|
+
|
|
124
|
+
if latitude is None:
|
|
125
|
+
with self._lock:
|
|
126
|
+
self._payload.pop("location", None)
|
|
127
|
+
return
|
|
128
|
+
if (
|
|
129
|
+
type(latitude) not in (int, float)
|
|
130
|
+
or type(longitude) not in (int, float)
|
|
131
|
+
or longitude is None
|
|
132
|
+
or not math.isfinite(latitude)
|
|
133
|
+
or not math.isfinite(longitude)
|
|
134
|
+
or not -90 <= latitude <= 90
|
|
135
|
+
or not -180 <= longitude <= 180
|
|
136
|
+
or source not in ("gps", "configured", "simulation")
|
|
137
|
+
):
|
|
138
|
+
raise ConfigurationError("Valid latitude, longitude and location source are required")
|
|
139
|
+
with self._lock:
|
|
140
|
+
self._payload["location"] = {
|
|
141
|
+
"latitude": latitude,
|
|
142
|
+
"longitude": longitude,
|
|
143
|
+
"source": source,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
def _request(self, operation: str) -> DeviceInfo:
|
|
147
|
+
with self._http_lock:
|
|
148
|
+
with self._lock:
|
|
149
|
+
payload = dict(self._payload) if operation == "heartbeat" else None
|
|
150
|
+
result = DeviceInfo.parse(
|
|
151
|
+
self._transport.request(
|
|
152
|
+
operation,
|
|
153
|
+
payload,
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
previous = self.status.device
|
|
157
|
+
if previous and (previous.robot_id, previous.project_id) != (
|
|
158
|
+
result.robot_id,
|
|
159
|
+
result.project_id,
|
|
160
|
+
):
|
|
161
|
+
raise ProtocolError("Device identity changed unexpectedly")
|
|
162
|
+
with self._lock:
|
|
163
|
+
self._status = ConnectionStatus(self._status.state, result, self._status.error)
|
|
164
|
+
return result
|
|
165
|
+
|
|
166
|
+
def verify(self) -> DeviceInfo:
|
|
167
|
+
"""Validate credentials without marking the robot connected or retrying."""
|
|
168
|
+
try:
|
|
169
|
+
return self._request("verify")
|
|
170
|
+
except ExprtsError as error:
|
|
171
|
+
self._record_failure(error)
|
|
172
|
+
raise
|
|
173
|
+
|
|
174
|
+
def heartbeat(self) -> DeviceInfo:
|
|
175
|
+
"""Send one heartbeat; failures propagate without automatic retries."""
|
|
176
|
+
try:
|
|
177
|
+
result = self._request("heartbeat")
|
|
178
|
+
except ExprtsError as error:
|
|
179
|
+
self._record_failure(error)
|
|
180
|
+
raise
|
|
181
|
+
self._set_status(ConnectionState.CONNECTED, result)
|
|
182
|
+
return result
|
|
183
|
+
|
|
184
|
+
def _record_failure(self, error: ExprtsError) -> None:
|
|
185
|
+
state = ConnectionState.RETRYING
|
|
186
|
+
if isinstance(error, AuthenticationError):
|
|
187
|
+
state = ConnectionState.AUTHENTICATION_FAILED
|
|
188
|
+
elif isinstance(error, ProtocolError) or (
|
|
189
|
+
isinstance(error, APIError) and not error.retryable
|
|
190
|
+
):
|
|
191
|
+
state = ConnectionState.FAILED
|
|
192
|
+
self._set_status(state, error=str(error))
|
|
193
|
+
|
|
194
|
+
def connect(self) -> DeviceInfo:
|
|
195
|
+
"""Verify and send the first heartbeat synchronously, without retries."""
|
|
196
|
+
self.verify()
|
|
197
|
+
return self.heartbeat()
|
|
198
|
+
|
|
199
|
+
def start(self) -> "ExprtsClient":
|
|
200
|
+
"""Start one background worker. A stopped client can be restarted."""
|
|
201
|
+
with self._lock:
|
|
202
|
+
if self._thread is not None and self._thread.is_alive():
|
|
203
|
+
raise RuntimeError("Connectivity worker is already running")
|
|
204
|
+
self._stop.clear()
|
|
205
|
+
self._set_status(ConnectionState.CONNECTING)
|
|
206
|
+
self._thread = threading.Thread(
|
|
207
|
+
target=self._run, name="exprts-connectivity", daemon=True
|
|
208
|
+
)
|
|
209
|
+
self._thread.start()
|
|
210
|
+
return self
|
|
211
|
+
|
|
212
|
+
def stop(self, timeout: float | None = None) -> bool:
|
|
213
|
+
"""Interrupt retry waits and join the worker; return whether it stopped.
|
|
214
|
+
|
|
215
|
+
An in-flight HTTP request cannot be cancelled. The default join budget is
|
|
216
|
+
the configured socket timeout plus one second. Never call from a control loop.
|
|
217
|
+
"""
|
|
218
|
+
self._stop.set()
|
|
219
|
+
self._connected.clear()
|
|
220
|
+
with self._lock:
|
|
221
|
+
thread = self._thread
|
|
222
|
+
if thread is not None:
|
|
223
|
+
thread.join(self._config.timeout + 1 if timeout is None else timeout)
|
|
224
|
+
stopped = thread is None or not thread.is_alive()
|
|
225
|
+
if stopped:
|
|
226
|
+
self._set_status(ConnectionState.STOPPED)
|
|
227
|
+
return stopped
|
|
228
|
+
|
|
229
|
+
close = stop
|
|
230
|
+
|
|
231
|
+
def wait_until_connected(self, timeout: float = 10.0) -> bool:
|
|
232
|
+
"""Wait up to timeout seconds for a successful heartbeat."""
|
|
233
|
+
return self._connected.wait(timeout)
|
|
234
|
+
|
|
235
|
+
def _run(self) -> None:
|
|
236
|
+
verified = False
|
|
237
|
+
delay = 1.0
|
|
238
|
+
try:
|
|
239
|
+
while not self._stop.is_set():
|
|
240
|
+
try:
|
|
241
|
+
if not verified:
|
|
242
|
+
self.verify()
|
|
243
|
+
verified = True
|
|
244
|
+
result = self.heartbeat()
|
|
245
|
+
delay = 1.0
|
|
246
|
+
self._stop.wait(result.heartbeat_interval_seconds)
|
|
247
|
+
except AuthenticationError as error:
|
|
248
|
+
self._set_status(ConnectionState.AUTHENTICATION_FAILED, error=str(error))
|
|
249
|
+
return
|
|
250
|
+
except (TransportError, APIError) as error:
|
|
251
|
+
if isinstance(error, APIError) and not error.retryable:
|
|
252
|
+
self._set_status(ConnectionState.FAILED, error=str(error))
|
|
253
|
+
return
|
|
254
|
+
verified = False
|
|
255
|
+
self._set_status(ConnectionState.RETRYING, error=str(error))
|
|
256
|
+
wait = random.uniform(
|
|
257
|
+
min(delay, self._config.max_backoff) / 2,
|
|
258
|
+
min(delay, self._config.max_backoff),
|
|
259
|
+
)
|
|
260
|
+
if isinstance(error, APIError) and error.retry_after is not None:
|
|
261
|
+
wait = max(wait, error.retry_after)
|
|
262
|
+
self._stop.wait(wait)
|
|
263
|
+
delay = min(delay * 2, self._config.max_backoff)
|
|
264
|
+
except ProtocolError as error:
|
|
265
|
+
self._set_status(ConnectionState.FAILED, error=str(error))
|
|
266
|
+
return
|
|
267
|
+
except Exception:
|
|
268
|
+
# Do not expose arbitrary exception messages or thread tracebacks.
|
|
269
|
+
self._set_status(
|
|
270
|
+
ConnectionState.FAILED, error="Unexpected connectivity failure"
|
|
271
|
+
)
|
|
272
|
+
return
|
|
273
|
+
finally:
|
|
274
|
+
if self._stop.is_set():
|
|
275
|
+
self._set_status(ConnectionState.STOPPED)
|
|
276
|
+
|
|
277
|
+
def __enter__(self) -> "ExprtsClient":
|
|
278
|
+
return self.start()
|
|
279
|
+
|
|
280
|
+
def __exit__(self, *_: object) -> None:
|
|
281
|
+
self.stop()
|
|
282
|
+
|
|
283
|
+
def report_sync(self, report: JSONDict) -> JSONDict:
|
|
284
|
+
"""Send a bounded offline-buffer report (blocking; use its worker)."""
|
|
285
|
+
with self._http_lock:
|
|
286
|
+
return self._transport.request("synchronization/report", report)
|
|
287
|
+
|
|
288
|
+
def get_stream(self, stream_id: Identifier) -> JSONDict:
|
|
289
|
+
"""Fetch the assigned schema and recording policy (blocking)."""
|
|
290
|
+
from uuid import UUID
|
|
291
|
+
|
|
292
|
+
with self._http_lock:
|
|
293
|
+
return self._transport.request("streams/" + str(UUID(str(stream_id))))
|
|
294
|
+
|
|
295
|
+
def ingest_stream(self, stream_id: Identifier, batch: JSONDict) -> JSONDict:
|
|
296
|
+
"""Submit a bounded batch (blocking); prefer recorder() in robot loops."""
|
|
297
|
+
from uuid import UUID
|
|
298
|
+
|
|
299
|
+
with self._http_lock:
|
|
300
|
+
return self._transport.request(
|
|
301
|
+
"streams/" + str(UUID(str(stream_id))) + "/batches", batch
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def recorder(self, stream_id: Identifier, **options: Any) -> "StreamRecorder":
|
|
305
|
+
from .recording import StreamRecorder
|
|
306
|
+
|
|
307
|
+
return StreamRecorder(self, stream_id, **options)
|
|
308
|
+
|
|
309
|
+
def get_task(self, task_id: Identifier) -> JSONDict:
|
|
310
|
+
from uuid import UUID
|
|
311
|
+
|
|
312
|
+
with self._http_lock:
|
|
313
|
+
return self._transport.request("experiences/tasks/" + str(UUID(str(task_id))))
|
|
314
|
+
|
|
315
|
+
def create_episode(self, **definition: Any) -> JSONDict:
|
|
316
|
+
"""Start an episode for this robot (blocking, outside control loops)."""
|
|
317
|
+
with self._http_lock:
|
|
318
|
+
return self._transport.request("experiences/episodes", definition)
|
|
319
|
+
|
|
320
|
+
def append_events(self, episode_id: Identifier, events: list[JSONDict]) -> JSONDict:
|
|
321
|
+
from uuid import UUID
|
|
322
|
+
|
|
323
|
+
with self._http_lock:
|
|
324
|
+
return self._transport.request(
|
|
325
|
+
"experiences/episodes/" + str(UUID(str(episode_id))) + "/events", {"events": events}
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
def complete_episode(self, episode_id: Identifier, **outcome: Any) -> JSONDict:
|
|
329
|
+
from uuid import UUID
|
|
330
|
+
|
|
331
|
+
with self._http_lock:
|
|
332
|
+
return self._transport.request(
|
|
333
|
+
"experiences/episodes/" + str(UUID(str(episode_id))) + "/complete", outcome
|
|
334
|
+
)
|
exprts_ai/config.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Explicit configuration takes precedence over environment variables."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
from .errors import ConfigurationError
|
|
10
|
+
|
|
11
|
+
_TOKEN = re.compile(r"exprts_dev_[0-9a-f]{24}_[A-Za-z0-9_-]{43}\Z")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Config:
|
|
16
|
+
api_url: str
|
|
17
|
+
device_token: str = field(repr=False)
|
|
18
|
+
timeout: float = 3.0
|
|
19
|
+
max_backoff: float = 30.0
|
|
20
|
+
max_retry_after: float = 300.0
|
|
21
|
+
|
|
22
|
+
def __post_init__(self) -> None:
|
|
23
|
+
try:
|
|
24
|
+
parsed = urlsplit(self.api_url)
|
|
25
|
+
port = parsed.port
|
|
26
|
+
except (ValueError, TypeError, AttributeError):
|
|
27
|
+
raise ConfigurationError("Invalid API URL") from None
|
|
28
|
+
if (
|
|
29
|
+
parsed.scheme not in ("http", "https")
|
|
30
|
+
or not parsed.hostname
|
|
31
|
+
or parsed.username is not None
|
|
32
|
+
or parsed.password is not None
|
|
33
|
+
or parsed.query
|
|
34
|
+
or parsed.fragment
|
|
35
|
+
or parsed.path not in ("", "/")
|
|
36
|
+
or port == 0
|
|
37
|
+
or any(c.isspace() or ord(c) < 32 for c in self.api_url)
|
|
38
|
+
):
|
|
39
|
+
raise ConfigurationError("Use an HTTP(S) API origin without a path or credentials")
|
|
40
|
+
if parsed.scheme == "http" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
|
|
41
|
+
raise ConfigurationError("HTTPS is required outside localhost")
|
|
42
|
+
if not isinstance(self.device_token, str) or not _TOKEN.fullmatch(self.device_token):
|
|
43
|
+
raise ConfigurationError("A valid robot device credential is required")
|
|
44
|
+
for name, maximum in (("timeout", 60), ("max_backoff", 3600), ("max_retry_after", 86400)):
|
|
45
|
+
value = getattr(self, name)
|
|
46
|
+
if (
|
|
47
|
+
isinstance(value, bool)
|
|
48
|
+
or not isinstance(value, (int, float))
|
|
49
|
+
or not math.isfinite(value)
|
|
50
|
+
or not 0 < value <= maximum
|
|
51
|
+
):
|
|
52
|
+
raise ConfigurationError(f"{name} must be positive and at most {maximum} seconds")
|
|
53
|
+
object.__setattr__(self, "api_url", self.api_url.rstrip("/"))
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_env(
|
|
57
|
+
cls,
|
|
58
|
+
*,
|
|
59
|
+
api_url: str | None = None,
|
|
60
|
+
device_token: str | None = None,
|
|
61
|
+
timeout: float = 3.0,
|
|
62
|
+
max_backoff: float = 30.0,
|
|
63
|
+
max_retry_after: float = 300.0,
|
|
64
|
+
) -> "Config":
|
|
65
|
+
return cls(
|
|
66
|
+
api_url=api_url
|
|
67
|
+
if api_url is not None
|
|
68
|
+
else os.environ.get(
|
|
69
|
+
"ATONODE_API_URL", os.environ.get("EXPRTS_API_URL", "https://api.atonode.com")
|
|
70
|
+
),
|
|
71
|
+
device_token=device_token
|
|
72
|
+
if device_token is not None
|
|
73
|
+
else os.environ.get("ATONODE_DEVICE_TOKEN", os.environ.get("EXPRTS_DEVICE_TOKEN", "")),
|
|
74
|
+
timeout=timeout,
|
|
75
|
+
max_backoff=max_backoff,
|
|
76
|
+
max_retry_after=max_retry_after,
|
|
77
|
+
)
|
exprts_ai/data.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Server-side project data APIs. Never embed project API keys in browser apps."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
from urllib.error import HTTPError, URLError
|
|
7
|
+
from urllib.parse import urlencode, urlsplit
|
|
8
|
+
from urllib.request import ProxyHandler, Request, build_opener
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
from ._types import Identifier, JSONDict
|
|
12
|
+
from .errors import APIError, ProtocolError, TransportError
|
|
13
|
+
from .transport import _NoRedirects, retry_after
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ProjectDataClient:
|
|
17
|
+
def __init__(
|
|
18
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
19
|
+
) -> None:
|
|
20
|
+
origin = urlsplit(api_url)
|
|
21
|
+
if (
|
|
22
|
+
origin.scheme not in ("https", "http")
|
|
23
|
+
or not origin.hostname
|
|
24
|
+
or origin.username
|
|
25
|
+
or origin.password
|
|
26
|
+
or origin.path not in ("", "/")
|
|
27
|
+
or origin.query
|
|
28
|
+
or origin.fragment
|
|
29
|
+
or (
|
|
30
|
+
origin.scheme == "http" and origin.hostname not in ("localhost", "127.0.0.1", "::1")
|
|
31
|
+
)
|
|
32
|
+
):
|
|
33
|
+
raise ValueError("Use an HTTPS API origin")
|
|
34
|
+
if not re.fullmatch(r"exprts_sk_[0-9a-f]{24}_[A-Za-z0-9_-]{43}", api_key):
|
|
35
|
+
raise ValueError("Project API key required")
|
|
36
|
+
if not 0 < timeout <= 60:
|
|
37
|
+
raise ValueError("Invalid timeout")
|
|
38
|
+
self._base = api_url.rstrip("/") + "/v1/projects/" + str(UUID(str(project_id))) + "/data"
|
|
39
|
+
self._key = api_key
|
|
40
|
+
self._timeout = timeout
|
|
41
|
+
self._opener = build_opener(ProxyHandler({}), _NoRedirects())
|
|
42
|
+
|
|
43
|
+
def _request(self, path: str, method: str = "GET", data: JSONDict | None = None) -> JSONDict:
|
|
44
|
+
body = json.dumps(data, allow_nan=False).encode() if data is not None else None
|
|
45
|
+
if body and len(body) > 2 * 1024 * 1024:
|
|
46
|
+
raise ValueError("Request exceeds 2 MiB")
|
|
47
|
+
req = Request(
|
|
48
|
+
self._base + path,
|
|
49
|
+
data=body,
|
|
50
|
+
method=method,
|
|
51
|
+
headers={"Authorization": "Bearer " + self._key, "Content-Type": "application/json"},
|
|
52
|
+
)
|
|
53
|
+
try:
|
|
54
|
+
with self._opener.open(req, timeout=self._timeout) as response:
|
|
55
|
+
raw = response.read(getattr(self, "_max_response_bytes", 4 * 1024 * 1024) + 1)
|
|
56
|
+
except HTTPError as error:
|
|
57
|
+
code = error.code
|
|
58
|
+
delay = retry_after(error.headers.get("Retry-After"), 3600)
|
|
59
|
+
error.close()
|
|
60
|
+
raise APIError(code, delay) from None
|
|
61
|
+
except (URLError, OSError):
|
|
62
|
+
raise TransportError("Data API unavailable") from None
|
|
63
|
+
if len(raw) > getattr(self, "_max_response_bytes", 4 * 1024 * 1024):
|
|
64
|
+
raise ProtocolError("Response limit exceeded")
|
|
65
|
+
try:
|
|
66
|
+
decoded = json.loads(raw)
|
|
67
|
+
if not isinstance(decoded, dict):
|
|
68
|
+
raise ProtocolError("Expected JSON object response")
|
|
69
|
+
return decoded
|
|
70
|
+
except ValueError:
|
|
71
|
+
raise ProtocolError("Invalid JSON response") from None
|
|
72
|
+
|
|
73
|
+
def resources(self, kind: str = "table") -> JSONDict:
|
|
74
|
+
return self._request("/resources?" + urlencode({"kind": kind}))
|
|
75
|
+
|
|
76
|
+
def create_resource(self, **definition: Any) -> JSONDict:
|
|
77
|
+
return self._request("/resources", "POST", definition)
|
|
78
|
+
|
|
79
|
+
def update_resource(self, resource_id: Identifier, **definition: Any) -> JSONDict:
|
|
80
|
+
return self._request("/resources/" + str(UUID(str(resource_id))), "PATCH", definition)
|
|
81
|
+
|
|
82
|
+
def records(self, table_id: Identifier, **query: Any) -> JSONDict:
|
|
83
|
+
return self._request("/tables/" + str(UUID(str(table_id))) + "/records?" + urlencode(query))
|
|
84
|
+
|
|
85
|
+
def insert(self, table_id: Identifier, values: JSONDict, schema_version: int = 1) -> JSONDict:
|
|
86
|
+
return self._request(
|
|
87
|
+
"/tables/" + str(UUID(str(table_id))) + "/records",
|
|
88
|
+
"POST",
|
|
89
|
+
dict(values=values, schema_version=schema_version),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def update(
|
|
93
|
+
self, table_id: Identifier, record_id: Identifier, values: JSONDict, schema_version: int = 1
|
|
94
|
+
) -> JSONDict:
|
|
95
|
+
return self._request(
|
|
96
|
+
"/tables/" + str(UUID(str(table_id))) + "/records/" + str(UUID(str(record_id))),
|
|
97
|
+
"PATCH",
|
|
98
|
+
dict(values=values, schema_version=schema_version),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def delete(self, table_id: Identifier, record_id: Identifier) -> JSONDict:
|
|
102
|
+
return self._request(
|
|
103
|
+
"/tables/" + str(UUID(str(table_id))) + "/records/" + str(UUID(str(record_id))),
|
|
104
|
+
"DELETE",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
def samples(self, stream_id: Identifier, **query: Any) -> JSONDict:
|
|
108
|
+
return self._request(
|
|
109
|
+
"/streams/" + str(UUID(str(stream_id))) + "/samples?" + urlencode(query)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def latest(self, stream_id: Identifier, robot_id: Identifier) -> JSONDict:
|
|
113
|
+
return self._request(
|
|
114
|
+
"/streams/" + str(UUID(str(stream_id))) + "/latest?" + urlencode({"robot_id": robot_id})
|
|
115
|
+
)
|
exprts_ai/datasets.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Authorized customer dataset registry, lineage and bulk raw exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .storage import ProjectStorageClient
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from urllib.parse import urlencode
|
|
12
|
+
|
|
13
|
+
from ._types import FilePath, Identifier, JSONDict
|
|
14
|
+
from .data import ProjectDataClient
|
|
15
|
+
from .experiences import identifier
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ProjectDatasetClient(ProjectDataClient):
|
|
19
|
+
def __init__(
|
|
20
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
21
|
+
) -> None:
|
|
22
|
+
super().__init__(api_url=api_url, api_key=api_key, project_id=project_id, timeout=timeout)
|
|
23
|
+
self._base = self._base.removesuffix("/data") + "/datasets"
|
|
24
|
+
self._max_response_bytes = 20 * 1024 * 1024
|
|
25
|
+
|
|
26
|
+
def datasets(self, **query: Any) -> JSONDict:
|
|
27
|
+
return self._request("?" + urlencode(query))
|
|
28
|
+
|
|
29
|
+
def create(self, name: str, description: str = "") -> JSONDict:
|
|
30
|
+
return self._request("", "POST", dict(name=name, description=description))
|
|
31
|
+
|
|
32
|
+
def dataset(self, dataset_id: Identifier) -> JSONDict:
|
|
33
|
+
return self._request("/" + identifier(dataset_id))
|
|
34
|
+
|
|
35
|
+
def register_version(self, dataset_id: Identifier, **definition: Any) -> JSONDict:
|
|
36
|
+
return self._request("/" + identifier(dataset_id) + "/versions", "POST", definition)
|
|
37
|
+
|
|
38
|
+
def manifest(self, dataset_id: Identifier, version_id: Identifier) -> JSONDict:
|
|
39
|
+
return self._request(
|
|
40
|
+
"/" + identifier(dataset_id) + "/versions/" + identifier(version_id) + "/manifest"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def download_url(self, dataset_id: Identifier, version_id: Identifier) -> JSONDict:
|
|
44
|
+
return self._request(
|
|
45
|
+
"/" + identifier(dataset_id) + "/versions/" + identifier(version_id) + "/download"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def delete_dataset(self, dataset_id: Identifier) -> JSONDict:
|
|
49
|
+
return self._request("/" + identifier(dataset_id), "DELETE")
|
|
50
|
+
|
|
51
|
+
def download_version(
|
|
52
|
+
self,
|
|
53
|
+
dataset_id: Identifier,
|
|
54
|
+
version_id: Identifier,
|
|
55
|
+
directory: FilePath,
|
|
56
|
+
*,
|
|
57
|
+
storage_client: ProjectStorageClient,
|
|
58
|
+
max_bytes: int = 1024**3,
|
|
59
|
+
) -> JSONDict:
|
|
60
|
+
manifest: JSONDict = self.manifest(dataset_id, version_id)["data"]
|
|
61
|
+
directory = Path(directory)
|
|
62
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
files = {a["file_id"]: a for a in manifest.get("artifacts", [])}
|
|
64
|
+
for source in manifest.get("sources", []):
|
|
65
|
+
for file in source["files"]:
|
|
66
|
+
files[file["id"]] = {
|
|
67
|
+
**file,
|
|
68
|
+
"file_id": file["id"],
|
|
69
|
+
"size_bytes": file["verified_bytes"] or 0,
|
|
70
|
+
}
|
|
71
|
+
total = sum(f["size_bytes"] for f in files.values())
|
|
72
|
+
if not 0 < max_bytes <= 10 * 1024**3 or total > max_bytes:
|
|
73
|
+
raise ValueError("Dataset exceeds download limit")
|
|
74
|
+
for file_id, entry in files.items():
|
|
75
|
+
file_id = identifier(file_id)
|
|
76
|
+
storage_client.download_file(
|
|
77
|
+
file_id, directory / (file_id + ".bin"), max_bytes=entry["size_bytes"]
|
|
78
|
+
)
|
|
79
|
+
# No source-supplied paths are used as local paths.
|
|
80
|
+
(directory / "manifest.json").write_text(json.dumps(manifest, indent=2))
|
|
81
|
+
return manifest
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ProjectPipelineClient(ProjectDataClient):
|
|
85
|
+
def __init__(
|
|
86
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
87
|
+
) -> None:
|
|
88
|
+
super().__init__(api_url=api_url, api_key=api_key, project_id=project_id, timeout=timeout)
|
|
89
|
+
self._base = self._base.removesuffix("/data") + "/pipelines"
|
|
90
|
+
|
|
91
|
+
def webhooks(self) -> JSONDict:
|
|
92
|
+
return self._request("/webhooks")
|
|
93
|
+
|
|
94
|
+
def create_webhook(self, url: str, topics: list[str]) -> JSONDict:
|
|
95
|
+
return self._request("/webhooks", "POST", dict(url=url, topics=topics))
|
|
96
|
+
|
|
97
|
+
def set_webhook_enabled(self, hook_id: Identifier, enabled: bool) -> JSONDict:
|
|
98
|
+
return self._request("/webhooks/" + identifier(hook_id), "PATCH", dict(enabled=enabled))
|
|
99
|
+
|
|
100
|
+
def deliveries(self, **query: Any) -> JSONDict:
|
|
101
|
+
return self._request("/deliveries?" + urlencode(query))
|
|
102
|
+
|
|
103
|
+
def retry_delivery(self, delivery_id: Identifier) -> JSONDict:
|
|
104
|
+
return self._request("/deliveries/" + identifier(delivery_id) + "/retry", "POST")
|
exprts_ai/errors.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Sanitized errors: never include response bodies, URLs or request credentials."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ExprtsError(Exception):
|
|
5
|
+
"""Base SDK error."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ConfigurationError(ExprtsError, ValueError):
|
|
9
|
+
"""Invalid local configuration."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TransportError(ExprtsError):
|
|
13
|
+
"""Network or TLS failure. Retrying may succeed."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ProtocolError(ExprtsError):
|
|
17
|
+
"""Unexpected or oversized server response."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class APIError(ExprtsError):
|
|
21
|
+
"""HTTP failure with bounded retry metadata, without server-provided text."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, status_code: int, retry_after: float | None = None):
|
|
24
|
+
self.status_code = status_code
|
|
25
|
+
self.retry_after = retry_after
|
|
26
|
+
super().__init__(f"Atonode API returned HTTP {status_code}")
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def retryable(self) -> bool:
|
|
30
|
+
return self.status_code in (408, 429, 500, 502, 503, 504)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AuthenticationError(APIError):
|
|
34
|
+
"""Credential rejected, revoked, expired, or robot/project unavailable."""
|