Debian Codegraph @

hass_nabucasa/service_discovery.py

raw
1 """Service discovery."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import contextlib
7 import logging
8 from typing import TYPE_CHECKING, Any, Literal, TypedDict, get_args
9
10 import voluptuous as vol
11
12 from .api import ApiBase, CloudApiError, api_exception_handler
13 from .const import (
14 FIVE_MINUTES_IN_SECONDS,
15 ONE_HOUR_IN_SECONDS,
16 TWELVE_HOURS_IN_SECONDS,
17 )
18 from .events.types import CloudEvent, CloudEventType
19 from .utils import jitter, seconds_as_dhms, utcnow
20
21 if TYPE_CHECKING:
22 from . import Cloud, _ClientT
23
24 _LOGGER = logging.getLogger(__name__)
25
26 MIN_REFRESH_INTERVAL = 60
27 TIME_DELTA_FOR_INITIAL_LOAD_RETRY = TWELVE_HOURS_IN_SECONDS
28
29 ServiceDiscoveryAction = Literal[
30 "account_services",
31 "acme_directory",
32 "alexa_access_token",
33 "google_report_state_request_sync",
34 "google_report_state_websocket",
35 "instance_connection",
36 "llm_connection_details",
37 "relayer_connect",
38 "remote_access_dns_challenge_remove",
39 "remote_access_dns_challenge_set",
40 "remote_access_ping_targets",
41 "remote_access_register",
42 "remote_access_resolve_dns_cname",
43 "remote_access_snitun_token",
44 "storage_files_delete",
45 "storage_files_download",
46 "storage_files_list",
47 "storage_files_upload",
48 "subscription_info",
49 "subscription_migrate_paypal",
50 "voice_connection_details",
51 "webhook_generate",
52 "webrtc_ice_servers",
53 ]
54
55 VALID_ACTION_NAMES = frozenset(get_args(ServiceDiscoveryAction))
56
57
58 def _filter_and_validate_actions(actions: dict[str, Any]) -> dict[str, str]:
59 """Filter actions to only known keys and validate they are valid URLs."""
60 if not isinstance(actions, dict):
61 raise vol.Invalid("actions must be a dictionary")
62
63 filtered = {}
64 for key in VALID_ACTION_NAMES:
65 if not (value := actions.get(key)):
66 raise vol.Invalid(f"Action '{key}' is missing")
67
68 try:
69 vol.Url(value)
70 except vol.Invalid as err:
71 raise vol.Invalid(f"Action '{key}' has invalid URL: {err}") from err
72 filtered[key] = value
73
74 return filtered
75
76
77 SERVICE_DISCOVERY_SCHEMA = vol.Schema(
78 {
79 vol.Required("actions"): _filter_and_validate_actions,
80 vol.Required("valid_for"): vol.All(int, vol.Range(min=0)),
81 vol.Required("version"): str,
82 },
83 extra=vol.REMOVE_EXTRA,
84 )
85
86
87 class ServiceDiscoveryError(CloudApiError):
88 """Exception raised when handling service discovery API."""
89
90
91 class ServiceDiscoveryInvalidResponseError(ServiceDiscoveryError):
92 """Exception raised when service discovery API returns invalid data."""
93
94
95 class ServiceDiscoveryMissingParameterError(ServiceDiscoveryError):
96 """Exception raised when required format parameters are missing."""
97
98
99 class ServiceDiscoveryMissingActionError(ServiceDiscoveryError):
100 """Exception raised when an action has no URL configured."""
101
102
103 class ServiceDiscoveryResponse(TypedDict):
104 """Response from service discovery API."""
105
106 actions: dict[str, str]
107 valid_for: int
108 version: str
109
110
111 class ServiceDiscoveryCacheData(TypedDict):
112 """Cached service discovery data."""
113
114 data: ServiceDiscoveryResponse
115 valid_until: float
116
117
118 def _is_cache_valid(cache: ServiceDiscoveryCacheData) -> bool:
119 """Check if cache is still valid."""
120 try:
121 return cache["valid_until"] > utcnow().timestamp()
122 except KeyError, TypeError:
123 return False
124
125
126 def _calculate_sleep_time(valid_until: float) -> int:
127 """Calculate sleep time until next refresh."""
128 remaining = valid_until - utcnow().timestamp()
129
130 # For expired or very soon expiring caches, spread refreshes over 1-5 min
131 if remaining <= MIN_REFRESH_INTERVAL:
132 return round(jitter(MIN_REFRESH_INTERVAL, FIVE_MINUTES_IN_SECONDS))
133
134 return round(
135 max(MIN_REFRESH_INTERVAL, remaining + jitter(5, ONE_HOUR_IN_SECONDS)),
136 )
137
138
139 class ServiceDiscovery(ApiBase):
140 """Class to handle service discovery."""
141
142 def __init__(
143 self,
144 cloud: Cloud[_ClientT],
145 *,
146 action_overrides: dict[ServiceDiscoveryAction, str] | None = None,
147 ) -> None:
148 """Initialize service discovery."""
149 super().__init__(cloud)
150 self._load_service_discovery_data_lock = asyncio.Lock()
151 self._service_discovery_refresh_task: asyncio.Task[None] | None = None
152 self._memory_cache: ServiceDiscoveryCacheData | None = None
153 self._action_overrides = action_overrides or {}
154
155 if TYPE_CHECKING:
156 assert self._cloud.api_server is not None
157 assert self._cloud.relayer_server is not None
158
159 self._fallback_actions: dict[ServiceDiscoveryAction, str] = {
160 "account_services": f"https://{self._cloud.api_server}/account/services",
161 "acme_directory": f"https://{self._cloud.acme_server}/directory",
162 "alexa_access_token": f"https://{self._cloud.api_server}/alexa/access_token",
163 "google_report_state_request_sync": f"https://{self._cloud.remotestate_server}/request_sync",
164 "google_report_state_websocket": f"wss://{self._cloud.remotestate_server}/v1",
165 "instance_connection": f"https://{self._cloud.api_server}/instance/connection",
166 "llm_connection_details": f"https://{self._cloud.api_server}/llm/connection_details",
167 "relayer_connect": f"wss://{self._cloud.relayer_server}/websocket",
168 "remote_access_dns_challenge_remove": f"https://{self._cloud.api_server}/instance/dns_challenge_cleanup",
169 "remote_access_dns_challenge_set": f"https://{self._cloud.api_server}/instance/dns_challenge_txt",
170 "remote_access_ping_targets": f"https://{self._cloud.api_server}/instance/remote_ping_targets",
171 "remote_access_register": f"https://{self._cloud.api_server}/instance/register",
172 "remote_access_resolve_dns_cname": f"https://{self._cloud.api_server}/account/instance/resolve_dns_cname",
173 "remote_access_snitun_token": f"https://{self._cloud.api_server}/instance/snitun_token",
174 "storage_files_delete": f"https://{self._cloud.api_server}/files",
175 "storage_files_download": f"https://{self._cloud.api_server}/files/download_details/{{storage_type}}/{{filename}}",
176 "storage_files_list": f"https://{self._cloud.api_server}/v2/files/{{storage_type}}",
177 "storage_files_upload": f"https://{self._cloud.api_server}/files/upload_details",
178 "subscription_info": f"https://{self._cloud.api_server}/account/payments/subscription_info",
179 "subscription_migrate_paypal": f"https://{self._cloud.api_server}/account/payments/migrate_paypal_agreement",
180 "voice_connection_details": f"https://{self._cloud.api_server}/voice/connection_details",
181 "webhook_generate": f"https://{self._cloud.api_server}/instance/webhook",
182 "webrtc_ice_servers": f"https://{self._cloud.api_server}/v2/webrtc/ice_servers",
183 }
184
185 @property
186 def hostname(self) -> str:
187 """Get the hostname for service discovery."""
188 if TYPE_CHECKING:
189 assert self._cloud.api_server is not None
190 return self._cloud.api_server
191
192 @api_exception_handler(ServiceDiscoveryError)
193 async def _fetch_well_known_service_discovery(self) -> ServiceDiscoveryResponse:
194 """Fetch service discovery data from the well-known API."""
195 validated_data: dict[str, Any] = await self._call_cloud_api(
196 path="/.well-known/service-discovery",
197 schema=SERVICE_DISCOVERY_SCHEMA,
198 skip_token_check=True,
199 )
200 _LOGGER.debug(
201 "Service discovery %s with %d actions fetched",
202 validated_data["version"],
203 len(validated_data["actions"]),
204 )
205 return ServiceDiscoveryResponse(
206 actions=validated_data["actions"],
207 valid_for=validated_data["valid_for"],
208 version=validated_data["version"],
209 )
210
211 async def _load_service_discovery_data(self) -> ServiceDiscoveryCacheData:
212 """Load discovery data from cache or fetch from API."""
213 async with self._load_service_discovery_data_lock:
214 cache = self._memory_cache
215
216 if cache is not None and _is_cache_valid(cache):
217 _LOGGER.debug("Using cached service discovery data")
218 return cache
219
220 try:
221 discovery_data = await self._fetch_well_known_service_discovery()
222 except ServiceDiscoveryError:
223 if not cache:
224 raise
225
226 _LOGGER.info(
227 "Unable to fetch service discovery data, using expired cache"
228 )
229 return cache
230
231 cache_data = ServiceDiscoveryCacheData(
232 data=discovery_data,
233 valid_until=utcnow().timestamp() + discovery_data["valid_for"],
234 )
235 self._memory_cache = cache_data
236
237 _LOGGER.debug(
238 "Service discovery data cached, valid for %s",
239 seconds_as_dhms(discovery_data["valid_for"]),
240 )
241
242 await self._cloud.events.publish(
243 event=CloudEvent(type=CloudEventType.SERVICE_DISCOVERY_UPDATE)
244 )
245
246 return cache_data
247
248 async def async_start_service_discovery(self) -> None:
249 """Start service discovery and wait for initial load."""
250 if (
251 self._service_discovery_refresh_task is None
252 or self._service_discovery_refresh_task.done()
253 ):
254 try:
255 await self._load_service_discovery_data()
256 except ServiceDiscoveryError as err:
257 _LOGGER.debug("Failed to load initial service discovery data: %s", err)
258
259 self._service_discovery_refresh_task = asyncio.create_task(
260 self._schedule_service_discovery_refresh(),
261 name="service_discovery_refresh",
262 )
263
264 async def _schedule_service_discovery_refresh(self) -> None:
265 """Schedule automatic refresh of service discovery data."""
266 while True:
267 try:
268 if self._memory_cache is None:
269 # If we get here the initial load failed, retry after fixed delay
270 next_check = (
271 utcnow().timestamp() + TIME_DELTA_FOR_INITIAL_LOAD_RETRY
272 )
273 else:
274 next_check = self._memory_cache["valid_until"]
275
276 sleep_time = _calculate_sleep_time(next_check)
277
278 _LOGGER.debug(
279 "Scheduling service discovery refresh in %s",
280 seconds_as_dhms(sleep_time),
281 )
282 await asyncio.sleep(sleep_time)
283
284 await self._load_service_discovery_data()
285 except asyncio.CancelledError:
286 _LOGGER.debug("Service discovery refresh task cancelled")
287 raise
288 except ServiceDiscoveryError as err:
289 _LOGGER.info("Unable to refresh service discovery data: %s", err)
290
291 async def async_stop_service_discovery(self) -> None:
292 """Stop the service discovery component."""
293 if (
294 self._service_discovery_refresh_task is not None
295 and not self._service_discovery_refresh_task.done()
296 ):
297 self._service_discovery_refresh_task.cancel()
298 with contextlib.suppress(asyncio.CancelledError):
299 await self._service_discovery_refresh_task
300 self._service_discovery_refresh_task = None
301
302 def _get_fallback_action_url(self, action: ServiceDiscoveryAction) -> str:
303 """Get fallback action."""
304 if (fallback_action_url := self._fallback_actions.get(action)) is not None:
305 _LOGGER.info(
306 "Using fallback action URL for %s: %s", action, fallback_action_url
307 )
308 return fallback_action_url
309 raise ServiceDiscoveryMissingActionError(
310 f"No fallback URL for action: {action}"
311 )
312
313 def _get_service_action_url(self, action: ServiceDiscoveryAction) -> str:
314 """Get URL for a specific action."""
315 if action_override_url := self._action_overrides.get(action):
316 _LOGGER.info(
317 "Using overridden action URL for %s: %s", action, action_override_url
318 )
319 return action_override_url
320
321 if self._memory_cache and (
322 cached_action_url := self._memory_cache["data"]["actions"].get(action)
323 ):
324 _LOGGER.debug(
325 "Using cached action URL for %s: %s", action, cached_action_url
326 )
327 return cached_action_url
328 return self._get_fallback_action_url(action)
329
330 def action_url(self, action: ServiceDiscoveryAction, **kwargs: str) -> str:
331 """Get URL for a specific action with optional format parameters."""
332 if action not in VALID_ACTION_NAMES:
333 raise ServiceDiscoveryMissingActionError(f"Unknown action: {action}")
334
335 try:
336 return self._get_service_action_url(action).format_map(kwargs)
337 except KeyError as err:
338 raise ServiceDiscoveryMissingParameterError(
339 f"Missing required format parameter {err} for action '{action}'"
340 ) from err