Debian Codegraph @

src/globus_sdk/experimental/gcs_downloader.py

raw
1 """
2 The GCSDownloader provides HTTPS file download capabilities for Globus Connect Server.
3 """
4
5 from __future__ import annotations
6
7 import logging
8 import sys
9 import types
10 import typing as t
11 import urllib.parse
12
13 import globus_sdk
14 import globus_sdk.transport
15 from globus_sdk._internal.type_definitions import Closable
16 from globus_sdk.experimental.gcs_collection_client import GCSCollectionClient
17 from globus_sdk.transport.default_retry_checks import DEFAULT_RETRY_CHECKS
18
19 if sys.version_info >= (3, 11):
20 from typing import Self
21 else:
22 from typing_extensions import Self
23
24 log = logging.getLogger(__name__)
25
26
27 class GCSDownloader:
28 """
29 An object which manages connection and authentication state to enable HTTPS
30 downloads from a specific Globus Connect Server collection.
31
32 The initial request to read a file features support for determining authentication
33 requirements dynamically, and subsequent requests will reuse that authentication
34 data.
35
36 Using a single :class:`GCSDownloader` to access distinct collections is not
37 supported. A separate downloader should be used for each collection.
38
39 Downloaders may be used as context managers, in which case they automatically call
40 their ``close()`` method on exit:
41
42 >>> with GCSDownloader(app) as downloader:
43 >>> print(downloader.read_file(url))
44
45 :param app: The :class:`GlobusApp` used to authenticate calls to this server.
46 :param gcs_client: The underlying client used for the file read request. Typically
47 omitted. When not provided, one will be constructed on demand by the downloader.
48 :param transfer_client: A client used when detecting collection information.
49 Typically omitted. When not provided, one will be constructed on demand by the
50 downloader.
51 :param transport: A transport for the downloader, used for authentication
52 sniffing operations. When a client is built by the downloader it will
53 inherit this transport.
54 """
55
56 def __init__(
57 self,
58 app: globus_sdk.GlobusApp,
59 *,
60 gcs_client: GCSCollectionClient | None = None,
61 transfer_client: globus_sdk.TransferClient | None = None,
62 transport: globus_sdk.transport.RequestsTransport | None = None,
63 ) -> None:
64 self.app = app
65 self._resources_to_close: list[Closable] = []
66
67 if transport is not None:
68 self.transport = transport
69 else:
70 self.transport = globus_sdk.transport.RequestsTransport()
71 self._resources_to_close.append(self.transport)
72
73 # the downloader will need a RetryConfig when it uses its own transport
74 self._retry_config = globus_sdk.transport.RetryConfig()
75 self._retry_config.checks.register_many_checks(DEFAULT_RETRY_CHECKS)
76
77 self.gcs_client = gcs_client
78
79 # set the transfer_client if provided
80 self.transfer_client = transfer_client
81
82 def __enter__(self) -> Self:
83 return self
84
85 def __exit__(
86 self,
87 exc_type: type[BaseException] | None,
88 exc_val: BaseException | None,
89 exc_tb: types.TracebackType | None,
90 ) -> None:
91 self.close()
92
93 def close(self) -> None:
94 """
95 Close all resources which are owned by this downloader.
96 """
97 for resource in self._resources_to_close:
98 log.debug(
99 f"closing resource of type {type(resource).__name__} "
100 f"for {type(self).__name__}"
101 )
102 resource.close()
103
104 @t.overload
105 def read_file(self, file_uri: str, *, as_text: t.Literal[True]) -> str: ...
106 @t.overload
107 def read_file(self, file_uri: str, *, as_text: t.Literal[False]) -> bytes: ...
108 @t.overload
109 def read_file(self, file_uri: str) -> str: ...
110
111 def read_file(self, file_uri: str, *, as_text: bool = True) -> str | bytes:
112 """
113 Given a file URI on a GCS Collection, read the data.
114
115 :param file_uri: The full URI of the file on the collection which is being
116 downloaded.
117 :param as_text: When ``True``, the file contents are decoded into a string. Set
118 to ``False`` to retrieve data as bytes.
119
120 .. caution::
121
122 The file read is done naively as a GET request. This may be unsuitable for
123 very large files.
124 """
125 # dynamically build a client if needed
126 if self.gcs_client is None:
127 self.gcs_client = self._get_client_from_uri(file_uri)
128 self._resources_to_close.append(self.gcs_client)
129
130 response = self.gcs_client.get(file_uri)
131 if as_text:
132 return response.text
133 return response.binary_content
134
135 def _get_client_from_uri(self, file_uri: str) -> GCSCollectionClient:
136 collection_id = self._sniff_collection_id(file_uri)
137 collection_address = _get_collection_address(file_uri)
138
139 client = self._gcs_client_constructor(
140 collection_client_id=collection_id,
141 collection_address=collection_address,
142 )
143 self.app.add_scope_requirements(
144 {client.scopes.resource_server: self._determine_required_scopes(client)}
145 )
146 return client
147
148 def _gcs_client_constructor(
149 self, *, collection_client_id: str, collection_address: str
150 ) -> GCSCollectionClient:
151 return GCSCollectionClient(
152 collection_client_id,
153 collection_address,
154 app=self.app,
155 transport=self.transport,
156 )
157
158 def _determine_required_scopes(
159 self, client: GCSCollectionClient
160 ) -> list[globus_sdk.Scope]:
161 if self.transfer_client is None:
162 self.transfer_client = globus_sdk.TransferClient(
163 app=self.app, transport=self.transport
164 )
165 self._resources_to_close.append(self.transfer_client)
166
167 required_scopes: list[globus_sdk.Scope] = [client.scopes.https]
168 if _uses_data_access(self.transfer_client, client.collection_id):
169 required_scopes.append(client.scopes.data_access)
170 return required_scopes
171
172 def _sniff_collection_id(self, file_uri: str) -> str:
173 response = self.transport.request(
174 "GET",
175 file_uri,
176 caller_info=globus_sdk.transport.RequestCallerInfo(
177 retry_config=self._retry_config
178 ),
179 allow_redirects=False,
180 )
181 if "Location" not in response.headers:
182 msg = (
183 f"Attempting to detect the collection ID for the file at '{file_uri}' "
184 "failed. Did not receive a redirect with Location header on "
185 "unauthenticated call."
186 )
187 raise RuntimeError(msg)
188
189 location_header = response.headers["Location"]
190 parsed_location = urllib.parse.urlparse(location_header)
191 parsed_location_qs = urllib.parse.parse_qs(parsed_location.query)
192
193 if "client_id" not in parsed_location_qs:
194 msg = (
195 f"Attempting to detect the collection ID for the file at '{file_uri}' "
196 "failed. Location header did not encode a 'client_id'."
197 )
198 raise RuntimeError(msg)
199
200 client_ids = parsed_location_qs["client_id"]
201 if len(client_ids) != 1:
202 msg = (
203 f"Attempting to detect the collection ID for the file at '{file_uri}' "
204 "failed. Multiple 'client_id' params were present."
205 )
206 raise RuntimeError(msg)
207
208 return client_ids[0]
209
210
211 def _get_collection_address(file_uri: str) -> str:
212 parsed = urllib.parse.urlparse(file_uri)
213 return f"{parsed.scheme}://{parsed.netloc}"
214
215
216 def _uses_data_access(
217 transfer_client: globus_sdk.TransferClient, collection_id: str
218 ) -> bool:
219 doc = transfer_client.get_endpoint(collection_id)
220 if doc["entity_type"] != "GCSv5_mapped_collection":
221 return False
222 if doc["high_assurance"]:
223 return False
224 return True