Debian Codegraph @

hass_nabucasa/api.py

raw
1 """Define the API base class."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable, Coroutine
6 import contextlib
7 from dataclasses import dataclass
8 from functools import wraps
9 from json import JSONDecodeError
10 import logging
11 from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, final
12
13 from aiohttp import (
14 ClientError,
15 ClientResponse,
16 ClientResponseError,
17 ClientTimeout,
18 ContentTypeError,
19 hdrs,
20 )
21 from aiohttp.typedefs import Query
22 import voluptuous as vol
23 from voluptuous.humanize import humanize_error
24 from yarl import URL
25
26 from .auth import Unauthenticated, UnknownError
27 from .exceptions import CloudError
28
29 if TYPE_CHECKING:
30 from . import Cloud, _ClientT
31 from .service_discovery import ServiceDiscoveryAction
32
33 P = ParamSpec("P")
34 T = TypeVar("T")
35
36 _LOGGER = logging.getLogger(__name__)
37
38 ALLOW_EMPTY_RESPONSE = frozenset(
39 {
40 "DELETE",
41 "POST",
42 "HEAD",
43 }
44 )
45
46 DEFAULT_API_TIMEOUT = ClientTimeout(total=60)
47
48
49 def api_exception_handler(
50 exception: type[CloudApiError],
51 ) -> Callable[
52 [Callable[P, Awaitable[T]]],
53 Callable[P, Coroutine[Any, Any, T]],
54 ]:
55 """Handle API exceptions."""
56
57 def decorator(
58 func: Callable[P, Awaitable[T]],
59 ) -> Callable[P, Coroutine[Any, Any, T]]:
60 @wraps(func)
61 async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
62 try:
63 return await func(*args, **kwargs)
64 except (
65 CloudApiNonRetryableError,
66 CloudApiCodedError,
67 exception,
68 ):
69 raise
70 except CloudApiError as err:
71 raise exception(
72 err,
73 orig_exc=err,
74 reason=err.reason,
75 status=err.status,
76 ) from err
77 except (UnknownError, Unauthenticated) as err:
78 raise exception(err, orig_exc=err) from err
79 except Exception as err:
80 raise exception(
81 f"Unexpected error while calling API: {err}",
82 orig_exc=err,
83 ) from err
84
85 return wrapper
86
87 return decorator
88
89
90 class CloudApiError(CloudError):
91 """Exception raised when handling cloud API."""
92
93 def __init__(
94 self,
95 context: str | Exception,
96 *,
97 orig_exc: Exception | None = None,
98 reason: str | None = None,
99 status: int | None = None,
100 ) -> None:
101 """Initialize."""
102 super().__init__(context)
103 self.orig_exc = orig_exc
104 self.reason = reason
105 self.status = status
106
107
108 class CloudApiCodedError(CloudApiError):
109 """Exception raised when handling cloud API."""
110
111 def __init__(self, context: str | Exception, *, code: str) -> None:
112 """Initialize."""
113 super().__init__(context)
114 self.code = code
115
116
117 class CloudApiTimeoutError(CloudApiError):
118 """Exception raised when handling cloud API times out."""
119
120
121 class CloudApiClientError(CloudApiError):
122 """Exception raised when handling cloud API client error."""
123
124
125 class CloudApiNonRetryableError(CloudApiCodedError):
126 """Exception raised when handling cloud API non-retryable error."""
127
128
129 class CloudApiInvalidResponseError(CloudApiError):
130 """Exception raised when API response fails schema validation."""
131
132
133 @dataclass
134 class CloudApiRawResponse:
135 """A raw response from the cloud API."""
136
137 response: ClientResponse
138 data: Any = None
139
140
141 class ApiBase:
142 """Class to help communicate with the cloud API."""
143
144 def __init__(self, cloud: Cloud[_ClientT]) -> None:
145 """Initialize the API base."""
146 self._cloud = cloud
147
148 @property
149 def hostname(self) -> str | None:
150 """Get the hostname for path-based API calls."""
151 return None
152
153 @property
154 def non_retryable_error_codes(self) -> set[str]:
155 """Get the non-retryable error codes."""
156 return set()
157
158 @property
159 @final
160 def _non_retryable_error_codes(self) -> set[str]:
161 """Get the non-retryable error codes."""
162 return {"NC-CE-02", "NC-CE-03"}.union(self.non_retryable_error_codes)
163
164 def _do_log_request(
165 self,
166 method: str,
167 url: str | URL,
168 include_path_in_log: bool = True,
169 ) -> None:
170 """Log the response."""
171 if not _LOGGER.isEnabledFor(logging.DEBUG):
172 return
173 url = url if isinstance(url, URL) else URL(url)
174 target = url.path if include_path_in_log else ""
175 _LOGGER.debug("Sending %s request to %s%s", method, url.host, target)
176
177 def _do_log_response(
178 self,
179 resp: ClientResponse,
180 data: list[Any] | dict[Any, Any] | str | None = None,
181 include_path_in_log: bool = True,
182 ) -> None:
183 """Log the response."""
184 if not _LOGGER.isEnabledFor(logging.DEBUG):
185 return
186 isok = resp.status < 400
187 target = resp.url.path if include_path_in_log else ""
188 if len(resp.url.query) > 0:
189 allowed_values = {"true", "false"}
190 query_params = [
191 f"{key}=***"
192 if value.lower() not in allowed_values
193 else f"{key}={value}"
194 for key, value in resp.url.query.items()
195 ]
196 target += f"?{'&'.join(query_params)}"
197 _LOGGER.debug(
198 "Response for %s from %s%s (%s) %s",
199 resp.method,
200 resp.url.host,
201 target,
202 resp.status,
203 data["reason"]
204 if not isok and isinstance(data, dict) and "reason" in data
205 else data["message"]
206 if not isok and isinstance(data, dict) and "message" in data
207 else "",
208 )
209
210 async def _call_raw_api(
211 self,
212 *,
213 url: str,
214 method: str,
215 client_timeout: ClientTimeout,
216 headers: dict[str, Any],
217 jsondata: dict[str, Any] | None = None,
218 data: Any | None = None,
219 params: Query | None = None,
220 include_path_in_log: bool = True,
221 ) -> ClientResponse:
222 """Call raw API."""
223 self._do_log_request(method, url, include_path_in_log)
224 try:
225 resp = await self._cloud.websession.request(
226 method=method,
227 url=url,
228 timeout=client_timeout,
229 headers=headers,
230 json=jsondata,
231 data=data,
232 params=params,
233 )
234 except TimeoutError as err:
235 raise CloudApiTimeoutError(
236 f"Timeout reached while calling API: total allowed time is "
237 f"{client_timeout.total} seconds",
238 orig_exc=err,
239 ) from err
240 except ClientResponseError as err:
241 raise CloudApiClientError(
242 f"Failed to fetch: ({err.status}) {err.message}",
243 orig_exc=err,
244 status=err.status,
245 ) from err
246 except ClientError as err:
247 raise CloudApiClientError(f"Failed to fetch: {err}", orig_exc=err) from err
248 except Exception as err:
249 raise CloudApiError(
250 f"Unexpected error while calling API: {err}",
251 orig_exc=err,
252 ) from err
253
254 return resp
255
256 async def _call_cloud_api(
257 self,
258 *,
259 action: ServiceDiscoveryAction | None = None,
260 action_values: dict[str, Any] | None = None,
261 path: str | None = None,
262 method: str = "GET",
263 client_timeout: ClientTimeout | None = None,
264 jsondata: dict[str, Any] | None = None,
265 headers: dict[str, Any] | None = None,
266 skip_token_check: bool = False,
267 raw_response: bool = False,
268 params: Query | None = None,
269 include_path_in_log: bool = True,
270 schema: vol.Schema | None = None,
271 ) -> Any:
272 """Call cloud API."""
273 if action is None and path is None:
274 raise CloudApiError("Either 'action' or 'path' parameter must be provided")
275
276 data: dict[str, Any] | list[Any] | str | None = None
277 if not skip_token_check:
278 await self._cloud.auth.async_check_token()
279 if TYPE_CHECKING:
280 assert self._cloud.id_token is not None
281
282 if action is not None:
283 final_url = self._cloud.service_discovery.action_url(
284 action=action,
285 **(action_values or {}),
286 )
287 else:
288 final_url = f"https://{self.hostname}{path}"
289
290 resp = await self._call_raw_api(
291 method=method,
292 url=final_url,
293 client_timeout=client_timeout or DEFAULT_API_TIMEOUT,
294 headers={
295 hdrs.ACCEPT: "application/json",
296 hdrs.AUTHORIZATION: f"Bearer {self._cloud.id_token}",
297 hdrs.CONTENT_TYPE: "application/json",
298 hdrs.USER_AGENT: self._cloud.client.client_name,
299 **(headers or {}),
300 },
301 jsondata=jsondata,
302 params=params,
303 include_path_in_log=include_path_in_log,
304 )
305
306 if resp.status < 500:
307 with contextlib.suppress(ContentTypeError, JSONDecodeError):
308 data = await resp.json()
309
310 self._do_log_response(resp, data, include_path_in_log)
311
312 if data is None and resp.method.upper() not in ALLOW_EMPTY_RESPONSE:
313 raise CloudApiError("Failed to parse API response") from None
314
315 if (
316 resp.status == 400
317 and isinstance(data, dict)
318 and (message := data.get("message"))
319 and (code := message.split(" ")[0])
320 and code in self._non_retryable_error_codes
321 ):
322 raise CloudApiNonRetryableError(message, code=code) from None
323
324 if resp.status == 403 and self._cloud.subscription_expired:
325 raise CloudApiNonRetryableError(
326 "Subscription has expired",
327 code="subscription_expired",
328 ) from None
329
330 if raw_response:
331 return CloudApiRawResponse(data=data, response=resp)
332
333 try:
334 resp.raise_for_status()
335 except ClientResponseError as err:
336 reason = (
337 data.get("reason", data.get("message"))
338 if isinstance(data, dict)
339 else None
340 )
341 raise CloudApiError(
342 f"Failed to fetch: ({err.status}) {err.message}",
343 orig_exc=err,
344 reason=reason,
345 status=resp.status,
346 ) from err
347
348 if schema is not None and data is not None:
349 try:
350 data = schema(data)
351 except vol.Invalid as err:
352 raise CloudApiInvalidResponseError(
353 f"Invalid response: {humanize_error(data, err)}",
354 orig_exc=err,
355 ) from err
356
357 return data