-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path_http.py
More file actions
188 lines (173 loc) · 5.85 KB
/
Copy path_http.py
File metadata and controls
188 lines (173 loc) · 5.85 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from __future__ import annotations
import time
from collections.abc import Mapping
from typing import Any
import anyio
import httpx
from ._jsonapi import build_headers, parse_error_payload
from .errors import (
AuthError,
NotFound,
RateLimited,
ServerError,
TFEError,
)
_RETRY_STATUSES = {429, 502, 503, 504}
class HTTPTransport:
def __init__(
self,
address: str,
token: str,
*,
timeout: float,
verify_tls: bool,
user_agent_suffix: str | None,
max_retries: int,
backoff_base: float,
backoff_cap: float,
backoff_jitter: bool,
http2: bool,
proxies: dict | None,
ca_bundle: str | None,
):
self.base = address.rstrip("/")
self.headers = build_headers(user_agent_suffix)
if token:
self.headers["Authorization"] = f"Bearer {token}"
self.timeout = timeout
self.verify = verify_tls
self.max_retries = max_retries
self.backoff_base = backoff_base
self.backoff_cap = backoff_cap
self.backoff_jitter = backoff_jitter
self.http2 = http2
self.proxies = proxies
self.ca_bundle = ca_bundle
self._sync = httpx.Client(
http2=http2, timeout=timeout, verify=ca_bundle or verify_tls
) # proxies=proxies
self._async = httpx.AsyncClient(
http2=http2, timeout=timeout, verify=ca_bundle or verify_tls
) # proxies=proxies
def request(
self,
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json_body: Mapping[str, Any] | None = None,
headers: dict[str, str] | None = None,
allow_redirects: bool = True,
) -> httpx.Response:
url = f"{self.base}{path}"
hdrs = dict(self.headers)
if headers:
hdrs.update(headers)
attempt = 0
while True:
try:
resp = self._sync.request(
method,
url,
params=params,
json=json_body,
headers=hdrs,
follow_redirects=allow_redirects,
)
except httpx.HTTPError as e:
if attempt >= self.max_retries:
raise ServerError(str(e)) from e
self._sleep(attempt, None)
attempt += 1
continue
if resp.status_code in _RETRY_STATUSES and attempt < self.max_retries:
retry_after = _parse_retry_after(resp)
self._sleep(attempt, retry_after)
attempt += 1
continue
self._raise_if_error(resp)
return resp
async def arequest(
self,
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json_body: Mapping[str, Any] | None = None,
headers: dict[str, str] | None = None,
allow_redirects: bool = True,
) -> httpx.Response:
url = f"{self.base}{path}"
hdrs = dict(self.headers)
hdrs.update(headers or {})
attempt = 0
while True:
try:
resp = await self._async.request(
method,
url,
params=params,
json=json_body,
headers=hdrs,
follow_redirects=allow_redirects,
)
except httpx.HTTPError as e:
if attempt >= self.max_retries:
raise ServerError(str(e)) from e
await self._asleep(attempt, None)
attempt += 1
continue
if resp.status_code in _RETRY_STATUSES and attempt < self.max_retries:
retry_after = _parse_retry_after(resp)
await self._asleep(attempt, retry_after)
attempt += 1
continue
self._raise_if_error(resp)
return resp
def _sleep(self, attempt: int, retry_after: float | None) -> None:
if retry_after is not None:
time.sleep(retry_after)
return
delay = min(self.backoff_cap, self.backoff_base * (2**attempt))
time.sleep(delay)
async def _asleep(self, attempt: int, retry_after: float | None) -> None:
if retry_after is not None:
await anyio.sleep(retry_after)
return
delay = min(self.backoff_cap, self.backoff_base * (2**attempt))
await anyio.sleep(delay)
def _raise_if_error(self, resp: httpx.Response) -> None:
status = resp.status_code
if 200 <= status < 300:
return
try:
payload: Any = resp.json()
except Exception:
payload = {}
errors = parse_error_payload(payload)
msg: str = f"HTTP {status}"
if errors:
maybe_detail = errors[0].get("detail")
maybe_title = errors[0].get("title")
if isinstance(maybe_detail, str) and maybe_detail:
msg = maybe_detail
elif isinstance(maybe_title, str) and maybe_title:
msg = maybe_title
if status in (401, 403):
raise AuthError(msg, status=status, errors=errors)
if status == 404:
raise NotFound(msg, status=status, errors=errors)
if status == 429:
ra = _parse_retry_after(resp)
raise RateLimited(msg, status=status, errors=errors, retry_after=ra)
if status >= 500:
raise ServerError(msg, status=status, errors=errors)
raise TFEError(msg, status=status, errors=errors)
def _parse_retry_after(resp: httpx.Response) -> float | None:
ra = resp.headers.get("Retry-After")
if not ra:
return None
try:
return float(ra)
except Exception:
return None