Repository navigation
Expand file tree
/
Copy pathapi_client.py
More file actions
49 lines (42 loc) · 1.71 KB
/
Copy pathapi_client.py
File metadata and controls
49 lines (42 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import random
import sys
import time
import requests
MAX_RETRIES = max(1, int(os.environ.get("API_MAX_RETRIES", "6")))
BASE_BACKOFF = max(0.1, float(os.environ.get("API_BACKOFF_SECONDS", "2")))
MAX_BACKOFF = max(BASE_BACKOFF, float(os.environ.get("API_MAX_BACKOFF_SECONDS", "45")))
RETRYABLE_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}
def auth_headers(api_key):
return {"Authorization": f"Bearer {api_key}"} if api_key else None
def retry(operation, label):
last_error = None
for attempt in range(1, MAX_RETRIES + 1):
try:
return operation()
except Exception as exc:
last_error = exc
response = getattr(exc, "response", None)
status = getattr(response, "status_code", None)
if status is not None and status not in RETRYABLE_STATUS:
raise
if attempt == MAX_RETRIES:
break
retry_after = None
if response is not None:
value = response.headers.get("Retry-After")
try:
retry_after = float(value) if value else None
except ValueError:
retry_after = None
delay = retry_after if retry_after is not None else min(
MAX_BACKOFF, BASE_BACKOFF * (2 ** (attempt - 1))
)
delay += random.uniform(0, min(1.0, delay * 0.2))
print(
f"{label} failed on attempt {attempt}/{MAX_RETRIES}; retrying in {delay:.1f}s: {exc}",
file=sys.stderr,
flush=True,
)
time.sleep(delay)
raise RuntimeError(f"{label} failed after {MAX_RETRIES} attempts: {last_error}") from last_error