aice-core 0.3.0__tar.gz

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,28 @@
1
+ # Python bytecode / caches
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+
11
+ # Virtualenvs & editors
12
+ .venv/
13
+ .env
14
+ .env.*
15
+ !.env.example
16
+ .vscode/
17
+ .idea/
18
+ .DS_Store
19
+
20
+ # Build artifacts
21
+ build/
22
+ dist/
23
+ *.egg-info/
24
+ node_modules/
25
+ *.tsbuildinfo
26
+
27
+ # uv / pnpm lockfiles tracked per-package don't ignore them.
28
+ _skills
@@ -0,0 +1,68 @@
1
+ # Changelog aice-core
2
+
3
+ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
4
+
5
+ ## 0.3.0
6
+
7
+ ### Changed BREAKING
8
+ - Renamed `PermissionError` → `AiceForbiddenError` (the 403 error class).
9
+ The old name shadowed Python's builtin `PermissionError`, which could
10
+ silently conflate an AICE API 403 with a real filesystem/OS permission
11
+ error caught in the same `except` block. No aliasing/backward-compat
12
+ shim was added this is a straightforward rename with no behavior
13
+ change, and per this repo's pre-1.0 convention (see
14
+ `docs/conventions.md`) a MINOR bump is the "notice this" signal in lieu
15
+ of a MAJOR one.
16
+
17
+ **Migration:** `from aice_core import PermissionError` →
18
+ `from aice_core import AiceForbiddenError`. Same for
19
+ `aice_core.exceptions.PermissionError`. No other behavior changed —
20
+ still raised for 403 responses, still carries the same
21
+ `status_code`/`code`/`request_id`/`details` fields.
22
+
23
+ Checked every package in this monorepo: only `aice-sandbox` referenced
24
+ this symbol directly (internally, for error translation not part of
25
+ its own public API), and it's updated in this same change. No other
26
+ package needed a code change, but every package's `aice-core` dependency
27
+ floor is bumped to `>=0.3.0,<0.4` regardless, to avoid a
28
+ cross-package dependency-resolution conflict if `aice-sandbox` (now
29
+ requiring `>=0.3.0`) and any other package (previously allowing `<0.3`)
30
+ are ever installed into the same environment.
31
+
32
+ ## 0.2.0
33
+
34
+ ### Added
35
+ - Idempotency-key support on `SyncTransport.request` / `AsyncTransport.request`
36
+ and `.request_multipart`:
37
+ - `POST`/`PATCH` requests now auto-generate an `Idempotency-Key` header by
38
+ default, and the auto-retry-on-transient-failure behavior now requires
39
+ that key to be present. Previously, `POST`/`PATCH` were retried on
40
+ 5xx/429/network failure with no deduplication signal at all.
41
+ - Pass `idempotency_key=None` to opt a call out entirely it will be
42
+ attempted exactly once and any transient failure surfaces immediately
43
+ instead of being retried blind.
44
+ - Pass an explicit string to reuse a caller-managed key.
45
+ - `GET`/`PUT`/`DELETE` are unaffected always retry-eligible, no key
46
+ attached, since they're idempotent by HTTP semantics already.
47
+ - New public exports: `NOT_GIVEN`, `NotGiven`, `IDEMPOTENCY_HEADER`.
48
+
49
+ ### Changed
50
+ - `SyncTransport`/`AsyncTransport`'s retry loop was refactored into one
51
+ shared `_execute` helper per sync/async, replacing four near-duplicate
52
+ copies (`request` and `request_multipart` each had their own). No
53
+ behavior change for existing non-mutating calls.
54
+ - The `APIConnectionError` message on retry exhaustion changed from
55
+ `"Request failed after N retries"` to `"Request failed after N
56
+ attempt(s)"`, to stay accurate for a call that made exactly one attempt
57
+ (no retry eligibility). Update anything matching this message by exact
58
+ string.
59
+
60
+ ### Migration notes
61
+ - This is a behavior change for every existing `POST`/`PATCH` call across
62
+ every dependent package that doesn't explicitly opt out: those calls now
63
+ send an `Idempotency-Key` header they didn't send before. Safe regardless
64
+ of whether the receiving service understands the header yet (an
65
+ unrecognized header is ignored), but it only actually prevents a
66
+ duplicate once that service implements deduplication on it.
67
+ - Dependent packages must bump their `aice-core` floor to `>=0.2.0` to use
68
+ the new `idempotency_key` parameter.
@@ -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,27 @@
1
+ # aice-core
2
+
3
+ Shared primitives for every AICE Python SDK: HTTP transport, retry/backoff,
4
+ typed errors, and auth context. Each service SDK (`aice-reco-sdk`,
5
+ `aice-knowledge`, `aice-crawler`, …) depends on this package; nothing in here
6
+ is service-specific.
7
+
8
+ ## What lives here
9
+
10
+ - **`AuthContext`** holds the API key, decodes service scopes, raises
11
+ `InsufficientScopeError` client-side before any request goes out.
12
+ - **`SyncTransport` / `AsyncTransport`** the single `_request()` entry point
13
+ every service client routes through. Injects auth, handles retries,
14
+ maps HTTP errors to typed exceptions, sets `User-Agent`.
15
+ - **Error hierarchy** (`aice_core.exceptions`) one shared set of errors.
16
+ - **`Page[T]`** generic paginated iterator (`SyncPage` / `AsyncPage`).
17
+
18
+ ## What doesn't live here
19
+
20
+ Service-specific endpoints, request/response models, or resource classes.
21
+ Those are in their own packages under `python/<service>/`.
22
+
23
+ ## Why this exists
24
+
25
+ Six different implementations of "retry on 5xx with exponential backoff, map
26
+ 401 to AuthError" is five too many. Fixing retry once, here, fixes retry
27
+ everywhere.
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "aice-core"
7
+ version = "0.3.0"
8
+ description = "Shared HTTP transport, retry, error and auth primitives for the AICE Python SDKs"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Adanian Labs", email = "engineering@adanianlabs.io" },
14
+ ]
15
+ keywords = ["aice", "sdk", "http", "transport"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = [
26
+ "httpx>=0.27",
27
+ "pydantic>=2.0",
28
+ "typing-extensions>=4.0; python_version < '3.11'",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest>=8.3",
34
+ "pytest-asyncio>=0.24",
35
+ "respx>=0.21",
36
+ "mypy>=1.10",
37
+ "ruff>=0.4",
38
+ ]
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/aice_core"]
42
+
43
+ [tool.pytest.ini_options]
44
+ asyncio_mode = "auto"
45
+ testpaths = ["tests"]
46
+
47
+ [tool.ruff]
48
+ line-length = 100
49
+ target-version = "py311"
@@ -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
+ ]
@@ -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)
File without changes