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/experiences.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Blocking experience APIs for trusted server integrations, outside control loops."""
|
|
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
|
+
from urllib.parse import urlencode
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
from ._types import FilePath, Identifier, JSONDict
|
|
13
|
+
from .data import ProjectDataClient
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def identifier(value: Identifier) -> str:
|
|
17
|
+
return str(UUID(str(value)))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ProjectExperienceClient(ProjectDataClient):
|
|
21
|
+
def __init__(
|
|
22
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
23
|
+
) -> None:
|
|
24
|
+
super().__init__(api_url=api_url, api_key=api_key, project_id=project_id, timeout=timeout)
|
|
25
|
+
self._base = self._base.removesuffix("/data") + "/experiences"
|
|
26
|
+
|
|
27
|
+
def tasks(self, **query: Any) -> JSONDict:
|
|
28
|
+
return self._request("/tasks?" + urlencode(query))
|
|
29
|
+
|
|
30
|
+
def create_task(self, **definition: Any) -> JSONDict:
|
|
31
|
+
return self._request("/tasks", "POST", definition)
|
|
32
|
+
|
|
33
|
+
def episodes(self, **query: Any) -> JSONDict:
|
|
34
|
+
return self._request("/episodes?" + urlencode(query))
|
|
35
|
+
|
|
36
|
+
def create_episode(self, **definition: Any) -> JSONDict:
|
|
37
|
+
return self._request("/episodes", "POST", definition)
|
|
38
|
+
|
|
39
|
+
def episode(self, episode_id: Identifier) -> JSONDict:
|
|
40
|
+
return self._request("/episodes/" + identifier(episode_id))
|
|
41
|
+
|
|
42
|
+
def events(self, episode_id: Identifier, **query: Any) -> JSONDict:
|
|
43
|
+
return self._request("/episodes/" + identifier(episode_id) + "/events?" + urlencode(query))
|
|
44
|
+
|
|
45
|
+
def append_events(self, episode_id: Identifier, events: list[JSONDict]) -> JSONDict:
|
|
46
|
+
return self._request(
|
|
47
|
+
"/episodes/" + identifier(episode_id) + "/events", "POST", {"events": events}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def complete_episode(self, episode_id: Identifier, **outcome: Any) -> JSONDict:
|
|
51
|
+
return self._request("/episodes/" + identifier(episode_id) + "/complete", "POST", outcome)
|
|
52
|
+
|
|
53
|
+
def export_episodes(self, episode_ids: list[Identifier]) -> JSONDict:
|
|
54
|
+
self._max_response_bytes = 20 * 1024 * 1024
|
|
55
|
+
return self._request(
|
|
56
|
+
"/exports", "POST", {"episode_ids": [identifier(e) for e in episode_ids]}
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def download_episodes(
|
|
60
|
+
self,
|
|
61
|
+
episode_ids: list[Identifier],
|
|
62
|
+
directory: FilePath,
|
|
63
|
+
*,
|
|
64
|
+
storage_client: ProjectStorageClient,
|
|
65
|
+
max_bytes: int = 1024**3,
|
|
66
|
+
) -> JSONDict:
|
|
67
|
+
import json
|
|
68
|
+
from pathlib import Path
|
|
69
|
+
|
|
70
|
+
manifest: JSONDict = self.export_episodes(episode_ids)["data"]
|
|
71
|
+
total = sum(f["verified_bytes"] or 0 for f in manifest["files"])
|
|
72
|
+
if not 0 < max_bytes <= 10 * 1024**3 or total > max_bytes:
|
|
73
|
+
raise ValueError("Export exceeds download limit")
|
|
74
|
+
directory = Path(directory)
|
|
75
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
for file in manifest["files"]:
|
|
77
|
+
storage_client.download_file(
|
|
78
|
+
file["id"],
|
|
79
|
+
directory / (identifier(file["id"]) + ".bin"),
|
|
80
|
+
max_bytes=file["verified_bytes"] or 0,
|
|
81
|
+
)
|
|
82
|
+
(directory / "manifest.json").write_text(json.dumps(manifest, indent=2))
|
|
83
|
+
return manifest
|
exprts_ai/models.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Validated connectivity responses, independent of robotics frameworks."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from .errors import ProtocolError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _timestamp(value: Any) -> datetime:
|
|
12
|
+
if not isinstance(value, str):
|
|
13
|
+
raise ValueError
|
|
14
|
+
result = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
15
|
+
if result.tzinfo is None:
|
|
16
|
+
raise ValueError
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class DeviceInfo:
|
|
22
|
+
project_id: UUID
|
|
23
|
+
robot_id: UUID
|
|
24
|
+
heartbeat_interval_seconds: int
|
|
25
|
+
heartbeat_timeout_seconds: int
|
|
26
|
+
server_time: datetime
|
|
27
|
+
last_heartbeat_at: datetime | None
|
|
28
|
+
authenticated: bool = True
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def parse(cls, value: Any) -> "DeviceInfo":
|
|
32
|
+
try:
|
|
33
|
+
if not isinstance(value, dict) or value.get("authenticated") is not True:
|
|
34
|
+
raise ValueError
|
|
35
|
+
interval, timeout = (
|
|
36
|
+
value["heartbeat_interval_seconds"],
|
|
37
|
+
value["heartbeat_timeout_seconds"],
|
|
38
|
+
)
|
|
39
|
+
if type(interval) is not int or not 1 <= interval <= 3600:
|
|
40
|
+
raise ValueError
|
|
41
|
+
if type(timeout) is not int or not interval * 2 <= timeout <= 86400:
|
|
42
|
+
raise ValueError
|
|
43
|
+
return cls(
|
|
44
|
+
project_id=UUID(value["project_id"]),
|
|
45
|
+
robot_id=UUID(value["robot_id"]),
|
|
46
|
+
heartbeat_interval_seconds=interval,
|
|
47
|
+
heartbeat_timeout_seconds=timeout,
|
|
48
|
+
server_time=_timestamp(value["server_time"]),
|
|
49
|
+
last_heartbeat_at=_timestamp(value["last_heartbeat_at"])
|
|
50
|
+
if value["last_heartbeat_at"] is not None
|
|
51
|
+
else None,
|
|
52
|
+
)
|
|
53
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
54
|
+
raise ProtocolError("Invalid device response") from None
|
exprts_ai/py.typed
ADDED
|
File without changes
|
exprts_ai/realtime.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Project-scoped polling subscriptions; no credentials in URLs or event payloads."""
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Iterator, Sequence
|
|
6
|
+
from typing import cast
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
|
|
9
|
+
from ._types import Identifier, JSONDict
|
|
10
|
+
from .data import ProjectDataClient
|
|
11
|
+
from .errors import APIError, TransportError
|
|
12
|
+
from .experiences import identifier
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ProjectRealtimeClient(ProjectDataClient):
|
|
16
|
+
def __init__(
|
|
17
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
18
|
+
) -> None:
|
|
19
|
+
super().__init__(api_url=api_url, api_key=api_key, project_id=project_id, timeout=timeout)
|
|
20
|
+
self._base = self._base.removesuffix("/data") + "/realtime"
|
|
21
|
+
self.diagnostics: JSONDict = {}
|
|
22
|
+
|
|
23
|
+
def connect(self, topics: Sequence[str], *, stream_ids: Sequence[Identifier] = ()) -> JSONDict:
|
|
24
|
+
return cast(
|
|
25
|
+
JSONDict,
|
|
26
|
+
self._request(
|
|
27
|
+
"/connections", "POST", dict(topics=list(topics), stream_ids=list(stream_ids))
|
|
28
|
+
)["data"],
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
def poll(self, connection_id: str, *, after: int) -> JSONDict:
|
|
32
|
+
result = self._request(
|
|
33
|
+
"/connections/" + identifier(connection_id) + "/events?" + urlencode({"after": after})
|
|
34
|
+
)
|
|
35
|
+
self.diagnostics = result["meta"]
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
def disconnect(self, connection_id: str) -> JSONDict:
|
|
39
|
+
return self._request("/connections/" + identifier(connection_id), "DELETE")
|
|
40
|
+
|
|
41
|
+
def events(
|
|
42
|
+
self,
|
|
43
|
+
topics: Sequence[str],
|
|
44
|
+
*,
|
|
45
|
+
stream_ids: Sequence[Identifier] = (),
|
|
46
|
+
after: int | None = None,
|
|
47
|
+
stop: threading.Event | None = None,
|
|
48
|
+
) -> Iterator[JSONDict]:
|
|
49
|
+
"""Blocking iterator. Retain sequence for resume; inspect diagnostics for gaps.
|
|
50
|
+
|
|
51
|
+
Consume outside robot loops. Stop is a threading.Event. Events are at-least
|
|
52
|
+
once on reconnect; deduplicate by project and sequence. No callback queue.
|
|
53
|
+
"""
|
|
54
|
+
stop = stop if stop is not None else threading.Event()
|
|
55
|
+
connection: JSONDict | None = None
|
|
56
|
+
delay = 1
|
|
57
|
+
cursor = after
|
|
58
|
+
try:
|
|
59
|
+
while not stop.is_set():
|
|
60
|
+
try:
|
|
61
|
+
if connection is None:
|
|
62
|
+
connection = self.connect(topics, stream_ids=stream_ids)
|
|
63
|
+
if cursor is None:
|
|
64
|
+
cursor = int(connection["cursor"])
|
|
65
|
+
assert cursor is not None
|
|
66
|
+
result = self.poll(connection["id"], after=cursor)
|
|
67
|
+
delay = 1
|
|
68
|
+
yield from result["data"]
|
|
69
|
+
cursor = result["meta"]["cursor"]
|
|
70
|
+
stop.wait(result["meta"]["poll_interval_seconds"])
|
|
71
|
+
except (APIError, TransportError) as error:
|
|
72
|
+
if isinstance(error, APIError) and error.status_code == 410:
|
|
73
|
+
connection = None
|
|
74
|
+
elif isinstance(error, APIError) and not error.retryable:
|
|
75
|
+
raise
|
|
76
|
+
wait = random.uniform(delay / 2, delay)
|
|
77
|
+
if isinstance(error, APIError) and error.retry_after:
|
|
78
|
+
wait = max(wait, error.retry_after)
|
|
79
|
+
self.diagnostics = {**self.diagnostics, "reconnecting": True}
|
|
80
|
+
stop.wait(wait)
|
|
81
|
+
delay = min(60, delay * 2)
|
|
82
|
+
finally:
|
|
83
|
+
if connection:
|
|
84
|
+
try:
|
|
85
|
+
self.disconnect(connection["id"])
|
|
86
|
+
except (APIError, TransportError):
|
|
87
|
+
pass # Lease expires even when explicit disconnect cannot reach backend.
|
exprts_ai/recording.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Bounded recording outside control loops with optional persistent synchronization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from ._types import Identifier, JSONDict, StreamWriter
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .sync import OfflineBuffer
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import sqlite3
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections import deque
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from uuid import UUID, uuid4
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class StreamRecorder:
|
|
22
|
+
"""Call record() with source time/sequence; HTTP runs in a daemon worker.
|
|
23
|
+
|
|
24
|
+
Construct/configure before starting control loops. Overflow drops newest data
|
|
25
|
+
and increments dropped_samples. close() has a bounded join deadline.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
client: StreamWriter,
|
|
31
|
+
stream_id: Identifier,
|
|
32
|
+
*,
|
|
33
|
+
capacity: int = 1000,
|
|
34
|
+
batch_size: int = 100,
|
|
35
|
+
calibration: JSONDict | None = None,
|
|
36
|
+
offline_buffer: OfflineBuffer | None = None,
|
|
37
|
+
resource: JSONDict | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
self.client = client
|
|
40
|
+
self.stream_id = str(UUID(str(stream_id)))
|
|
41
|
+
if not 1 <= capacity <= 10000 or not 1 <= batch_size <= 1000:
|
|
42
|
+
raise ValueError("Invalid recorder bounds")
|
|
43
|
+
self.offline_buffer = offline_buffer
|
|
44
|
+
self.resource = resource if resource is not None else client.get_stream(self.stream_id)
|
|
45
|
+
self.policy = self.resource["policy"]
|
|
46
|
+
self.calibration = dict(calibration or {})
|
|
47
|
+
self.queue: deque[tuple[JSONDict, bool]] = deque()
|
|
48
|
+
self.buffer: deque[JSONDict] = deque(maxlen=self.policy["buffer_samples"])
|
|
49
|
+
self.capacity = capacity
|
|
50
|
+
self.batch_size = batch_size
|
|
51
|
+
self.dropped_samples = 0
|
|
52
|
+
self.sent_samples = 0
|
|
53
|
+
self.failed_batches = 0
|
|
54
|
+
self._lock = threading.Lock()
|
|
55
|
+
self._wake = threading.Event()
|
|
56
|
+
self._stop = threading.Event()
|
|
57
|
+
self._historical = -float("inf")
|
|
58
|
+
self._live = -float("inf")
|
|
59
|
+
self._interval = -float("inf")
|
|
60
|
+
self._episode = False
|
|
61
|
+
self._last_sequence = -1
|
|
62
|
+
self._last_timestamp: datetime | None = None
|
|
63
|
+
self._thread = threading.Thread(
|
|
64
|
+
target=self._run, daemon=True, name="exprts-stream-recorder"
|
|
65
|
+
)
|
|
66
|
+
self._thread.start()
|
|
67
|
+
|
|
68
|
+
def begin_episode(self) -> None:
|
|
69
|
+
self._episode = True
|
|
70
|
+
|
|
71
|
+
def end_episode(self) -> None:
|
|
72
|
+
self._episode = False
|
|
73
|
+
|
|
74
|
+
def _enqueue(self, sample: JSONDict, live: bool = False) -> None:
|
|
75
|
+
if len(self.queue) >= self.capacity:
|
|
76
|
+
self.dropped_samples += 1
|
|
77
|
+
else:
|
|
78
|
+
self.queue.append((sample, live))
|
|
79
|
+
self._wake.set()
|
|
80
|
+
|
|
81
|
+
def record(self, values: JSONDict, *, timestamp: datetime, sequence: int) -> bool:
|
|
82
|
+
# Bound input size before copying. Invalid values are rejected locally.
|
|
83
|
+
if not isinstance(timestamp, datetime) or timestamp.tzinfo is None:
|
|
84
|
+
raise ValueError("Timezone-aware source timestamp required")
|
|
85
|
+
if type(sequence) is not int or sequence < 0:
|
|
86
|
+
raise ValueError("Nonnegative sequence required")
|
|
87
|
+
if len(values) > 64 or any(
|
|
88
|
+
type(v) not in (str, int, float, bool, type(None))
|
|
89
|
+
or (isinstance(v, str) and len(v) > 4096)
|
|
90
|
+
for v in values.values()
|
|
91
|
+
):
|
|
92
|
+
raise ValueError("Sample exceeds field limits")
|
|
93
|
+
sample: JSONDict = {
|
|
94
|
+
"timestamp": timestamp.astimezone(timezone.utc).isoformat(),
|
|
95
|
+
"sequence": sequence,
|
|
96
|
+
"values": dict(values),
|
|
97
|
+
}
|
|
98
|
+
if len(json.dumps(sample, allow_nan=False).encode()) > 16384:
|
|
99
|
+
raise ValueError("Sample exceeds 16 KiB")
|
|
100
|
+
clock = time.monotonic()
|
|
101
|
+
with self._lock:
|
|
102
|
+
if self._stop.is_set():
|
|
103
|
+
return False
|
|
104
|
+
if sequence <= self._last_sequence:
|
|
105
|
+
raise ValueError("Sequence must increase")
|
|
106
|
+
if self._last_timestamp is not None and timestamp < self._last_timestamp:
|
|
107
|
+
raise ValueError("Source timestamps must not go backwards")
|
|
108
|
+
self._last_timestamp = timestamp
|
|
109
|
+
self._last_sequence = sequence
|
|
110
|
+
mode = self.policy["mode"]
|
|
111
|
+
if mode == "disabled":
|
|
112
|
+
return False
|
|
113
|
+
if (
|
|
114
|
+
mode in ("event", "on_demand")
|
|
115
|
+
and clock - self._historical >= 1 / self.policy["historical_hz"]
|
|
116
|
+
):
|
|
117
|
+
self.buffer.append(sample)
|
|
118
|
+
self._historical = clock
|
|
119
|
+
if clock - self._live >= 1 / self.policy["live_hz"]:
|
|
120
|
+
self._enqueue(sample, True)
|
|
121
|
+
self._live = clock
|
|
122
|
+
historical = (
|
|
123
|
+
mode == "continuous"
|
|
124
|
+
or (mode == "episode" and self._episode)
|
|
125
|
+
or (
|
|
126
|
+
mode == "interval" and clock - self._interval >= self.policy["interval_seconds"]
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
if historical and clock - self._historical >= 1 / self.policy["historical_hz"]:
|
|
130
|
+
self._enqueue(sample)
|
|
131
|
+
self._historical = clock
|
|
132
|
+
if mode == "interval":
|
|
133
|
+
self._interval = clock
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
def trigger(self) -> None:
|
|
137
|
+
with self._lock:
|
|
138
|
+
if self.policy["mode"] not in ("event", "on_demand"):
|
|
139
|
+
raise ValueError("Stream is not trigger-based")
|
|
140
|
+
for sample in self.buffer:
|
|
141
|
+
self._enqueue(sample)
|
|
142
|
+
self.buffer.clear()
|
|
143
|
+
|
|
144
|
+
def _run(self) -> None:
|
|
145
|
+
while not self._stop.is_set():
|
|
146
|
+
self._wake.wait(0.25)
|
|
147
|
+
self._wake.clear()
|
|
148
|
+
if self._stop.wait(2):
|
|
149
|
+
break
|
|
150
|
+
with self._lock:
|
|
151
|
+
if not self.queue:
|
|
152
|
+
continue
|
|
153
|
+
samples: list[JSONDict] = []
|
|
154
|
+
live = self.queue[0][1]
|
|
155
|
+
size = 0
|
|
156
|
+
remaining: deque[tuple[JSONDict, bool]] = deque()
|
|
157
|
+
while self.queue:
|
|
158
|
+
sample, entry_live = self.queue.popleft()
|
|
159
|
+
length = len(json.dumps(sample).encode())
|
|
160
|
+
if (
|
|
161
|
+
entry_live == live
|
|
162
|
+
and len(samples) < self.batch_size
|
|
163
|
+
and size + length <= 512 * 1024
|
|
164
|
+
):
|
|
165
|
+
samples.append(sample)
|
|
166
|
+
size += length
|
|
167
|
+
else:
|
|
168
|
+
remaining.append((sample, entry_live))
|
|
169
|
+
self.queue = remaining
|
|
170
|
+
payload = {
|
|
171
|
+
"idempotency_key": uuid4().hex,
|
|
172
|
+
"schema_version": self.resource["schema_version"],
|
|
173
|
+
"samples": samples,
|
|
174
|
+
"capture": self.policy["mode"]
|
|
175
|
+
if self.policy["mode"] != "live_only"
|
|
176
|
+
else "continuous",
|
|
177
|
+
"live": live,
|
|
178
|
+
"calibration": self.calibration,
|
|
179
|
+
}
|
|
180
|
+
if self.offline_buffer is not None and not live:
|
|
181
|
+
try:
|
|
182
|
+
job = self.offline_buffer.enqueue(
|
|
183
|
+
"ingest_stream", payload, stream_id=self.stream_id, samples=len(samples)
|
|
184
|
+
)
|
|
185
|
+
if job is None:
|
|
186
|
+
self.dropped_samples += len(samples)
|
|
187
|
+
except (OSError, ValueError, RuntimeError, sqlite3.Error):
|
|
188
|
+
self.failed_batches += 1
|
|
189
|
+
self.dropped_samples += len(samples)
|
|
190
|
+
continue
|
|
191
|
+
succeeded = False
|
|
192
|
+
for attempt in range(3):
|
|
193
|
+
try:
|
|
194
|
+
self.client.ingest_stream(self.stream_id, payload)
|
|
195
|
+
succeeded = True
|
|
196
|
+
self.sent_samples += len(samples)
|
|
197
|
+
break
|
|
198
|
+
except Exception:
|
|
199
|
+
self.failed_batches += 1
|
|
200
|
+
if self._stop.wait(min(2**attempt, 4)):
|
|
201
|
+
break
|
|
202
|
+
if not succeeded:
|
|
203
|
+
self.dropped_samples += len(samples)
|
|
204
|
+
|
|
205
|
+
def close(self, timeout: float = 5) -> bool:
|
|
206
|
+
self._stop.set()
|
|
207
|
+
self._wake.set()
|
|
208
|
+
self._thread.join(max(0, min(timeout, 60)))
|
|
209
|
+
if self._thread.is_alive():
|
|
210
|
+
return False
|
|
211
|
+
with self._lock:
|
|
212
|
+
pending = list(self.queue)
|
|
213
|
+
self.queue.clear()
|
|
214
|
+
if self.offline_buffer is None:
|
|
215
|
+
self.dropped_samples += len(pending)
|
|
216
|
+
return True
|
|
217
|
+
historical = [sample for sample, live in pending if not live]
|
|
218
|
+
self.dropped_samples += sum(1 for _, live in pending if live)
|
|
219
|
+
# Graceful shutdown persists historical jobs. Live updates are never replayed.
|
|
220
|
+
for start in range(0, len(historical), min(self.batch_size, 30)):
|
|
221
|
+
samples = historical[start : start + min(self.batch_size, 30)]
|
|
222
|
+
try:
|
|
223
|
+
job = self.offline_buffer.enqueue(
|
|
224
|
+
"ingest_stream",
|
|
225
|
+
{
|
|
226
|
+
"idempotency_key": uuid4().hex,
|
|
227
|
+
"schema_version": self.resource["schema_version"],
|
|
228
|
+
"samples": samples,
|
|
229
|
+
"capture": self.policy["mode"],
|
|
230
|
+
"live": False,
|
|
231
|
+
"calibration": self.calibration,
|
|
232
|
+
},
|
|
233
|
+
stream_id=self.stream_id,
|
|
234
|
+
samples=len(samples),
|
|
235
|
+
)
|
|
236
|
+
if job is None:
|
|
237
|
+
self.dropped_samples += len(samples)
|
|
238
|
+
except (OSError, ValueError, RuntimeError, sqlite3.Error):
|
|
239
|
+
self.failed_batches += 1
|
|
240
|
+
self.dropped_samples += len(samples)
|
|
241
|
+
return True
|
|
242
|
+
|
|
243
|
+
def __enter__(self) -> StreamRecorder:
|
|
244
|
+
return self
|
|
245
|
+
|
|
246
|
+
def __exit__(self, *args: object) -> None:
|
|
247
|
+
self.close()
|
exprts_ai/storage.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Phase 7 verified multipart storage. Bearer keys never reach capability URLs."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from http.client import HTTPResponse
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
from urllib.error import HTTPError, URLError
|
|
10
|
+
from urllib.parse import urlencode, urlsplit
|
|
11
|
+
from urllib.request import Request
|
|
12
|
+
|
|
13
|
+
from ._types import FilePath, Identifier, JSONDict
|
|
14
|
+
from .data import ProjectDataClient
|
|
15
|
+
from .errors import APIError, ProtocolError, TransportError
|
|
16
|
+
from .experiences import identifier
|
|
17
|
+
from .transport import retry_after
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ProjectStorageClient(ProjectDataClient):
|
|
21
|
+
def __init__(
|
|
22
|
+
self, *, api_url: str, api_key: str, project_id: Identifier, timeout: float = 15
|
|
23
|
+
) -> None:
|
|
24
|
+
super().__init__(api_url=api_url, api_key=api_key, project_id=project_id, timeout=timeout)
|
|
25
|
+
self._base = self._base.removesuffix("/data") + "/storage"
|
|
26
|
+
|
|
27
|
+
def files(self, **query: Any) -> JSONDict:
|
|
28
|
+
return self._request("/files?" + urlencode(query))
|
|
29
|
+
|
|
30
|
+
def file(self, file_id: Identifier) -> JSONDict:
|
|
31
|
+
return self._request("/files/" + identifier(file_id))
|
|
32
|
+
|
|
33
|
+
def reserve(self, **definition: Any) -> JSONDict:
|
|
34
|
+
return self._request("/uploads", "POST", definition)
|
|
35
|
+
|
|
36
|
+
def authorize_part(self, file_id: Identifier, number: int) -> JSONDict:
|
|
37
|
+
if type(number) is not int or not 1 <= number <= 10000:
|
|
38
|
+
raise ValueError("Invalid part number")
|
|
39
|
+
return self._request("/files/" + identifier(file_id) + "/parts/" + str(number), "POST")
|
|
40
|
+
|
|
41
|
+
def complete(self, file_id: Identifier) -> JSONDict:
|
|
42
|
+
return self._request("/files/" + identifier(file_id) + "/complete", "POST")
|
|
43
|
+
|
|
44
|
+
def download_url(self, file_id: Identifier) -> JSONDict:
|
|
45
|
+
return self._request("/files/" + identifier(file_id) + "/download", "POST")
|
|
46
|
+
|
|
47
|
+
def delete_file(self, file_id: Identifier) -> JSONDict:
|
|
48
|
+
return self._request("/files/" + identifier(file_id), "DELETE")
|
|
49
|
+
|
|
50
|
+
def _capability(
|
|
51
|
+
self,
|
|
52
|
+
url: str,
|
|
53
|
+
*,
|
|
54
|
+
method: str = "GET",
|
|
55
|
+
data: bytes | None = None,
|
|
56
|
+
headers: dict[str, str] | None = None,
|
|
57
|
+
) -> HTTPResponse:
|
|
58
|
+
origin = urlsplit(url)
|
|
59
|
+
if origin.scheme != "https" and not (
|
|
60
|
+
origin.scheme == "http" and origin.hostname in ("localhost", "127.0.0.1", "::1")
|
|
61
|
+
):
|
|
62
|
+
raise ProtocolError("Invalid storage capability origin")
|
|
63
|
+
if not origin.hostname or origin.username or origin.password or origin.fragment:
|
|
64
|
+
raise ProtocolError("Invalid storage capability URL")
|
|
65
|
+
headers = headers or {}
|
|
66
|
+
if any(
|
|
67
|
+
key.lower() in ("authorization", "cookie", "proxy-authorization") for key in headers
|
|
68
|
+
):
|
|
69
|
+
raise ProtocolError("Unexpected credential header")
|
|
70
|
+
try:
|
|
71
|
+
return cast(
|
|
72
|
+
HTTPResponse,
|
|
73
|
+
self._opener.open(
|
|
74
|
+
Request(url, data=data, method=method, headers=headers), timeout=self._timeout
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
except HTTPError as error:
|
|
78
|
+
code = error.code
|
|
79
|
+
delay = retry_after(error.headers.get("Retry-After"), 3600)
|
|
80
|
+
error.close()
|
|
81
|
+
raise APIError(code, delay) from None
|
|
82
|
+
except (URLError, OSError):
|
|
83
|
+
raise TransportError("Storage transfer unavailable") from None
|
|
84
|
+
|
|
85
|
+
def upload_file(
|
|
86
|
+
self,
|
|
87
|
+
path: FilePath,
|
|
88
|
+
*,
|
|
89
|
+
idempotency_key: str,
|
|
90
|
+
content_type: str = "application/octet-stream",
|
|
91
|
+
**metadata: Any,
|
|
92
|
+
) -> JSONDict:
|
|
93
|
+
"""Resume the same reservation using its idempotency key; no implicit retries."""
|
|
94
|
+
path = Path(path)
|
|
95
|
+
with path.open("rb") as source:
|
|
96
|
+
digest = hashlib.sha256()
|
|
97
|
+
size = 0
|
|
98
|
+
while chunk := source.read(1024 * 1024):
|
|
99
|
+
digest.update(chunk)
|
|
100
|
+
size += len(chunk)
|
|
101
|
+
item = self.reserve(
|
|
102
|
+
name=path.name,
|
|
103
|
+
size_bytes=size,
|
|
104
|
+
sha256=digest.hexdigest(),
|
|
105
|
+
idempotency_key=idempotency_key,
|
|
106
|
+
content_type=content_type,
|
|
107
|
+
**metadata,
|
|
108
|
+
)["data"]
|
|
109
|
+
if item["state"] == "ready":
|
|
110
|
+
return {"data": item}
|
|
111
|
+
part_size = item["part_size"]
|
|
112
|
+
if type(part_size) is not int or not 1 <= part_size <= 64 * 1024 * 1024:
|
|
113
|
+
raise ProtocolError("Unsupported storage part size")
|
|
114
|
+
remote = self.file(item["id"])["data"]
|
|
115
|
+
if remote.get("assembled"):
|
|
116
|
+
return self.complete(item["id"])
|
|
117
|
+
uploaded = {p["PartNumber"]: p["Size"] for p in remote.get("parts", [])}
|
|
118
|
+
source.seek(0)
|
|
119
|
+
number = 1
|
|
120
|
+
while chunk := source.read(part_size):
|
|
121
|
+
if uploaded.get(number) == len(chunk):
|
|
122
|
+
number += 1
|
|
123
|
+
continue
|
|
124
|
+
capability = self.authorize_part(item["id"], number)["data"]
|
|
125
|
+
with self._capability(
|
|
126
|
+
capability["url"], method="PUT", data=chunk, headers=capability["headers"]
|
|
127
|
+
):
|
|
128
|
+
pass
|
|
129
|
+
number += 1
|
|
130
|
+
return self.complete(item["id"])
|
|
131
|
+
|
|
132
|
+
def download_file(
|
|
133
|
+
self, file_id: Identifier, destination: FilePath, *, max_bytes: int = 1024 * 1024 * 1024
|
|
134
|
+
) -> Path:
|
|
135
|
+
"""Stream to disk and verify SHA-256 before atomically replacing destination."""
|
|
136
|
+
item = self.file(file_id)["data"]
|
|
137
|
+
expected = item["verified_bytes"]
|
|
138
|
+
if item["state"] != "ready" or type(expected) is not int or not 0 < expected <= max_bytes:
|
|
139
|
+
raise ValueError("File unavailable or exceeds download limit")
|
|
140
|
+
capability = self.download_url(file_id)["data"]
|
|
141
|
+
destination = Path(destination)
|
|
142
|
+
temporary = None
|
|
143
|
+
try:
|
|
144
|
+
with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as output:
|
|
145
|
+
temporary = output.name
|
|
146
|
+
digest = hashlib.sha256()
|
|
147
|
+
size = 0
|
|
148
|
+
with self._capability(capability["url"]) as source:
|
|
149
|
+
while chunk := source.read(1024 * 1024):
|
|
150
|
+
size += len(chunk)
|
|
151
|
+
if size > expected:
|
|
152
|
+
raise ProtocolError("Download exceeds verified size")
|
|
153
|
+
digest.update(chunk)
|
|
154
|
+
output.write(chunk)
|
|
155
|
+
if size != expected or digest.hexdigest() != item["sha256"]:
|
|
156
|
+
raise ProtocolError("Download integrity check failed")
|
|
157
|
+
os.replace(temporary, destination)
|
|
158
|
+
temporary = None
|
|
159
|
+
finally:
|
|
160
|
+
if temporary:
|
|
161
|
+
os.unlink(temporary)
|
|
162
|
+
return destination
|