sessions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright 2024 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. from contextlib import asynccontextmanager
  16. import functools
  17. import time
  18. from typing import Mapping, Optional
  19. from google.auth import _exponential_backoff, exceptions
  20. from google.auth.aio import transport
  21. from google.auth.aio.credentials import Credentials
  22. from google.auth.exceptions import TimeoutError
  23. try:
  24. from google.auth.aio.transport.aiohttp import Request as AiohttpRequest
  25. AIOHTTP_INSTALLED = True
  26. except ImportError: # pragma: NO COVER
  27. AIOHTTP_INSTALLED = False
  28. @asynccontextmanager
  29. async def timeout_guard(timeout):
  30. """
  31. timeout_guard is an asynchronous context manager to apply a timeout to an asynchronous block of code.
  32. Args:
  33. timeout (float): The time in seconds before the context manager times out.
  34. Raises:
  35. google.auth.exceptions.TimeoutError: If the code within the context exceeds the provided timeout.
  36. Usage:
  37. async with timeout_guard(10) as with_timeout:
  38. await with_timeout(async_function())
  39. """
  40. start = time.monotonic()
  41. total_timeout = timeout
  42. def _remaining_time():
  43. elapsed = time.monotonic() - start
  44. remaining = total_timeout - elapsed
  45. if remaining <= 0:
  46. raise TimeoutError(
  47. f"Context manager exceeded the configured timeout of {total_timeout}s."
  48. )
  49. return remaining
  50. async def with_timeout(coro):
  51. try:
  52. remaining = _remaining_time()
  53. response = await asyncio.wait_for(coro, remaining)
  54. return response
  55. except (asyncio.TimeoutError, TimeoutError) as e:
  56. raise TimeoutError(
  57. f"The operation {coro} exceeded the configured timeout of {total_timeout}s."
  58. ) from e
  59. try:
  60. yield with_timeout
  61. finally:
  62. _remaining_time()
  63. class AsyncAuthorizedSession:
  64. """This is an asynchronous implementation of :class:`google.auth.requests.AuthorizedSession` class.
  65. We utilize an instance of a class that implements :class:`google.auth.aio.transport.Request` configured
  66. by the caller or otherwise default to `google.auth.aio.transport.aiohttp.Request` if the external aiohttp
  67. package is installed.
  68. A Requests Session class with credentials.
  69. This class is used to perform asynchronous requests to API endpoints that require
  70. authorization::
  71. import aiohttp
  72. from google.auth.aio.transport import sessions
  73. async with sessions.AsyncAuthorizedSession(credentials) as authed_session:
  74. response = await authed_session.request(
  75. 'GET', 'https://www.googleapis.com/storage/v1/b')
  76. The underlying :meth:`request` implementation handles adding the
  77. credentials' headers to the request and refreshing credentials as needed.
  78. Args:
  79. credentials (google.auth.aio.credentials.Credentials):
  80. The credentials to add to the request.
  81. auth_request (Optional[google.auth.aio.transport.Request]):
  82. An instance of a class that implements
  83. :class:`~google.auth.aio.transport.Request` used to make requests
  84. and refresh credentials. If not passed,
  85. an instance of :class:`~google.auth.aio.transport.aiohttp.Request`
  86. is created.
  87. Raises:
  88. - google.auth.exceptions.TransportError: If `auth_request` is `None`
  89. and the external package `aiohttp` is not installed.
  90. - google.auth.exceptions.InvalidType: If the provided credentials are
  91. not of type `google.auth.aio.credentials.Credentials`.
  92. """
  93. def __init__(
  94. self, credentials: Credentials, auth_request: Optional[transport.Request] = None
  95. ):
  96. if not isinstance(credentials, Credentials):
  97. raise exceptions.InvalidType(
  98. f"The configured credentials of type {type(credentials)} are invalid and must be of type `google.auth.aio.credentials.Credentials`"
  99. )
  100. self._credentials = credentials
  101. _auth_request = auth_request
  102. if not _auth_request and AIOHTTP_INSTALLED:
  103. _auth_request = AiohttpRequest()
  104. if _auth_request is None:
  105. raise exceptions.TransportError(
  106. "`auth_request` must either be configured or the external package `aiohttp` must be installed to use the default value."
  107. )
  108. self._auth_request = _auth_request
  109. async def request(
  110. self,
  111. method: str,
  112. url: str,
  113. data: Optional[bytes] = None,
  114. headers: Optional[Mapping[str, str]] = None,
  115. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  116. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  117. **kwargs,
  118. ) -> transport.Response:
  119. """
  120. Args:
  121. method (str): The http method used to make the request.
  122. url (str): The URI to be requested.
  123. data (Optional[bytes]): The payload or body in HTTP request.
  124. headers (Optional[Mapping[str, str]]): Request headers.
  125. timeout (float):
  126. The amount of time in seconds to wait for the server response
  127. with each individual request.
  128. max_allowed_time (float):
  129. If the method runs longer than this, a ``Timeout`` exception is
  130. automatically raised. Unlike the ``timeout`` parameter, this
  131. value applies to the total method execution time, even if
  132. multiple requests are made under the hood.
  133. Mind that it is not guaranteed that the timeout error is raised
  134. at ``max_allowed_time``. It might take longer, for example, if
  135. an underlying request takes a lot of time, but the request
  136. itself does not timeout, e.g. if a large file is being
  137. transmitted. The timout error will be raised after such
  138. request completes.
  139. Returns:
  140. google.auth.aio.transport.Response: The HTTP response.
  141. Raises:
  142. google.auth.exceptions.TimeoutError: If the method does not complete within
  143. the configured `max_allowed_time` or the request exceeds the configured
  144. `timeout`.
  145. """
  146. retries = _exponential_backoff.AsyncExponentialBackoff(
  147. total_attempts=transport.DEFAULT_MAX_RETRY_ATTEMPTS
  148. )
  149. async with timeout_guard(max_allowed_time) as with_timeout:
  150. await with_timeout(
  151. # Note: before_request will attempt to refresh credentials if expired.
  152. self._credentials.before_request(
  153. self._auth_request, method, url, headers
  154. )
  155. )
  156. # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
  157. # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
  158. async for _ in retries: # pragma: no branch
  159. response = await with_timeout(
  160. self._auth_request(url, method, data, headers, timeout, **kwargs)
  161. )
  162. if response.status_code not in transport.DEFAULT_RETRYABLE_STATUS_CODES:
  163. break
  164. return response
  165. @functools.wraps(request)
  166. async def get(
  167. self,
  168. url: str,
  169. data: Optional[bytes] = None,
  170. headers: Optional[Mapping[str, str]] = None,
  171. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  172. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  173. **kwargs,
  174. ) -> transport.Response:
  175. return await self.request(
  176. "GET", url, data, headers, max_allowed_time, timeout, **kwargs
  177. )
  178. @functools.wraps(request)
  179. async def post(
  180. self,
  181. url: str,
  182. data: Optional[bytes] = None,
  183. headers: Optional[Mapping[str, str]] = None,
  184. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  185. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  186. **kwargs,
  187. ) -> transport.Response:
  188. return await self.request(
  189. "POST", url, data, headers, max_allowed_time, timeout, **kwargs
  190. )
  191. @functools.wraps(request)
  192. async def put(
  193. self,
  194. url: str,
  195. data: Optional[bytes] = None,
  196. headers: Optional[Mapping[str, str]] = None,
  197. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  198. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  199. **kwargs,
  200. ) -> transport.Response:
  201. return await self.request(
  202. "PUT", url, data, headers, max_allowed_time, timeout, **kwargs
  203. )
  204. @functools.wraps(request)
  205. async def patch(
  206. self,
  207. url: str,
  208. data: Optional[bytes] = None,
  209. headers: Optional[Mapping[str, str]] = None,
  210. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  211. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  212. **kwargs,
  213. ) -> transport.Response:
  214. return await self.request(
  215. "PATCH", url, data, headers, max_allowed_time, timeout, **kwargs
  216. )
  217. @functools.wraps(request)
  218. async def delete(
  219. self,
  220. url: str,
  221. data: Optional[bytes] = None,
  222. headers: Optional[Mapping[str, str]] = None,
  223. max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
  224. timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
  225. **kwargs,
  226. ) -> transport.Response:
  227. return await self.request(
  228. "DELETE", url, data, headers, max_allowed_time, timeout, **kwargs
  229. )
  230. async def close(self) -> None:
  231. """
  232. Close the underlying auth request session.
  233. """
  234. await self._auth_request.close()