perception-sdk 0.1.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.
@@ -0,0 +1,42 @@
1
+ """A Python client and command line for the Perception console API."""
2
+
3
+ from ._http import VERSION as __version__
4
+ from .admin import AdminClient
5
+ from .client import PART_SIZE, Client
6
+ from .errors import (
7
+ APIConnectionError,
8
+ AuthenticationError,
9
+ ConfigurationError,
10
+ ConflictError,
11
+ NotFoundError,
12
+ PayloadTooLarge,
13
+ PerceptionError,
14
+ PermissionDenied,
15
+ ServerError,
16
+ UploadError,
17
+ ValidationError,
18
+ )
19
+ from .models import ApiKey, IssuedApiKey, KeyList, Source, WhoAmI
20
+
21
+ __all__ = [
22
+ "PART_SIZE",
23
+ "APIConnectionError",
24
+ "AdminClient",
25
+ "ApiKey",
26
+ "AuthenticationError",
27
+ "Client",
28
+ "ConfigurationError",
29
+ "ConflictError",
30
+ "IssuedApiKey",
31
+ "KeyList",
32
+ "NotFoundError",
33
+ "PayloadTooLarge",
34
+ "PerceptionError",
35
+ "PermissionDenied",
36
+ "ServerError",
37
+ "Source",
38
+ "UploadError",
39
+ "ValidationError",
40
+ "WhoAmI",
41
+ "__version__",
42
+ ]
@@ -0,0 +1,262 @@
1
+ """The one HTTP transport `Client` and `AdminClient` share: authentication, retries and error mapping.
2
+
3
+ Two `httpx.Client`s live here. One talks to the API and carries the credential. The other PUTs
4
+ upload parts to the blob store's pre-signed URLs and carries no credential at all: a pre-signed URL
5
+ is its own authorization, and the API key has no business leaving for a storage host."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import re
12
+ import time
13
+ from typing import Any
14
+ from urllib.parse import quote
15
+
16
+ import httpx
17
+
18
+ from .errors import APIConnectionError, PerceptionError, UploadError, error_for_status
19
+
20
+ VERSION = "0.1.0"
21
+ USER_AGENT = f"perception-sdk/{VERSION}"
22
+
23
+ # A GET is tried this many times in all, waiting this long before each retry.
24
+ GET_ATTEMPTS = 3
25
+ GET_RETRY_DELAYS_S = (0.5, 1.0)
26
+ GET_RETRY_STATUSES = frozenset({502, 503, 504})
27
+
28
+ # A part PUT is retried this many times after its first attempt fails in a way that can pass.
29
+ PART_RETRY_DELAYS_S = (0.5, 1, 2)
30
+
31
+ log = logging.getLogger("perception_sdk")
32
+
33
+ # Indirected so tests can skip the waits.
34
+ _sleep = time.sleep
35
+
36
+ _REDACTED = "[redacted]"
37
+ _LOCATIONS = frozenset({"body", "query", "path", "header", "cookie"})
38
+ _S3_CODE = re.compile(r"<Code>([^<]{1,128})</Code>")
39
+
40
+
41
+ def seg(value: object) -> str:
42
+ """A path segment, escaped so an id can never reach a different route."""
43
+ return quote(str(value), safe="")
44
+
45
+
46
+ class HTTP:
47
+ def __init__(
48
+ self,
49
+ base_url: str,
50
+ token: str,
51
+ *,
52
+ timeout: float,
53
+ transport: httpx.BaseTransport | None,
54
+ blob_transport: httpx.BaseTransport | None = None,
55
+ ) -> None:
56
+ self.base_url = base_url.rstrip("/")
57
+ self._token = token
58
+ self._api = httpx.Client(
59
+ base_url=self.base_url,
60
+ headers={"User-Agent": USER_AGENT, "Authorization": f"Bearer {token}"},
61
+ timeout=timeout,
62
+ transport=transport,
63
+ )
64
+ self._blob = httpx.Client(
65
+ headers={"User-Agent": USER_AGENT}, timeout=timeout, transport=blob_transport
66
+ )
67
+
68
+ def __repr__(self) -> str:
69
+ return f"HTTP(base_url={self.base_url!r})"
70
+
71
+ def close(self) -> None:
72
+ self._api.close()
73
+ self._blob.close()
74
+
75
+ # --- the API ------------------------------------------------------------------------------
76
+
77
+ def get(self, path: str, *, params: dict[str, Any] | None = None) -> Any:
78
+ return self._request("GET", path, params=params)
79
+
80
+ def post(self, path: str, body: Any = None, *, timeout: float | None = None) -> Any:
81
+ return self._request("POST", path, body=body, timeout=timeout)
82
+
83
+ def patch(self, path: str, body: Any) -> Any:
84
+ return self._request("PATCH", path, body=body)
85
+
86
+ def delete(self, path: str) -> Any:
87
+ return self._request("DELETE", path)
88
+
89
+ def location(self, path: str) -> str:
90
+ """GET a route that answers with a redirect, and return where it points instead of
91
+ following it. The link is the caller's to fetch: it goes to the blob store, and the API
92
+ key must not go with it."""
93
+ response = self._send("GET", path)
94
+ target = response.headers.get("location")
95
+ if response.is_redirect and target:
96
+ return target
97
+ if response.is_success:
98
+ raise PerceptionError(
99
+ response.status_code,
100
+ "invalid_response",
101
+ f"GET {path} answered {response.status_code} without a redirect",
102
+ )
103
+ self._answer(response) # raises the refusal
104
+ raise AssertionError("unreachable") # pragma: no cover
105
+
106
+ def _request(
107
+ self,
108
+ method: str,
109
+ path: str,
110
+ *,
111
+ body: Any = None,
112
+ params: dict[str, Any] | None = None,
113
+ timeout: float | None = None,
114
+ ) -> Any:
115
+ return self._answer(self._send(method, path, body=body, params=params, timeout=timeout))
116
+
117
+ def _send(
118
+ self,
119
+ method: str,
120
+ path: str,
121
+ *,
122
+ body: Any = None,
123
+ params: dict[str, Any] | None = None,
124
+ timeout: float | None = None,
125
+ ) -> httpx.Response:
126
+ """GETs are retried on a failed connection and on 502/503/504. Nothing else is: a POST
127
+ that timed out may have been carried out, and sending it again could do it twice."""
128
+ attempts = GET_ATTEMPTS if method == "GET" else 1
129
+ query = {k: v for k, v in (params or {}).items() if v is not None}
130
+ extra: dict[str, Any] = {} if timeout is None else {"timeout": timeout}
131
+ for attempt in range(1, attempts + 1):
132
+ retry = attempt < attempts
133
+ try:
134
+ response = self._api.request(method, path, json=body, params=query, **extra)
135
+ except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
136
+ if retry:
137
+ self._wait(method, path, attempt, type(exc).__name__)
138
+ continue
139
+ raise APIConnectionError(
140
+ 0, "connection_error", f"{method} {path}: {type(exc).__name__}"
141
+ ) from exc
142
+ except httpx.TransportError as exc:
143
+ raise APIConnectionError(
144
+ 0, "connection_error", f"{method} {path}: {type(exc).__name__}"
145
+ ) from exc
146
+ if retry and response.status_code in GET_RETRY_STATUSES:
147
+ self._wait(method, path, attempt, f"HTTP {response.status_code}")
148
+ continue
149
+ return response
150
+ raise AssertionError("unreachable") # pragma: no cover
151
+
152
+ def _wait(self, method: str, path: str, attempt: int, reason: str) -> None:
153
+ delay = GET_RETRY_DELAYS_S[attempt - 1]
154
+ log.debug(
155
+ "%s %s attempt %d failed (%s); retrying in %ss", method, path, attempt, reason, delay
156
+ )
157
+ _sleep(delay)
158
+
159
+ def _answer(self, response: httpx.Response) -> Any:
160
+ if response.is_success:
161
+ if not response.content:
162
+ return None
163
+ try:
164
+ return response.json()
165
+ except ValueError:
166
+ # a proxy's or a load balancer's page, say: not an answer from the API
167
+ raise PerceptionError(
168
+ response.status_code,
169
+ "invalid_response",
170
+ f"{response.request.method} {response.request.url.path} answered"
171
+ f" {response.status_code} with a body that is not JSON",
172
+ ) from None
173
+ status = response.status_code
174
+ error, detail = _parse_error(response)
175
+ if isinstance(error, str):
176
+ error = self._scrub(error)
177
+ raise error_for_status(status)(status, error, self._scrub(detail))
178
+
179
+ def _scrub(self, text: str | None) -> str | None:
180
+ """An API that echoed the credential back must not put it in an exception message, in
181
+ either the `error` field or the `detail`."""
182
+ if text is None or not self._token:
183
+ return text
184
+ return text.replace(self._token, _REDACTED)
185
+
186
+ # --- the blob store -----------------------------------------------------------------------
187
+
188
+ def put_part(self, url: str, data: bytes, part_number: int) -> str:
189
+ """PUT one part to its pre-signed URL and return its ETag, which `complete` names it by.
190
+
191
+ A failure that can pass (no response, 408, 429 or 5xx) is retried three times after waits
192
+ of 0.5, 1 and 2 s. The URL is never quoted in an error: its signature is a credential."""
193
+ for attempt in range(len(PART_RETRY_DELAYS_S) + 1):
194
+ try:
195
+ response = self._blob.put(url, content=data)
196
+ except httpx.TransportError as exc:
197
+ failure = UploadError(
198
+ 0, "connection_error", f"part {part_number}: {type(exc).__name__}"
199
+ )
200
+ retryable = True
201
+ else:
202
+ if response.is_success:
203
+ etag = response.headers.get("etag")
204
+ if not etag:
205
+ raise UploadError(
206
+ response.status_code,
207
+ "missing_etag",
208
+ f"part {part_number}: the blob store returned no ETag",
209
+ )
210
+ return etag
211
+ status = response.status_code
212
+ match = _S3_CODE.search(response.text)
213
+ failure = UploadError(
214
+ status,
215
+ match.group(1) if match else "upload_failed",
216
+ f"part {part_number} was refused by the blob store",
217
+ )
218
+ retryable = status in (408, 429) or status >= 500
219
+ if not retryable or attempt == len(PART_RETRY_DELAYS_S):
220
+ raise failure
221
+ delay = PART_RETRY_DELAYS_S[attempt]
222
+ log.debug(
223
+ "part %d attempt %d failed (%s); retrying in %ss",
224
+ part_number,
225
+ attempt + 1,
226
+ failure,
227
+ delay,
228
+ )
229
+ _sleep(delay)
230
+ raise AssertionError("unreachable") # pragma: no cover
231
+
232
+
233
+ def _parse_error(response: httpx.Response) -> tuple[Any, str | None]:
234
+ """The API answers a refusal as ``{"error": ..., "detail": "<sentence>"}``; FastAPI's own
235
+ validation answers ``{"detail": [{"loc": [...], "msg": ...}, ...]}``, and an `HTTPException`
236
+ answers ``{"detail": "<sentence>"}``. Anything else is reported as its text."""
237
+ try:
238
+ body = response.json()
239
+ except ValueError:
240
+ text = response.text.strip()
241
+ return None, text[:1000] or None
242
+ if not isinstance(body, dict):
243
+ return None, json.dumps(body)[:1000]
244
+ error = body.get("error")
245
+ raw = body.get("detail")
246
+ if isinstance(raw, list):
247
+ return (error if error is not None else "validation_error"), "; ".join(
248
+ _issue(item) for item in raw
249
+ )
250
+ if raw is None or isinstance(raw, str):
251
+ return error, raw
252
+ return error, json.dumps(raw)
253
+
254
+
255
+ def _issue(item: Any) -> str:
256
+ if not isinstance(item, dict):
257
+ return str(item)
258
+ loc = [str(p) for p in item.get("loc", [])]
259
+ if loc and loc[0] in _LOCATIONS:
260
+ loc = loc[1:]
261
+ msg = str(item.get("msg", ""))
262
+ return f"{'.'.join(loc)}: {msg}" if loc else msg
@@ -0,0 +1,193 @@
1
+ """`AdminClient`: what the engine's operator does with the admin token."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import httpx
9
+
10
+ from ._http import HTTP, seg
11
+ from .client import _body, _setting, _when
12
+ from .models import ApiKey, IssuedApiKey, KeyList
13
+
14
+ if TYPE_CHECKING: # typing.Self is 3.11+; the import is never made at runtime
15
+ from typing_extensions import Self
16
+
17
+
18
+ class AdminClient:
19
+ """A client for the operator's routes, authenticated with the admin token.
20
+
21
+ `base_url` and `admin_token` fall back to ``PERCEPTION_API_URL`` and
22
+ ``PERCEPTION_ADMIN_TOKEN``."""
23
+
24
+ def __init__(
25
+ self,
26
+ base_url: str | None = None,
27
+ admin_token: str | None = None,
28
+ *,
29
+ timeout: float = 30.0,
30
+ transport: httpx.BaseTransport | None = None,
31
+ ) -> None:
32
+ url = _setting(base_url, "PERCEPTION_API_URL", "API URL")
33
+ token = _setting(admin_token, "PERCEPTION_ADMIN_TOKEN", "admin token")
34
+ self._http = HTTP(url, token, timeout=timeout, transport=transport)
35
+ self.tenants = Tenants(self._http)
36
+ self.subjects = Subjects(self._http)
37
+ self.keys = TenantKeys(self._http)
38
+ self.dead_letters = DeadLetters(self._http)
39
+ self.quarantine = Quarantine(self._http)
40
+ self.subscriptions = Subscriptions(self._http)
41
+
42
+ @property
43
+ def base_url(self) -> str:
44
+ return self._http.base_url
45
+
46
+ def __repr__(self) -> str:
47
+ return f"AdminClient(base_url={self.base_url!r})"
48
+
49
+ def __enter__(self) -> Self:
50
+ return self
51
+
52
+ def __exit__(self, *exc: object) -> None:
53
+ self.close()
54
+
55
+ def close(self) -> None:
56
+ self._http.close()
57
+
58
+
59
+ def _tenant(tenant_id: str) -> str:
60
+ return f"/admin/tenants/{seg(tenant_id)}"
61
+
62
+
63
+ class Tenants:
64
+ def __init__(self, http: HTTP) -> None:
65
+ self._http = http
66
+
67
+ def list(self) -> dict[str, Any]:
68
+ """``{"tenants": [{"tenant_id", "created_at"}, ...], "truncated": bool}``, by id, at most
69
+ 200."""
70
+ return self._http.get("/admin/tenants")
71
+
72
+ def create(self, tenant_id: str) -> dict[str, Any]:
73
+ """Create a tenant. Creating one that exists is not an error."""
74
+ return self._http.post("/admin/tenants", {"tenant_id": tenant_id})
75
+
76
+
77
+ class Subjects:
78
+ def __init__(self, http: HTTP) -> None:
79
+ self._http = http
80
+
81
+ def create(self, tenant_id: str, subject_id: str) -> dict[str, Any]:
82
+ """Create a subject (a person, place or thing media is about) in a tenant."""
83
+ return self._http.post(_tenant(tenant_id) + "/subjects", {"subject_id": subject_id})
84
+
85
+
86
+ class TenantKeys:
87
+ """Any tenant's API keys."""
88
+
89
+ def __init__(self, http: HTTP) -> None:
90
+ self._http = http
91
+
92
+ def list(self, tenant_id: str) -> KeyList:
93
+ """The tenant's keys, newest first, revoked and expired ones included; at most 200, with
94
+ `.truncated` saying whether there are more. `NotFoundError` for a tenant that does not
95
+ exist."""
96
+ return KeyList.from_dict(self._http.get(_tenant(tenant_id) + "/api-keys"))
97
+
98
+ def create(
99
+ self,
100
+ tenant_id: str,
101
+ name: str | None = None,
102
+ expires_at: datetime | str | None = None,
103
+ ) -> IssuedApiKey:
104
+ """Issue a key for a tenant; `name` defaults to empty. Its secret, `.api_key`, is returned
105
+ this once."""
106
+ body = _body(name=name, expires_at=_when(expires_at))
107
+ return IssuedApiKey.from_dict(
108
+ self._http.post(_tenant(tenant_id) + "/api-keys", body or None)
109
+ )
110
+
111
+ def revoke(self, tenant_id: str, key_id: str) -> ApiKey:
112
+ """Revoke a key. The operator may revoke any of a tenant's keys; revoking one again keeps
113
+ its first `revoked_at`."""
114
+ path = f"{_tenant(tenant_id)}/api-keys/{seg(key_id)}:revoke"
115
+ return ApiKey.from_dict(self._http.post(path))
116
+
117
+ def rotate(
118
+ self, tenant_id: str, key_id: str, expires_at: datetime | str | None = None
119
+ ) -> IssuedApiKey:
120
+ """Revoke a key and issue its replacement under the same name, in one step. Without
121
+ `expires_at` the new key never expires, even if the old key had an expiry."""
122
+ path = f"{_tenant(tenant_id)}/api-keys/{seg(key_id)}:rotate"
123
+ body = _body(expires_at=_when(expires_at))
124
+ return IssuedApiKey.from_dict(self._http.post(path, body or None))
125
+
126
+
127
+ class DeadLetters:
128
+ """Work that failed for good, kept so it can be retried or given up on."""
129
+
130
+ def __init__(self, http: HTTP) -> None:
131
+ self._http = http
132
+
133
+ def list(self, tenant_id: str, status: str | None = None) -> list[dict[str, Any]]:
134
+ out = self._http.get(_tenant(tenant_id) + "/dead-letters", params={"status": status})
135
+ return out["dead_letters"]
136
+
137
+ def requeue(self, tenant_id: str, dead_letter_id: str) -> dict[str, Any]:
138
+ return self._http.post(f"{_tenant(tenant_id)}/dead-letters/{seg(dead_letter_id)}:requeue")
139
+
140
+ def abandon(
141
+ self, tenant_id: str, dead_letter_id: str, reason: str | None = None
142
+ ) -> dict[str, Any]:
143
+ path = f"{_tenant(tenant_id)}/dead-letters/{seg(dead_letter_id)}:abandon"
144
+ return self._http.post(path, _body(reason=reason) or None)
145
+
146
+
147
+ class Quarantine:
148
+ """Records held back because they failed validation."""
149
+
150
+ def __init__(self, http: HTTP) -> None:
151
+ self._http = http
152
+
153
+ def list(self, tenant_id: str, status: str | None = None) -> list[dict[str, Any]]:
154
+ out = self._http.get(_tenant(tenant_id) + "/quarantine", params={"status": status})
155
+ return out["quarantine"]
156
+
157
+ def resolve(
158
+ self, tenant_id: str, quarantine_id: str, status: str, reason: str
159
+ ) -> dict[str, Any]:
160
+ """`status` is one of repaired, dead_lettered, requeued or abandoned."""
161
+ path = f"{_tenant(tenant_id)}/quarantine/{seg(quarantine_id)}:resolve"
162
+ return self._http.post(path, {"status": status, "reason": reason})
163
+
164
+
165
+ class Subscriptions:
166
+ """Where a subject's outputs are delivered (a webhook or a signal)."""
167
+
168
+ def __init__(self, http: HTTP) -> None:
169
+ self._http = http
170
+
171
+ def _path(self, tenant_id: str, subject_id: str) -> str:
172
+ return f"{_tenant(tenant_id)}/subjects/{seg(subject_id)}/output-subscriptions"
173
+
174
+ def list(self, tenant_id: str, subject_id: str) -> list[dict[str, Any]]:
175
+ return self._http.get(self._path(tenant_id, subject_id))["subscriptions"]
176
+
177
+ def create(
178
+ self,
179
+ tenant_id: str,
180
+ subject_id: str,
181
+ sink: str,
182
+ target: str,
183
+ *,
184
+ secret_ref: str | None = None,
185
+ stream: str | None = None,
186
+ active: bool | None = None,
187
+ ) -> dict[str, Any]:
188
+ body = _body(sink=sink, target=target, secret_ref=secret_ref, stream=stream, active=active)
189
+ return self._http.post(self._path(tenant_id, subject_id), body)
190
+
191
+ def deactivate(self, tenant_id: str, subject_id: str, subscription_id: str) -> dict[str, Any]:
192
+ path = f"{self._path(tenant_id, subject_id)}/{seg(subscription_id)}:deactivate"
193
+ return self._http.post(path)