| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import logging |
| 5 |
import pathlib |
| 6 |
import time |
| 7 |
import typing as t |
| 8 |
|
| 9 |
import requests |
| 10 |
|
| 11 |
from globus_sdk import __version__, config, exc |
| 12 |
from globus_sdk.authorizers import GlobusAuthorizer |
| 13 |
from globus_sdk.transport.encoders import ( |
| 14 |
FormRequestEncoder, |
| 15 |
JSONRequestEncoder, |
| 16 |
RequestEncoder, |
| 17 |
) |
| 18 |
|
| 19 |
from ._clientinfo import GlobusClientInfo |
| 20 |
from .caller_info import RequestCallerInfo |
| 21 |
from .retry import RetryContext |
| 22 |
from .retry_check_runner import RetryCheckRunner |
| 23 |
from .retry_config import RetryConfig |
| 24 |
|
| 25 |
log = logging.getLogger(__name__) |
| 26 |
|
| 27 |
|
| 28 |
class RequestsTransport: |
| 29 |
""" |
| 30 |
The RequestsTransport handles HTTP request sending and retries. |
| 31 |
|
| 32 |
It receives raw request information from a client class, and then performs the |
| 33 |
following steps |
| 34 |
- encode the data in a prepared request |
| 35 |
- repeatedly send the request until no retry is requested by the configured hooks |
| 36 |
- return the last response or reraise the last exception |
| 37 |
|
| 38 |
If the maximum number of retries is reached, the final response or exception will |
| 39 |
be returned or raised. |
| 40 |
|
| 41 |
:param verify_ssl: Explicitly enable or disable SSL verification, |
| 42 |
or configure the path to a CA certificate bundle to use for SSL verification |
| 43 |
:param http_timeout: Explicitly set an HTTP timeout value in seconds. This parameter |
| 44 |
defaults to 60s but can be set via the ``GLOBUS_SDK_HTTP_TIMEOUT`` environment |
| 45 |
variable. Any value set via this parameter takes precedence over the environment |
| 46 |
variable. |
| 47 |
|
| 48 |
:ivar dict[str, str] headers: The headers which are sent on every request. These |
| 49 |
may be augmented by the transport when sending requests. |
| 50 |
""" |
| 51 |
|
| 52 |
#: default maximum number of retries |
| 53 |
DEFAULT_MAX_RETRIES = 5 |
| 54 |
|
| 55 |
#: the encoders are a mapping of encoding names to encoder objects |
| 56 |
encoders: dict[str, RequestEncoder] = { |
| 57 |
"text": RequestEncoder(), |
| 58 |
"json": JSONRequestEncoder(), |
| 59 |
"form": FormRequestEncoder(), |
| 60 |
} |
| 61 |
|
| 62 |
BASE_USER_AGENT = f"globus-sdk-py-{__version__}" |
| 63 |
|
| 64 |
def __init__( |
| 65 |
self, |
| 66 |
verify_ssl: bool | str | pathlib.Path | None = None, |
| 67 |
http_timeout: float | None = None, |
| 68 |
) -> None: |
| 69 |
self.session = requests.Session() |
| 70 |
self.verify_ssl = config.get_ssl_verify(verify_ssl) |
| 71 |
self.http_timeout = config.get_http_timeout(http_timeout) |
| 72 |
self._user_agent = self.BASE_USER_AGENT |
| 73 |
self.globus_client_info: GlobusClientInfo = GlobusClientInfo( |
| 74 |
update_callback=self._handle_clientinfo_update |
| 75 |
) |
| 76 |
self.headers: dict[str, str] = { |
| 77 |
"Accept": "application/json", |
| 78 |
"User-Agent": self.user_agent, |
| 79 |
"X-Globus-Client-Info": self.globus_client_info.format(), |
| 80 |
} |
| 81 |
|
| 82 |
def close(self) -> None: |
| 83 |
""" |
| 84 |
Closes all resources owned by the transport, primarily the underlying |
| 85 |
network session. |
| 86 |
""" |
| 87 |
self.session.close() |
| 88 |
|
| 89 |
@property |
| 90 |
def user_agent(self) -> str: |
| 91 |
return self._user_agent |
| 92 |
|
| 93 |
@user_agent.setter |
| 94 |
def user_agent(self, value: str) -> None: |
| 95 |
""" |
| 96 |
Set the ``user_agent`` and update the ``User-Agent`` header in ``headers``. |
| 97 |
|
| 98 |
:param value: The new user-agent string to set (after the base user-agent) |
| 99 |
""" |
| 100 |
self._user_agent = f"{self.BASE_USER_AGENT}/{value}" |
| 101 |
self.headers["User-Agent"] = self._user_agent |
| 102 |
|
| 103 |
def _handle_clientinfo_update( |
| 104 |
self, |
| 105 |
info: GlobusClientInfo, # pylint: disable=unused-argument |
| 106 |
) -> None: |
| 107 |
""" |
| 108 |
When the attached ``GlobusClientInfo`` is updated, write it back into |
| 109 |
``headers``. |
| 110 |
|
| 111 |
If the client info is cleared, it will be removed from the headers. |
| 112 |
""" |
| 113 |
formatted = self.globus_client_info.format() |
| 114 |
if formatted: |
| 115 |
self.headers["X-Globus-Client-Info"] = formatted |
| 116 |
else: |
| 117 |
# discard the element, so that this can be invoked multiple times |
| 118 |
self.headers.pop("X-Globus-Client-Info", None) |
| 119 |
|
| 120 |
@contextlib.contextmanager |
| 121 |
def tune( |
| 122 |
self, |
| 123 |
*, |
| 124 |
verify_ssl: bool | str | pathlib.Path | None = None, |
| 125 |
http_timeout: float | None = None, |
| 126 |
) -> t.Iterator[None]: |
| 127 |
""" |
| 128 |
Temporarily adjust some of the request sending settings of the transport. |
| 129 |
This method works as a context manager, and will reset settings to their |
| 130 |
original values after it exits. |
| 131 |
|
| 132 |
:param verify_ssl: Explicitly enable or disable SSL verification, |
| 133 |
or configure the path to a CA certificate bundle to use for SSL verification |
| 134 |
:param http_timeout: Explicitly set an HTTP timeout value in seconds |
| 135 |
|
| 136 |
**Example Usage** |
| 137 |
|
| 138 |
This can be used with any client class to temporarily set values in the context |
| 139 |
of one or more HTTP requests. To increase the HTTP request timeout from the |
| 140 |
default of 60 to 120 seconds, |
| 141 |
|
| 142 |
>>> client = ... # any client class |
| 143 |
>>> with client.transport.tune(http_timeout=120): |
| 144 |
>>> foo = client.get_foo() |
| 145 |
|
| 146 |
See also: :meth:`RetryConfig.tune`. |
| 147 |
""" |
| 148 |
saved_settings = ( |
| 149 |
self.verify_ssl, |
| 150 |
self.http_timeout, |
| 151 |
) |
| 152 |
if verify_ssl is not None: |
| 153 |
if isinstance(verify_ssl, bool): |
| 154 |
self.verify_ssl = verify_ssl |
| 155 |
else: |
| 156 |
self.verify_ssl = str(verify_ssl) |
| 157 |
if http_timeout is not None: |
| 158 |
self.http_timeout = http_timeout |
| 159 |
yield |
| 160 |
( |
| 161 |
self.verify_ssl, |
| 162 |
self.http_timeout, |
| 163 |
) = saved_settings |
| 164 |
|
| 165 |
def _encode( |
| 166 |
self, |
| 167 |
method: str, |
| 168 |
url: str, |
| 169 |
query_params: dict[str, t.Any] | None = None, |
| 170 |
data: dict[str, t.Any] | list[t.Any] | str | bytes | None = None, |
| 171 |
headers: dict[str, str] | None = None, |
| 172 |
encoding: str | None = None, |
| 173 |
) -> requests.Request: |
| 174 |
if headers: |
| 175 |
headers = {**self.headers, **headers} |
| 176 |
else: |
| 177 |
headers = self.headers |
| 178 |
|
| 179 |
if encoding is None: |
| 180 |
if isinstance(data, (bytes, str)): |
| 181 |
encoding = "text" |
| 182 |
else: |
| 183 |
encoding = "json" |
| 184 |
|
| 185 |
if encoding not in self.encoders: |
| 186 |
raise ValueError( |
| 187 |
f"Unknown encoding '{encoding}' is not supported by this transport." |
| 188 |
) |
| 189 |
|
| 190 |
return self.encoders[encoding].encode(method, url, query_params, data, headers) |
| 191 |
|
| 192 |
def _set_authz_header( |
| 193 |
self, authorizer: GlobusAuthorizer | None, req: requests.Request |
| 194 |
) -> None: |
| 195 |
if authorizer: |
| 196 |
authz_header = authorizer.get_authorization_header() |
| 197 |
if authz_header: |
| 198 |
req.headers["Authorization"] = authz_header |
| 199 |
else: |
| 200 |
req.headers.pop("Authorization", None) # remove any possible value |
| 201 |
|
| 202 |
def _retry_sleep(self, retry_config: RetryConfig, ctx: RetryContext) -> None: |
| 203 |
""" |
| 204 |
Given a retry context, compute the amount of time to sleep and sleep that much |
| 205 |
This is always the minimum of the backoff (run on the context) and the |
| 206 |
``max_sleep``. |
| 207 |
|
| 208 |
:param ctx: The context object which describes the state of the request and the |
| 209 |
retries which may already have been attempted. |
| 210 |
""" |
| 211 |
sleep_period = min(retry_config.backoff(ctx), retry_config.max_sleep) |
| 212 |
log.debug( |
| 213 |
"request retry_sleep(%s) [max=%s]", |
| 214 |
sleep_period, |
| 215 |
retry_config.max_sleep, |
| 216 |
) |
| 217 |
time.sleep(sleep_period) |
| 218 |
|
| 219 |
def request( |
| 220 |
self, |
| 221 |
method: str, |
| 222 |
url: str, |
| 223 |
*, |
| 224 |
caller_info: RequestCallerInfo, |
| 225 |
query_params: dict[str, t.Any] | None = None, |
| 226 |
data: dict[str, t.Any] | list[t.Any] | str | bytes | None = None, |
| 227 |
headers: dict[str, str] | None = None, |
| 228 |
encoding: str | None = None, |
| 229 |
allow_redirects: bool = True, |
| 230 |
stream: bool = False, |
| 231 |
) -> requests.Response: |
| 232 |
""" |
| 233 |
Send an HTTP request |
| 234 |
|
| 235 |
:param url: URL for the request |
| 236 |
:param method: HTTP request method, as an all caps string |
| 237 |
:param caller_info: Contextual information about the caller of the request, |
| 238 |
including the authorizer and retry configuration. |
| 239 |
:param query_params: Parameters to be encoded as a query string |
| 240 |
:param headers: HTTP headers to add to the request |
| 241 |
:param data: Data to send as the request body. May pass through encoding. |
| 242 |
:param encoding: A way to encode request data. "json", "form", and "text" |
| 243 |
are all valid values. Custom encodings can be used only if they are |
| 244 |
registered with the transport. By default, strings get "text" behavior and |
| 245 |
all other objects get "json". |
| 246 |
:param allow_redirects: Follow Location headers on redirect response |
| 247 |
automatically. Defaults to ``True`` |
| 248 |
:param stream: Do not immediately download the response content. Defaults to |
| 249 |
``False`` |
| 250 |
|
| 251 |
:return: ``requests.Response`` object |
| 252 |
""" |
| 253 |
log.debug("starting request for %s", url) |
| 254 |
resp: requests.Response | None = None |
| 255 |
req = self._encode(method, url, query_params, data, headers, encoding) |
| 256 |
retry_config = caller_info.retry_config |
| 257 |
checker = RetryCheckRunner(caller_info.retry_config.checks) |
| 258 |
|
| 259 |
log.debug("transport request state initialized") |
| 260 |
for attempt in range(retry_config.max_retries + 1): |
| 261 |
log.debug("transport request retry cycle. attempt=%d", attempt) |
| 262 |
# add Authorization header, or (if it's a NullAuthorizer) possibly |
| 263 |
# explicitly remove the Authorization header |
| 264 |
# done fresh for each request, to handle potential for refreshed credentials |
| 265 |
self._set_authz_header(caller_info.authorizer, req) |
| 266 |
|
| 267 |
ctx = RetryContext(attempt, caller_info=caller_info) |
| 268 |
try: |
| 269 |
log.debug("request about to send") |
| 270 |
resp = ctx.response = self.session.send( |
| 271 |
req.prepare(), |
| 272 |
timeout=self.http_timeout, |
| 273 |
verify=self.verify_ssl, |
| 274 |
allow_redirects=allow_redirects, |
| 275 |
stream=stream, |
| 276 |
) |
| 277 |
except requests.RequestException as err: |
| 278 |
log.debug("request hit error (RequestException)") |
| 279 |
ctx.exception = err |
| 280 |
if attempt >= retry_config.max_retries or not checker.should_retry(ctx): |
| 281 |
log.warning("request done (fail, error)") |
| 282 |
raise exc.convert_request_exception(err) |
| 283 |
log.debug("request may retry (should-retry=true)") |
| 284 |
else: |
| 285 |
log.debug("request success, still check should-retry") |
| 286 |
if not checker.should_retry(ctx): |
| 287 |
log.debug("request done (success)") |
| 288 |
return resp |
| 289 |
log.debug("request may retry, will check attempts") |
| 290 |
|
| 291 |
# the request will be retried, so sleep... |
| 292 |
if attempt < retry_config.max_retries: |
| 293 |
log.debug("under attempt limit, will sleep") |
| 294 |
self._retry_sleep(retry_config, ctx) |
| 295 |
if resp is None: |
| 296 |
raise ValueError("Somehow, retries ended without a response") |
| 297 |
log.warning("request reached max retries, done (fail, response)") |
| 298 |
return resp |