-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
148 lines (117 loc) · 4.87 KB
/
Copy pathutils.py
File metadata and controls
148 lines (117 loc) · 4.87 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""HTTP request utilities with endpoint probes and retry logic."""
from __future__ import annotations
import time
from datetime import datetime
from typing import Any
import requests
import config
# ── endpoint connectivity probe ─────────────────────────────────────────────
_probe_cache: dict[str, bool] = {}
def probe_endpoints() -> None:
"""Probe all known endpoints once at startup."""
endpoints = {
"ncbi": "https://api.ncbi.nlm.nih.gov/datasets/v2/taxonomy/taxon/1",
"uniprot": "https://rest.uniprot.org/uniprotkb/search?query=taxonomy_id:1&format=json&size=1",
"rcsb_search": "https://search.rcsb.org/rcsbsearch/v2/query",
"rcsb_fasta": "https://www.rcsb.org/fasta/entry/1AKE/download",
}
for name, url in endpoints.items():
if _probe_cache.get(name):
continue
log(f"Probing endpoint [{name}]: {url[:70]}...")
if name == "rcsb_search":
_probe_one_post(
url,
{
"query": {
"type": "terminal",
"service": "text",
"parameters": {
"attribute": "struct.title",
"operator": "contains_phrase",
"value": "probe",
},
},
"return_type": "entry",
"request_options": {"paginate": {"start": 0, "rows": 1}},
},
)
else:
_probe_one_get(url)
_probe_cache[name] = True
log(f" Endpoint [{name}]: available")
status = ", ".join(f"{name}=available" for name in _probe_cache)
log(f"Endpoint probing completed: {status}")
def _probe_one_get(url: str) -> None:
"""Probe one GET endpoint and raise RuntimeError on failure."""
try:
resp = requests.get(url, timeout=config.PROBE_TIMEOUT)
resp.raise_for_status()
except requests.RequestException as exc:
log(f" Endpoint unavailable: {url}", "ERROR")
raise RuntimeError(f"Could not connect to {url}") from exc
def _probe_one_post(url: str, json_data: dict[str, Any]) -> None:
"""Probe one POST endpoint and raise RuntimeError on failure."""
try:
resp = requests.post(url, json=json_data, timeout=config.PROBE_TIMEOUT)
resp.raise_for_status()
except requests.RequestException as exc:
log(f" Endpoint unavailable: {url}", "ERROR")
raise RuntimeError(f"Could not connect to {url}") from exc
# ── logging ─────────────────────────────────────────────────────────────────
def log(message: str, level: str = "INFO") -> None:
"""Print a timestamped log message."""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{ts}] [{level}] {message}", flush=True)
# ── core request helpers ────────────────────────────────────────────────────
def _try_request(
method: str,
url: str,
*,
timeout: int = config.TIMEOUT,
max_retries: int = config.MAX_RETRIES,
json_data: dict[str, Any] | None = None,
) -> requests.Response:
"""Issue an HTTP request with retries."""
last_exc: Exception | None = None
for attempt in range(max_retries + 1):
try:
if method == "GET":
resp = requests.get(url, timeout=timeout)
else:
resp = requests.post(url, json=json_data, timeout=timeout)
resp.raise_for_status()
return resp
except requests.RequestException as exc:
last_exc = exc
if attempt < max_retries:
wait = config.RETRY_BACKOFF_BASE ** (attempt + 1)
log(
f"{method} {url[:80]}... failed "
f"(attempt {attempt + 1}/{max_retries}): {exc!r:.100}. "
f"Retrying in {wait:.0f}s...",
"WARNING",
)
time.sleep(wait)
raise last_exc # type: ignore[misc]
def http_get(
url: str,
timeout: int = config.TIMEOUT,
max_retries: int = config.MAX_RETRIES,
) -> requests.Response:
"""HTTP GET with retry handling."""
return _try_request("GET", url, timeout=timeout, max_retries=max_retries)
def http_post(
url: str,
json_data: dict[str, Any],
timeout: int = config.TIMEOUT,
max_retries: int = config.MAX_RETRIES,
) -> requests.Response:
"""HTTP POST with retry handling."""
return _try_request(
"POST",
url,
timeout=timeout,
max_retries=max_retries,
json_data=json_data,
)