-
Notifications
You must be signed in to change notification settings - Fork 4
/
connection_live.py
371 lines (315 loc) · 13.5 KB
/
connection_live.py
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import json
import os
import time
from dataclasses import dataclass
from dataclasses import field
from datetime import datetime
from functools import partial
from importlib.metadata import version
from typing import Any
from typing import Literal
from typing import Optional
from typing import cast
import regex
from requests import ReadTimeout
from requests import RequestException
from requests import Response
from requests import Session
from dsp_tools.models.exceptions import BadCredentialsError
from dsp_tools.models.exceptions import BaseError
from dsp_tools.models.exceptions import InputError
from dsp_tools.models.exceptions import PermanentConnectionError
from dsp_tools.models.exceptions import UserError
from dsp_tools.utils.create_logger import get_log_filename_str
from dsp_tools.utils.create_logger import get_logger
from dsp_tools.utils.set_encoder import SetEncoder
HTTP_OK = 200
HTTP_UNAUTHORIZED = 401
logger = get_logger(__name__)
LOGFILES = get_log_filename_str(logger)
@dataclass
class RequestParameters:
method: Literal["POST", "GET", "PUT", "DELETE"]
url: str
timeout: int
data: dict[str, Any] | None = None
data_serialized: bytes | None = field(init=False, default=None)
headers: dict[str, str] | None = None
files: dict[str, tuple[str, Any]] | None = None
def __post_init__(self) -> None:
self.data_serialized = self._serialize_payload(self.data)
def _serialize_payload(self, payload: dict[str, Any] | None) -> bytes | None:
# If data is not encoded as bytes, issues can occur with non-ASCII characters,
# where the content-length of the request will turn out to be different from the actual length.
return json.dumps(payload, cls=SetEncoder, ensure_ascii=False).encode("utf-8") if payload else None
def as_kwargs(self) -> dict[str, Any]:
return {
"method": self.method,
"url": self.url,
"timeout": self.timeout,
"data": self.data_serialized,
"headers": self.headers,
"files": self.files,
}
@dataclass
class ConnectionLive:
"""
A Connection instance represents a connection to a DSP server.
Attributes:
server: address of the server, e.g https://api.dasch.swiss
token: session token received by the server after login
"""
server: str
token: Optional[str] = None
session: Session = field(init=False, default=Session())
# downtimes of server-side services -> API still processes request
# -> retry too early has side effects (e.g. duplicated resources)
timeout_put_post: int = field(init=False, default=30 * 60)
timeout_get_delete: int = field(init=False, default=20)
def __post_init__(self) -> None:
self.session.headers["User-Agent"] = f'DSP-TOOLS/{version("dsp-tools")}'
if self.server.endswith("/"):
self.server = self.server[:-1]
def login(self, email: str, password: str) -> None:
"""
Retrieve a session token and store it as class attribute.
Args:
email: email address of the user
password: password of the user
Raises:
UserError: if DSP-API returns no token with the provided user credentials
"""
try:
response = self.post(
route="/v2/authentication",
data={"email": email, "password": password},
timeout=10,
)
except BadCredentialsError:
raise UserError(f"Username and/or password are not valid on server '{self.server}'") from None
except PermanentConnectionError as e:
raise UserError(e.message) from None
if not response.get("token"):
raise UserError("Unable to retrieve a token from the server with the provided credentials.")
self.token = response["token"]
self.session.headers["Authorization"] = f"Bearer {self.token}"
def logout(self) -> None:
"""
Delete the token on the server and in this class.
"""
if self.token:
self.delete(route="/v2/authentication")
self.token = None
del self.session.headers["Authorization"]
def get_token(self) -> str:
"""
Return the token of this connection.
Returns:
token
Raises:
BaseError: if no token is available
"""
if not self.token:
raise BaseError("No token available.")
return self.token
def post(
self,
route: str,
data: dict[str, Any] | None = None,
files: dict[str, tuple[str, Any]] | None = None,
headers: dict[str, str] | None = None,
timeout: int | None = None,
) -> dict[str, Any]:
"""
Make an HTTP POST request to the server to which this connection has been established.
Args:
route: route that will be called on the server
data: payload of the HTTP request
files: files to be uploaded, if any
headers: headers for the HTTP request
timeout: timeout of the HTTP request, or None if the default should be used
Returns:
response from server
Raises:
PermanentConnectionError: if the server returns a permanent error
"""
if data:
headers = headers or {}
if "Content-Type" not in headers:
headers["Content-Type"] = "application/json; charset=UTF-8"
params = RequestParameters(
"POST", self._make_url(route), timeout or self.timeout_put_post, data, headers, files
)
response = self._try_network_action(params)
return cast(dict[str, Any], response.json())
def get(
self,
route: str,
headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
Make an HTTP GET request to the server to which this connection has been established.
Args:
route: route that will be called on the server
headers: headers for the HTTP request
Returns:
response from server
Raises:
PermanentConnectionError: if the server returns a permanent error
"""
params = RequestParameters("GET", self._make_url(route), self.timeout_get_delete, headers=headers)
response = self._try_network_action(params)
return cast(dict[str, Any], response.json())
def put(
self,
route: str,
data: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
Make an HTTP GET request to the server to which this connection has been established.
Args:
route: route that will be called on the server
data: payload of the HTTP request
headers: headers of the HTTP request
Returns:
response from server
Raises:
PermanentConnectionError: if the server returns a permanent error
"""
if data:
headers = headers or {}
if "Content-Type" not in headers:
headers["Content-Type"] = "application/json; charset=UTF-8"
params = RequestParameters("PUT", self._make_url(route), self.timeout_put_post, data, headers)
response = self._try_network_action(params)
return cast(dict[str, Any], response.json())
def delete(
self,
route: str,
headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
Make an HTTP GET request to the server to which this connection has been established.
Args:
route: route that will be called on the server
headers: headers for the HTTP request
Returns:
response from server
Raises:
PermanentConnectionError: if the server returns a permanent error
"""
params = RequestParameters("DELETE", self._make_url(route), self.timeout_get_delete, headers=headers)
response = self._try_network_action(params)
return cast(dict[str, Any], response.json())
def _make_url(self, route: str) -> str:
if not route.startswith("/"):
route = f"/{route}"
return self.server + route
def _try_network_action(self, params: RequestParameters) -> Response:
"""
Try 7 times to execute an HTTP request.
If a timeout error, a ConnectionError, or a requests.RequestException occur,
or if the response indicates that there is a non-permanent server-side problem,
this function waits and retries the HTTP request.
The waiting times are 1, 2, 4, 8, 16, 32, 64 seconds.
Args:
params: keyword arguments for the HTTP request
Raises:
BadCredentialsError: if the server returns a 401 status code on the route /v2/authentication
PermanentConnectionError: if the server returns a permanent error
unexpected exceptions: if the action fails with an unexpected exception
Returns:
the return value of action
"""
action = partial(self.session.request, **params.as_kwargs())
for i in range(7):
try:
self._log_request(params)
response = action()
except (TimeoutError, ReadTimeout):
self._log_and_sleep(reason="Timeout Error", retry_counter=i, exc_info=True)
continue
except (ConnectionError, RequestException):
self._renew_session()
self._log_and_sleep(reason="Connection Error raised", retry_counter=i, exc_info=True)
continue
self._log_response(response)
if response.status_code == HTTP_OK:
return response
self._handle_non_ok_responses(response, params.url, i)
# after 7 vain attempts to create a response, try it a last time and let it escalate
return action()
def _handle_non_ok_responses(self, response: Response, request_url: str, retry_counter: int) -> None:
permanent_error_regexes = [
r"OntologyConstraintException",
r"DuplicateValueException",
r"Project '[0-9A-F]{4}' not found",
]
if "v2/authentication" in request_url and response.status_code == HTTP_UNAUTHORIZED:
raise BadCredentialsError("Bad credentials")
elif any(regex.search(x, response.text) for x in permanent_error_regexes):
msg = f"Error occurred due to user input. Original message:\n{response.text}"
raise InputError(msg)
elif not self._in_testing_environment():
self._log_and_sleep(reason="Non-200 response code", retry_counter=retry_counter, exc_info=False)
return None
else:
msg = f"Permanently unable to execute the network action. See logs for more details: {LOGFILES}"
raise PermanentConnectionError(msg)
def _renew_session(self) -> None:
self.session.close()
self.session = Session()
self.session.headers["User-Agent"] = f'DSP-TOOLS/{version("dsp-tools")}'
if self.token:
self.session.headers["Authorization"] = f"Bearer {self.token}"
def _log_and_sleep(self, reason: str, retry_counter: int, exc_info: bool) -> None:
msg = f"{reason}: Try reconnecting to DSP server, next attempt in {2 ** retry_counter} seconds..."
print(f"{datetime.now()}: {msg}")
logger.error(f"{msg} ({retry_counter=:})", exc_info=exc_info)
time.sleep(2**retry_counter)
def _log_response(self, response: Response) -> None:
dumpobj: dict[str, Any] = {
"status_code": response.status_code,
"headers": self._anonymize(dict(response.headers)),
}
try:
dumpobj["content"] = self._anonymize(json.loads(response.text))
except json.JSONDecodeError:
dumpobj["content"] = response.text if "token" not in response.text else "***"
logger.debug(f"RESPONSE: {json.dumps(dumpobj)}")
def _anonymize(self, data: dict[str, Any] | None) -> dict[str, Any] | None:
if not data:
return data
data = data.copy()
if "token" in data:
data["token"] = self._mask(data["token"])
if "Set-Cookie" in data:
data["Set-Cookie"] = self._mask(data["Set-Cookie"])
if "Authorization" in data:
if match := regex.search(r"^Bearer (.+)", data["Authorization"]):
data["Authorization"] = f"Bearer {self._mask(match.group(1))}"
if "password" in data:
data["password"] = "*" * len(data["password"])
return data
def _mask(self, sensitive_info: str) -> str:
unmasked_until = 5
if len(sensitive_info) <= unmasked_until * 2:
return "*" * len(sensitive_info)
else:
return f"{sensitive_info[:unmasked_until]}[+{len(sensitive_info) - unmasked_until}]"
def _in_testing_environment(self) -> bool:
in_testing_env = os.getenv("DSP_TOOLS_TESTING") # set in .github/workflows/tests-on-push.yml
return in_testing_env == "true"
def _log_request(self, params: RequestParameters) -> None:
dumpobj = {
"method": params.method,
"url": params.url,
"headers": self._anonymize(dict(self.session.headers) | (params.headers or {})),
"timeout": params.timeout,
}
if params.data:
dumpobj["data"] = self._anonymize(params.data)
if params.files:
dumpobj["files"] = params.files["file"][0]
logger.debug(f"REQUEST: {json.dumps(dumpobj, cls=SetEncoder)}")