Debian Codegraph @

src/auth0/authentication/rest_async.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import asyncio
4 from typing import Any
5
6 import aiohttp
7
8 from .exceptions import RateLimitError
9 from .types import RequestData
10
11 from .rest import EmptyResponse, JsonResponse, PlainResponse, Response, RestClient
12
13
14 def _clean_params(params: dict[Any, Any] | None) -> dict[Any, Any] | None:
15 if params is None:
16 return params
17 return {k: v for k, v in params.items() if v is not None}
18
19
20 class AsyncRestClient(RestClient):
21 """Provides simple methods for handling all RESTful api endpoints.
22
23 Args:
24 telemetry (bool, optional): Enable or disable Telemetry
25 (defaults to True)
26 timeout (float or tuple, optional): Change the requests
27 connect and read timeout. Pass a tuple to specify
28 both values separately or a float to set both to it.
29 (defaults to 5.0 for both)
30 options (RestClientOptions): Pass an instance of
31 RestClientOptions to configure additional RestClient
32 options, such as rate-limit retries. Overrides matching
33 options passed to the constructor.
34 (defaults to 3)
35 """
36
37 def __init__(self, *args: Any, **kwargs: Any) -> None:
38 super().__init__(*args, **kwargs)
39 self._session: aiohttp.ClientSession | None = None
40 sock_connect, sock_read = (
41 self.timeout
42 if isinstance(self.timeout, tuple)
43 else (self.timeout, self.timeout)
44 )
45 self.timeout = aiohttp.ClientTimeout(
46 sock_connect=sock_connect, sock_read=sock_read
47 ) # type: ignore[assignment]
48
49 def set_session(self, session: aiohttp.ClientSession) -> None:
50 """Set Client Session to improve performance by reusing session.
51 Session should be closed manually or within context manager.
52 """
53 self._session = session
54
55 async def _request_with_session(
56 self, session: aiohttp.ClientSession, *args: Any, **kwargs: Any
57 ) -> Any:
58 # Track the API request attempt number
59 attempt = 0
60
61 # Reset the metrics tracker
62 self._metrics = {"retries": 0, "backoff": []}
63
64 while True:
65 # Increment attempt number
66 attempt += 1
67
68 try:
69 async with session.request(*args, **kwargs) as response:
70 return await self._process_response(response)
71
72 except RateLimitError as e:
73 # If the attempt number is greater than the configured retries, raise RateLimitError
74 if attempt > self._retries:
75 raise e
76
77 wait = self._calculate_wait(attempt)
78
79 # Skip calling sleep() when running unit tests
80 if self._skip_sleep is False:
81 # sleep() functions in seconds, so convert the milliseconds formula above accordingly
82 await asyncio.sleep(wait / 1000)
83
84 async def _request(self, *args: Any, **kwargs: Any) -> Any:
85 kwargs["headers"] = kwargs.get("headers", self.base_headers)
86 kwargs["timeout"] = self.timeout
87 if self._session is not None:
88 # Request with re-usable session
89 return await self._request_with_session(self._session, *args, **kwargs)
90 else:
91 # Request without re-usable session
92 async with aiohttp.ClientSession() as session:
93 return await self._request_with_session(session, *args, **kwargs)
94
95 async def get(
96 self,
97 url: str,
98 params: dict[str, Any] | None = None,
99 headers: dict[str, str] | None = None,
100 ) -> Any:
101 request_headers = self.base_headers.copy()
102 request_headers.update(headers or {})
103
104 return await self._request(
105 "get", url, params=_clean_params(params), headers=request_headers
106 )
107
108 async def post(
109 self,
110 url: str,
111 data: RequestData | None = None,
112 headers: dict[str, str] | None = None,
113 ) -> Any:
114 request_headers = self.base_headers.copy()
115 request_headers.update(headers or {})
116 return await self._request("post", url, json=data, headers=request_headers)
117
118 async def file_post(
119 self,
120 url: str,
121 data: dict[str, Any],
122 files: dict[str, Any],
123 ) -> Any:
124 headers = self.base_headers.copy()
125 headers.pop("Content-Type")
126 return await self._request("post", url, data={**data, **files}, headers=headers)
127
128 async def patch(self, url: str, data: RequestData | None = None) -> Any:
129 return await self._request("patch", url, json=data)
130
131 async def put(self, url: str, data: RequestData | None = None) -> Any:
132 return await self._request("put", url, json=data)
133
134 async def delete(
135 self,
136 url: str,
137 params: dict[str, Any] | None = None,
138 data: RequestData | None = None,
139 ) -> Any:
140 return await self._request(
141 "delete", url, json=data, params=_clean_params(params) or {}
142 )
143
144 async def _process_response(self, response: aiohttp.ClientResponse) -> Any:
145 parsed_response = await self._parse(response)
146 return parsed_response.content()
147
148 async def _parse(self, response: aiohttp.ClientResponse) -> Response:
149 text = await response.text()
150 requests_response = RequestsResponse(response, text)
151 if not text:
152 return EmptyResponse(response.status)
153 try:
154 return JsonResponse(requests_response)
155 except ValueError:
156 return PlainResponse(requests_response)
157
158
159 class RequestsResponse:
160 def __init__(self, response: aiohttp.ClientResponse, text: str) -> None:
161 self.status_code = response.status
162 self.headers = response.headers
163 self.text = text