-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase.py
More file actions
210 lines (176 loc) · 7.09 KB
/
base.py
File metadata and controls
210 lines (176 loc) · 7.09 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
from datetime import datetime, timedelta
import logging
import base64
from typing import Any
import httpx
from obelisk.exceptions import AuthenticationError, ObeliskError
from obelisk.strategies.retry import RetryStrategy, NoRetryStrategy
from obelisk.types import ObeliskKind
class BaseClient:
"""
Base class handling Obelisk auth and doing the core HTTP communication.
Only exists in asynchronous variety, as it is not usually directly useful for user code.
"""
_client: str = ""
_secret: str = ""
_token: str | None = None
"""Current authentication token"""
_token_expires: datetime | None = None
"""Deadline after which token is no longer useable"""
grace_period: timedelta = timedelta(seconds=10)
"""Controls how much before the expiration deadline a token will be refreshed."""
retry_strategy: RetryStrategy
kind: ObeliskKind
log: logging.Logger
def __init__(
self,
client: str,
secret: str,
retry_strategy: RetryStrategy = NoRetryStrategy(), # noqa: B008 # This is fine to bew shared
kind: ObeliskKind = ObeliskKind.CLASSIC,
) -> None:
self._client = client
self._secret = secret
self.retry_strategy = retry_strategy
self.kind = kind
self.log = logging.getLogger("obelisk")
async def _get_token(self) -> None:
auth_string = str(
base64.b64encode(f"{self._client}:{self._secret}".encode()), "utf-8"
)
headers = {
"Authorization": f"Basic {auth_string}",
"Content-Type": (
"application/json"
if self.kind.use_json_auth
else "application/x-www-form-urlencoded"
),
}
payload = {"grant_type": "client_credentials"}
async with httpx.AsyncClient() as client:
request: httpx.Response | None = None
response = None
last_error = None
retry = self.retry_strategy.make()
while not response or await retry.should_retry():
try:
request = await client.post(
self.kind.token_url,
json=payload if self.kind.use_json_auth else None,
data=payload if not self.kind.use_json_auth else None,
headers=headers,
)
response = request.json()
except Exception as e: # noqa: PERF203 # retry strategy should add delay
last_error = e
self.log.error(e)
continue
if response is None and last_error is not None:
raise last_error
if request is None:
raise last_error or ObeliskError("Could not create HTTP request")
if request.status_code != 200:
if "error" in response:
self.log.warning(f"Could not authenticate, {response['error']}")
raise AuthenticationError
self._token = response["access_token"]
self._token_expires = datetime.now() + timedelta(
seconds=response["expires_in"]
)
async def _verify_token(self) -> None:
if (
self._token is None
or self._token_expires is None
or self._token_expires >= (datetime.now() - self.grace_period)
):
retry = self.retry_strategy.make()
first = True
while first or await retry.should_retry():
first = False
try:
await self._get_token()
return
except: # noqa: E722
self.log.info("excepted, Retrying token fetch")
continue
async def http_post(
self, url: str, data: Any = None, params: dict[str, str] | None = None
) -> httpx.Response:
"""
Send an HTTP POST request to Obelisk,
with proper auth.
Possibly refreshes the authentication token and performs backoff as per `retry_strategy`.
This method is not of stable latency because of these properties.
No validation is performed on the input data,
callers are responsible for formatting it in a method Obelisk understands.
"""
await self._verify_token()
headers = {
"Authorization": f"Bearer {self._token}",
"Content-Type": "application/json",
}
if params is None:
params = {}
async with httpx.AsyncClient() as client:
response = None
retry = self.retry_strategy.make()
last_error = None
while not response or await retry.should_retry():
if response is not None:
self.log.debug(f"Retrying, last response: {response.status_code}")
try:
response = await client.post(
url,
json=data,
params={k: v for k, v in params.items() if v is not None},
headers=headers,
)
if response.status_code // 100 == 2:
return response
except Exception as e:
self.log.error(e)
last_error = e
continue
if not response and last_error:
raise last_error
return response
async def http_get(
self, url: str, params: dict[str, str] | None = None
) -> httpx.Response:
"""
Send an HTTP GET request to Obelisk,
with proper auth.
Possibly refreshes the authentication token and performs backoff as per `retry_strategy`.
This method is not of stable latency because of these properties.
No validation is performed on the input data,
callers are responsible for formatting it in a method Obelisk understands.
"""
await self._verify_token()
headers = {
"Authorization": f"Bearer {self._token}",
"Content-Type": "application/json",
}
if params is None:
params = {}
async with httpx.AsyncClient() as client:
response = None
retry = self.retry_strategy.make()
last_error = None
while not response or await retry.should_retry():
if response is not None:
self.log.debug(f"Retrying, last response: {response.status_code}")
try:
response = await client.get(
url,
params={k: v for k, v in params.items() if v is not None},
headers=headers,
)
if response.status_code // 100 == 2:
return response
except Exception as e:
self.log.error(e)
last_error = e
continue
if not response and last_error:
raise last_error
return response