stableops 0.7.1__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.
- stableops/__init__.py +83 -0
- stableops/addresses.py +256 -0
- stableops/checkout_sessions.py +158 -0
- stableops/client.py +137 -0
- stableops/errors.py +41 -0
- stableops/http.py +536 -0
- stableops/payment_orders.py +235 -0
- stableops/types.py +225 -0
- stableops/webhooks.py +378 -0
- stableops-0.7.1.dist-info/METADATA +112 -0
- stableops-0.7.1.dist-info/RECORD +13 -0
- stableops-0.7.1.dist-info/WHEEL +4 -0
- stableops-0.7.1.dist-info/licenses/LICENSE +184 -0
stableops/http.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
"""HTTP client with retry logic."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable, Dict, Literal, Mapping, Optional, Union
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from importlib.metadata import version as _pkg_version
|
|
11
|
+
|
|
12
|
+
_SDK_VERSION = _pkg_version("stableops")
|
|
13
|
+
except Exception:
|
|
14
|
+
_SDK_VERSION = "unknown"
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from stableops.errors import StableOpsError
|
|
19
|
+
|
|
20
|
+
IDEMPOTENCY_HEADER = "idempotency-key"
|
|
21
|
+
|
|
22
|
+
DEFAULT_BASE_URL = "https://api.stableops.dev"
|
|
23
|
+
DEFAULT_TIMEOUT = 30.0
|
|
24
|
+
DEFAULT_MAX_RETRIES = 2
|
|
25
|
+
DEFAULT_BASE_DELAY = 0.2
|
|
26
|
+
DEFAULT_MAX_DELAY = 5.0
|
|
27
|
+
|
|
28
|
+
HttpMethod = Literal["GET", "POST", "PATCH", "DELETE"]
|
|
29
|
+
|
|
30
|
+
# debug 钩子签名:接收一个 dict 事件(init / request / response / error)。
|
|
31
|
+
# 传 True 走 logging.getLogger("stableops") .debug;也可传任意可调用对象自行处理。
|
|
32
|
+
DebugCallback = Callable[[Dict[str, Any]], None]
|
|
33
|
+
DebugOption = Union[bool, DebugCallback, None]
|
|
34
|
+
|
|
35
|
+
_SENSITIVE_HEADERS = frozenset({"authorization", IDEMPOTENCY_HEADER, "cookie", "set-cookie"})
|
|
36
|
+
|
|
37
|
+
_logger = logging.getLogger("stableops")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def mask_secret(value: Optional[str]) -> Optional[str]:
|
|
41
|
+
"""Mask a secret, keeping first/last 4 chars when long enough."""
|
|
42
|
+
if value is None:
|
|
43
|
+
return None
|
|
44
|
+
if len(value) <= 8:
|
|
45
|
+
return "***"
|
|
46
|
+
return f"{value[:4]}***{value[-4:]}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _mask_headers(headers: Mapping[str, str]) -> Dict[str, str]:
|
|
50
|
+
out: Dict[str, str] = {}
|
|
51
|
+
for k, v in headers.items():
|
|
52
|
+
lower = k.lower()
|
|
53
|
+
if lower in _SENSITIVE_HEADERS:
|
|
54
|
+
if lower == "authorization" and v.startswith("Bearer "):
|
|
55
|
+
masked = mask_secret(v[7:]) or "***"
|
|
56
|
+
out[k] = f"Bearer {masked}"
|
|
57
|
+
else:
|
|
58
|
+
out[k] = mask_secret(v) or "***"
|
|
59
|
+
else:
|
|
60
|
+
out[k] = v
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _resolve_debug(option: DebugOption) -> Optional[DebugCallback]:
|
|
65
|
+
if not option:
|
|
66
|
+
return None
|
|
67
|
+
if callable(option):
|
|
68
|
+
return option
|
|
69
|
+
|
|
70
|
+
def _default(event: Dict[str, Any]) -> None:
|
|
71
|
+
_logger.debug("stableops %s", event)
|
|
72
|
+
|
|
73
|
+
return _default
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_retryable_status(status: int) -> bool:
|
|
77
|
+
"""Check if HTTP status is retryable."""
|
|
78
|
+
return status == 429 or status >= 500
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_retryable_error(error: Exception) -> bool:
|
|
82
|
+
"""Check if error is retryable."""
|
|
83
|
+
if isinstance(error, httpx.TimeoutException):
|
|
84
|
+
return True
|
|
85
|
+
if isinstance(error, httpx.NetworkError):
|
|
86
|
+
return True
|
|
87
|
+
if isinstance(error, httpx.HTTPStatusError):
|
|
88
|
+
return is_retryable_status(error.response.status_code)
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def compute_delay(
|
|
93
|
+
attempt: int, base_delay: float, max_delay: float, retry_after: Optional[float] = None
|
|
94
|
+
) -> float:
|
|
95
|
+
"""Compute retry delay with exponential backoff and jitter."""
|
|
96
|
+
if retry_after is not None:
|
|
97
|
+
return min(retry_after, max_delay)
|
|
98
|
+
|
|
99
|
+
# Exponential backoff: base_delay * 2^attempt
|
|
100
|
+
delay = base_delay * (2**attempt)
|
|
101
|
+
|
|
102
|
+
# Full jitter: random between 0 and delay
|
|
103
|
+
delay = random.uniform(0, delay)
|
|
104
|
+
|
|
105
|
+
return min(delay, max_delay)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class HttpClient:
|
|
109
|
+
"""Synchronous HTTP client with retry logic."""
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
api_key: Optional[str] = None,
|
|
114
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
115
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
116
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
117
|
+
base_delay: float = DEFAULT_BASE_DELAY,
|
|
118
|
+
max_delay: float = DEFAULT_MAX_DELAY,
|
|
119
|
+
debug: DebugOption = None,
|
|
120
|
+
) -> None:
|
|
121
|
+
"""Initialize HTTP client.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
api_key: API key for authentication
|
|
125
|
+
base_url: Base API URL
|
|
126
|
+
timeout: Request timeout in seconds
|
|
127
|
+
max_retries: Maximum number of retries
|
|
128
|
+
base_delay: Base delay for exponential backoff
|
|
129
|
+
max_delay: Maximum delay between retries
|
|
130
|
+
debug: True 走 logging "stableops" logger,可调用对象则自行处理;
|
|
131
|
+
敏感字段(api_key / authorization / idempotency-key 等)始终先脱敏。
|
|
132
|
+
"""
|
|
133
|
+
self.base_url = base_url.rstrip("/")
|
|
134
|
+
self.timeout = timeout
|
|
135
|
+
self.max_retries = max_retries
|
|
136
|
+
self.base_delay = base_delay
|
|
137
|
+
self.max_delay = max_delay
|
|
138
|
+
self._debug = _resolve_debug(debug)
|
|
139
|
+
|
|
140
|
+
headers = {
|
|
141
|
+
"content-type": "application/json",
|
|
142
|
+
"accept": "application/json",
|
|
143
|
+
"user-agent": f"StableOpsSDK/{_SDK_VERSION}",
|
|
144
|
+
}
|
|
145
|
+
if api_key:
|
|
146
|
+
headers["authorization"] = f"Bearer {api_key}"
|
|
147
|
+
|
|
148
|
+
self.client = httpx.Client(
|
|
149
|
+
base_url=self.base_url,
|
|
150
|
+
headers=headers,
|
|
151
|
+
timeout=self.timeout,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
if self._debug:
|
|
155
|
+
self._debug(
|
|
156
|
+
{
|
|
157
|
+
"type": "init",
|
|
158
|
+
"config": {
|
|
159
|
+
"base_url": self.base_url,
|
|
160
|
+
"api_key": mask_secret(api_key),
|
|
161
|
+
"timeout": self.timeout,
|
|
162
|
+
"max_retries": self.max_retries,
|
|
163
|
+
"base_delay": self.base_delay,
|
|
164
|
+
"max_delay": self.max_delay,
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def request(
|
|
170
|
+
self,
|
|
171
|
+
method: HttpMethod,
|
|
172
|
+
path: str,
|
|
173
|
+
body: Optional[Dict[str, Any]] = None,
|
|
174
|
+
query: Optional[Dict[str, Any]] = None,
|
|
175
|
+
idempotency_key: Optional[str] = None,
|
|
176
|
+
) -> Any:
|
|
177
|
+
"""Make HTTP request with retry logic.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
method: HTTP method
|
|
181
|
+
path: Request path
|
|
182
|
+
body: Request body (JSON)
|
|
183
|
+
query: Query parameters
|
|
184
|
+
idempotency_key: Idempotency key for write operations
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
Response JSON
|
|
188
|
+
|
|
189
|
+
Raises:
|
|
190
|
+
StableOpsError: On API error or network failure
|
|
191
|
+
"""
|
|
192
|
+
url = path
|
|
193
|
+
if query:
|
|
194
|
+
# Filter out None values
|
|
195
|
+
filtered_query = {k: v for k, v in query.items() if v is not None}
|
|
196
|
+
if filtered_query:
|
|
197
|
+
url = f"{path}?{urlencode(filtered_query)}"
|
|
198
|
+
|
|
199
|
+
headers = {}
|
|
200
|
+
if idempotency_key:
|
|
201
|
+
headers[IDEMPOTENCY_HEADER] = idempotency_key
|
|
202
|
+
|
|
203
|
+
for attempt in range(self.max_retries + 1):
|
|
204
|
+
started = time.monotonic()
|
|
205
|
+
if self._debug:
|
|
206
|
+
merged = {**dict(self.client.headers), **headers}
|
|
207
|
+
self._debug(
|
|
208
|
+
{
|
|
209
|
+
"type": "request",
|
|
210
|
+
"method": method,
|
|
211
|
+
"url": f"{self.base_url}{url}",
|
|
212
|
+
"headers": _mask_headers(merged),
|
|
213
|
+
"body": body,
|
|
214
|
+
"attempt": attempt,
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
try:
|
|
218
|
+
response = self.client.request(
|
|
219
|
+
method=method,
|
|
220
|
+
url=url,
|
|
221
|
+
json=body,
|
|
222
|
+
headers=headers,
|
|
223
|
+
)
|
|
224
|
+
if self._debug:
|
|
225
|
+
self._debug(
|
|
226
|
+
{
|
|
227
|
+
"type": "response",
|
|
228
|
+
"method": method,
|
|
229
|
+
"url": f"{self.base_url}{url}",
|
|
230
|
+
"status": response.status_code,
|
|
231
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
232
|
+
"headers": dict(response.headers),
|
|
233
|
+
"body": _safe_json(response),
|
|
234
|
+
"attempt": attempt,
|
|
235
|
+
}
|
|
236
|
+
)
|
|
237
|
+
response.raise_for_status()
|
|
238
|
+
return response.json()
|
|
239
|
+
|
|
240
|
+
except httpx.HTTPStatusError as e:
|
|
241
|
+
status = e.response.status_code
|
|
242
|
+
|
|
243
|
+
# Don't retry 4xx errors (except 429)
|
|
244
|
+
if 400 <= status < 500 and status != 429:
|
|
245
|
+
error_data = self._parse_error(e.response)
|
|
246
|
+
raise StableOpsError(
|
|
247
|
+
message=error_data.get("message", str(e)),
|
|
248
|
+
status=status,
|
|
249
|
+
code=error_data.get("code", "api_error"),
|
|
250
|
+
details=error_data.get("details"),
|
|
251
|
+
) from e
|
|
252
|
+
|
|
253
|
+
# Retry on 429 and 5xx
|
|
254
|
+
if attempt < self.max_retries and is_retryable_status(status):
|
|
255
|
+
retry_after = self._parse_retry_after(e.response)
|
|
256
|
+
delay = compute_delay(attempt, self.base_delay, self.max_delay, retry_after)
|
|
257
|
+
time.sleep(delay)
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
# Max retries exceeded
|
|
261
|
+
error_data = self._parse_error(e.response)
|
|
262
|
+
raise StableOpsError(
|
|
263
|
+
message=error_data.get("message", str(e)),
|
|
264
|
+
status=status,
|
|
265
|
+
code=error_data.get("code", "api_error"),
|
|
266
|
+
details=error_data.get("details"),
|
|
267
|
+
) from e
|
|
268
|
+
|
|
269
|
+
except (httpx.TimeoutException, httpx.NetworkError) as e:
|
|
270
|
+
if self._debug:
|
|
271
|
+
self._debug(
|
|
272
|
+
{
|
|
273
|
+
"type": "error",
|
|
274
|
+
"method": method,
|
|
275
|
+
"url": f"{self.base_url}{url}",
|
|
276
|
+
"attempt": attempt,
|
|
277
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
278
|
+
"error": {"type": type(e).__name__, "message": str(e)},
|
|
279
|
+
}
|
|
280
|
+
)
|
|
281
|
+
# Retry on timeout and network errors
|
|
282
|
+
if attempt < self.max_retries:
|
|
283
|
+
delay = compute_delay(attempt, self.base_delay, self.max_delay)
|
|
284
|
+
time.sleep(delay)
|
|
285
|
+
continue
|
|
286
|
+
|
|
287
|
+
# Max retries exceeded
|
|
288
|
+
error_type = "timeout" if isinstance(e, httpx.TimeoutException) else "network_error"
|
|
289
|
+
raise StableOpsError(
|
|
290
|
+
message=str(e),
|
|
291
|
+
status=0,
|
|
292
|
+
code=error_type,
|
|
293
|
+
details=None,
|
|
294
|
+
) from e
|
|
295
|
+
|
|
296
|
+
# Should never reach here
|
|
297
|
+
raise StableOpsError(
|
|
298
|
+
message="Max retries exceeded",
|
|
299
|
+
status=0,
|
|
300
|
+
code="max_retries_exceeded",
|
|
301
|
+
details=None,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def _parse_error(self, response: httpx.Response) -> Dict[str, Any]:
|
|
305
|
+
"""Parse error response."""
|
|
306
|
+
try:
|
|
307
|
+
return response.json() # type: ignore[no-any-return]
|
|
308
|
+
except Exception:
|
|
309
|
+
return {"message": response.text or "Unknown error", "code": "unknown_error"}
|
|
310
|
+
|
|
311
|
+
def _parse_retry_after(self, response: httpx.Response) -> Optional[float]:
|
|
312
|
+
"""Parse Retry-After header."""
|
|
313
|
+
retry_after = response.headers.get("retry-after")
|
|
314
|
+
if not retry_after:
|
|
315
|
+
return None
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
return float(retry_after)
|
|
319
|
+
except ValueError:
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
def close(self) -> None:
|
|
323
|
+
"""Close HTTP client."""
|
|
324
|
+
self.client.close()
|
|
325
|
+
|
|
326
|
+
def __enter__(self) -> "HttpClient":
|
|
327
|
+
"""Context manager entry."""
|
|
328
|
+
return self
|
|
329
|
+
|
|
330
|
+
def __exit__(self, *args: Any) -> None:
|
|
331
|
+
"""Context manager exit."""
|
|
332
|
+
self.close()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class AsyncHttpClient:
|
|
336
|
+
"""Asynchronous HTTP client with retry logic."""
|
|
337
|
+
|
|
338
|
+
def __init__(
|
|
339
|
+
self,
|
|
340
|
+
api_key: Optional[str] = None,
|
|
341
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
342
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
343
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
344
|
+
base_delay: float = DEFAULT_BASE_DELAY,
|
|
345
|
+
max_delay: float = DEFAULT_MAX_DELAY,
|
|
346
|
+
debug: DebugOption = None,
|
|
347
|
+
) -> None:
|
|
348
|
+
"""Initialize async HTTP client."""
|
|
349
|
+
self.base_url = base_url.rstrip("/")
|
|
350
|
+
self.timeout = timeout
|
|
351
|
+
self.max_retries = max_retries
|
|
352
|
+
self.base_delay = base_delay
|
|
353
|
+
self.max_delay = max_delay
|
|
354
|
+
self._debug = _resolve_debug(debug)
|
|
355
|
+
|
|
356
|
+
headers = {
|
|
357
|
+
"content-type": "application/json",
|
|
358
|
+
"accept": "application/json",
|
|
359
|
+
"user-agent": f"StableOpsSDK/{_SDK_VERSION}",
|
|
360
|
+
}
|
|
361
|
+
if api_key:
|
|
362
|
+
headers["authorization"] = f"Bearer {api_key}"
|
|
363
|
+
|
|
364
|
+
self.client = httpx.AsyncClient(
|
|
365
|
+
base_url=self.base_url,
|
|
366
|
+
headers=headers,
|
|
367
|
+
timeout=self.timeout,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
if self._debug:
|
|
371
|
+
self._debug(
|
|
372
|
+
{
|
|
373
|
+
"type": "init",
|
|
374
|
+
"config": {
|
|
375
|
+
"base_url": self.base_url,
|
|
376
|
+
"api_key": mask_secret(api_key),
|
|
377
|
+
"timeout": self.timeout,
|
|
378
|
+
"max_retries": self.max_retries,
|
|
379
|
+
"base_delay": self.base_delay,
|
|
380
|
+
"max_delay": self.max_delay,
|
|
381
|
+
},
|
|
382
|
+
}
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
async def request(
|
|
386
|
+
self,
|
|
387
|
+
method: HttpMethod,
|
|
388
|
+
path: str,
|
|
389
|
+
body: Optional[Dict[str, Any]] = None,
|
|
390
|
+
query: Optional[Dict[str, Any]] = None,
|
|
391
|
+
idempotency_key: Optional[str] = None,
|
|
392
|
+
) -> Any:
|
|
393
|
+
"""Make async HTTP request with retry logic."""
|
|
394
|
+
import asyncio
|
|
395
|
+
|
|
396
|
+
url = path
|
|
397
|
+
if query:
|
|
398
|
+
filtered_query = {k: v for k, v in query.items() if v is not None}
|
|
399
|
+
if filtered_query:
|
|
400
|
+
url = f"{path}?{urlencode(filtered_query)}"
|
|
401
|
+
|
|
402
|
+
headers = {}
|
|
403
|
+
if idempotency_key:
|
|
404
|
+
headers[IDEMPOTENCY_HEADER] = idempotency_key
|
|
405
|
+
|
|
406
|
+
for attempt in range(self.max_retries + 1):
|
|
407
|
+
started = time.monotonic()
|
|
408
|
+
if self._debug:
|
|
409
|
+
merged = {**dict(self.client.headers), **headers}
|
|
410
|
+
self._debug(
|
|
411
|
+
{
|
|
412
|
+
"type": "request",
|
|
413
|
+
"method": method,
|
|
414
|
+
"url": f"{self.base_url}{url}",
|
|
415
|
+
"headers": _mask_headers(merged),
|
|
416
|
+
"body": body,
|
|
417
|
+
"attempt": attempt,
|
|
418
|
+
}
|
|
419
|
+
)
|
|
420
|
+
try:
|
|
421
|
+
response = await self.client.request(
|
|
422
|
+
method=method,
|
|
423
|
+
url=url,
|
|
424
|
+
json=body,
|
|
425
|
+
headers=headers,
|
|
426
|
+
)
|
|
427
|
+
if self._debug:
|
|
428
|
+
self._debug(
|
|
429
|
+
{
|
|
430
|
+
"type": "response",
|
|
431
|
+
"method": method,
|
|
432
|
+
"url": f"{self.base_url}{url}",
|
|
433
|
+
"status": response.status_code,
|
|
434
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
435
|
+
"headers": dict(response.headers),
|
|
436
|
+
"body": _safe_json(response),
|
|
437
|
+
"attempt": attempt,
|
|
438
|
+
}
|
|
439
|
+
)
|
|
440
|
+
response.raise_for_status()
|
|
441
|
+
return response.json()
|
|
442
|
+
|
|
443
|
+
except httpx.HTTPStatusError as e:
|
|
444
|
+
status = e.response.status_code
|
|
445
|
+
|
|
446
|
+
if 400 <= status < 500 and status != 429:
|
|
447
|
+
error_data = self._parse_error(e.response)
|
|
448
|
+
raise StableOpsError(
|
|
449
|
+
message=error_data.get("message", str(e)),
|
|
450
|
+
status=status,
|
|
451
|
+
code=error_data.get("code", "api_error"),
|
|
452
|
+
details=error_data.get("details"),
|
|
453
|
+
) from e
|
|
454
|
+
|
|
455
|
+
if attempt < self.max_retries and is_retryable_status(status):
|
|
456
|
+
retry_after = self._parse_retry_after(e.response)
|
|
457
|
+
delay = compute_delay(attempt, self.base_delay, self.max_delay, retry_after)
|
|
458
|
+
await asyncio.sleep(delay)
|
|
459
|
+
continue
|
|
460
|
+
|
|
461
|
+
error_data = self._parse_error(e.response)
|
|
462
|
+
raise StableOpsError(
|
|
463
|
+
message=error_data.get("message", str(e)),
|
|
464
|
+
status=status,
|
|
465
|
+
code=error_data.get("code", "api_error"),
|
|
466
|
+
details=error_data.get("details"),
|
|
467
|
+
) from e
|
|
468
|
+
|
|
469
|
+
except (httpx.TimeoutException, httpx.NetworkError) as e:
|
|
470
|
+
if self._debug:
|
|
471
|
+
self._debug(
|
|
472
|
+
{
|
|
473
|
+
"type": "error",
|
|
474
|
+
"method": method,
|
|
475
|
+
"url": f"{self.base_url}{url}",
|
|
476
|
+
"attempt": attempt,
|
|
477
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
478
|
+
"error": {"type": type(e).__name__, "message": str(e)},
|
|
479
|
+
}
|
|
480
|
+
)
|
|
481
|
+
if attempt < self.max_retries:
|
|
482
|
+
delay = compute_delay(attempt, self.base_delay, self.max_delay)
|
|
483
|
+
await asyncio.sleep(delay)
|
|
484
|
+
continue
|
|
485
|
+
|
|
486
|
+
error_type = "timeout" if isinstance(e, httpx.TimeoutException) else "network_error"
|
|
487
|
+
raise StableOpsError(
|
|
488
|
+
message=str(e),
|
|
489
|
+
status=0,
|
|
490
|
+
code=error_type,
|
|
491
|
+
details=None,
|
|
492
|
+
) from e
|
|
493
|
+
|
|
494
|
+
raise StableOpsError(
|
|
495
|
+
message="Max retries exceeded",
|
|
496
|
+
status=0,
|
|
497
|
+
code="max_retries_exceeded",
|
|
498
|
+
details=None,
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
def _parse_error(self, response: httpx.Response) -> Dict[str, Any]:
|
|
502
|
+
"""Parse error response."""
|
|
503
|
+
try:
|
|
504
|
+
return response.json() # type: ignore[no-any-return]
|
|
505
|
+
except Exception:
|
|
506
|
+
return {"message": response.text or "Unknown error", "code": "unknown_error"}
|
|
507
|
+
|
|
508
|
+
def _parse_retry_after(self, response: httpx.Response) -> Optional[float]:
|
|
509
|
+
"""Parse Retry-After header."""
|
|
510
|
+
retry_after = response.headers.get("retry-after")
|
|
511
|
+
if not retry_after:
|
|
512
|
+
return None
|
|
513
|
+
|
|
514
|
+
try:
|
|
515
|
+
return float(retry_after)
|
|
516
|
+
except ValueError:
|
|
517
|
+
return None
|
|
518
|
+
|
|
519
|
+
async def close(self) -> None:
|
|
520
|
+
"""Close HTTP client."""
|
|
521
|
+
await self.client.aclose()
|
|
522
|
+
|
|
523
|
+
async def __aenter__(self) -> "AsyncHttpClient":
|
|
524
|
+
"""Async context manager entry."""
|
|
525
|
+
return self
|
|
526
|
+
|
|
527
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
528
|
+
"""Async context manager exit."""
|
|
529
|
+
await self.close()
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _safe_json(response: httpx.Response) -> Any:
|
|
533
|
+
try:
|
|
534
|
+
return response.json()
|
|
535
|
+
except Exception:
|
|
536
|
+
return response.text
|