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.
exprts_ai/sync.py ADDED
@@ -0,0 +1,506 @@
1
+ """Private, bounded SQLite spool. All disk/network work belongs outside robot loops."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import random
7
+ import sqlite3
8
+ import sys
9
+ import threading
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, cast
13
+ from uuid import UUID, uuid4
14
+
15
+ from ._types import EpisodeWriter, FilePath, FileUploader, Identifier, JSONDict, StreamWriter
16
+ from .errors import APIError, ProtocolError, TransportError
17
+
18
+
19
+ class _DirectoryLease:
20
+ def __init__(self, path: Path) -> None:
21
+ self.file = path.open("a+b")
22
+ try:
23
+ if sys.platform == "win32":
24
+ import msvcrt
25
+
26
+ self.file.write(b"0")
27
+ self.file.flush()
28
+ self.file.seek(0)
29
+ msvcrt.locking(self.file.fileno(), msvcrt.LK_NBLCK, 1)
30
+ else:
31
+ import fcntl
32
+
33
+ fcntl.flock(self.file, fcntl.LOCK_EX | fcntl.LOCK_NB)
34
+ except OSError:
35
+ self.file.close()
36
+ raise RuntimeError("A synchronization worker already owns this buffer") from None
37
+
38
+ def close(self) -> None:
39
+ self.file.close()
40
+
41
+ def __del__(self) -> None:
42
+ self.file.close()
43
+
44
+
45
+ class OfflineBuffer:
46
+ """Durable FIFO jobs with stable payloads, per-stream limits and crash recovery.
47
+
48
+ One consumer per directory (an OS file lock prevents competing workers).
49
+ Bind scope to API origin/project/robot, never a credential. Terminal errors
50
+ block FIFO until retry(job_id) or discard(job_id) is explicitly requested.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ directory: FilePath,
56
+ *,
57
+ scope: str,
58
+ max_bytes: int = 64 * 1024 * 1024,
59
+ max_jobs: int = 10000,
60
+ stream_bytes: int = 8 * 1024 * 1024,
61
+ overflow: str = "reject",
62
+ ) -> None:
63
+ if not scope or len(scope) > 500:
64
+ raise ValueError("Stable origin/project/robot scope required")
65
+ if not 4096 <= stream_bytes <= max_bytes <= 1024**3 or not 1 <= max_jobs <= 100000:
66
+ raise ValueError("Invalid buffer limits")
67
+ if overflow not in ("reject", "drop_oldest"):
68
+ raise ValueError("Unknown overflow policy")
69
+ self.directory = Path(directory)
70
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
71
+ if self.directory.is_symlink():
72
+ raise ValueError("Buffer directory cannot be a symlink")
73
+ os.chmod(self.directory, 0o700)
74
+ self._lock = threading.RLock()
75
+ self._stop = threading.Event()
76
+ self._thread: threading.Thread | None = None
77
+ self._worker_error: str | None = None
78
+ self._guard = _DirectoryLease(self.directory / "consumer.lock")
79
+ self.max_bytes, self.max_jobs, self.stream_bytes = max_bytes, max_jobs, stream_bytes
80
+ self.overflow = overflow
81
+ path = self.directory / "queue.sqlite3"
82
+ if path.is_symlink():
83
+ raise ValueError("Buffer database cannot be a symlink")
84
+ self.db = sqlite3.connect(path, check_same_thread=False, timeout=5)
85
+ os.chmod(path, 0o600)
86
+ # DELETE journal avoids an unbounded WAL; SQLite pages are reused under max_page_count.
87
+ self.db.execute("PRAGMA journal_mode=DELETE")
88
+ self.db.execute("PRAGMA synchronous=FULL")
89
+ self.db.execute("PRAGMA max_page_count=" + str((max_bytes * 2 + 8 * 1024**2) // 4096))
90
+ self.db.executescript("""
91
+ CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
92
+ CREATE TABLE IF NOT EXISTS jobs (id INTEGER PRIMARY KEY AUTOINCREMENT,
93
+ operation TEXT NOT NULL, stream TEXT NOT NULL, payload TEXT NOT NULL,
94
+ digest TEXT NOT NULL, size INTEGER NOT NULL, samples INTEGER NOT NULL,
95
+ blob BLOB, attempts INTEGER NOT NULL DEFAULT 0, due REAL NOT NULL DEFAULT 0,
96
+ blocked INTEGER NOT NULL DEFAULT 0, error TEXT);
97
+ CREATE INDEX IF NOT EXISTS jobs_stream ON jobs(stream);
98
+ CREATE TABLE IF NOT EXISTS receipts (id INTEGER PRIMARY KEY, result TEXT NOT NULL);
99
+ CREATE TABLE IF NOT EXISTS gaps (id INTEGER PRIMARY KEY AUTOINCREMENT,
100
+ stream TEXT NOT NULL, samples INTEGER NOT NULL, reason TEXT NOT NULL);
101
+ """)
102
+ fingerprint = hashlib.sha256(scope.encode()).hexdigest()
103
+ with self.db:
104
+ existing = self.db.execute("SELECT value FROM metadata WHERE key='scope'").fetchone()
105
+ if existing and existing[0] != fingerprint:
106
+ self._guard.close()
107
+ raise ValueError("Buffer belongs to another origin/project/robot")
108
+ self.db.execute("INSERT OR IGNORE INTO metadata VALUES ('scope', ?)", (fingerprint,))
109
+ for key in ("dropped_samples", "dropped_jobs", "completed", "retries"):
110
+ self.db.execute("INSERT OR IGNORE INTO metadata VALUES (?, ?)", (key, "0"))
111
+
112
+ def _increment(self, key: str, value: int) -> None:
113
+ self.db.execute(
114
+ "UPDATE metadata SET value=CAST(value AS INTEGER)+? WHERE key=?", (value, key)
115
+ )
116
+
117
+ def _gap(self, stream: str, samples: int, reason: str) -> None:
118
+ self.db.execute(
119
+ "INSERT INTO gaps(stream,samples,reason) VALUES (?,?,?)", (stream, samples, reason)
120
+ )
121
+ self.db.execute(
122
+ "DELETE FROM gaps WHERE id NOT IN (SELECT id FROM gaps ORDER BY id DESC LIMIT 100)"
123
+ )
124
+
125
+ def result(self, job_id: int) -> JSONDict | None:
126
+ """Last 100 successful receipts, including IDs assigned to offline episode starts."""
127
+ with self._lock:
128
+ row = self.db.execute("SELECT result FROM receipts WHERE id=?", (job_id,)).fetchone()
129
+ return cast(JSONDict, json.loads(row[0])) if row else None
130
+
131
+ def enqueue(
132
+ self,
133
+ operation: str,
134
+ payload: JSONDict,
135
+ *,
136
+ stream_id: Identifier | None = None,
137
+ samples: int = 0,
138
+ ) -> int | None:
139
+ """Blocking durable write; returns job ID or None on rejected overflow.
140
+
141
+ Each stream may use a separate buffer/directory for independent limits/policy.
142
+ Never queue bearer tokens, capability URLs or unbounded application records.
143
+ """
144
+ if operation not in (
145
+ "ingest_stream",
146
+ "create_episode",
147
+ "append_events",
148
+ "complete_episode",
149
+ ):
150
+ raise ValueError("Unsupported synchronization operation")
151
+ if type(samples) is not int or samples < 0:
152
+ raise ValueError("Invalid sample count")
153
+ payload = json.loads(json.dumps(payload, allow_nan=False))
154
+ stream = str(UUID(str(stream_id))) if stream_id else operation
155
+ if operation == "ingest_stream":
156
+ if not stream_id or payload.get("live"):
157
+ raise ValueError("Only historical stream batches can be buffered")
158
+ payload.setdefault("idempotency_key", uuid4().hex)
159
+ if operation == "create_episode":
160
+ payload.setdefault("idempotency_key", uuid4().hex)
161
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False)
162
+ size = len(raw.encode())
163
+ if size > min(self.stream_bytes, 2 * 1024 * 1024):
164
+ raise ValueError("Job exceeds buffer/payload limit")
165
+ with self._lock, self.db:
166
+ while True:
167
+ total, count = self.db.execute(
168
+ "SELECT COALESCE(SUM(size),0), COUNT(*) FROM jobs"
169
+ ).fetchone()
170
+ used = self.db.execute(
171
+ "SELECT COALESCE(SUM(size),0) FROM jobs WHERE stream=?", (stream,)
172
+ ).fetchone()[0]
173
+ if (
174
+ total + size <= self.max_bytes
175
+ and count < self.max_jobs
176
+ and used + size <= self.stream_bytes
177
+ ):
178
+ break
179
+ # Never evict the job currently in flight; _lock spans send/ack.
180
+ row = self.db.execute(
181
+ "SELECT id,samples FROM jobs WHERE stream=? ORDER BY id LIMIT 1", (stream,)
182
+ ).fetchone()
183
+ if self.overflow == "reject" or not row:
184
+ self._gap(stream, samples, "overflow_rejected")
185
+ self._increment("dropped_samples", samples)
186
+ self._increment("dropped_jobs", 1)
187
+ return None
188
+ self.db.execute("DELETE FROM jobs WHERE id=?", (row[0],))
189
+ self._gap(stream, row[1], "overflow_evicted")
190
+ self._increment("dropped_samples", row[1])
191
+ self._increment("dropped_jobs", 1)
192
+ cursor = self.db.execute(
193
+ "INSERT INTO jobs(operation,stream,payload,digest,size,samples) VALUES "
194
+ "(?,?,?,?,?,?)",
195
+ (
196
+ operation,
197
+ stream,
198
+ raw,
199
+ hashlib.sha256(raw.encode()).hexdigest(),
200
+ size,
201
+ samples,
202
+ ),
203
+ )
204
+ return cursor.lastrowid
205
+
206
+ def enqueue_file(
207
+ self, path: FilePath, *, content_type: str = "application/octet-stream", **metadata: Any
208
+ ) -> int | None:
209
+ """Snapshot a bounded file before returning; retries resume verified multipart upload.
210
+
211
+ Run on a data worker, never in a robot control loop. The snapshot is kept in
212
+ SQLite, so removal and job acknowledgement are atomic. Limit files to 64 MiB.
213
+ """
214
+ source = Path(path)
215
+ limit = min(self.stream_bytes, self.max_bytes, 64 * 1024 * 1024)
216
+ with source.open("rb") as handle:
217
+ blob = handle.read(limit + 1)
218
+ if not blob or len(blob) > limit:
219
+ raise ValueError("File exceeds snapshot limit or is empty")
220
+ payload = dict(
221
+ content_type=content_type,
222
+ idempotency_key=uuid4().hex,
223
+ _filename=source.name,
224
+ **metadata,
225
+ )
226
+ raw = json.dumps(payload, sort_keys=True, allow_nan=False)
227
+ size = len(blob) + len(raw.encode())
228
+ if len(raw.encode()) > 16384:
229
+ raise ValueError("File metadata exceeds limit")
230
+ with self._lock, self.db:
231
+ used, count = self.db.execute(
232
+ "SELECT COALESCE(SUM(size),0),COUNT(*) FROM jobs"
233
+ ).fetchone()
234
+ stream_used = self.db.execute(
235
+ "SELECT COALESCE(SUM(size),0) FROM jobs WHERE stream='files'"
236
+ ).fetchone()[0]
237
+ if (
238
+ used + size > self.max_bytes
239
+ or stream_used + size > self.stream_bytes
240
+ or count >= self.max_jobs
241
+ ):
242
+ self._increment("dropped_jobs", 1)
243
+ return None
244
+ return self.db.execute(
245
+ "INSERT INTO jobs(operation,stream,payload,digest,size,samples,blob) "
246
+ "VALUES (?,?,?,?,?,0,?)",
247
+ (
248
+ "upload_file",
249
+ "files",
250
+ raw,
251
+ hashlib.sha256(raw.encode() + blob).hexdigest(),
252
+ size,
253
+ blob,
254
+ ),
255
+ ).lastrowid
256
+
257
+ def status(self) -> JSONDict:
258
+ with self._lock:
259
+ count, size, blocked = self.db.execute(
260
+ "SELECT COUNT(*),COALESCE(SUM(size),0),COALESCE(SUM(blocked),0) FROM jobs"
261
+ ).fetchone()
262
+ counters = {
263
+ k: int(v)
264
+ for k, v in self.db.execute("SELECT key,value FROM metadata WHERE key!='scope'")
265
+ }
266
+ jobs = [
267
+ dict(
268
+ zip(
269
+ ("id", "operation", "stream", "attempts", "blocked", "error"),
270
+ r,
271
+ strict=False,
272
+ )
273
+ )
274
+ for r in self.db.execute(
275
+ "SELECT id,operation,stream,attempts,blocked,error FROM jobs ORDER BY "
276
+ "id LIMIT 100"
277
+ )
278
+ ]
279
+ gaps = [
280
+ dict(stream=r[0], samples=r[1], reason=r[2])
281
+ for r in self.db.execute(
282
+ "SELECT stream,samples,reason FROM gaps ORDER BY id DESC LIMIT 100"
283
+ )
284
+ ]
285
+ return dict(
286
+ worker_running=bool(self._thread and self._thread.is_alive()),
287
+ worker_error=self._worker_error,
288
+ pending=count,
289
+ bytes=size,
290
+ blocked=blocked,
291
+ jobs=jobs,
292
+ gaps=gaps,
293
+ **counters,
294
+ )
295
+
296
+ def report(self) -> JSONDict:
297
+ """Return a bounded diagnostic snapshot without customer payloads or paths."""
298
+ with self._lock:
299
+ status = self.status()
300
+ jobs = [
301
+ dict(
302
+ id=r[0],
303
+ operation=r[1],
304
+ stream=r[2],
305
+ attempts=r[3],
306
+ blocked=bool(r[4]),
307
+ error=r[5],
308
+ size_bytes=r[6],
309
+ samples=r[7],
310
+ next_retry_at=float(r[8]),
311
+ )
312
+ for r in self.db.execute(
313
+ "SELECT id,operation,stream,attempts,blocked,error,size,samples,due "
314
+ "FROM jobs ORDER BY id LIMIT 25"
315
+ )
316
+ ]
317
+ receipts = [
318
+ dict(job_id=r[0], **json.loads(r[1]))
319
+ for r in self.db.execute("SELECT id,result FROM receipts ORDER BY id DESC LIMIT 25")
320
+ ]
321
+ return dict(
322
+ buffer_id=self.db.execute(
323
+ "SELECT value FROM metadata WHERE key='scope'"
324
+ ).fetchone()[0],
325
+ **{
326
+ k: status[k]
327
+ for k in (
328
+ "pending",
329
+ "bytes",
330
+ "blocked",
331
+ "completed",
332
+ "retries",
333
+ "dropped_samples",
334
+ "dropped_jobs",
335
+ "worker_running",
336
+ "worker_error",
337
+ )
338
+ },
339
+ max_bytes=self.max_bytes,
340
+ max_jobs=self.max_jobs,
341
+ stream_bytes=self.stream_bytes,
342
+ overflow=self.overflow,
343
+ jobs=jobs,
344
+ receipts=receipts,
345
+ )
346
+
347
+ def retry(self, job_id: int) -> None:
348
+ with self._lock, self.db:
349
+ self.db.execute("UPDATE jobs SET blocked=0,due=0,error=NULL WHERE id=?", (job_id,))
350
+
351
+ def discard(self, job_id: int) -> None:
352
+ with self._lock, self.db:
353
+ row = self.db.execute(
354
+ "SELECT samples,stream FROM jobs WHERE id=?", (job_id,)
355
+ ).fetchone()
356
+ if row:
357
+ self._gap(row[1], row[0], "explicit_discard")
358
+ self._increment("dropped_samples", row[0])
359
+ self._increment("dropped_jobs", 1)
360
+ self.db.execute("DELETE FROM jobs WHERE id=?", (job_id,))
361
+
362
+ def sync_once(self, client: object) -> bool:
363
+ """Send at most one FIFO job. Safe to retry after a process crash."""
364
+ with self._lock:
365
+ row = self.db.execute(
366
+ "SELECT id,operation,stream,payload,digest,attempts,due,blocked FROM "
367
+ "jobs ORDER BY id LIMIT 1"
368
+ ).fetchone()
369
+ if not row or row[7] or row[6] > time.time():
370
+ return False
371
+ job_id, op, stream, raw, digest, attempts, _, _ = row
372
+ try:
373
+ blob_row = self.db.execute("SELECT blob FROM jobs WHERE id=?", (job_id,)).fetchone()
374
+ blob = blob_row[0] or b""
375
+ if hashlib.sha256(raw.encode() + blob).hexdigest() != digest:
376
+ raise ValueError("Integrity mismatch")
377
+ payload = json.loads(raw)
378
+ if op == "upload_file":
379
+ import tempfile
380
+
381
+ # Private bounded scratch snapshot is deleted even after errors.
382
+ with tempfile.TemporaryDirectory(prefix="exprts-sync-") as scratch:
383
+ filename = payload.pop("_filename", "recording.bin")
384
+ if Path(filename).name != filename or filename in (".", ".."):
385
+ raise ValueError("Invalid snapshot filename")
386
+ path = Path(scratch) / filename
387
+ path.write_bytes(blob)
388
+ result = cast(FileUploader, client).upload_file(path, **payload)
389
+ elif op == "ingest_stream":
390
+ result = cast(StreamWriter, client).ingest_stream(stream, payload)
391
+ elif op == "create_episode":
392
+ result = cast(EpisodeWriter, client).create_episode(**payload)
393
+ else:
394
+ episode = str(UUID(payload.pop("episode_id")))
395
+ if op == "append_events":
396
+ result = cast(EpisodeWriter, client).append_events(
397
+ episode, payload["events"]
398
+ )
399
+ else:
400
+ result = cast(EpisodeWriter, client).complete_episode(episode, **payload)
401
+ except Exception as error:
402
+ retryable = (
403
+ isinstance(error, TransportError)
404
+ or isinstance(error, APIError)
405
+ and error.retryable
406
+ )
407
+ delay = random.uniform(1, min(60, 2 ** min(attempts + 1, 6)))
408
+ if isinstance(error, APIError) and error.retry_after is not None:
409
+ delay = max(delay, min(error.retry_after, 3600))
410
+ # Persist only sanitized codes; arbitrary exceptions may contain secrets.
411
+ code = (
412
+ "http_" + str(error.status_code)
413
+ if isinstance(error, APIError)
414
+ else "transport"
415
+ if retryable
416
+ else "validation_or_integrity"
417
+ )
418
+ with self.db:
419
+ self.db.execute(
420
+ "UPDATE jobs SET attempts=attempts+1,due=?,blocked=?,error=? WHERE id=?",
421
+ (time.time() + delay, int(not retryable), code, job_id),
422
+ )
423
+ self._increment("retries", int(retryable))
424
+ return False
425
+ with self.db:
426
+ # Keep only bounded identifiers/status; never store capabilities or credentials.
427
+ if isinstance(result, dict):
428
+ result = result.get("data", result)
429
+ receipt: dict[str, str] = {
430
+ k: str(result[k])[:100]
431
+ for k in ("id", "file_id", "status", "state")
432
+ if isinstance(result, dict) and k in result
433
+ }
434
+ else:
435
+ receipt = {}
436
+ from datetime import datetime, timezone
437
+
438
+ receipt["acknowledged_at"] = datetime.now(timezone.utc).isoformat()
439
+ self.db.execute("INSERT INTO receipts VALUES (?,?)", (job_id, json.dumps(receipt)))
440
+ self.db.execute(
441
+ "DELETE FROM receipts WHERE id NOT IN (SELECT id FROM receipts ORDER "
442
+ "BY id DESC LIMIT 100)"
443
+ )
444
+ self.db.execute("DELETE FROM jobs WHERE id=?", (job_id,))
445
+ self._increment("completed", 1)
446
+ return True
447
+
448
+ def start(
449
+ self, client: object, *, report_interval_seconds: float | None = None
450
+ ) -> "OfflineBuffer":
451
+ """Start background recovery outside control loops. Single consumer per directory."""
452
+ if report_interval_seconds is not None and not 30 <= report_interval_seconds <= 3600:
453
+ raise ValueError("Report interval must be 30–3600 seconds")
454
+ reporter = (
455
+ getattr(client, "report_sync", None) if report_interval_seconds is not None else None
456
+ )
457
+ if report_interval_seconds is not None and not callable(reporter):
458
+ raise ValueError("This client does not support device synchronization reports")
459
+ with self._lock:
460
+ if self._thread and self._thread.is_alive():
461
+ return self
462
+ self._worker_error = None
463
+ self._stop.clear()
464
+
465
+ def run() -> None:
466
+ next_report = 0.0
467
+ while not self._stop.is_set():
468
+ try:
469
+ if reporter is not None and time.monotonic() >= next_report:
470
+ # Metadata reporting shares the existing background worker;
471
+ # failures never block or discard queued customer data.
472
+ next_report = time.monotonic() + float(report_interval_seconds or 30)
473
+ try:
474
+ reporter(self.report())
475
+ except APIError as error:
476
+ if not error.retryable:
477
+ next_report = float("inf")
478
+ elif error.retry_after:
479
+ next_report = max(
480
+ next_report, time.monotonic() + min(error.retry_after, 3600)
481
+ )
482
+ except ProtocolError:
483
+ next_report = float("inf")
484
+ except TransportError:
485
+ pass
486
+ if not self.sync_once(client):
487
+ self._stop.wait(0.5)
488
+ except (sqlite3.Error, OSError):
489
+ self._worker_error = "local_storage_unavailable"
490
+ return
491
+
492
+ self._thread = threading.Thread(target=run, daemon=True, name="exprts-offline-sync")
493
+ self._thread.start()
494
+ return self
495
+
496
+ def close(self, timeout: float = 5) -> bool:
497
+ self._stop.set()
498
+ if self._thread:
499
+ self._thread.join(max(0, min(timeout, 60)))
500
+ if self._thread.is_alive():
501
+ return False
502
+ with self._lock:
503
+ if self._guard:
504
+ self._guard.close()
505
+ self.db.close()
506
+ return True
exprts_ai/transport.py ADDED
@@ -0,0 +1,97 @@
1
+ """Bounded standard-library HTTP transport. No redirects or ambient proxies."""
2
+
3
+ import gzip
4
+ import json
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from email.utils import parsedate_to_datetime
8
+ from http.client import HTTPException
9
+ from typing import Any
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
12
+
13
+ from .config import Config
14
+ from .errors import APIError, AuthenticationError, ProtocolError, TransportError
15
+
16
+ MAX_RESPONSE_BYTES = 65536
17
+
18
+
19
+ class _NoRedirects(HTTPRedirectHandler):
20
+ def redirect_request(
21
+ self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str
22
+ ) -> None:
23
+ return None
24
+
25
+
26
+ def retry_after(value: str | None, maximum: float) -> float | None:
27
+ if not value:
28
+ return None
29
+ try:
30
+ seconds = (
31
+ float(int(value))
32
+ if value.isdigit()
33
+ else (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds()
34
+ )
35
+ return min(maximum, max(0.0, seconds))
36
+ except (TypeError, ValueError, OverflowError):
37
+ return None
38
+
39
+
40
+ class HTTPTransport:
41
+ def __init__(self, config: Config):
42
+ self._config = config
43
+ # System proxies can leak bearer credentials when configured incorrectly.
44
+ self._opener = build_opener(ProxyHandler({}), _NoRedirects())
45
+
46
+ def request(self, operation: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
47
+ if operation not in (
48
+ "verify",
49
+ "heartbeat",
50
+ "experiences/episodes",
51
+ "synchronization/report",
52
+ ) and not re.fullmatch(
53
+ r"(?:streams/[0-9a-f-]{36}(?:/batches)?|experiences/tasks/[0-9a-f-]{36}|experiences/episodes/[0-9a-f-]{36}/(?:events|complete))",
54
+ operation,
55
+ ):
56
+ raise ValueError("Unsupported device operation")
57
+ encoded = json.dumps(payload, allow_nan=False).encode() if payload is not None else None
58
+ if encoded and len(encoded) > 2 * 1024 * 1024:
59
+ raise ValueError("Request exceeds 2 MiB")
60
+ request = Request(
61
+ self._config.api_url + "/v1/device/" + operation,
62
+ data=gzip.compress(encoded, mtime=0)
63
+ if encoded is not None and operation.endswith("/batches")
64
+ else encoded,
65
+ headers={
66
+ "Authorization": "Bearer " + self._config.device_token,
67
+ "Content-Type": "application/json",
68
+ "Accept": "application/json",
69
+ **({"Content-Encoding": "gzip"} if operation.endswith("/batches") else {}),
70
+ "User-Agent": "atonode_sdk/0.3.0",
71
+ },
72
+ )
73
+ try:
74
+ with self._opener.open(request, timeout=self._config.timeout) as response:
75
+ if response.status not in (200, 201):
76
+ raise APIError(response.status)
77
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
78
+ except HTTPError as error:
79
+ status = error.code
80
+ delay = retry_after(error.headers.get("Retry-After"), self._config.max_retry_after)
81
+ error.close()
82
+ cls = AuthenticationError if status in (401, 403) else APIError
83
+ raise cls(status, delay) from None
84
+ except (URLError, OSError, TimeoutError, HTTPException):
85
+ raise TransportError("Atonode connection unavailable") from None
86
+ if len(raw) > MAX_RESPONSE_BYTES:
87
+ raise ProtocolError("Device response exceeds size limit")
88
+ try:
89
+ result = json.loads(raw)
90
+ if not isinstance(result, dict) or "data" not in result:
91
+ raise ValueError
92
+ data = result["data"]
93
+ if not isinstance(data, dict):
94
+ raise ValueError("Expected data object")
95
+ return data
96
+ except (ValueError, UnicodeError, RecursionError):
97
+ raise ProtocolError("Invalid JSON response") from None