2024-07-12 02:30:23 +02:00
|
|
|
from typing import Any
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
import requests
|
2023-10-12 19:43:45 +02:00
|
|
|
from typing_extensions import override
|
2022-01-13 22:02:54 +01:00
|
|
|
from urllib3.util import Retry
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
|
|
|
|
class OutgoingSession(requests.Session):
|
2021-06-29 20:54:49 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
role: str,
|
2024-03-05 03:40:17 +01:00
|
|
|
timeout: float,
|
2024-07-12 02:30:23 +02:00
|
|
|
headers: dict[str, str] | None = None,
|
|
|
|
max_retries: int | Retry | None = None,
|
2021-06-29 20:54:49 +02:00
|
|
|
) -> None:
|
2021-05-07 01:56:31 +02:00
|
|
|
super().__init__()
|
2024-07-12 02:30:23 +02:00
|
|
|
retry: Retry | None = Retry(total=0)
|
2021-06-29 20:54:49 +02:00
|
|
|
if max_retries is not None:
|
|
|
|
if isinstance(max_retries, Retry):
|
|
|
|
retry = max_retries
|
|
|
|
else:
|
|
|
|
retry = Retry(total=max_retries, backoff_factor=1)
|
|
|
|
outgoing_adapter = OutgoingHTTPAdapter(role=role, timeout=timeout, max_retries=retry)
|
2021-05-07 01:56:31 +02:00
|
|
|
self.mount("http://", outgoing_adapter)
|
|
|
|
self.mount("https://", outgoing_adapter)
|
2021-05-07 01:57:46 +02:00
|
|
|
if headers:
|
|
|
|
self.headers.update(headers)
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
|
|
|
|
class OutgoingHTTPAdapter(requests.adapters.HTTPAdapter):
|
2021-05-07 01:57:30 +02:00
|
|
|
role: str
|
2024-03-05 03:40:17 +01:00
|
|
|
timeout: float
|
2021-05-07 01:56:31 +02:00
|
|
|
|
2024-07-12 02:30:23 +02:00
|
|
|
def __init__(self, role: str, timeout: float, max_retries: Retry | None) -> None:
|
2021-05-07 01:57:30 +02:00
|
|
|
self.role = role
|
2021-05-07 01:56:31 +02:00
|
|
|
self.timeout = timeout
|
2021-06-29 20:54:49 +02:00
|
|
|
super().__init__(max_retries=max_retries)
|
2021-05-07 01:56:31 +02:00
|
|
|
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
2021-08-04 11:18:13 +02:00
|
|
|
def send(self, *args: Any, **kwargs: Any) -> requests.Response:
|
2021-05-07 01:56:31 +02:00
|
|
|
if kwargs.get("timeout") is None:
|
|
|
|
kwargs["timeout"] = self.timeout
|
|
|
|
return super().send(*args, **kwargs)
|
2021-05-07 01:57:30 +02:00
|
|
|
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
2024-07-12 02:30:17 +02:00
|
|
|
def proxy_headers(self, proxy: str) -> dict[str, str]:
|
2021-05-07 01:57:30 +02:00
|
|
|
return {"X-Smokescreen-Role": self.role}
|