entitybind 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.
entitybind/http.py ADDED
@@ -0,0 +1,319 @@
1
+ """HTTP transport: identification headers, idempotency, retries and typed errors.
2
+
3
+ Every request carries `User-Agent: entitybind-cli/<version>` and
4
+ `X-EntityBind-Client: cli`. Mutating requests carry an `Idempotency-Key` that
5
+ stays the same across retries, so a retried POST cannot run twice where the
6
+ server honours the key. Only 429 and 503 are retried (plus connection failures
7
+ that happened before a request was sent), always after the server's
8
+ `Retry-After` when it gives one.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import time
15
+ import uuid
16
+ from collections.abc import Callable, Mapping
17
+ from dataclasses import dataclass, field
18
+ from email.utils import parsedate_to_datetime
19
+ from typing import Any
20
+
21
+ import httpx
22
+
23
+ from entitybind.errors import ApiError, CliError, NetworkError, is_entitlement_code
24
+ from entitybind.products import CLIENT_HEADER, USER_AGENT
25
+
26
+ RETRY_STATUSES = frozenset({429, 503})
27
+ MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
28
+ DEFAULT_MAX_RETRIES = 3
29
+ DEFAULT_TIMEOUT = 60.0
30
+ # A Retry-After longer than this is reported rather than slept through: a CLI
31
+ # that silently blocks for ten minutes looks hung to a person and to an agent.
32
+ MAX_RETRY_WAIT = 60.0
33
+
34
+ _DEFAULT_CODES = {
35
+ 400: "bad_request",
36
+ 401: "unauthorized",
37
+ 402: "payment_required",
38
+ 403: "forbidden",
39
+ 404: "not_found",
40
+ 405: "method_not_allowed",
41
+ 409: "conflict",
42
+ 410: "gone",
43
+ 413: "payload_too_large",
44
+ 422: "invalid_request",
45
+ 429: "rate_limited",
46
+ 500: "internal_error",
47
+ 502: "bad_gateway",
48
+ 503: "service_unavailable",
49
+ 504: "gateway_timeout",
50
+ }
51
+
52
+
53
+ def new_idempotency_key() -> str:
54
+ return f"cli-{uuid.uuid4().hex}"
55
+
56
+
57
+ def _with_key(error: CliError, key: str | None) -> CliError:
58
+ """Name the Idempotency-Key a failed mutating request carried, so a retry can reuse it."""
59
+ if key is not None:
60
+ error.data.setdefault("idempotency_key", key)
61
+ return error
62
+
63
+
64
+ @dataclass
65
+ class ApiResponse:
66
+ status: int
67
+ headers: httpx.Headers
68
+ body: Any
69
+ text: str
70
+ idempotency_key: str | None = None
71
+ attempts: int = 1
72
+ extra: dict[str, Any] = field(default_factory=dict)
73
+
74
+ def header(self, name: str) -> str | None:
75
+ return self.headers.get(name)
76
+
77
+
78
+ def parse_body(response: httpx.Response) -> Any:
79
+ text = response.text
80
+ if not text.strip():
81
+ return None
82
+ content_type = response.headers.get("content-type", "")
83
+ if "json" in content_type or text.lstrip()[:1] in ("{", "["):
84
+ try:
85
+ return json.loads(text)
86
+ except ValueError:
87
+ return None
88
+ return None
89
+
90
+
91
+ def retry_after_seconds(headers: Mapping[str, str], now: Callable[[], float]) -> float | None:
92
+ raw = headers.get("retry-after")
93
+ if raw is None:
94
+ return None
95
+ value = raw.strip()
96
+ try:
97
+ return max(0.0, float(value))
98
+ except ValueError:
99
+ pass
100
+ try:
101
+ moment = parsedate_to_datetime(value)
102
+ except (TypeError, ValueError, IndexError):
103
+ return None
104
+ return max(0.0, moment.timestamp() - now())
105
+
106
+
107
+ def _error_fields(body: Any) -> dict[str, Any]:
108
+ """Read Core, AML, OAuth (RFC 6749) and FastAPI error shapes alike."""
109
+ fields: dict[str, Any] = {}
110
+ if not isinstance(body, dict):
111
+ return fields
112
+ error = body.get("error")
113
+ if isinstance(error, dict):
114
+ fields["code"] = error.get("code")
115
+ fields["message"] = error.get("message")
116
+ fields["correlation_id"] = error.get("correlation_id") or body.get("request_id")
117
+ fields["remediation"] = error.get("remediation", body.get("remediation"))
118
+ fields["details"] = error.get("details")
119
+ elif isinstance(error, str):
120
+ fields["code"] = error
121
+ fields["message"] = body.get("error_description") or error
122
+ elif "detail" in body:
123
+ detail = body["detail"]
124
+ fields["message"] = detail if isinstance(detail, str) else json.dumps(detail)[:500]
125
+ return fields
126
+
127
+
128
+ def error_from_response(response: httpx.Response, body: Any, now: Callable[[], float]) -> ApiError:
129
+ fields = _error_fields(body)
130
+ status = response.status_code
131
+ message = fields.get("message")
132
+ if not isinstance(message, str) or not message.strip():
133
+ snippet = " ".join(response.text.split())[:300]
134
+ message = snippet or f"HTTP {status}"
135
+ code = fields.get("code")
136
+ if not isinstance(code, str) or not code:
137
+ code = _DEFAULT_CODES.get(status, "http_error")
138
+ correlation = fields.get("correlation_id") or response.headers.get("x-request-id")
139
+ return ApiError(
140
+ status,
141
+ message,
142
+ code=code,
143
+ correlation_id=str(correlation) if correlation else None,
144
+ remediation=fields.get("remediation"),
145
+ details=fields.get("details"),
146
+ retry_after=retry_after_seconds(response.headers, now),
147
+ body=body,
148
+ )
149
+
150
+
151
+ class ApiClient:
152
+ """One product's HTTP API, authenticated with a bearer credential."""
153
+
154
+ def __init__(
155
+ self,
156
+ base_url: str,
157
+ *,
158
+ token: str | None = None,
159
+ transport: httpx.BaseTransport | None = None,
160
+ timeout: float = DEFAULT_TIMEOUT,
161
+ max_retries: int = DEFAULT_MAX_RETRIES,
162
+ sleep: Callable[[float], None] = time.sleep,
163
+ now: Callable[[], float] = time.time,
164
+ notify: Callable[[str], None] | None = None,
165
+ ) -> None:
166
+ self.base_url = base_url
167
+ self._token = token
168
+ self._timeout = timeout
169
+ self._max_retries = max(0, max_retries)
170
+ self._sleep = sleep
171
+ self._now = now
172
+ self._notify = notify
173
+ self._http = httpx.Client(
174
+ base_url=base_url,
175
+ transport=transport,
176
+ timeout=httpx.Timeout(timeout, connect=min(timeout, 15.0)),
177
+ follow_redirects=False,
178
+ headers={
179
+ "User-Agent": USER_AGENT,
180
+ "X-EntityBind-Client": CLIENT_HEADER,
181
+ "Accept": "application/json",
182
+ },
183
+ )
184
+
185
+ @property
186
+ def authenticated(self) -> bool:
187
+ return bool(self._token)
188
+
189
+ def close(self) -> None:
190
+ self._http.close()
191
+
192
+ def __enter__(self) -> ApiClient:
193
+ return self
194
+
195
+ def __exit__(self, *exc: object) -> None:
196
+ self.close()
197
+
198
+ def _backoff(self, attempt: int) -> float:
199
+ return float(min(2**attempt, 30))
200
+
201
+ def _retry_wait(self, response: httpx.Response, attempt: int) -> float | None:
202
+ advised = retry_after_seconds(response.headers, self._now)
203
+ wait = self._backoff(attempt) if advised is None else advised
204
+ return None if wait > MAX_RETRY_WAIT else wait
205
+
206
+ def _say(self, message: str) -> None:
207
+ if self._notify is not None:
208
+ self._notify(message)
209
+
210
+ def request(
211
+ self,
212
+ method: str,
213
+ path: str,
214
+ *,
215
+ json_body: Any = None,
216
+ form: Mapping[str, str] | None = None,
217
+ params: Mapping[str, Any] | None = None,
218
+ idempotency_key: str | None = None,
219
+ with_idempotency: bool = True,
220
+ authenticated: bool = True,
221
+ timeout: float | None = None,
222
+ ) -> ApiResponse:
223
+ verb = method.upper()
224
+ headers: dict[str, str] = {}
225
+ if authenticated and self._token:
226
+ headers["Authorization"] = f"Bearer {self._token}"
227
+ key: str | None = None
228
+ if verb in MUTATING_METHODS and with_idempotency:
229
+ key = idempotency_key or new_idempotency_key()
230
+ headers["Idempotency-Key"] = key
231
+ clean_params: dict[str, Any] | None = None
232
+ if params is not None:
233
+ clean_params = {k: v for k, v in params.items() if v is not None}
234
+ request_timeout = httpx.Timeout(
235
+ timeout or self._timeout, connect=min(timeout or self._timeout, 15.0)
236
+ )
237
+ attempt = 0
238
+ while True:
239
+ try:
240
+ response = self._http.request(
241
+ verb,
242
+ path,
243
+ json=json_body,
244
+ data=dict(form) if form is not None else None,
245
+ params=clean_params,
246
+ headers=headers,
247
+ timeout=request_timeout,
248
+ )
249
+ except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
250
+ # Nothing reached the server, so a retry cannot duplicate work.
251
+ if attempt < self._max_retries:
252
+ wait = self._backoff(attempt)
253
+ self._say(f"could not connect ({type(exc).__name__}); retrying in {wait:g}s")
254
+ self._sleep(wait)
255
+ attempt += 1
256
+ continue
257
+ raise _with_key(
258
+ NetworkError(
259
+ f"could not connect to {self.base_url} ({type(exc).__name__})",
260
+ code="connection_failed",
261
+ ),
262
+ key,
263
+ ) from exc
264
+ except httpx.TimeoutException as exc:
265
+ raise _with_key(
266
+ NetworkError(
267
+ f"timed out waiting for {self.base_url} after "
268
+ f"{timeout or self._timeout:g}s",
269
+ code="timeout",
270
+ hint="raise --http-timeout, or use an asynchronous job for long work",
271
+ ),
272
+ key,
273
+ ) from exc
274
+ except httpx.HTTPError as exc:
275
+ raise _with_key(
276
+ NetworkError(
277
+ f"request to {self.base_url} failed ({type(exc).__name__})",
278
+ code="network_error",
279
+ ),
280
+ key,
281
+ ) from exc
282
+ if response.status_code in RETRY_STATUSES and attempt < self._max_retries:
283
+ body = parse_body(response)
284
+ code = _error_fields(body).get("code")
285
+ quota = response.status_code == 429 and is_entitlement_code(
286
+ code if isinstance(code, str) else None
287
+ )
288
+ retry_wait = None if quota else self._retry_wait(response, attempt)
289
+ if retry_wait is not None:
290
+ self._say(
291
+ f"HTTP {response.status_code} from server; retrying in {retry_wait:g}s "
292
+ f"(retry {attempt + 1} of {self._max_retries})"
293
+ )
294
+ self._sleep(retry_wait)
295
+ attempt += 1
296
+ continue
297
+ return self._finish(response, key, attempt + 1)
298
+
299
+ def _finish(self, response: httpx.Response, key: str | None, attempts: int) -> ApiResponse:
300
+ body = parse_body(response)
301
+ if 200 <= response.status_code < 300:
302
+ return ApiResponse(
303
+ status=response.status_code,
304
+ headers=response.headers,
305
+ body=body,
306
+ text=response.text,
307
+ idempotency_key=key,
308
+ attempts=attempts,
309
+ )
310
+ raise _with_key(error_from_response(response, body, self._now), key)
311
+
312
+ def get(self, path: str, **kwargs: Any) -> ApiResponse:
313
+ return self.request("GET", path, **kwargs)
314
+
315
+ def post(self, path: str, **kwargs: Any) -> ApiResponse:
316
+ return self.request("POST", path, **kwargs)
317
+
318
+ def delete(self, path: str, **kwargs: Any) -> ApiResponse:
319
+ return self.request("DELETE", path, **kwargs)