Debian Codegraph @

src/globus_sdk/client.py

raw
1 from __future__ import annotations
2
3 import logging
4 import sys
5 import types
6 import typing as t
7 import urllib.parse
8
9 from globus_sdk import GlobusSDKUsageError, config, exc
10 from globus_sdk._internal.classprop import classproperty
11 from globus_sdk._internal.type_definitions import Closable
12 from globus_sdk._internal.utils import slash_join
13 from globus_sdk.authorizers import GlobusAuthorizer
14 from globus_sdk.paging import PaginatorTable
15 from globus_sdk.response import GlobusHTTPResponse
16 from globus_sdk.scopes import Scope, ScopeCollection
17 from globus_sdk.transport import RequestCallerInfo, RequestsTransport, RetryConfig
18 from globus_sdk.transport.default_retry_checks import DEFAULT_RETRY_CHECKS
19
20 if sys.version_info >= (3, 10):
21 from typing import TypeAlias
22 else:
23 from typing_extensions import TypeAlias
24
25 if sys.version_info >= (3, 11):
26 from typing import Self
27 else:
28 from typing_extensions import Self
29
30 if t.TYPE_CHECKING:
31 from globus_sdk.globus_app import GlobusApp
32
33 log = logging.getLogger(__name__)
34
35 _DataParamType: TypeAlias = t.Union[None, str, bytes, t.Dict[str, t.Any]]
36
37
38 class BaseClient:
39 r"""
40 Abstract base class for clients with error handling for Globus APIs.
41
42 :param app: A ``GlobusApp`` which will be used for handling authorization and
43 storing and validating tokens. Passing an ``app`` will automatically include
44 a client's default scopes in the ``app``'s scope requirements unless specific
45 ``app_scopes`` are given. If ``app_name`` is not given, the ``app``'s
46 ``app_name`` will be used. Mutually exclusive with ``authorizer``.
47 :param app_scopes: Optional list of ``Scope`` objects to be added to ``app``'s
48 scope requirements instead of ``default_scope_requirements``. Requires ``app``.
49 :param authorizer: A ``GlobusAuthorizer`` which will generate Authorization headers.
50 Mutually exclusive with ``app``.
51 :param app_name: Optional "nice name" for the application. Has no bearing on the
52 semantics of client actions. It is just passed as part of the User-Agent
53 string, and may be useful when debugging issues with the Globus Team.
54 If both``app`` and ``app_name`` are given, this value takes priority.
55 :param base_url: The URL for the service. Most client types initialize this value
56 intelligently by default. Set it when inheriting from BaseClient or
57 communicating through a proxy. This value takes precedence over the class
58 attribute of the same name.
59 :param transport: A :class:`RequestsTransport` object for sending and
60 retrying requests. By default, one will be constructed by the client.
61 :param retry_config: A :class:`RetryConfig` object with parameters to
62 control request retry behavior. By default, one will be constructed by
63 the client.
64 """
65
66 # service name is used to lookup a service URL from config
67 service_name: str = "_base"
68
69 # the URL for the service
70 # NOTE: this is not the only way to define a base url. See the docstring of the
71 # `BaseClient._resolve_base_url` method for more details.
72 base_url: str = "_base"
73
74 #: the class for errors raised by this client on HTTP 4xx and 5xx errors
75 #: this can be set in subclasses, but must always be a subclass of GlobusError
76 error_class: type[exc.GlobusAPIError] = exc.GlobusAPIError
77
78 #: the scopes for this client may be present as a ``ScopeCollection``
79 scopes: ScopeCollection | None = None
80
81 def __init__(
82 self,
83 *,
84 environment: str | None = None,
85 base_url: str | None = None,
86 app: GlobusApp | None = None,
87 app_scopes: list[Scope] | None = None,
88 authorizer: GlobusAuthorizer | None = None,
89 app_name: str | None = None,
90 transport: RequestsTransport | None = None,
91 retry_config: RetryConfig | None = None,
92 ) -> None:
93 # check for input parameter conflicts
94 if app_scopes and not app:
95 raise exc.GlobusSDKUsageError(
96 f"A {type(self).__name__} must have an 'app' to use 'app_scopes'."
97 )
98 if app and authorizer:
99 raise exc.GlobusSDKUsageError(
100 f"A {type(self).__name__} cannot use both an 'app' and an 'authorizer'."
101 )
102
103 self._resources_to_close: list[Closable] = []
104
105 # Determine the client's environment
106 # Either the provided kwarg or derived from the app used
107 #
108 # If neither is specified, fallback to the GLOBUS_SDK_ENVIRONMENT environment
109 # variable.
110 if environment:
111 self.environment = environment
112 elif app:
113 self.environment = app.config.environment
114 else:
115 self.environment = config.get_environment_name()
116
117 # resolve the base_url for the client (see docstring for resolution precedence)
118 self.base_url = self._resolve_base_url(base_url, self.environment)
119
120 self.retry_config: RetryConfig = retry_config or RetryConfig()
121 self._register_standard_retry_checks(self.retry_config)
122
123 # the client owns the Transport, and is responsible for closing on close,
124 # if and only if the client creates the Transport
125 if transport is not None:
126 self.transport = transport
127 else:
128 self.transport = RequestsTransport()
129 self._resources_to_close.append(self.transport)
130
131 log.debug(f"initialized transport of type {type(self.transport)}")
132
133 # setup paginated methods
134 self.paginated = PaginatorTable(self)
135
136 # set application name if available from app_name
137 # if this is not set, `app.app_name` may be applied below
138 self._app_name: str | None = None
139 if app_name is not None:
140 self.app_name = app_name
141
142 # attach the app or authorizer provided
143 # starting app attributes as `None` and calling the attachment method
144 self.authorizer = authorizer
145 self._app: GlobusApp | None = None
146 self.app_scopes: list[Scope] | None = None
147 if app:
148 self.attach_globus_app(app, app_scopes=app_scopes)
149
150 @property
151 def default_scope_requirements(self) -> list[Scope]:
152 """
153 Scopes that will automatically be added to this client's app's
154 scope_requirements during _finalize_app.
155
156 For clients with static scope requirements this can just be a static
157 value. Clients with dynamic requirements should use @property and must
158 return sane results while the Base Client is being initialized.
159 """
160 raise NotImplementedError
161
162 def _register_standard_retry_checks(self, retry_config: RetryConfig) -> None:
163 """
164 Setup the standard checks for this client.
165
166 This is called during init and may be overridden by subclasses.
167 """
168 retry_config.checks.register_many_checks(DEFAULT_RETRY_CHECKS)
169
170 @classmethod
171 def _resolve_base_url(cls, init_base_url: str | None, environment: str) -> str:
172 """
173 Resolve the client's base url.
174
175 Precedence (this evaluation will fall through if an option is not set):
176 1. [Highest] Constructor `base_url` value.
177 2. Class `base_url` attribute.
178 3. Class `service_name` attribute (computed).
179
180 :param init_base_url: The `base_url` value supplied to the constructor.
181 :param environment: The environment to use for service URL resolution.
182 :returns: The resolved base URL.
183 :raises: GlobusSDKUsageError if base_url cannot be resolved.
184 """
185 if init_base_url is not None:
186 log.debug(f"Creating client of type {cls}")
187 return init_base_url
188 elif cls.base_url != "_base":
189 log.debug(f"Creating client of type {cls}")
190 return cls.base_url
191 elif cls.service_name != "_base":
192 log.debug(f'Creating client of type {cls} for service "{cls.service_name}"')
193 return config.get_service_url(cls.service_name, environment)
194
195 raise GlobusSDKUsageError(
196 f"Unable to resolve base_url in client {cls}. "
197 f"Clients must define either one or both of 'base_url' and 'service_name'."
198 )
199
200 def attach_globus_app(
201 self, app: GlobusApp, app_scopes: list[Scope] | None = None
202 ) -> None:
203 """
204 Attach a ``GlobusApp`` to this client and, conversely, register this client with
205 that app. The client's default scopes will be added to the app's scope
206 requirements unless ``app_scopes`` is used to override this.
207
208 If the ``app_name`` is not set on the client, it will be set to match that of
209 the app.
210
211 .. note::
212
213 This method is only safe to call once per client object. It is implicitly
214 called if the client is initialized with an app.
215
216 :param app: The ``GlobusApp`` to attach to this client.
217 :param app_scopes: Optional list of ``Scope`` objects to be added to ``app``'s
218 scope requirements instead of ``default_scope_requirements``. These will be
219 stored in the ``app_scopes`` attribute of the client.
220
221 :raises GlobusSDKUsageError: If the attachment appears to conflict with the
222 state of the client. e.g., an app or authorizer is already in place.
223 """
224 # If there are any incompatible or ambiguous data, usage error.
225 # "In the face of ambiguity, refuse the temptation to guess."
226 if self._app:
227 raise exc.GlobusSDKUsageError(
228 f"Cannot attach GlobusApp to {type(self).__name__} when one is "
229 "already attached."
230 )
231 if self.app_scopes:
232 # technically, we *could* allow for this, but it's not clear what
233 # it would mean if a user wrote the following:
234 #
235 # c = ClientClass()
236 # c.app_scopes = [foo]
237 # c.attach_globus_app(app, app_scopes=[bar])
238 #
239 # did the user expect a merge, overwrite, or other behavior?
240 raise exc.GlobusSDKUsageError(
241 f"Cannot attach GlobusApp to {type(self).__name__} when `app_scopes` "
242 "is already set. "
243 "The scopes for this client cannot be consistently resolved."
244 )
245 if self.authorizer:
246 raise exc.GlobusSDKUsageError(
247 f"Cannot attach GlobusApp to {type(self).__name__} when it "
248 "has an authorizer assigned."
249 )
250 if self.resource_server is None:
251 raise exc.GlobusSDKUsageError(
252 "Unable to use an 'app' with a client with no "
253 "'resource_server' defined."
254 )
255 # the client's environment must match the app's
256 #
257 # there are only two ways to get to a mismatch:
258 #
259 # 1. pass an explicit environment which doesn't match the app, e.g.,
260 # `MyClient(environment="a", app=app)` where `app.config.environment="b"`
261 #
262 # 2. initialize a client without an app and later attach an app which doesn't
263 # match, e.g., `MyClient(environment="a").attach_globus_app(app)`
264 #
265 # in these cases, the user has explicitly given us conflicting instructions
266 if self.environment != app.config.environment:
267 raise exc.GlobusSDKUsageError(
268 f"[Environment Mismatch] {type(self).__name__}'s environment "
269 f"({self.environment}) does not match the GlobusApp's configured "
270 f"environment ({app.config.environment})."
271 )
272
273 # now, assign the app, app_name, and scopes
274 self._app = app
275 self.app_scopes = app_scopes or self.default_scope_requirements
276 if self.app_name is None:
277 self.app_name = app.app_name
278
279 # register the scope requirements on the app side
280 self._app.add_scope_requirements({self.resource_server: self.app_scopes})
281
282 # finally, set up auto-gare redriving by attaching any necessary retry checks.
283 self.retry_config.checks.register_many_checks(app.get_client_retry_checks())
284
285 def add_app_scope(
286 self, scope_collection: str | Scope | t.Iterable[str | Scope]
287 ) -> BaseClient:
288 """
289 Add a given scope collection to this client's ``GlobusApp`` scope requirements
290 for this client's ``resource_server``. This allows defining additional scope
291 requirements beyond the client's ``default_scope_requirements``.
292
293 Returns ``self`` for chaining.
294
295 Raises ``GlobusSDKUsageError`` if this client was not initialized with a
296 ``GlobusApp``.
297
298 :param scope_collection: A scope or scopes of
299 ``str | Scope | t.Iterable[str | Scope]`` to be added to
300 the app's required scopes.
301
302 .. tab-set::
303
304 .. tab-item:: Example Usage
305
306 .. code-block:: python
307
308 app = UserApp("myapp", ...)
309 flows_client = (
310 FlowsClient(app=app)
311 .add_app_scope(FlowsScopes.manage_flows)
312 .add_app_scope(FlowsScopes.run_manage)
313 )
314
315 """
316 if not self._app:
317 raise exc.GlobusSDKUsageError(
318 "Cannot 'add_app_scope' on a client that does not have an 'app'."
319 )
320 if self.resource_server is None:
321 raise ValueError(
322 "Unable to use an 'app' with a client with no "
323 "'resource_server' defined."
324 )
325 self._app.add_scope_requirements({self.resource_server: scope_collection})
326
327 return self
328
329 @property
330 def app_name(self) -> str | None:
331 return self._app_name
332
333 @app_name.setter
334 def app_name(self, value: str) -> None:
335 self._app_name = self.transport.user_agent = value
336
337 @classproperty
338 def resource_server( # pylint: disable=missing-param-doc
339 self_or_cls: BaseClient | type[BaseClient],
340 ) -> str | None:
341 """
342 The resource_server name for the API and scopes associated with this client.
343
344 This information is pulled from the ``scopes`` attribute of the client class.
345 If the client does not have associated scopes, this value will be ``None``.
346
347 This must return sane results while the Base Client is being initialized.
348 """
349 if self_or_cls.scopes is None:
350 return None
351 return self_or_cls.scopes.resource_server
352
353 def close(self) -> None:
354 """
355 Close all resources which are owned by this client.
356
357 This only closes transports which are created implicitly via client init.
358 Externally constructed transports will not be closed.
359 """
360 for resource in self._resources_to_close:
361 log.debug(
362 f"closing resource of type {type(resource).__name__} "
363 f"for {type(self).__name__}"
364 )
365 resource.close()
366
367 # clients can act as context managers, and such usage calls close()
368 def __enter__(self) -> Self:
369 return self
370
371 def __exit__(
372 self,
373 exc_type: type[BaseException] | None,
374 exc_val: BaseException | None,
375 exc_tb: types.TracebackType | None,
376 ) -> None:
377 self.close()
378
379 def get( # pylint: disable=missing-param-doc
380 self,
381 path: str,
382 *,
383 query_params: dict[str, t.Any] | None = None,
384 headers: dict[str, str] | None = None,
385 automatic_authorization: bool = True,
386 ) -> GlobusHTTPResponse:
387 """
388 Make a GET request to the specified path.
389
390 See :py:meth:`~.BaseClient.request` for details on the various parameters.
391 """
392 log.debug(f"GET to {path} with query_params {query_params}")
393 return self.request(
394 "GET",
395 path,
396 query_params=query_params,
397 headers=headers,
398 automatic_authorization=automatic_authorization,
399 )
400
401 def post( # pylint: disable=missing-param-doc
402 self,
403 path: str,
404 *,
405 query_params: dict[str, t.Any] | None = None,
406 data: _DataParamType = None,
407 headers: dict[str, str] | None = None,
408 encoding: str | None = None,
409 automatic_authorization: bool = True,
410 ) -> GlobusHTTPResponse:
411 """
412 Make a POST request to the specified path.
413
414 See :py:meth:`~.BaseClient.request` for details on the various parameters.
415 """
416 log.debug(f"POST to {path} with query_params {query_params}")
417 return self.request(
418 "POST",
419 path,
420 query_params=query_params,
421 data=data,
422 headers=headers,
423 encoding=encoding,
424 automatic_authorization=automatic_authorization,
425 )
426
427 def delete( # pylint: disable=missing-param-doc
428 self,
429 path: str,
430 *,
431 query_params: dict[str, t.Any] | None = None,
432 headers: dict[str, str] | None = None,
433 automatic_authorization: bool = True,
434 ) -> GlobusHTTPResponse:
435 """
436 Make a DELETE request to the specified path.
437
438 See :py:meth:`~.BaseClient.request` for details on the various parameters.
439 """
440 log.debug(f"DELETE to {path} with query_params {query_params}")
441 return self.request(
442 "DELETE",
443 path,
444 query_params=query_params,
445 headers=headers,
446 automatic_authorization=automatic_authorization,
447 )
448
449 def put( # pylint: disable=missing-param-doc
450 self,
451 path: str,
452 *,
453 query_params: dict[str, t.Any] | None = None,
454 data: _DataParamType = None,
455 headers: dict[str, str] | None = None,
456 encoding: str | None = None,
457 automatic_authorization: bool = True,
458 ) -> GlobusHTTPResponse:
459 """
460 Make a PUT request to the specified path.
461
462 See :py:meth:`~.BaseClient.request` for details on the various parameters.
463 """
464 log.debug(f"PUT to {path} with query_params {query_params}")
465 return self.request(
466 "PUT",
467 path,
468 query_params=query_params,
469 data=data,
470 headers=headers,
471 encoding=encoding,
472 automatic_authorization=automatic_authorization,
473 )
474
475 def patch( # pylint: disable=missing-param-doc
476 self,
477 path: str,
478 *,
479 query_params: dict[str, t.Any] | None = None,
480 data: _DataParamType = None,
481 headers: dict[str, str] | None = None,
482 encoding: str | None = None,
483 automatic_authorization: bool = True,
484 ) -> GlobusHTTPResponse:
485 """
486 Make a PATCH request to the specified path.
487
488 See :py:meth:`~.BaseClient.request` for details on the various parameters.
489 """
490 log.debug(f"PATCH to {path} with query_params {query_params}")
491 return self.request(
492 "PATCH",
493 path,
494 query_params=query_params,
495 data=data,
496 headers=headers,
497 encoding=encoding,
498 automatic_authorization=automatic_authorization,
499 )
500
501 def request(
502 self,
503 method: str,
504 path: str,
505 *,
506 query_params: dict[str, t.Any] | None = None,
507 data: _DataParamType = None,
508 headers: dict[str, str] | None = None,
509 encoding: str | None = None,
510 allow_redirects: bool = True,
511 stream: bool = False,
512 automatic_authorization: bool = True,
513 ) -> GlobusHTTPResponse:
514 """
515 Send an HTTP request
516
517 :param method: HTTP request method, as an all caps string
518 :param path: Path for the request, with or without leading slash
519 :param query_params: Parameters to be encoded as a query string
520 :param headers: HTTP headers to add to the request. Authorization headers may
521 be overwritten unless ``automatic_authorization`` is False.
522 :param data: Data to send as the request body. May pass through encoding.
523 :param encoding: A way to encode request data. "json", "form", and "text"
524 are all valid values. Custom encodings can be used only if they are
525 registered with the transport. By default, strings get "text" behavior and
526 all other objects get "json".
527 :param allow_redirects: Follow Location headers on redirect response
528 automatically. Defaults to ``True``
529 :param stream: Do not immediately download the response content. Defaults to
530 ``False``
531 :param automatic_authorization: Use this client's ``app`` or ``authorizer``
532 to automatically generate an Authorization header.
533
534 :raises GlobusAPIError: a `GlobusAPIError` will be raised if the response to the
535 request is received and has a status code in the 4xx or 5xx categories
536 """
537 # prepare data...
538 # copy headers if present
539 rheaders = {**headers} if headers else {}
540
541 # if a client is asked to make a request against a full URL, not just the path
542 # component, then do not resolve the path, simply pass it through as the URL
543 if path.startswith(("https://", "http://")):
544 url = path
545 else:
546 url = slash_join(self.base_url, urllib.parse.quote(path))
547
548 caller_info = RequestCallerInfo(retry_config=self.retry_config)
549
550 # either use given authorizer or get one from app
551 if automatic_authorization:
552 caller_info.authorizer = self.authorizer
553 if self._app and (resource_server := self.resource_server):
554 caller_info.resource_server = resource_server
555 caller_info.authorizer = self._app.get_authorizer(resource_server)
556
557 # make the request
558 log.debug("request will hit URL: %s", url)
559 r = self.transport.request(
560 method,
561 url,
562 caller_info=caller_info,
563 data=data,
564 query_params=query_params,
565 headers=rheaders,
566 encoding=encoding,
567 allow_redirects=allow_redirects,
568 stream=stream,
569 )
570 log.debug("request made to URL: %s", r.url)
571
572 if 200 <= r.status_code < 400:
573 log.debug(f"request completed with response code: {r.status_code}")
574 return GlobusHTTPResponse(r, self)
575
576 log.debug(f"request completed with (error) response code: {r.status_code}")
577 raise self.error_class(r)