aice-core 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.
aice_core/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ """Shared HTTP transport, retry, error, and auth primitives for AICE SDKs."""
2
+
3
+ from aice_core.auth import ActingUser, AuthContext, acting_as
4
+ from aice_core.exceptions import (
5
+ AiceError,
6
+ APIConnectionError,
7
+ AiceForbiddenError,
8
+ AuthenticationError,
9
+ InsufficientScopeError,
10
+ NotFoundError,
11
+ RateLimitError,
12
+ ServerError,
13
+ ValidationError,
14
+ )
15
+ from aice_core.pagination import AsyncPage, Page, SyncPage
16
+ from aice_core.transport import (
17
+ IDEMPOTENCY_HEADER,
18
+ NOT_GIVEN,
19
+ AsyncTransport,
20
+ NotGiven,
21
+ SyncTransport,
22
+ )
23
+
24
+ __version__ = "0.3.0"
25
+
26
+ __all__ = [
27
+ "AuthContext",
28
+ "ActingUser",
29
+ "acting_as",
30
+ "SyncTransport",
31
+ "AsyncTransport",
32
+ "NotGiven",
33
+ "NOT_GIVEN",
34
+ "IDEMPOTENCY_HEADER",
35
+ "Page",
36
+ "SyncPage",
37
+ "AsyncPage",
38
+ "AiceError",
39
+ "APIConnectionError",
40
+ "AiceForbiddenError",
41
+ "AuthenticationError",
42
+ "InsufficientScopeError",
43
+ "NotFoundError",
44
+ "RateLimitError",
45
+ "ServerError",
46
+ "ValidationError",
47
+ "__version__",
48
+ ]
aice_core/auth.py ADDED
@@ -0,0 +1,185 @@
1
+ """Auth context: holds the credential and the acting user.
2
+
3
+ The credential is a tenant key: one key per organization, issued by the AICE
4
+ console and accepted by every AICE service. It says nothing about users, so
5
+ each request also names the user it acts for:
6
+
7
+ Authorization: Bearer <tenant key>
8
+ X-User-Id: <uuid> required by agent platform, crawler, knowledge, reco
9
+ X-User-Role: <role> optional (reco: admin/owner/service_role may write/train)
10
+ X-User-Scopes: a,b optional (knowledge: narrows visibility)
11
+
12
+ Set the user once on the client (``user_id=``), or per request with
13
+ :func:`acting_as`, which is safe across threads and asyncio tasks.
14
+
15
+ The credential is a bearer token issued by the AICE control plane.
16
+ When it is a signed token carrying scope claims (the multi-tenant case), this
17
+ class decodes those claims (without verifying verification is the server's
18
+ job) so sub-clients can fail fast on insufficient scope instead of making a
19
+ round trip.
20
+
21
+ Treat this as a *DX* affordance, never as a security boundary.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import base64
27
+ import json
28
+ from collections.abc import Iterable, Iterator
29
+ from contextlib import contextmanager
30
+ from contextvars import ContextVar
31
+ from dataclasses import dataclass
32
+ from typing import Any
33
+
34
+ from aice_core.exceptions import InsufficientScopeError
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ActingUser:
39
+ """Who a request acts for. Sent as X-User-* headers, never put in the key."""
40
+
41
+ user_id: str
42
+ role: str | None = None
43
+ scopes: tuple[str, ...] | None = None
44
+
45
+ def as_headers(self) -> dict[str, str]:
46
+ headers = {"X-User-Id": self.user_id}
47
+ if self.role:
48
+ headers["X-User-Role"] = self.role
49
+ if self.scopes is not None:
50
+ headers["X-User-Scopes"] = ",".join(self.scopes)
51
+ return headers
52
+
53
+
54
+ _acting_user: ContextVar[ActingUser | None] = ContextVar("aice_acting_user", default=None)
55
+
56
+
57
+ @contextmanager
58
+ def acting_as(
59
+ user_id: str,
60
+ *,
61
+ role: str | None = None,
62
+ scopes: Iterable[str] | None = None,
63
+ ) -> Iterator[ActingUser]:
64
+ """Act as ``user_id`` for every AICE call made inside the block.
65
+
66
+ Overrides the client's default user. Scoped to the current thread / asyncio
67
+ task, so one client can serve many users concurrently::
68
+
69
+ with acting_as(request.user.id, role=request.user.role):
70
+ reco.recommend(...)
71
+ """
72
+ user = ActingUser(user_id, role, tuple(scopes) if scopes is not None else None)
73
+ token = _acting_user.set(user)
74
+ try:
75
+ yield user
76
+ finally:
77
+ _acting_user.reset(token)
78
+
79
+
80
+ class AuthContext:
81
+ """Shared credential + acting-user view.
82
+
83
+ Usage::
84
+
85
+ auth = AuthContext(api_key=tenant_key, user_id="3fa85f64-...", user_role="admin")
86
+ headers = auth.as_headers()
87
+ # -> {"Authorization": "Bearer ...", "X-User-Id": "3fa8...", "X-User-Role": "admin"}
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ api_key: str,
93
+ *,
94
+ user_id: str | None = None,
95
+ user_role: str | None = None,
96
+ user_scopes: Iterable[str] | None = None,
97
+ scopes: frozenset[str] | None = None,
98
+ environment: str = "production",
99
+ ) -> None:
100
+ if not api_key:
101
+ raise ValueError("api_key must not be empty.")
102
+ self._api_key = api_key
103
+ self._default_user = (
104
+ ActingUser(user_id, user_role, tuple(user_scopes) if user_scopes is not None else None)
105
+ if user_id
106
+ else None
107
+ )
108
+ self._scopes: frozenset[str] = scopes if scopes is not None else self._decode_scopes(api_key)
109
+ self._environment = environment
110
+
111
+ # ── Public API ─────────────────────────────────────────────────────
112
+
113
+ @property
114
+ def api_key(self) -> str:
115
+ return self._api_key
116
+
117
+ @property
118
+ def scopes(self) -> frozenset[str]:
119
+ """The set of service scopes this credential claims to carry.
120
+ Empty when the credential is opaque (e.g. not a JWT)."""
121
+ return self._scopes
122
+
123
+ @property
124
+ def environment(self) -> str:
125
+ return self._environment
126
+
127
+ @property
128
+ def acting_user(self) -> ActingUser | None:
129
+ """The user this request acts for: an :func:`acting_as` block wins over the client default."""
130
+ return _acting_user.get() or self._default_user
131
+
132
+ def as_headers(self) -> dict[str, str]:
133
+ """Return the HTTP headers needed to authenticate a single request."""
134
+ headers = {"Authorization": f"Bearer {self._api_key}"}
135
+ user = self.acting_user
136
+ if user is not None:
137
+ headers.update(user.as_headers())
138
+ return headers
139
+
140
+ def require_scope(self, service: str) -> None:
141
+ """Fail fast when the credential is not scoped for ``service``.
142
+
143
+ No-op when the credential is opaque (we can't tell client-side) —
144
+ the server will still reject it on call.
145
+ """
146
+ if not self._scopes:
147
+ return
148
+ if service not in self._scopes and "*" not in self._scopes:
149
+ raise InsufficientScopeError(
150
+ f"This credential is not scoped for '{service}'. "
151
+ f"Granted scopes: {sorted(self._scopes)}"
152
+ )
153
+
154
+ def is_scoped_for(self, service: str) -> bool:
155
+ """Non-throwing scope check for conditional UI / feature discovery."""
156
+ if not self._scopes:
157
+ return True
158
+ return service in self._scopes or "*" in self._scopes
159
+
160
+ # ── Internals ──────────────────────────────────────────────────────
161
+
162
+ @staticmethod
163
+ def _decode_scopes(token: str) -> frozenset[str]:
164
+ """Best-effort scope extraction.
165
+
166
+ Handles JWT-like ``<hdr>.<payload>.<sig>`` shapes; anything else
167
+ yields an empty frozenset meaning "we can't tell, defer to server."
168
+ Signature verification deliberately does NOT happen here.
169
+ """
170
+ parts = token.split(".")
171
+ if len(parts) != 3:
172
+ return frozenset()
173
+ try:
174
+ padded = parts[1] + "=" * (-len(parts[1]) % 4)
175
+ claims: dict[str, Any] = json.loads(
176
+ base64.urlsafe_b64decode(padded).decode("utf-8")
177
+ )
178
+ except Exception:
179
+ return frozenset()
180
+ raw = claims.get("scope") or claims.get("scp") or []
181
+ if isinstance(raw, str):
182
+ return frozenset(raw.split())
183
+ if isinstance(raw, list):
184
+ return frozenset(str(s) for s in raw)
185
+ return frozenset()
@@ -0,0 +1,78 @@
1
+ """Typed error hierarchy shared by every AICE Python SDK.
2
+
3
+ Every raised error carries ``status_code`` (HTTP status, when one came back),
4
+ ``code`` (the service's own error code string, when provided), and
5
+ ``request_id`` (the ``X-Request-Id`` the server stamped on the response), so
6
+ callers can reference a failing call precisely in support requests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+
14
+ class AiceError(Exception):
15
+ """Base class for every error the AICE SDKs raise."""
16
+
17
+ def __init__(
18
+ self,
19
+ message: str,
20
+ *,
21
+ status_code: int | None = None,
22
+ code: str | None = None,
23
+ request_id: str | None = None,
24
+ details: dict[str, Any] | None = None,
25
+ ) -> None:
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+ self.code = code
29
+ self.request_id = request_id
30
+ self.details = details or {}
31
+
32
+ def __repr__(self) -> str:
33
+ return (
34
+ f"{type(self).__name__}(status={self.status_code!r}, "
35
+ f"code={self.code!r}, request_id={self.request_id!r}, "
36
+ f"message={str(self)!r})"
37
+ )
38
+
39
+
40
+ class APIConnectionError(AiceError):
41
+ """No response was received network failure, DNS, refused connection, etc."""
42
+
43
+
44
+ class AuthenticationError(AiceError):
45
+ """401 credential missing, invalid, or expired."""
46
+
47
+
48
+ class AiceForbiddenError(AiceError):
49
+ """403 authenticated but not authorised for this resource."""
50
+
51
+
52
+ class NotFoundError(AiceError):
53
+ """404 resource does not exist."""
54
+
55
+
56
+ class ValidationError(AiceError):
57
+ """400 or 422 the request body/params failed validation. ``details``
58
+ carries field-level errors when the server returned them."""
59
+
60
+
61
+ class RateLimitError(AiceError):
62
+ """429 the server asked us to slow down. ``retry_after`` mirrors the
63
+ ``Retry-After`` header (seconds) when present."""
64
+
65
+ def __init__(self, *args: Any, retry_after: float | None = None, **kwargs: Any) -> None:
66
+ super().__init__(*args, **kwargs)
67
+ self.retry_after = retry_after
68
+
69
+
70
+ class ServerError(AiceError):
71
+ """5xx the service failed. These are always retryable by the transport."""
72
+
73
+
74
+ class InsufficientScopeError(AiceError):
75
+ """Raised client-side when the credential is not scoped for the requested
76
+ service. This is a DX aid so developers don't have to wait for a 403 from
77
+ the server to find out it is *not* a security boundary (the server still
78
+ validates scopes independently on every call)."""
@@ -0,0 +1,94 @@
1
+ """Generic paginated iterators for AICE list endpoints.
2
+
3
+ Both cursor-based and offset-based pagination are supported behind the same
4
+ ``SyncPage`` / ``AsyncPage`` interface. Service SDKs wire their own page
5
+ fetcher in via callables; this module knows nothing about specific response
6
+ shapes.
7
+
8
+ **Status as of this writing: not yet wired into any service client.**
9
+ Every ``list()``/``list_pages()`` method across every service (checked
10
+ across the whole repo) currently returns a single page's raw array from
11
+ one request, with no cursor follow-through via this module. That's either
12
+ fine (the backend doesn't paginate that endpoint) or a real gap (a cursor
13
+ is being silently dropped) telling the two apart requires checking the
14
+ actual backend route, which isn't possible from this package alone. See
15
+ ``docs/conventions.md``'s "Pagination" section before wiring this into a
16
+ service: confirm with the backend owner first.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
22
+ from typing import Any, Generic, TypeVar
23
+
24
+ T = TypeVar("T")
25
+
26
+
27
+ class Page(Generic[T]):
28
+ """One page of a list response.
29
+
30
+ Iterating a Page yields every item across every page, fetching subsequent
31
+ pages transparently via the bound fetcher.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ *,
37
+ data: list[T],
38
+ has_more: bool,
39
+ next_cursor: str | None = None,
40
+ raw: dict[str, Any] | None = None,
41
+ ) -> None:
42
+ self.data = data
43
+ self.has_more = has_more
44
+ self.next_cursor = next_cursor
45
+ self.raw = raw or {}
46
+
47
+
48
+ class SyncPage(Page[T]):
49
+ """A page that knows how to fetch its own successor (synchronously)."""
50
+
51
+ def __init__(
52
+ self,
53
+ *,
54
+ fetch_next: Callable[[str | None], "SyncPage[T]"],
55
+ data: list[T],
56
+ has_more: bool,
57
+ next_cursor: str | None = None,
58
+ raw: dict[str, Any] | None = None,
59
+ ) -> None:
60
+ super().__init__(data=data, has_more=has_more, next_cursor=next_cursor, raw=raw)
61
+ self._fetch_next = fetch_next
62
+
63
+ def __iter__(self) -> Iterator[T]:
64
+ page: SyncPage[T] | None = self
65
+ while page is not None:
66
+ yield from page.data
67
+ if not page.has_more:
68
+ return
69
+ page = page._fetch_next(page.next_cursor)
70
+
71
+
72
+ class AsyncPage(Page[T]):
73
+ """A page that knows how to fetch its own successor (asynchronously)."""
74
+
75
+ def __init__(
76
+ self,
77
+ *,
78
+ fetch_next: Callable[[str | None], Awaitable["AsyncPage[T]"]],
79
+ data: list[T],
80
+ has_more: bool,
81
+ next_cursor: str | None = None,
82
+ raw: dict[str, Any] | None = None,
83
+ ) -> None:
84
+ super().__init__(data=data, has_more=has_more, next_cursor=next_cursor, raw=raw)
85
+ self._fetch_next = fetch_next
86
+
87
+ async def __aiter__(self) -> AsyncIterator[T]:
88
+ page: AsyncPage[T] | None = self
89
+ while page is not None:
90
+ for item in page.data:
91
+ yield item
92
+ if not page.has_more:
93
+ return
94
+ page = await self._fetch_next(page.next_cursor)
aice_core/py.typed ADDED
File without changes
aice_core/transport.py ADDED
@@ -0,0 +1,479 @@
1
+ """The shared HTTP transport every AICE Python SDK funnels through.
2
+
3
+ Handles auth injection, retries with exponential backoff + jitter, response
4
+ parsing, idempotency-key handling for mutating requests, and mapping HTTP
5
+ status codes to typed exceptions. Per-service SDKs build thin resource
6
+ classes on top of this; nothing in this file knows about any specific
7
+ service.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import random
13
+ import time
14
+ import uuid
15
+ from typing import Any, Awaitable, Callable
16
+
17
+ import httpx
18
+
19
+ from aice_core.auth import AuthContext
20
+ from aice_core.exceptions import (
21
+ AiceError,
22
+ APIConnectionError,
23
+ AiceForbiddenError,
24
+ AuthenticationError,
25
+ NotFoundError,
26
+ RateLimitError,
27
+ ServerError,
28
+ ValidationError,
29
+ )
30
+
31
+ _DEFAULT_TIMEOUT = 30.0
32
+ _DEFAULT_MAX_RETRIES = 3
33
+ _BASE_RETRY_DELAY_SECONDS = 0.5
34
+ _MAX_RETRY_DELAY_SECONDS = 10.0
35
+ _USER_AGENT_TEMPLATE = "aice-sdk-python/{version} ({service})"
36
+
37
+ # Methods that are NOT inherently idempotent at the HTTP level. A request
38
+ # using one of these is only safe to auto-retry on a transient failure if
39
+ # the server can deduplicate it which is what the idempotency key is for.
40
+ _MUTATING_METHODS = frozenset({"POST", "PATCH"})
41
+
42
+ IDEMPOTENCY_HEADER = "Idempotency-Key"
43
+
44
+
45
+ class NotGiven:
46
+ """Sentinel distinguishing 'no idempotency key argument passed' (in
47
+ which case one is auto-generated for mutating methods) from an explicit
48
+ ``idempotency_key=None`` (which opts the call out of auto-retry
49
+ entirely the caller is saying "do not retry this for me, ever, even
50
+ on a transient failure").
51
+ """
52
+
53
+ def __repr__(self) -> str: # pragma: no cover - debugging aid only
54
+ return "NOT_GIVEN"
55
+
56
+
57
+ NOT_GIVEN = NotGiven()
58
+
59
+
60
+ def _retryable_status(status: int) -> bool:
61
+ return status == 429 or status >= 500
62
+
63
+
64
+ def _backoff(attempt: int, retry_after: float | None = None) -> float:
65
+ """Exponential backoff with jitter; honor Retry-After when present."""
66
+ if retry_after is not None:
67
+ return retry_after
68
+ delay = min(_BASE_RETRY_DELAY_SECONDS * (2**attempt), _MAX_RETRY_DELAY_SECONDS)
69
+ return delay + random.uniform(0, 0.5)
70
+
71
+
72
+ def _request_id_from(response: httpx.Response) -> str | None:
73
+ return response.headers.get("X-Request-Id") or response.headers.get("x-request-id")
74
+
75
+
76
+ def _map_error(response: httpx.Response) -> AiceError:
77
+ """Map an HTTP error response to a typed exception."""
78
+ request_id = _request_id_from(response)
79
+ status = response.status_code
80
+ payload: dict[str, Any] = {}
81
+ try:
82
+ parsed = response.json()
83
+ if isinstance(parsed, dict):
84
+ payload = parsed
85
+ except Exception:
86
+ pass
87
+
88
+ message = (
89
+ payload.get("message")
90
+ or payload.get("detail")
91
+ or payload.get("error")
92
+ or response.text
93
+ or f"HTTP {status}"
94
+ )
95
+ code = payload.get("code") if isinstance(payload.get("code"), str) else None
96
+ details = payload.get("details") if isinstance(payload.get("details"), dict) else None
97
+
98
+ common = dict(status_code=status, code=code, request_id=request_id, details=details)
99
+
100
+ if status == 401:
101
+ return AuthenticationError(message, **common)
102
+ if status == 403:
103
+ return AiceForbiddenError(message, **common)
104
+ if status == 404:
105
+ return NotFoundError(message, **common)
106
+ if status == 429:
107
+ retry_after_hdr = response.headers.get("Retry-After")
108
+ retry_after = float(retry_after_hdr) if retry_after_hdr else None
109
+ return RateLimitError(message, retry_after=retry_after, **common)
110
+ if status in (400, 422):
111
+ return ValidationError(message, **common)
112
+ if status >= 500:
113
+ return ServerError(message, **common)
114
+ return AiceError(message, **common)
115
+
116
+
117
+ def _parse_body(response: httpx.Response) -> Any:
118
+ if response.status_code == 204 or not response.content:
119
+ return None
120
+ try:
121
+ return response.json()
122
+ except ValueError:
123
+ return response.text
124
+
125
+
126
+ def _resolve_idempotency(
127
+ method: str, idempotency_key: str | None | NotGiven
128
+ ) -> tuple[str | None, bool]:
129
+ """Return (key_to_send, retry_eligible) for a request.
130
+
131
+ - Non-mutating methods (GET/PUT/DELETE/...) are always retry-eligible;
132
+ no key is attached since it's meaningless for them.
133
+ - Mutating methods (POST/PATCH) get an auto-generated key by default,
134
+ making them retry-eligible. Passing ``idempotency_key=None`` explicitly
135
+ opts out of both the header and the retry.
136
+ - Passing an explicit string key is always honored and makes the call
137
+ retry-eligible (the caller is asserting the server can dedupe on it).
138
+ """
139
+ method = method.upper()
140
+ if method not in _MUTATING_METHODS:
141
+ return None, True
142
+
143
+ if idempotency_key is NOT_GIVEN:
144
+ return uuid.uuid4().hex, True
145
+ if idempotency_key is None:
146
+ return None, False
147
+ return idempotency_key, True # type: ignore[return-value]
148
+
149
+
150
+ class _BaseTransport:
151
+ """Shared init/close logic; sync/async concrete subclasses live below."""
152
+
153
+ def __init__(
154
+ self,
155
+ *,
156
+ base_url: str,
157
+ auth: AuthContext,
158
+ service: str,
159
+ timeout: float = _DEFAULT_TIMEOUT,
160
+ max_retries: int = _DEFAULT_MAX_RETRIES,
161
+ default_headers: dict[str, str] | None = None,
162
+ http_client: httpx.Client | httpx.AsyncClient | None = None,
163
+ ) -> None:
164
+ self._base_url = base_url.rstrip("/")
165
+ self._auth = auth
166
+ self._service = service
167
+ self._timeout = timeout
168
+ self._max_retries = max_retries
169
+ self._default_headers = default_headers or {}
170
+ self._injected_client = http_client # caller-managed; we don't close it
171
+
172
+ def _build_headers(
173
+ self,
174
+ extra: dict[str, str] | None = None,
175
+ *,
176
+ omit_content_type: bool = False,
177
+ ) -> dict[str, str]:
178
+ headers = {
179
+ "User-Agent": _USER_AGENT_TEMPLATE.format(
180
+ version=_core_version(), service=self._service
181
+ ),
182
+ "X-Request-Id": uuid.uuid4().hex,
183
+ **self._auth.as_headers(),
184
+ **self._default_headers,
185
+ }
186
+ if not omit_content_type:
187
+ headers["Content-Type"] = "application/json"
188
+ if extra:
189
+ headers.update(extra)
190
+ return headers
191
+
192
+
193
+ class SyncTransport(_BaseTransport):
194
+ """Sync transport (uses ``httpx.Client``)."""
195
+
196
+ def __init__(self, **kwargs: Any) -> None:
197
+ super().__init__(**kwargs)
198
+ self._client: httpx.Client = (
199
+ self._injected_client # type: ignore[assignment]
200
+ if isinstance(self._injected_client, httpx.Client)
201
+ else httpx.Client(base_url=self._base_url, timeout=self._timeout)
202
+ )
203
+
204
+ def close(self) -> None:
205
+ if not isinstance(self._injected_client, httpx.Client):
206
+ self._client.close()
207
+
208
+ def __enter__(self) -> "SyncTransport":
209
+ return self
210
+
211
+ def __exit__(self, *exc: Any) -> None:
212
+ self.close()
213
+
214
+ def _execute(
215
+ self,
216
+ do_request: Callable[[], httpx.Response],
217
+ *,
218
+ retry_eligible: bool,
219
+ ) -> Any:
220
+ """Shared retry loop for both ``request`` and ``request_multipart``.
221
+
222
+ ``retry_eligible`` gates retries for transient failures (network
223
+ errors, 429, 5xx). A non-retry-eligible call (a mutating request
224
+ with no idempotency key) still gets exactly one attempt it just
225
+ surfaces the failure immediately instead of retrying blind.
226
+ """
227
+ max_attempts = self._max_retries + 1 if retry_eligible else 1
228
+ last_exc: BaseException | None = None
229
+
230
+ for attempt in range(max_attempts):
231
+ try:
232
+ response = do_request()
233
+ except (
234
+ httpx.ConnectError,
235
+ httpx.ReadTimeout,
236
+ httpx.WriteTimeout,
237
+ httpx.PoolTimeout,
238
+ ) as exc:
239
+ last_exc = exc
240
+ if not retry_eligible or attempt >= max_attempts - 1:
241
+ raise APIConnectionError(
242
+ f"Could not reach {self._base_url}: {exc}"
243
+ ) from exc
244
+ time.sleep(_backoff(attempt))
245
+ continue
246
+
247
+ if response.status_code < 400:
248
+ return _parse_body(response)
249
+
250
+ if (
251
+ not retry_eligible
252
+ or not _retryable_status(response.status_code)
253
+ or attempt >= max_attempts - 1
254
+ ):
255
+ raise _map_error(response)
256
+
257
+ retry_after = None
258
+ if response.status_code == 429:
259
+ ra = response.headers.get("Retry-After")
260
+ if ra:
261
+ try:
262
+ retry_after = float(ra)
263
+ except ValueError:
264
+ pass
265
+ time.sleep(_backoff(attempt, retry_after))
266
+
267
+ raise APIConnectionError(f"Request failed after {max_attempts} attempt(s)") from last_exc
268
+
269
+ def request(
270
+ self,
271
+ method: str,
272
+ path: str,
273
+ *,
274
+ json: Any = None,
275
+ params: dict[str, Any] | None = None,
276
+ headers: dict[str, str] | None = None,
277
+ timeout: float | None = None,
278
+ idempotency_key: str | None | NotGiven = NOT_GIVEN,
279
+ ) -> Any:
280
+ """Issue one HTTP call with retries, return the decoded body.
281
+
282
+ For POST/PATCH, an idempotency key is auto-generated and sent
283
+ unless ``idempotency_key=None`` is passed explicitly, in which case
284
+ the call is attempted exactly once with no auto-retry on transient
285
+ failure. Pass an explicit string to reuse a caller-managed key
286
+ (e.g. to make a logically-repeated call dedupe with a prior one).
287
+
288
+ Raises a subclass of :class:`AiceError` on any non-2xx response and
289
+ :class:`APIConnectionError` on network failures after retries are
290
+ exhausted.
291
+ """
292
+ key, retry_eligible = _resolve_idempotency(method, idempotency_key)
293
+ extra_headers = dict(headers or {})
294
+ if key:
295
+ extra_headers[IDEMPOTENCY_HEADER] = key
296
+ hdrs = self._build_headers(extra_headers)
297
+
298
+ return self._execute(
299
+ lambda: self._client.request(
300
+ method,
301
+ path,
302
+ json=json,
303
+ params=params,
304
+ headers=hdrs,
305
+ timeout=timeout or self._timeout,
306
+ ),
307
+ retry_eligible=retry_eligible,
308
+ )
309
+
310
+ def request_multipart(
311
+ self,
312
+ path: str,
313
+ *,
314
+ files: dict[str, Any],
315
+ data: dict[str, Any] | None = None,
316
+ timeout: float | None = None,
317
+ idempotency_key: str | None | NotGiven = NOT_GIVEN,
318
+ ) -> Any:
319
+ """POST a multipart/form-data body (file uploads). Shares auth,
320
+ retry, idempotency, and error mapping with ``request``; differs
321
+ only in body encoding. See ``request`` for idempotency-key
322
+ semantics multipart calls are always POST, so they're subject to
323
+ the same auto-key-and-retry-by-default behavior.
324
+ """
325
+ key, retry_eligible = _resolve_idempotency("POST", idempotency_key)
326
+ extra_headers: dict[str, str] = {}
327
+ if key:
328
+ extra_headers[IDEMPOTENCY_HEADER] = key
329
+ hdrs = self._build_headers(extra_headers, omit_content_type=True)
330
+
331
+ return self._execute(
332
+ lambda: self._client.post(
333
+ path,
334
+ files=files,
335
+ data=data,
336
+ headers=hdrs,
337
+ timeout=timeout or self._timeout,
338
+ ),
339
+ retry_eligible=retry_eligible,
340
+ )
341
+
342
+
343
+ class AsyncTransport(_BaseTransport):
344
+ """Async transport (uses ``httpx.AsyncClient``)."""
345
+
346
+ def __init__(self, **kwargs: Any) -> None:
347
+ super().__init__(**kwargs)
348
+ self._client: httpx.AsyncClient = (
349
+ self._injected_client # type: ignore[assignment]
350
+ if isinstance(self._injected_client, httpx.AsyncClient)
351
+ else httpx.AsyncClient(base_url=self._base_url, timeout=self._timeout)
352
+ )
353
+
354
+ async def aclose(self) -> None:
355
+ if not isinstance(self._injected_client, httpx.AsyncClient):
356
+ await self._client.aclose()
357
+
358
+ async def __aenter__(self) -> "AsyncTransport":
359
+ return self
360
+
361
+ async def __aexit__(self, *exc: Any) -> None:
362
+ await self.aclose()
363
+
364
+ async def _execute(
365
+ self,
366
+ do_request: Callable[[], Awaitable[httpx.Response]],
367
+ *,
368
+ retry_eligible: bool,
369
+ ) -> Any:
370
+ """Async mirror of ``SyncTransport._execute``; see there for the
371
+ idempotency/retry-eligibility rationale.
372
+ """
373
+ import asyncio
374
+
375
+ max_attempts = self._max_retries + 1 if retry_eligible else 1
376
+ last_exc: BaseException | None = None
377
+
378
+ for attempt in range(max_attempts):
379
+ try:
380
+ response = await do_request()
381
+ except (
382
+ httpx.ConnectError,
383
+ httpx.ReadTimeout,
384
+ httpx.WriteTimeout,
385
+ httpx.PoolTimeout,
386
+ ) as exc:
387
+ last_exc = exc
388
+ if not retry_eligible or attempt >= max_attempts - 1:
389
+ raise APIConnectionError(
390
+ f"Could not reach {self._base_url}: {exc}"
391
+ ) from exc
392
+ await asyncio.sleep(_backoff(attempt))
393
+ continue
394
+
395
+ if response.status_code < 400:
396
+ return _parse_body(response)
397
+
398
+ if (
399
+ not retry_eligible
400
+ or not _retryable_status(response.status_code)
401
+ or attempt >= max_attempts - 1
402
+ ):
403
+ raise _map_error(response)
404
+
405
+ retry_after = None
406
+ if response.status_code == 429:
407
+ ra = response.headers.get("Retry-After")
408
+ if ra:
409
+ try:
410
+ retry_after = float(ra)
411
+ except ValueError:
412
+ pass
413
+ await asyncio.sleep(_backoff(attempt, retry_after))
414
+
415
+ raise APIConnectionError(f"Request failed after {max_attempts} attempt(s)") from last_exc
416
+
417
+ async def request(
418
+ self,
419
+ method: str,
420
+ path: str,
421
+ *,
422
+ json: Any = None,
423
+ params: dict[str, Any] | None = None,
424
+ headers: dict[str, str] | None = None,
425
+ timeout: float | None = None,
426
+ idempotency_key: str | None | NotGiven = NOT_GIVEN,
427
+ ) -> Any:
428
+ """Async version of ``SyncTransport.request``. See there for
429
+ idempotency-key semantics."""
430
+ key, retry_eligible = _resolve_idempotency(method, idempotency_key)
431
+ extra_headers = dict(headers or {})
432
+ if key:
433
+ extra_headers[IDEMPOTENCY_HEADER] = key
434
+ hdrs = self._build_headers(extra_headers)
435
+
436
+ async def _do() -> httpx.Response:
437
+ return await self._client.request(
438
+ method,
439
+ path,
440
+ json=json,
441
+ params=params,
442
+ headers=hdrs,
443
+ timeout=timeout or self._timeout,
444
+ )
445
+
446
+ return await self._execute(_do, retry_eligible=retry_eligible)
447
+
448
+ async def request_multipart(
449
+ self,
450
+ path: str,
451
+ *,
452
+ files: dict[str, Any],
453
+ data: dict[str, Any] | None = None,
454
+ timeout: float | None = None,
455
+ idempotency_key: str | None | NotGiven = NOT_GIVEN,
456
+ ) -> Any:
457
+ """Async version of ``SyncTransport.request_multipart``."""
458
+ key, retry_eligible = _resolve_idempotency("POST", idempotency_key)
459
+ extra_headers: dict[str, str] = {}
460
+ if key:
461
+ extra_headers[IDEMPOTENCY_HEADER] = key
462
+ hdrs = self._build_headers(extra_headers, omit_content_type=True)
463
+
464
+ async def _do() -> httpx.Response:
465
+ return await self._client.post(
466
+ path,
467
+ files=files,
468
+ data=data,
469
+ headers=hdrs,
470
+ timeout=timeout or self._timeout,
471
+ )
472
+
473
+ return await self._execute(_do, retry_eligible=retry_eligible)
474
+
475
+
476
+ def _core_version() -> str:
477
+ from aice_core import __version__
478
+
479
+ return __version__
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: aice-core
3
+ Version: 0.3.0
4
+ Summary: Shared HTTP transport, retry, error and auth primitives for the AICE Python SDKs
5
+ Author-email: Adanian Labs <engineering@adanianlabs.io>
6
+ License: MIT
7
+ Keywords: aice,http,sdk,transport
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: pydantic>=2.0
18
+ Requires-Dist: typing-extensions>=4.0; python_version < '3.11'
19
+ Provides-Extra: dev
20
+ Requires-Dist: mypy>=1.10; extra == 'dev'
21
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
22
+ Requires-Dist: pytest>=8.3; extra == 'dev'
23
+ Requires-Dist: respx>=0.21; extra == 'dev'
24
+ Requires-Dist: ruff>=0.4; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # aice-core
28
+
29
+ Shared primitives for every AICE Python SDK: HTTP transport, retry/backoff,
30
+ typed errors, and auth context. Each service SDK (`aice-reco-sdk`,
31
+ `aice-knowledge`, `aice-crawler`, …) depends on this package; nothing in here
32
+ is service-specific.
33
+
34
+ ## What lives here
35
+
36
+ - **`AuthContext`** holds the API key, decodes service scopes, raises
37
+ `InsufficientScopeError` client-side before any request goes out.
38
+ - **`SyncTransport` / `AsyncTransport`** the single `_request()` entry point
39
+ every service client routes through. Injects auth, handles retries,
40
+ maps HTTP errors to typed exceptions, sets `User-Agent`.
41
+ - **Error hierarchy** (`aice_core.exceptions`) one shared set of errors.
42
+ - **`Page[T]`** generic paginated iterator (`SyncPage` / `AsyncPage`).
43
+
44
+ ## What doesn't live here
45
+
46
+ Service-specific endpoints, request/response models, or resource classes.
47
+ Those are in their own packages under `python/<service>/`.
48
+
49
+ ## Why this exists
50
+
51
+ Six different implementations of "retry on 5xx with exponential backoff, map
52
+ 401 to AuthError" is five too many. Fixing retry once, here, fixes retry
53
+ everywhere.
@@ -0,0 +1,9 @@
1
+ aice_core/__init__.py,sha256=mc2h7kPa5ngiyhhWeGMgsA_MxI9CKHBqHAHtQvx8ihc,1027
2
+ aice_core/auth.py,sha256=go4-S4k4rE4udhQalMHhXJao91Y8UW49OArhwvoooZg,6682
3
+ aice_core/exceptions.py,sha256=Oh2_N-5p5OFn2Hurs-KRfbb-delStYz6Nb0tzkcY-_A,2491
4
+ aice_core/pagination.py,sha256=t1iOR7i4DZAVZ9e4OPA8iXSx-wTeuRn2WDXPjlEiJL8,3129
5
+ aice_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ aice_core/transport.py,sha256=1_Apdv9oGah5lKutX_f7hdAlWhp5H54bf_MibedQ_1w,16223
7
+ aice_core-0.3.0.dist-info/METADATA,sha256=zl46tqtS1TxpHhXTzyi68PSodw23tg98w6yWmT-YRdM,2097
8
+ aice_core-0.3.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ aice_core-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any