authgebra 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.
- authgebra/__init__.py +92 -0
- authgebra/_core.py +477 -0
- authgebra/_generated/__init__.py +2 -0
- authgebra/_generated/aio.py +1535 -0
- authgebra/_generated/codes.py +29 -0
- authgebra/_generated/models.py +4041 -0
- authgebra/_generated/operations.py +108 -0
- authgebra/_generated/sync.py +1535 -0
- authgebra/_model.py +252 -0
- authgebra/_parse.py +158 -0
- authgebra/_version.py +3 -0
- authgebra/aclient.py +256 -0
- authgebra/client.py +272 -0
- authgebra/config.py +79 -0
- authgebra/errors.py +177 -0
- authgebra/models.py +263 -0
- authgebra/py.typed +0 -0
- authgebra-0.1.0.dist-info/METADATA +181 -0
- authgebra-0.1.0.dist-info/RECORD +22 -0
- authgebra-0.1.0.dist-info/WHEEL +5 -0
- authgebra-0.1.0.dist-info/licenses/LICENSE +42 -0
- authgebra-0.1.0.dist-info/top_level.txt +1 -0
authgebra/client.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Synchronous client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, Iterator, Mapping
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from . import _core, _parse
|
|
13
|
+
from ._generated.sync import AdminClient
|
|
14
|
+
from .config import Config
|
|
15
|
+
from .errors import (
|
|
16
|
+
ApiError,
|
|
17
|
+
PaginationError,
|
|
18
|
+
ProtocolError,
|
|
19
|
+
TransportError,
|
|
20
|
+
)
|
|
21
|
+
from .models import (
|
|
22
|
+
ApiResult,
|
|
23
|
+
BatchCheckRequest,
|
|
24
|
+
BatchCheckResult,
|
|
25
|
+
CheckRequest,
|
|
26
|
+
CheckResult,
|
|
27
|
+
ExplainRequest,
|
|
28
|
+
ExplainResult,
|
|
29
|
+
ListResourcesRequest,
|
|
30
|
+
ResourcePage,
|
|
31
|
+
RevisionResult,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger("authgebra")
|
|
35
|
+
|
|
36
|
+
#: Upper bound for the paging iterator; reaching it raises instead of looping on.
|
|
37
|
+
DEFAULT_MAX_PAGES = 100
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AuthorizationClient:
|
|
41
|
+
"""Decision endpoints. ``deny`` is a normal result; ``NOT_READY`` is an error, never a deny.
|
|
42
|
+
|
|
43
|
+
The decision endpoints are POSTs but pure reads (no mutation), so they follow the read retry rules.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, client: Client) -> None:
|
|
47
|
+
self._c = client
|
|
48
|
+
|
|
49
|
+
def check(
|
|
50
|
+
self, request: CheckRequest, *, request_id: str | None = None, traceparent: str | None = None
|
|
51
|
+
) -> CheckResult:
|
|
52
|
+
return _parse.check(self._post("/api/v1/authz/check", request.to_json(), request_id, traceparent))
|
|
53
|
+
|
|
54
|
+
def batch_check(
|
|
55
|
+
self, request: BatchCheckRequest, *, request_id: str | None = None, traceparent: str | None = None
|
|
56
|
+
) -> BatchCheckResult:
|
|
57
|
+
return _parse.batch(
|
|
58
|
+
self._post("/api/v1/authz/batch-check", request.to_json(), request_id, traceparent)
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def explain(
|
|
62
|
+
self, request: ExplainRequest, *, request_id: str | None = None, traceparent: str | None = None
|
|
63
|
+
) -> ExplainResult:
|
|
64
|
+
return _parse.explain(
|
|
65
|
+
self._post("/api/v1/authz/explain", request.to_json(), request_id, traceparent)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def list_resources(
|
|
69
|
+
self,
|
|
70
|
+
request: ListResourcesRequest,
|
|
71
|
+
*,
|
|
72
|
+
request_id: str | None = None,
|
|
73
|
+
traceparent: str | None = None,
|
|
74
|
+
) -> ResourcePage:
|
|
75
|
+
"""One page. Pass ``page.next_cursor`` back via ``request.with_cursor`` for the next one."""
|
|
76
|
+
return _parse.resource_page(
|
|
77
|
+
self._post("/api/v1/authz/list-resources", request.to_json(), request_id, traceparent)
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def iter_list_resources(
|
|
81
|
+
self,
|
|
82
|
+
request: ListResourcesRequest,
|
|
83
|
+
*,
|
|
84
|
+
max_pages: int = DEFAULT_MAX_PAGES,
|
|
85
|
+
traceparent: str | None = None,
|
|
86
|
+
) -> Iterator[ResourcePage]:
|
|
87
|
+
"""Yield pages lazily (backpressure: nothing is fetched until you ask for the next page).
|
|
88
|
+
|
|
89
|
+
``CURSOR_STALE`` propagates as :class:`~authgebra.CursorStaleError`; the SDK never restarts
|
|
90
|
+
the listing on its own. Pages from different snapshot generations are never stitched
|
|
91
|
+
together: a generation change raises :class:`~authgebra.PaginationError`.
|
|
92
|
+
"""
|
|
93
|
+
if max_pages < 1:
|
|
94
|
+
raise ValueError("max_pages must be >= 1")
|
|
95
|
+
trace = _core.resolve_traceparent(self._c.config, traceparent)
|
|
96
|
+
current = request
|
|
97
|
+
generation: int | None = None
|
|
98
|
+
seen: set[str] = set()
|
|
99
|
+
for _ in range(max_pages):
|
|
100
|
+
page = self.list_resources(current, traceparent=trace)
|
|
101
|
+
gen = page.meta.snapshot_generation if page.meta else None
|
|
102
|
+
if generation is None:
|
|
103
|
+
generation = gen
|
|
104
|
+
elif gen is not None and gen != generation:
|
|
105
|
+
raise PaginationError(
|
|
106
|
+
f"snapshot generation changed during paging ({generation} -> {gen}); restart explicitly"
|
|
107
|
+
)
|
|
108
|
+
yield page
|
|
109
|
+
cursor = page.page.next_cursor
|
|
110
|
+
if not page.page.has_more or cursor is None:
|
|
111
|
+
return
|
|
112
|
+
if cursor in seen:
|
|
113
|
+
raise PaginationError("server returned a repeated cursor; refusing to loop")
|
|
114
|
+
seen.add(cursor)
|
|
115
|
+
current = request.with_cursor(cursor)
|
|
116
|
+
raise PaginationError(f"page limit of {max_pages} reached while more pages remain")
|
|
117
|
+
|
|
118
|
+
def revision(
|
|
119
|
+
self, *, request_id: str | None = None, traceparent: str | None = None
|
|
120
|
+
) -> RevisionResult:
|
|
121
|
+
return _parse.revision(
|
|
122
|
+
self._c.request(
|
|
123
|
+
"GET", "/api/v1/authz/revision", request_id=request_id, traceparent=traceparent
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def _post(
|
|
128
|
+
self, path: str, body: Mapping[str, Any], request_id: str | None, traceparent: str | None
|
|
129
|
+
) -> ApiResult:
|
|
130
|
+
return self._c.request(
|
|
131
|
+
"POST", path, json=body, safe=True, request_id=request_id, traceparent=traceparent
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Client:
|
|
136
|
+
"""Synchronous Authgebra client.
|
|
137
|
+
|
|
138
|
+
>>> with Client(Config(base_url="https://authgebra.example", token_provider=lambda: token)) as c:
|
|
139
|
+
... c.authorization.check(CheckRequest(subject_id, "document:read")) # doctest: +SKIP
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
def __init__(self, config: Config) -> None:
|
|
143
|
+
self.config = config
|
|
144
|
+
self._owns_http = config.http_client is None
|
|
145
|
+
self._http: httpx.Client = config.http_client or httpx.Client(
|
|
146
|
+
verify=config.verify,
|
|
147
|
+
transport=config.transport,
|
|
148
|
+
follow_redirects=False,
|
|
149
|
+
trust_env=False,
|
|
150
|
+
)
|
|
151
|
+
self.authorization = AuthorizationClient(self)
|
|
152
|
+
self.admin = AdminClient(self)
|
|
153
|
+
|
|
154
|
+
def __enter__(self) -> Client:
|
|
155
|
+
return self
|
|
156
|
+
|
|
157
|
+
def __exit__(
|
|
158
|
+
self,
|
|
159
|
+
exc_type: type[BaseException] | None,
|
|
160
|
+
exc: BaseException | None,
|
|
161
|
+
tb: TracebackType | None,
|
|
162
|
+
) -> None:
|
|
163
|
+
self.close()
|
|
164
|
+
|
|
165
|
+
def close(self) -> None:
|
|
166
|
+
if self._owns_http:
|
|
167
|
+
self._http.close()
|
|
168
|
+
|
|
169
|
+
# ------------------------------------------------------------------ low level
|
|
170
|
+
|
|
171
|
+
def request(
|
|
172
|
+
self,
|
|
173
|
+
method: str,
|
|
174
|
+
path: str,
|
|
175
|
+
*,
|
|
176
|
+
query: Mapping[str, object] | None = None,
|
|
177
|
+
json: Any = None,
|
|
178
|
+
if_match: str | None = None,
|
|
179
|
+
idempotency_key: str | None = None,
|
|
180
|
+
request_id: str | None = None,
|
|
181
|
+
traceparent: str | None = None,
|
|
182
|
+
safe: bool | None = None,
|
|
183
|
+
envelope: bool = True,
|
|
184
|
+
) -> ApiResult:
|
|
185
|
+
"""Send one logical request (with bounded retries) and interpret the response.
|
|
186
|
+
|
|
187
|
+
``safe`` defaults to ``True`` for GET/HEAD only. Writes are not retried unless
|
|
188
|
+
``config.retry.retry_writes`` is set *and* ``idempotency_key`` is given.
|
|
189
|
+
"""
|
|
190
|
+
cfg = self.config
|
|
191
|
+
is_safe = method.upper() in ("GET", "HEAD") if safe is None else safe
|
|
192
|
+
body = None if json is None else _core.serialize_json(json)
|
|
193
|
+
trace = _core.resolve_traceparent(cfg, traceparent)
|
|
194
|
+
retries_done = 0
|
|
195
|
+
while True:
|
|
196
|
+
attempt_trace = trace if trace is None or retries_done == 0 else _core.child_traceparent(trace)
|
|
197
|
+
prep = _core.prepare(
|
|
198
|
+
cfg,
|
|
199
|
+
method,
|
|
200
|
+
path,
|
|
201
|
+
query=query,
|
|
202
|
+
body=body,
|
|
203
|
+
token=self._token(),
|
|
204
|
+
if_match=if_match,
|
|
205
|
+
idempotency_key=idempotency_key,
|
|
206
|
+
request_id=request_id,
|
|
207
|
+
traceparent=attempt_trace,
|
|
208
|
+
safe=is_safe,
|
|
209
|
+
)
|
|
210
|
+
try:
|
|
211
|
+
return _core.interpret(self._send(prep), envelope=envelope)
|
|
212
|
+
except (ApiError, TransportError, ProtocolError) as exc:
|
|
213
|
+
exc.attempts = retries_done + 1
|
|
214
|
+
if not _core.should_retry(
|
|
215
|
+
cfg.retry,
|
|
216
|
+
safe=prep.safe,
|
|
217
|
+
has_key=prep.has_key,
|
|
218
|
+
retries_done=retries_done,
|
|
219
|
+
error=exc,
|
|
220
|
+
):
|
|
221
|
+
raise
|
|
222
|
+
delay = _core.retry_delay(cfg.retry, retries_done, exc)
|
|
223
|
+
log.debug("retrying %s %s in %.3fs (attempt %d)", prep.method, path, delay, retries_done + 2)
|
|
224
|
+
(cfg.retry.sleep or time.sleep)(delay)
|
|
225
|
+
retries_done += 1
|
|
226
|
+
|
|
227
|
+
def _token(self) -> str | None:
|
|
228
|
+
provider = self.config.token_provider
|
|
229
|
+
if provider is None:
|
|
230
|
+
return None
|
|
231
|
+
token = provider()
|
|
232
|
+
if token is not None and not isinstance(token, str):
|
|
233
|
+
raise TypeError("token_provider must return str or None (use AsyncClient for async providers)")
|
|
234
|
+
return token
|
|
235
|
+
|
|
236
|
+
def _send(self, prep: _core.Prepared) -> _core.RawResponse:
|
|
237
|
+
cfg = self.config
|
|
238
|
+
deadline = time.monotonic() + cfg.timeout
|
|
239
|
+
remaining = cfg.timeout
|
|
240
|
+
timeout = httpx.Timeout(
|
|
241
|
+
connect=min(cfg.connect_timeout, remaining), read=remaining, write=remaining, pool=remaining
|
|
242
|
+
)
|
|
243
|
+
try:
|
|
244
|
+
with self._http.stream(
|
|
245
|
+
prep.method,
|
|
246
|
+
prep.url,
|
|
247
|
+
params=prep.params or None,
|
|
248
|
+
content=prep.content,
|
|
249
|
+
headers=prep.headers,
|
|
250
|
+
timeout=timeout,
|
|
251
|
+
) as response:
|
|
252
|
+
declared = response.headers.get("content-length")
|
|
253
|
+
if declared is not None and declared.isdigit() and int(declared) > cfg.max_response_bytes:
|
|
254
|
+
raise ProtocolError("response_too_large", status=response.status_code, request_id=prep.request_id)
|
|
255
|
+
chunks: list[bytes] = []
|
|
256
|
+
size = 0
|
|
257
|
+
for chunk in response.iter_bytes():
|
|
258
|
+
size += len(chunk)
|
|
259
|
+
if size > cfg.max_response_bytes:
|
|
260
|
+
raise ProtocolError(
|
|
261
|
+
"response_too_large", status=response.status_code, request_id=prep.request_id
|
|
262
|
+
)
|
|
263
|
+
chunks.append(chunk)
|
|
264
|
+
if time.monotonic() > deadline:
|
|
265
|
+
raise _core.build_transport_error("timeout", prep, "deadline exceeded")
|
|
266
|
+
headers = {name.lower(): value for name, value in response.headers.items()}
|
|
267
|
+
log.debug("%s %s -> %d", prep.method, prep.url.split("?", 1)[0], response.status_code)
|
|
268
|
+
return _core.RawResponse(response.status_code, headers, b"".join(chunks))
|
|
269
|
+
except (ProtocolError, TransportError):
|
|
270
|
+
raise
|
|
271
|
+
except httpx.HTTPError as exc:
|
|
272
|
+
raise _core.transport_error(exc, prep) from exc
|
authgebra/config.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Client configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ssl
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Callable, Mapping
|
|
8
|
+
|
|
9
|
+
from .models import RetryPolicy
|
|
10
|
+
|
|
11
|
+
#: Headers the SDK owns; callers cannot override them through ``Config.headers``.
|
|
12
|
+
RESERVED_HEADERS = frozenset(
|
|
13
|
+
{
|
|
14
|
+
"authorization",
|
|
15
|
+
"content-type",
|
|
16
|
+
"accept",
|
|
17
|
+
"user-agent",
|
|
18
|
+
"x-request-id",
|
|
19
|
+
"traceparent",
|
|
20
|
+
"tracestate",
|
|
21
|
+
"idempotency-key",
|
|
22
|
+
"if-match",
|
|
23
|
+
"host",
|
|
24
|
+
"content-length",
|
|
25
|
+
}
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(repr=False)
|
|
30
|
+
class Config:
|
|
31
|
+
"""Settings shared by :class:`~authgebra.Client` and :class:`~authgebra.AsyncClient`.
|
|
32
|
+
|
|
33
|
+
* ``token_provider`` is called before **every** attempt (so refreshed tokens are used). The
|
|
34
|
+
async client also accepts an ``async def`` provider. Tokens are never logged or put in errors.
|
|
35
|
+
* ``verify`` is ``True`` (system CAs), a CA bundle path, or an ``ssl.SSLContext``.
|
|
36
|
+
Disabling verification is intentionally not supported.
|
|
37
|
+
* ``timeout`` is the total wall-clock budget of one attempt; ``connect_timeout`` bounds connect.
|
|
38
|
+
* ``http_client`` / ``transport`` inject your own ``httpx`` client or transport; an injected
|
|
39
|
+
client is never closed by the SDK.
|
|
40
|
+
* ``trace_provider`` returns the caller's current W3C ``traceparent`` (for example from an
|
|
41
|
+
OpenTelemetry context) so calls continue the caller's trace.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
base_url: str
|
|
45
|
+
token_provider: Callable[[], Any] | None = None
|
|
46
|
+
connect_timeout: float = 5.0
|
|
47
|
+
timeout: float = 30.0
|
|
48
|
+
verify: bool | str | ssl.SSLContext = True
|
|
49
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
50
|
+
user_agent_suffix: str | None = None
|
|
51
|
+
max_response_bytes: int = 8 * 1024 * 1024
|
|
52
|
+
retry: RetryPolicy = field(default_factory=RetryPolicy)
|
|
53
|
+
auto_request_id: bool = True
|
|
54
|
+
auto_traceparent: bool = True
|
|
55
|
+
trace_provider: Callable[[], str | None] | None = None
|
|
56
|
+
http_client: Any = None
|
|
57
|
+
transport: Any = None
|
|
58
|
+
|
|
59
|
+
def __post_init__(self) -> None:
|
|
60
|
+
if not self.base_url.startswith(("http://", "https://")):
|
|
61
|
+
raise ValueError("base_url must start with http:// or https://")
|
|
62
|
+
if self.verify is False:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"disabling TLS verification is not supported; pass a CA bundle path or an ssl.SSLContext"
|
|
65
|
+
)
|
|
66
|
+
if self.connect_timeout <= 0 or self.timeout <= 0:
|
|
67
|
+
raise ValueError("timeouts must be positive (unbounded requests are not allowed)")
|
|
68
|
+
if self.max_response_bytes <= 0:
|
|
69
|
+
raise ValueError("max_response_bytes must be positive")
|
|
70
|
+
for name in self.headers:
|
|
71
|
+
if name.lower() in RESERVED_HEADERS:
|
|
72
|
+
raise ValueError(f"header {name!r} is managed by the SDK and cannot be overridden")
|
|
73
|
+
|
|
74
|
+
def __repr__(self) -> str:
|
|
75
|
+
return (
|
|
76
|
+
f"Config(base_url={self.base_url!r}, token_provider="
|
|
77
|
+
f"{'<set>' if self.token_provider else None}, timeout={self.timeout}, "
|
|
78
|
+
f"headers=<{len(self.headers)} custom>)"
|
|
79
|
+
)
|
authgebra/errors.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Typed error hierarchy.
|
|
2
|
+
|
|
3
|
+
Three distinct failure worlds (see ``sdks/README.md``):
|
|
4
|
+
|
|
5
|
+
* :class:`ApiError` - the server answered with a well-formed ``{"error": {...}}`` body.
|
|
6
|
+
* :class:`TransportError` - no usable HTTP response (timeout, reset, TLS ...).
|
|
7
|
+
* :class:`ProtocolError` - an HTTP response arrived but cannot be understood.
|
|
8
|
+
|
|
9
|
+
``decision = deny`` is **not** an error; it is a normal result. ``NOT_READY`` is an
|
|
10
|
+
error and must never be converted into a deny by this SDK.
|
|
11
|
+
Callers must branch on ``code`` / subclasses, never on ``message`` text.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from enum import Enum
|
|
18
|
+
from typing import Any, Mapping
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CommitState(str, Enum):
|
|
22
|
+
"""What is known about a write.
|
|
23
|
+
|
|
24
|
+
``COMMITTED_UNPUBLISHED`` is declared by the server (the mutation *did* execute).
|
|
25
|
+
``UNKNOWN`` is inferred by the SDK for a write whose transport failed: the
|
|
26
|
+
mutation may or may not have been applied. ``None`` means "nothing is known".
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
COMMITTED_UNPUBLISHED = "committed_unpublished"
|
|
30
|
+
UNKNOWN = "unknown"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Violation:
|
|
35
|
+
"""One entry of ``error.details.violations``."""
|
|
36
|
+
|
|
37
|
+
path: str | None
|
|
38
|
+
reason: str
|
|
39
|
+
message: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AuthgebraError(Exception):
|
|
43
|
+
"""Base class for every error raised by this SDK."""
|
|
44
|
+
|
|
45
|
+
attempts: int = 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ApiError(AuthgebraError):
|
|
49
|
+
"""The server returned an error envelope."""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
*,
|
|
54
|
+
status: int,
|
|
55
|
+
code: str,
|
|
56
|
+
known_code: bool,
|
|
57
|
+
message: str,
|
|
58
|
+
request_id: str | None,
|
|
59
|
+
body_request_id: str | None,
|
|
60
|
+
request_id_mismatch: bool,
|
|
61
|
+
request_id_header_valid: bool,
|
|
62
|
+
trace_id: str | None,
|
|
63
|
+
details: Mapping[str, Any] | None,
|
|
64
|
+
violations: tuple[Violation, ...],
|
|
65
|
+
retryable: bool | None,
|
|
66
|
+
retry_after_seconds: int | None,
|
|
67
|
+
commit_state: CommitState | None,
|
|
68
|
+
raw_body_excerpt: str,
|
|
69
|
+
) -> None:
|
|
70
|
+
super().__init__(f"{code} (HTTP {status}): {message}")
|
|
71
|
+
self.status = status
|
|
72
|
+
#: The raw code string exactly as sent (unknown codes are preserved).
|
|
73
|
+
self.code = code
|
|
74
|
+
#: Whether ``code`` belongs to the set known when this SDK was built.
|
|
75
|
+
self.known_code = known_code
|
|
76
|
+
self.message = message
|
|
77
|
+
#: Taken from the ``X-Request-ID`` header when valid, otherwise from the body.
|
|
78
|
+
self.request_id = request_id
|
|
79
|
+
self.body_request_id = body_request_id
|
|
80
|
+
self.request_id_mismatch = request_id_mismatch
|
|
81
|
+
self.request_id_header_valid = request_id_header_valid
|
|
82
|
+
self.trace_id = trace_id
|
|
83
|
+
self.details = details
|
|
84
|
+
self.violations = violations
|
|
85
|
+
#: Tri-state hint: True / False / None (server makes no statement).
|
|
86
|
+
self.retryable = retryable
|
|
87
|
+
self.retry_after_seconds = retry_after_seconds
|
|
88
|
+
self.commit_state = commit_state
|
|
89
|
+
#: Truncated body text, safe to log (the server redacts secrets).
|
|
90
|
+
self.raw_body_excerpt = raw_body_excerpt
|
|
91
|
+
|
|
92
|
+
def __str__(self) -> str:
|
|
93
|
+
base = f"{self.code} (HTTP {self.status}): {self.message}"
|
|
94
|
+
extra = []
|
|
95
|
+
if self.request_id:
|
|
96
|
+
extra.append(f"request_id={self.request_id}")
|
|
97
|
+
if self.trace_id:
|
|
98
|
+
extra.append(f"trace_id={self.trace_id}")
|
|
99
|
+
return f"{base} [{', '.join(extra)}]" if extra else base
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class CursorStaleError(ApiError):
|
|
103
|
+
"""``CURSOR_STALE``: restart pagination yourself; the SDK never does it silently."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class NotReadyError(ApiError):
|
|
107
|
+
"""``NOT_READY``: the system could not reach a trustworthy decision. Not a deny."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class RateLimitedError(ApiError):
|
|
111
|
+
"""``RATE_LIMITED``."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class ReloadPendingError(ApiError):
|
|
115
|
+
"""``AUTHZ_RELOAD_PENDING`` / ``IDENTITY_RELOAD_PENDING``.
|
|
116
|
+
|
|
117
|
+
The mutation was **committed** but is not yet published. Never resend it.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
API_ERROR_CLASSES: Mapping[str, type[ApiError]] = {
|
|
122
|
+
"CURSOR_STALE": CursorStaleError,
|
|
123
|
+
"NOT_READY": NotReadyError,
|
|
124
|
+
"RATE_LIMITED": RateLimitedError,
|
|
125
|
+
"AUTHZ_RELOAD_PENDING": ReloadPendingError,
|
|
126
|
+
"IDENTITY_RELOAD_PENDING": ReloadPendingError,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class TransportError(AuthgebraError):
|
|
131
|
+
"""No usable HTTP response.
|
|
132
|
+
|
|
133
|
+
``error`` is one of ``timeout``, ``connect_error``, ``tls_error``,
|
|
134
|
+
``connection_reset``, ``transport``. ``commit_state`` is
|
|
135
|
+
:attr:`CommitState.UNKNOWN` for writes (never assume "not committed").
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
error: str,
|
|
141
|
+
*,
|
|
142
|
+
commit_state: CommitState | None,
|
|
143
|
+
request_id: str | None,
|
|
144
|
+
detail: str = "",
|
|
145
|
+
) -> None:
|
|
146
|
+
super().__init__(f"transport error: {error}" + (f" ({detail})" if detail else ""))
|
|
147
|
+
self.error = error
|
|
148
|
+
self.commit_state = commit_state
|
|
149
|
+
self.request_id = request_id
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class ProtocolError(AuthgebraError):
|
|
153
|
+
"""A response arrived but violates the contract.
|
|
154
|
+
|
|
155
|
+
``error`` is one of ``non_json_response``, ``malformed_error_body``,
|
|
156
|
+
``malformed_success_body``, ``response_too_large``, ``unknown_decision``.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
def __init__(
|
|
160
|
+
self,
|
|
161
|
+
error: str,
|
|
162
|
+
*,
|
|
163
|
+
status: int | None,
|
|
164
|
+
request_id: str | None = None,
|
|
165
|
+
trace_id: str | None = None,
|
|
166
|
+
excerpt: str = "",
|
|
167
|
+
) -> None:
|
|
168
|
+
super().__init__(f"protocol error: {error}" + (f" (HTTP {status})" if status else ""))
|
|
169
|
+
self.error = error
|
|
170
|
+
self.status = status
|
|
171
|
+
self.request_id = request_id
|
|
172
|
+
self.trace_id = trace_id
|
|
173
|
+
self.excerpt = excerpt
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class PaginationError(AuthgebraError):
|
|
177
|
+
"""The paging iterator refused to continue (limit reached, cursor loop, generation change)."""
|