diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 09ba46f..6b4fbcd 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -2,12 +2,16 @@ from __future__ import annotations +import asyncio +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime import logging import re +from threading import Lock import time from typing import Any, Optional +from urllib.parse import urlsplit -import asyncio import aiohttp import requests @@ -37,6 +41,7 @@ LydosPlantMode, NuosSplitOperativeMode, PlantData, + PropertyType, ThermostatProperties, WaterHeaterMode, ZoneAttribute, @@ -53,26 +58,124 @@ def _parse_block_seconds(content: bytes) -> Optional[int]: match = _RATE_LIMIT_RE.search(content) if match is None: return None - return int(match.group(1)) + try: + return int(match.group(1)) + except ValueError: + return None -def _rate_limit_wait_seconds(content: bytes) -> int: - """Effective wait for a 429: parsed duration + 1s margin, else 5s.""" - parsed = _parse_block_seconds(content) - if parsed is None: - _LOGGER.warning( - "Rate limited (429) without parsable block duration; " - "falling back to 5s wait" - ) - return 5 - _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) - return parsed + 1 +_RECOVERY_MAX_REQUESTS = 8 +_RECOVERY_TIMEOUT_SECONDS = 15 +_RECOVERY_MAX_CONSECUTIVE_FAILURES = 4 +_RATE_LIMIT_FALLBACK_SECONDS = 60 +_RATE_LIMIT_MAX_FALLBACK_SECONDS = 15 * 60 + + +def _retry_after_seconds(value: str) -> float | None: + """Parse either form of Retry-After.""" + try: + if value.isascii() and value.isdecimal(): + return float(int(value)) + deadline = parsedate_to_datetime(value) + if deadline.tzinfo is not None: + return max(0, (deadline - datetime.now(timezone.utc)).total_seconds()) + except (ValueError, TypeError, OverflowError): + pass + return None class ConnectionException(Exception): """When can not connect to Ariston cloud""" +class _RateLimit: + """Coordinate authenticated requests for one account and API origin.""" + + def __init__(self) -> None: + self.deadline = 0.0 + self.fallback = _RATE_LIMIT_FALLBACK_SECONDS + self.pending = 0 + self.lock = Lock() + + def check(self) -> float: + with self.lock: + if self.pending or time.monotonic() < self.deadline: + raise ConnectionException(429, "Ariston API cooldown active") + return self.deadline + + def succeeded(self, previous_deadline: float) -> None: + with self.lock: + if self.deadline == previous_deadline and not self.pending: + self.fallback = _RATE_LIMIT_FALLBACK_SECONDS + + def blocked(self, content: bytes, retry_after: str) -> None: + parsed = _parse_block_seconds(content) + try: + body_delay = float(parsed + 1) if parsed is not None else None + except OverflowError: + body_delay = None + hints = [ + seconds + for seconds in ( + body_delay, + _retry_after_seconds(retry_after), + ) + if seconds is not None + ] + with self.lock: + now = time.monotonic() + if hints: + delay = max(hints) + else: + delay = self.fallback + if now >= self.deadline: + self.fallback = min(delay * 2, _RATE_LIMIT_MAX_FALLBACK_SECONDS) + else: + # Concurrent responses belong to the same cooldown. + delay = 0 + if now >= self.deadline: + _LOGGER.warning("Ariston API rate limited (429) for %.0f seconds", delay) + self.deadline = max(self.deadline, now + delay) + + +_RATE_LIMITS: dict[tuple[str, str | None, int | None, str], _RateLimit] = {} +_RATE_LIMITS_LOCK = Lock() + + +def _property_fallback_groups( + group: list[dict[str, Any]], used_cache: bool = False +) -> list[tuple[list[dict[str, Any]], bool]]: + if len(group) == 1: + return [] if used_cache else [(group, True)] + midpoint = (len(group) + 1) // 2 + return [(group[midpoint:], False), (group[:midpoint], False)] + + +def _expected_property_keys( + items: list[dict[str, Any]], features: dict[str, Any] +) -> set[tuple[str, int]]: + """Return the property keys required for a complete GALEVO recovery.""" + expected = {(item["id"], item["zn"]) for item in items} + if ( + features.get(DeviceFeatures.HP_SYS) is True + or features.get(DeviceFeatures.HYBRID_SYS) is True + ): + # Heat pumps can expose this reading through menu item 349 instead. + expected.discard((DeviceProperties.CH_FLOW_TEMP, 0)) + return expected + + +class _IncompleteProperties(ConnectionException): + """A recovery contains partial or provider-cached data.""" + + def __init__( + self, properties: dict[str, Any], cached_keys: set[tuple[str, int]] + ) -> None: + super().__init__("GALEVO property refresh did not return a complete fresh snapshot") + self.properties = properties + self.cached_keys = frozenset(cached_keys) + + class AristonAPI: """Ariston API class""" @@ -93,10 +196,16 @@ def __init__( # needs a running event loop) and logged in on first use. self.__r2_cookies: Optional[aiohttp.CookieJar] = None self.__r2_logged_in = False - # Per-instance 429 block window: instances for different accounts or - # API URLs must not silence each other; the three coordinators for - # one account still share one API instance. - self._blocked_until = 0.0 + origin = urlsplit(api_url) + default_port = {"http": 80, "https": 443}.get(origin.scheme) + key = ( + origin.scheme, origin.hostname, origin.port or default_port, + username.strip().casefold(), + ) + with _RATE_LIMITS_LOCK: + if key not in _RATE_LIMITS: + _RATE_LIMITS[key] = _RateLimit() + self._rate_limit = _RATE_LIMITS[key] # Sync (requests) R2 web-app session; created lazily on first use. self.__r2_requests_session: Optional[requests.Session] = None @@ -122,6 +231,8 @@ def connect(self) -> bool: return True + except ConnectionException: + raise except Exception as error: raise ConnectionException() from error @@ -567,11 +678,7 @@ def __request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" - if not is_retry and time.time() < self._blocked_until: - raise ConnectionException( - 429, - "Rate limited; skipping request until the block window ends", - ) + deadline = self._rate_limit.check() headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -597,15 +704,17 @@ def __request( case 404: return None case 429: - return self.__handle_rate_limit( - response, is_retry, method, path, params, body + self._rate_limit.blocked( + response.content, response.headers.get("Retry-After", "") ) + raise ConnectionException(429, "Ariston API rate limited") case _: if not is_retry: time.sleep(5) return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) + self._rate_limit.succeeded(deadline) if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -617,24 +726,6 @@ def _post(self, path: str, body: Any) -> Any: """POST request""" return self.__request("POST", path, None, body) - def __handle_rate_limit( - self, - response, - is_retry: bool, - method: str, - path: str, - params: Optional[dict[str, Any]], - body: Any, - ) -> Optional[dict[str, Any]]: - """Sleep out the 429 block window, retry once, per-instance deadline.""" - content = response.content - wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: - time.sleep(wait_seconds) - return self.__request(method, path, params, body, True) - raise ConnectionException(response.status_code, content.decode()) - def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" return self.__request("GET", path, params, None) @@ -748,6 +839,8 @@ async def async_connect(self) -> bool: return True + except ConnectionException: + raise except Exception as error: raise ConnectionException() from error @@ -830,28 +923,19 @@ async def async_set_consumptions_settings( async def async_get_properties( self, gw_id: str, features: dict[str, Any], culture: str, umsys: str ) -> dict[str, Any]: - """Async get device properties""" + """Get a full GALEVO batch, splitting it only on transient failures.""" path = f"{self.__api_url}{ARISTON_REMOTE}/{ARISTON_DATA_ITEMS}/{gw_id}/get?umsys={umsys}" items = self.get_items(features) try: - properties = await self._async_request_properties( + return await self._async_request_properties( path, items, features, culture, False - ) - except (ConnectionException, asyncio.TimeoutError) as error: - if ( - isinstance(error, ConnectionException) - and error.args[:1] != (500,) - ) or not items: + ) or {} + except (ConnectionException, TimeoutError) as error: + if isinstance(error, ConnectionException) and error.args[:1] != (500,): raise - _LOGGER.warning( - "GALEVO properties batch failed with HTTP 500 or timed out; retrying in pairs" - ) - properties = await self._async_recover_properties( + return await self._async_recover_properties( path, items, features, culture, error ) - if properties is not None: - return properties - return {} async def _async_request_properties( self, @@ -860,8 +944,10 @@ async def _async_request_properties( features: dict[str, Any], culture: str, use_cache: bool, + *, + recovery: bool = False, ) -> Any: - """Request a group of GALEVO properties.""" + """Send one property request, allowing reauthentication on the full batch.""" return await self._async_post( path, { @@ -871,99 +957,86 @@ async def _async_request_properties( "culture": culture, }, timeout_seconds=90, + retry_http_500=False, + is_retry=recovery, ) - async def _async_cached_property( + async def _async_recover_properties( self, path: str, - item: dict[str, Any], + items: list[dict[str, Any]], features: dict[str, Any], culture: str, - ) -> Any: - """Retry a property with the provider cache after a server error or timeout.""" - _LOGGER.warning( - "GALEVO property %s failed or timed out; trying cached value", - item["id"], - ) - try: - return await self._async_request_properties( - path, [item], features, culture, True - ) - except ConnectionException as error: - _LOGGER.warning( - "GALEVO property %s also failed with cache (HTTP %s)", - item["id"], - error.args[0] if error.args else "unknown", - ) - raise + initial_error: ConnectionException | TimeoutError, + ) -> dict[str, Any]: + """Bisect failed groups within a shared request and time budget.""" + if not items: + raise initial_error - async def _async_recover_property( - self, - path: str, - item: dict[str, Any], - features: dict[str, Any], - culture: str, - ) -> Any: - """Retry one property fresh, then cached on server error or timeout.""" + pending = _property_fallback_groups(items) + recovered: dict[tuple[str, int], dict[str, Any]] = {} + cached_keys: set[tuple[str, int]] = set() + attempts = failures = 0 + expected = _expected_property_keys(items, features) try: - return await self._async_request_properties( - path, [item], features, culture, False - ) - except (ConnectionException, asyncio.TimeoutError) as error: - if isinstance(error, ConnectionException) and error.args[:1] != (500,): - raise - return await self._async_cached_property(path, item, features, culture) + async with asyncio.timeout(_RECOVERY_TIMEOUT_SECONDS): + while ( + pending + and attempts < _RECOVERY_MAX_REQUESTS + and failures < _RECOVERY_MAX_CONSECUTIVE_FAILURES + ): + group, use_cache = pending.pop() + attempts += 1 + received = await self._async_recover_property_group( + path, group, features, culture, use_cache + ) + if received is None: + failures += 1 + pending.extend(_property_fallback_groups(group, use_cache)) + continue + failures = 0 if received else failures + 1 + recovered.update(received) + if use_cache: + cached_keys.update(received) + except TimeoutError: + pass + + properties = {"features": features, "items": list(recovered.values())} + if recovered and expected.issubset(recovered) and not cached_keys: + _LOGGER.debug("Recovered complete GALEVO properties in %s requests", attempts) + return properties + _LOGGER.debug( + "Incomplete GALEVO recovery after %s requests: %s/%s required properties, %s cached", + attempts, len(expected.intersection(recovered)), len(expected), len(cached_keys), + ) + if not recovered: + raise initial_error + raise _IncompleteProperties(properties, cached_keys) from initial_error - async def _async_recover_property_chunk( + async def _async_recover_property_group( self, path: str, - chunk: list[dict[str, Any]], + group: list[dict[str, Any]], features: dict[str, Any], culture: str, - ) -> list[dict[str, Any]]: - """Retry a pair, splitting on server error or timeout.""" + use_cache: bool, + ) -> dict[tuple[str, int], dict[str, Any]] | None: + """Return the requested items received, or None for a splittable failure.""" try: - response = await self._async_request_properties( - path, chunk, features, culture, False + result = await self._async_request_properties( + path, group, features, culture, use_cache, recovery=True ) - except (ConnectionException, asyncio.TimeoutError) as error: + except (ConnectionException, TimeoutError) as error: if isinstance(error, ConnectionException) and error.args[:1] != (500,): raise - if len(chunk) == 1: - response = await self._async_cached_property( - path, chunk[0], features, culture - ) - return response.get("items", []) if response else [] - recovered = [] - for item in chunk: - response = await self._async_recover_property( - path, item, features, culture - ) - if response: - recovered.extend(response.get("items", [])) - return recovered - return response.get("items", []) if response else [] + return None - async def _async_recover_properties( - self, - path: str, - items: list[dict[str, Any]], - features: dict[str, Any], - culture: str, - initial_error: ConnectionException | asyncio.TimeoutError, - ) -> dict[str, Any]: - """Collect pair retries, preserving the original error if none succeed.""" - properties = {"features": features, "items": []} - for index in range(0, len(items), 2): - chunk = items[index : index + 2] - properties["items"].extend( - await self._async_recover_property_chunk( - path, chunk, features, culture - ) - ) - if not properties["items"]: - raise initial_error - return properties + group_keys = {(item["id"], item["zn"]) for item in group} + received = { + (item.get("id"), item.get(PropertyType.ZONE)): item + for item in (result or {}).get("items", []) + } + return {key: item for key, item in received.items() if key in group_keys} async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" @@ -1461,13 +1534,10 @@ async def __async_request( body: Any = None, is_retry: bool = False, timeout_seconds: int = 30, + retry_http_500: bool = True, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" - if not is_retry and time.time() < self._blocked_until: - raise ConnectionException( - 429, - "Rate limited; skipping request until the block window ends", - ) + deadline = self._rate_limit.check() headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -1493,7 +1563,8 @@ async def __async_request( if not is_retry: if await self.async_connect(): return await self.__async_request( - method, path, params, body, True, timeout_seconds + method, path, params, body, True, timeout_seconds, + retry_http_500, ) raise ConnectionException( "Login failed (password changed?)" @@ -1502,17 +1573,16 @@ async def __async_request( case 404: return None case 429: - return await self.__async_handle_rate_limit( - response, is_retry, method, path, params, body, timeout_seconds - ) + await self.__async_handle_rate_limit(response) case _: - if not is_retry: + if not is_retry and (retry_http_500 or response.status != 500): await asyncio.sleep(5) return await self.__async_request( method, path, params, body, True, timeout_seconds ) raise ConnectionException(response.status) + self._rate_limit.succeeded(deadline) if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1521,33 +1591,36 @@ async def __async_request( return None async def _async_post( - self, path: str, body: Any, timeout_seconds: int = 30 + self, + path: str, + body: Any, + timeout_seconds: int = 30, + *, + retry_http_500: bool = True, + is_retry: bool = False, ) -> Any: - """Async POST request""" + """Async POST request.""" return await self.__async_request( - "POST", path, None, body, timeout_seconds=timeout_seconds + "POST", path, None, body, is_retry, timeout_seconds, retry_http_500 ) - async def __async_handle_rate_limit( - self, - response, - is_retry: bool, - method: str, - path: str, - params: Optional[dict[str, Any]], - body: Any, - timeout_seconds: int, - ) -> Optional[dict[str, Any]]: - """Sleep out the 429 block window, retry once, share the deadline.""" - content = await response.content.read() - wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: - await asyncio.sleep(wait_seconds) - return await self.__async_request( - method, path, params, body, True, timeout_seconds - ) - raise ConnectionException(response.status, content) + async def __async_handle_rate_limit(self, response: aiohttp.ClientResponse) -> None: + """Close the request gate while reading the server's cooldown hints.""" + with self._rate_limit.lock: + self._rate_limit.pending += 1 + content = b"" + try: + async with asyncio.timeout(1): + content = await response.content.read() + except (aiohttp.ClientError, TimeoutError): + pass + finally: + try: + self._rate_limit.blocked(content, response.headers.get("Retry-After", "")) + finally: + with self._rate_limit.lock: + self._rate_limit.pending -= 1 + raise ConnectionException(429, "Ariston API rate limited") async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 7307f9a..461ac9f 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -49,6 +49,7 @@ def __init__( self.consumptions_settings: dict[str, Any] = {} self.energy_account: dict[str, Any] = {} self.menu_items: list[dict[str, Any]] = [] + self.menu_items_fresh = False @property def consumption_type(self) -> str: @@ -122,71 +123,83 @@ def _should_include_hybrid_menu_items(self) -> bool: def update_state(self) -> None: """Update the device states from the cloud""" - if len(self.features) == 0: + self.menu_items_fresh = False + if not self.features: self.get_features() - self.data = self.api.get_properties( - self.gw, - self.features, - self.language_tag, - self.umsys, + data = self.api.get_properties( + self.gw, self.features, self.language_tag, self.umsys ) try: - self.menu_items = self.api.get_menu_items( - self.gw, - include_hybrid_items=self._should_include_hybrid_menu_items(), + menu_items = self.api.get_menu_items( + self.gw, include_hybrid_items=self._should_include_hybrid_menu_items() ) except ConnectionException as error: - if not self._should_retain_menu_items_after_error(error): - raise - self._update_state() + menu_items = self._menu_refresh_result(error) + self._apply_cloud_state(data, menu_items) async def async_update_state(self) -> None: - """Async update the device states from the cloud""" - if len(self.features) == 0: + """Async update the device states from the cloud.""" + self.menu_items_fresh = False + if not self.features: await self.async_get_features() - (self.data, self.menu_items) = await asyncio.gather( + # Wait for both requests to settle before accepting a new snapshot. + data, menu_items = await asyncio.gather( self.api.async_get_properties( - self.gw, - self.features, - self.language_tag, - self.umsys, + self.gw, self.features, self.language_tag, self.umsys ), - self._async_get_menu_items( - include_hybrid_items=self._should_include_hybrid_menu_items() + self.api.async_get_menu_items( + self.gw, + include_hybrid_items=self._should_include_hybrid_menu_items(), ), + return_exceptions=True, ) - self._update_state() + if isinstance(data, BaseException): + raise data + self._apply_cloud_state(data, self._menu_refresh_result(menu_items)) - async def _async_get_menu_items( - self, include_hybrid_items: bool = False - ) -> list[dict[str, Any]]: - """Get menu items while retaining the last values for server errors.""" - try: - return await self.api.async_get_menu_items( - self.gw, include_hybrid_items=include_hybrid_items - ) - except ConnectionException as error: - if not self._should_retain_menu_items_after_error(error): - raise - return self.menu_items - - def _should_retain_menu_items_after_error( - self, error: ConnectionException - ) -> bool: - """Log and identify menu server errors that can use cached values.""" - status = error.args[0] if error.args else None - if status not in (500, 550): - return False + @staticmethod + def _menu_refresh_result( + result: list[dict[str, Any]] | BaseException, + ) -> list[dict[str, Any]] | None: + """Keep cached menu values after a transient menu server error.""" + if not isinstance(result, BaseException): + return result + if isinstance(result, ConnectionException) and result.args[:1] in ((500,), (550,)): + _LOGGER.debug("Keeping cached GALEVO menu items after HTTP %s", result.args[0]) + return None + raise result - _LOGGER.warning( - "Could not fetch menu items for gateway %s (HTTP %s); " - "retaining the last successful values", - self.gw, - status, - ) - return True + def _apply_cloud_state( + self, data: dict[str, Any], menu_items: list[dict[str, Any]] | None + ) -> None: + """Keep the last snapshot and capabilities when the response loses items.""" + items = data.get("items", []) + keys = {(item.get("id"), item.get(PropertyType.ZONE)) for item in items} + previous_keys = { + (item.get("id"), item.get(PropertyType.ZONE)) + for item in self.data.get("items", []) + } + if DeviceFeatures.ZONES in self.features: + active_zones = {0, *self.zone_numbers} + previous_keys = {key for key in previous_keys if key[1] in active_zones} + if not keys or not previous_keys.issubset(keys): + raise ConnectionException("GALEVO property response is incomplete") + + previous_data, previous_menu = self.data, self.menu_items + previous_features = self.custom_features.copy() + self.data = data + if menu_items is not None: + self.menu_items = menu_items + try: + self._update_state() + except Exception: + self.data, self.menu_items = previous_data, previous_menu + self.custom_features.clear() + self.custom_features.update(previous_features) + raise + self.menu_items_fresh = menu_items is not None def _get_features(self) -> None: """Set custom features""" diff --git a/tests/test_ariston_api.py b/tests/test_ariston_api.py index 1df0e8a..61c0439 100644 --- a/tests/test_ariston_api.py +++ b/tests/test_ariston_api.py @@ -11,6 +11,8 @@ BsbOperativeMode, BsbZoneMode, DeviceFeatures, + DeviceProperties, + PropertyType, EvoPlantMode, LydosPlantMode, NuosSplitOperativeMode, @@ -21,6 +23,7 @@ class FakeResponse: def __init__(self, payload=None, status_code=200, content=None): + self.headers = {} self.status_code = status_code self.ok = 200 <= status_code < 400 self._payload = payload @@ -186,7 +189,7 @@ def test_expired_token_is_refreshed_and_request_retried(self): ) def test_rate_limit_is_reported_as_connection_exception(self): - api = AristonAPI("user", "password") + api = AristonAPI("test_rate_limit_is_reported_as_connection_exception", "password") with patch( "ariston.ariston_api.requests.request", @@ -195,7 +198,7 @@ def test_rate_limit_is_reported_as_connection_exception(self): with self.assertRaises(ConnectionException) as error: api.get_detailed_devices() - self.assertEqual(error.exception.args, (429, "rate limited")) + self.assertEqual(error.exception.args, (429, "Ariston API rate limited")) def test_sync_read_endpoints_return_payloads_and_empty_defaults(self): api = AristonAPI("user", "password", api_url="https://example.test/api/") @@ -469,7 +472,6 @@ def test_async_properties_recovers_from_batch_errors_with_small_requests(self): (["A", "B", "PlantMode"], False), (["A", "B"], False), (["PlantMode"], False), - (["PlantMode"], True), ], ), ( @@ -493,15 +495,11 @@ def test_async_properties_recovers_from_batch_errors_with_small_requests(self): async def post(path, body, **kwargs): requested = [item["id"] for item in body["items"]] requests.append((requested, body["useCache"])) - if len(requested) > 2 or ( - isinstance(failure, ConnectionException) - and requested == ["PlantMode"] - and not body["useCache"] - ): + if len(requested) > 2: raise failure return { "features": features, - "items": [{"id": name} for name in requested], + "items": [{"id": name, PropertyType.ZONE: 0} for name in requested], } async def exercise(): @@ -533,7 +531,7 @@ async def post(path, body, **kwargs): raise ConnectionException(500) if requested == ["B"] and not body["useCache"]: raise ConnectionException(500) - return {"items": [{"id": name} for name in requested]} + return {"items": [{"id": name, PropertyType.ZONE: 0} for name in requested]} async def exercise(): with patch.object(api, "get_items", return_value=items), patch.object( @@ -541,9 +539,13 @@ async def exercise(): ): return await api.async_get_properties("gw-1", features, "en", "si") - result = asyncio.run(exercise()) + request = exercise() + with self.assertRaisesRegex(ConnectionException, "complete fresh snapshot") as error: + asyncio.run(request) + self.assertEqual(error.exception.cached_keys, {("B", 0)}) self.assertEqual( - [item["id"] for item in result["items"]], ["A", "B", "C", "D"] + [item["id"] for item in error.exception.properties["items"]], + ["A", "B", "C", "D"], ) self.assertEqual( requests, @@ -570,17 +572,137 @@ async def exercise(status): await api.async_get_properties("gw-1", features, "en", "si") return error.exception, post.await_args_list - with self.assertLogs("ariston.ariston_api", level="WARNING") as logs: - server_error, server_calls = asyncio.run(exercise(500)) + server_error, server_calls = asyncio.run(exercise(500)) self.assertEqual(server_error.args, (500,)) - self.assertEqual(len(server_calls), 4) - self.assertTrue(server_calls[-1].args[1]["useCache"]) - self.assertIn("property A also failed with cache", logs.output[-1]) + self.assertEqual(len(server_calls), 5) + self.assertTrue(server_calls[-2].args[1]["useCache"]) auth_error, auth_calls = asyncio.run(exercise(401)) self.assertEqual(auth_error.args, (401,)) self.assertEqual(len(auth_calls), 1) + def test_galevo_full_batch_and_two_zone_recovery_use_response_zones(self): + for heat_pump in (False, True): + for fail_batch in (False, True): + with self.subTest(heat_pump=heat_pump, fail_batch=fail_batch): + self._assert_two_zone_properties(heat_pump, fail_batch) + + def _assert_two_zone_properties(self, heat_pump, fail_batch): + features = { + DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}, {ZoneAttribute.NUM: 2}], + DeviceFeatures.HP_SYS: heat_pump, + } + api = AristonAPI("user", "password") + items = api.get_items(features) + + def response_rows(requested): + return [ + {"id": item["id"], PropertyType.ZONE: item["zn"], "value": item["zn"]} + for item in requested + if not heat_pump or item["id"] != DeviceProperties.CH_FLOW_TEMP + ] + + async def post(path, body, **kwargs): + if fail_batch and body["items"] == items: + raise ConnectionException(500) + return {"items": response_rows(body["items"])} + + with patch.object(api, "_async_post", side_effect=post) as transport: + result = asyncio.run(api.async_get_properties("gw", features, "en", "si")) + + self.assertEqual(result["items"], response_rows(items)) + self.assertEqual(transport.await_count, 3 if fail_batch else 1) + self.assertEqual(transport.await_args_list[0].args[1]["items"], items) + self.assertFalse(transport.await_args_list[0].kwargs["retry_http_500"]) + + def test_recovery_enforces_request_budget_after_intermittent_failures(self): + api = AristonAPI("user", "password") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + attempts = 0 + + async def post(path, body, **kwargs): + nonlocal attempts + attempts += 1 + if attempts in (1, 2, 3, 4, 6, 8): + raise ConnectionException(500) + return { + "items": [ + {"id": item["id"], PropertyType.ZONE: item["zn"]} + for item in body["items"] + ] + } + + with patch.object(api, "_async_post", side_effect=post) as transport: + request = api.async_get_properties("gw", features, "en", "si") + with self.assertRaisesRegex(ConnectionException, "complete fresh snapshot"): + asyncio.run(request) + + self.assertEqual(transport.await_count, 9) + self.assertTrue(all(call.kwargs["is_retry"] for call in transport.await_args_list[1:])) + + def test_persistent_http_500_uses_one_wire_request_per_attempt(self): + api = AristonAPI("user", "password") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + session = FakeAsyncSession(FakeAsyncResponse(status_code=500)) + + with patch("ariston.ariston_api.aiohttp.ClientSession", return_value=session): + request = api.async_get_properties("gw", features, "en", "si") + with self.assertRaises(ConnectionException) as error: + asyncio.run(request) + + self.assertEqual(error.exception.args, (500,)) + self.assertEqual(len(session.calls), 5) + self.assertEqual(session.calls[0][1]["json"]["items"], api.get_items(features)) + + def test_recovery_deadline_cancels_in_flight_request(self): + api = AristonAPI("user", "password") + features = {DeviceFeatures.ZONES: []} + cancelled = False + + async def post(path, body, **kwargs): + nonlocal cancelled + if not kwargs["is_retry"]: + raise ConnectionException(500) + try: + await asyncio.Future() + finally: + cancelled = True + + with ( + patch("ariston.ariston_api._RECOVERY_TIMEOUT_SECONDS", 0), + patch.object(api, "_async_post", side_effect=post) as transport, + ): + request = api.async_get_properties("gw", features, "en", "si") + with self.assertRaises(ConnectionException) as error: + asyncio.run(request) + + self.assertEqual(error.exception.args, (500,)) + self.assertEqual(transport.await_count, 2) + self.assertTrue(cancelled) + + def test_partial_response_and_rate_limit_end_recovery(self): + features = {DeviceFeatures.ZONES: []} + for last_response in ({"items": []}, ConnectionException(429)): + with self.subTest(last_response=last_response): + api = AristonAPI("user", "password") + items = [{"id": "SameProperty", "zn": zn} for zn in (1, 2)] + response = {"id": "SameProperty", PropertyType.ZONE: 1} + with ( + patch.object(api, "get_items", return_value=items), + patch.object(api, "_async_post", side_effect=[ + ConnectionException(500), {"items": [response]}, last_response, + ]) as transport, + ): + request = api.async_get_properties("gw", features, "en", "si") + with self.assertRaises(ConnectionException) as error: + asyncio.run(request) + + self.assertEqual(transport.await_count, 3) + if isinstance(last_response, ConnectionException): + self.assertIs(error.exception, last_response) + else: + self.assertEqual(error.exception.properties["items"], [response]) + def test_async_write_endpoints_send_values_to_transport(self): api = AristonAPI("user", "password", api_url="https://example.test/api/") writes = ( @@ -636,7 +758,7 @@ async def run_all(): asyncio.run(run_all()) def test_async_request_empty_response_and_retry_failure_paths(self): - api = AristonAPI("user", "password") + api = AristonAPI("test_async_request_empty_response_and_retry_failure_paths", "password") request = api._AristonAPI__async_request async def exercise(): @@ -702,7 +824,7 @@ async def exercise(): ): with self.assertRaises(ConnectionException) as error: await request("GET", "https://example.test/rate-limited") - self.assertEqual(error.exception.args, (429, b"rate limited")) + self.assertEqual(error.exception.args, (429, "Ariston API rate limited")) asyncio.run(exercise()) diff --git a/tests/test_galevo_device.py b/tests/test_galevo_device.py index 000c410..8465a4a 100644 --- a/tests/test_galevo_device.py +++ b/tests/test_galevo_device.py @@ -437,7 +437,7 @@ async def refresh_without_features(): asyncio.run(refresh_without_features()) async_no_features.api.async_get_features_for_device.assert_awaited_once_with("gw-1") - def test_menu_http_500_and_550_preserve_previous_items_and_refresh_state(self): + def test_menu_http_500_and_550_refresh_properties_with_stale_menu(self): for status in (500, 550): with self.subTest(status=status): device = self.make_device() @@ -449,17 +449,17 @@ def test_menu_http_500_and_550_preserve_previous_items_and_refresh_state(self): side_effect=ConnectionException(status) ) - async def refresh(): - await device.async_update_state() + device.menu_items_fresh = True + asyncio.run(device.async_update_state()) - with self.assertLogs("ariston.galevo_device", level="WARNING"): - asyncio.run(refresh()) - - self.assertEqual(device.data, fresh_data) + self.assertIs(device.data, fresh_data) + self.assertFalse(device.menu_items_fresh) self.assertEqual(device.menu_items, previous_menu_items) self.assertEqual(device.signal_strength_value, 4) def _assert_async_refresh_data(self, device, api, requested_items, transport_patch): + device.data = {} + async def refresh(): with ( patch.object(api, "get_items", return_value=requested_items), @@ -487,7 +487,7 @@ async def post(path, body, **kwargs): raise failure return { "items": [ - {"id": item["id"], "zn": item["zn"], "value": 1} + {"id": item["id"], PropertyType.ZONE: item["zn"], "value": 1} for item in body["items"] ] } @@ -512,7 +512,7 @@ class SlowResponse: async def json(self): return { "items": [ - {"id": item["id"], "zn": item["zn"], "value": 1} + {"id": item["id"], PropertyType.ZONE: item["zn"], "value": 1} for item in requested_items ] } @@ -547,15 +547,18 @@ def test_menu_http_failure_on_first_refresh_and_recovery(self): side_effect=[ConnectionException(500), [{"id": 1, PropertyType.VALUE: 3}]] ) + device.data = {} + async def refresh_twice(): await device.async_update_state() self.assertEqual(device.menu_items, []) self.assertEqual(device.data, self.make_data()) + self.assertFalse(device.menu_items_fresh) await device.async_update_state() - with self.assertLogs("ariston.galevo_device", level="WARNING"): - asyncio.run(refresh_twice()) + asyncio.run(refresh_twice()) + self.assertTrue(device.menu_items_fresh) self.assertEqual(device.menu_items, [{"id": 1, PropertyType.VALUE: 3}]) def test_primary_properties_and_non_transient_menu_errors_still_raise(self): @@ -582,6 +585,48 @@ async def refresh_menu_auth_failure(): with self.assertRaises(ConnectionException): asyncio.run(refresh_menu_auth_failure()) + def test_partial_batch_retains_values_and_features_until_success(self): + device = self.make_device() + device._update_state() + previous_data = device.data + previous_features = device.custom_features.copy() + fresh = self.make_data() + device.api.async_get_properties = AsyncMock( + side_effect=[{"items": fresh["items"][:1]}, fresh] + ) + device.api.async_get_menu_items = AsyncMock(return_value=device.menu_items) + + async def refresh(): + with self.assertRaisesRegex(ConnectionException, "incomplete"): + await device.async_update_state() + self.assertIs(device.data, previous_data) + self.assertEqual(device.custom_features, previous_features) + await device.async_update_state() + self.assertIs(device.data, fresh) + + asyncio.run(refresh()) + + def test_refresh_accepts_snapshot_after_zone_is_removed(self): + device = self.make_device() + fresh_data = self.make_data() + device.features[DeviceFeatures.ZONES].append({ZoneAttribute.NUM: 2}) + device.data["items"].append( + {"id": ThermostatProperties.ZONE_MEASURED_TEMP, PropertyType.ZONE: 2} + ) + device.api.async_get_features_for_device = AsyncMock( + return_value={DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + ) + device.api.async_get_properties = AsyncMock(return_value=fresh_data) + device.api.async_get_menu_items = AsyncMock(return_value=device.menu_items) + + async def refresh(): + await device.async_get_features() + await device.async_update_state() + + asyncio.run(refresh()) + self.assertEqual(device.zone_numbers, [1]) + self.assertIs(device.data, fresh_data) + def test_sync_menu_http_failure_preserves_previous_items(self): device = self.make_device() previous_menu_items = list(device.menu_items) @@ -590,10 +635,11 @@ def test_sync_menu_http_failure_preserves_previous_items(self): device.api.get_properties.return_value = fresh_data device.api.get_menu_items.side_effect = ConnectionException(500) - with self.assertLogs("ariston.galevo_device", level="WARNING"): - device.update_state() + device.menu_items_fresh = True + device.update_state() - self.assertEqual(device.data, fresh_data) + self.assertIs(device.data, fresh_data) + self.assertFalse(device.menu_items_fresh) self.assertEqual(device.menu_items, previous_menu_items) def test_sync_non_transient_menu_errors_still_raise(self): @@ -755,6 +801,7 @@ def test_heat_pump_menu_items_availability_getters_and_error_handling(self): for item in data_without_ch_flow["items"] if item["id"] != DeviceProperties.CH_FLOW_TEMP ] + device.data = {} device.api.get_properties.return_value = data_without_ch_flow device.api.get_menu_items.return_value = hp_items diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 951952e..ddae2b1 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -1,226 +1,176 @@ -"""Unit tests for the 429 rate-limit handling in ariston.ariston_api.""" +"""Tests for shared HTTP 429 cooldowns without real network calls or sleeps.""" import asyncio -import time +from datetime import datetime, timezone +from email.utils import format_datetime +from types import SimpleNamespace import unittest -from typing import Any, Optional -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, Mock, patch -from ariston.ariston_api import ( - AristonAPI, - ConnectionException, - _parse_block_seconds, -) +from ariston.ariston_api import AristonAPI, ConnectionException, _retry_after_seconds -def _api() -> AristonAPI: - return AristonAPI("user", "pass") +PATH = "https://example.test/api" -def _sync_response(status: int, content: bytes = b"", json_data: Any = None): - response = MagicMock() - response.ok = status < 400 - response.status_code = status - response.content = content - if json_data is not None: - response.json.return_value = json_data - return response +def response(status, body=b"", retry_after=""): + return SimpleNamespace( + status=status, + status_code=status, + ok=status < 400, + content=body, + headers={"Retry-After": retry_after}, + json=lambda: {"ok": True}, + ) -class _FakeAiohttpContent: - def __init__(self, payload: bytes) -> None: - self._payload = payload - - async def read(self) -> bytes: - return self._payload - - -class _FakeAiohttpResponse: - def __init__( - self, status: int, payload: bytes = b"", json_data: Any = None - ) -> None: - self.status = status - self.ok = status < 400 - self.content = _FakeAiohttpContent(payload) - self.content_length = len(payload) - self._json_data = json_data - - async def json(self) -> Any: - return self._json_data - - -def _fake_session_cls(responses: list, calls: list): - class _Session: - def __init__(self, *args: Any, **kwargs: Any) -> None: - pass - - async def __aenter__(self) -> "_Session": - return self - - async def __aexit__(self, *exc: Any) -> bool: - return False - - async def request(self, *args: Any, **kwargs: Any): - calls.append(1) - return responses.pop(0) - - return _Session +def async_response(status, content=b"", retry_after=""): + result = response(status, content, retry_after) + result.content = SimpleNamespace(read=AsyncMock(return_value=content)) + result.content_length = len(content) + result.json = AsyncMock(return_value={"ok": True}) + return result class RateLimitTests(unittest.TestCase): - """429 handling: parse, sleep-out with a single retry, per-instance window.""" - - # -- parse helper -- - - def test_parse_block_seconds(self): - self.assertEqual( - _parse_block_seconds(b"Requests are blocked for 66 seconds"), 66 + def setUp(self): + self.now = 100 + self.clock = SimpleNamespace(monotonic=lambda: self.now, sleep=Mock()) + self.enterContext(patch("ariston.ariston_api.time", self.clock)) + self.enterContext(patch("ariston.ariston_api._RATE_LIMITS", {})) + self.api = AristonAPI("user", "pass", PATH) + + def assert_rate_limited(self, call): + with self.assertRaises(ConnectionException) as error: + call() + self.assertEqual(error.exception.args[0], 429) + + def test_honors_longer_hint_and_shares_deadline_only_with_same_account_origin(self): + http = self.enterContext(patch( + "ariston.ariston_api.requests.request", + side_effect=[ + response(429, b"Blocked for 66 seconds", "20"), + response(200, b"{}"), + response(200, b"{}"), + response(200, b"{}"), + ], + )) + self.assert_rate_limited(lambda: self.api._get(PATH)) + http.assert_called_once() + self.clock.sleep.assert_not_called() + + same_account = AristonAPI("USER", "pass", f"{PATH}/v2") + self.now = 166 + self.assert_rate_limited(lambda: same_account._get(PATH)) + self.assertEqual(AristonAPI("other", "pass", PATH)._get(PATH), {"ok": True}) + other_origin = AristonAPI("user", "pass", "https://other.test/api") + self.assertEqual(other_origin._get("https://other.test/api"), {"ok": True}) + + self.now = 167 + self.assertEqual(same_account._get(PATH), {"ok": True}) + self.assertEqual(http.call_count, 4) + + def test_fallback_doubles_until_capped_and_success_resets_it(self): + limited = response(429, b"Too many requests", "invalid") + http = self.enterContext(patch( + "ariston.ariston_api.requests.request", + side_effect=[limited] * 6 + [response(200, b"{}"), limited], + )) + for delay in (60, 120, 240, 480, 900, 900): + self.assert_rate_limited(lambda: self.api._get(PATH)) + self.now += delay - 1 + self.assert_rate_limited(lambda: self.api._get(PATH)) + self.now += 1 + + self.assertEqual(self.api._get(PATH), {"ok": True}) + self.assert_rate_limited(lambda: self.api._get(PATH)) + self.assertEqual(self.api._rate_limit.deadline, self.now + 60) + self.assertEqual(http.call_count, 8) + + def test_retry_after_http_date(self): + now = datetime(2026, 11, 19, 10, tzinfo=timezone.utc) + date = datetime(2026, 11, 19, 10, 2, tzinfo=timezone.utc) + with patch("ariston.ariston_api.datetime", wraps=datetime) as clock: + clock.now.return_value = now + self.assertEqual(_retry_after_seconds(format_datetime(date, usegmt=True)), 120) + + def test_server_error_retry_rechecks_cooldown(self): + peer = AristonAPI("user", "pass", PATH) + http = self.enterContext(patch( + "ariston.ariston_api.requests.request", + side_effect=[response(500), response(429, retry_after="80")], + )) + self.clock.sleep.side_effect = lambda _: self.assert_rate_limited( + lambda: peer._get(PATH) ) - self.assertEqual(_parse_block_seconds(b"Requests are blocked for 5 seconds"), 5) - self.assertIsNone(_parse_block_seconds(b"Too many requests")) - - # -- sync path (requests) -- - - def test_429_parses_wait_seconds(self): - responses = [ - _sync_response(429, b"Requests are blocked for 66 seconds"), - _sync_response(200, b"{}", {"ok": True}), - ] - http = MagicMock(side_effect=responses) - sleeps: list[int] = [] - api = _api() - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep", side_effect=sleeps.append - ): - result = api._get("https://example/api") - - self.assertEqual(result, {"ok": True}) - self.assertEqual(http.call_count, 2) # exactly one retry - self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin - self.assertGreater(api._blocked_until, 0) # block window was set - - def test_429_without_parsable_body(self): - responses = [ - _sync_response(429, b"Too many requests"), - _sync_response(200, b"{}", {"ok": True}), - ] - http = MagicMock(side_effect=responses) - sleeps: list[int] = [] - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep", side_effect=sleeps.append - ): - result = _api()._get("https://example/api") - - self.assertEqual(result, {"ok": True}) - self.assertEqual(sleeps, [5]) # documented fallback + self.assert_rate_limited(lambda: self.api._get(PATH)) self.assertEqual(http.call_count, 2) - - def test_429_twice_raises(self): - body = b"Requests are blocked for 10 seconds" - http = MagicMock( - side_effect=[_sync_response(429, body), _sync_response(429, body)] - ) - api = _api() - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep" - ): - with self.assertRaises(ConnectionException): - api._get("https://example/api") - - self.assertEqual(http.call_count, 2) # one retry, then raise - - def test_blocked_until_short_circuits(self): - api = _api() - api._blocked_until = time.time() + 30 - http = MagicMock() - with patch("ariston.ariston_api.requests.request", http): - with self.assertRaises(ConnectionException): - api._get("https://example/api") - - http.assert_not_called() # no network call inside the block window - - def test_block_window_is_per_instance(self): - """A 429 on one instance must not silence other instances.""" - blocked = _api() - other = _api() - http = MagicMock( - side_effect=[ - _sync_response(429, b"Requests are blocked for 30 seconds"), - _sync_response(200, b"{}", {"ok": True}), + self.assertEqual(self.api._rate_limit.deadline, 180) + + def test_async_429_on_server_error_retry_sets_shared_cooldown(self): + async def exercise(): + session = AsyncMock() + session.__aenter__.return_value = session + session.request.side_effect = [ + async_response(500), + async_response(429, retry_after="70"), + async_response(200, b"{}"), ] - ) - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep" - ): - self.assertEqual(blocked._get("https://example/api"), {"ok": True}) - - self.assertGreater(blocked._blocked_until, 0) - self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 - - # -- async path (aiohttp) -- - - def test_async_429_parses_and_retries(self): - responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked for 66 seconds"), - _FakeAiohttpResponse(200, b"{}", {"ok": True}), - ] - calls: list[int] = [] - sleeps: list[Optional[int]] = [] - - async def run() -> Any: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls(responses, calls), - ), patch( - "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append - ): - return await _api()._async_get("https://example/api") - - result = asyncio.run(run()) - - self.assertEqual(result, {"ok": True}) - self.assertEqual(len(calls), 2) # exactly one retry - self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin - - def test_async_blocked_until_short_circuits(self): - calls: list[int] = [] - api = _api() - api._blocked_until = time.time() + 30 - - async def run() -> None: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls([], calls), + with ( + patch("ariston.ariston_api.aiohttp.ClientSession", return_value=session), + patch("ariston.ariston_api.asyncio.sleep", new=AsyncMock()) as sleep, ): with self.assertRaises(ConnectionException): - await api._async_get("https://example/api") - - asyncio.run(run()) - - self.assertEqual(calls, []) # no network call inside the block window - - def test_async_block_window_is_per_instance(self): - """Async twin: a 429 on one instance must not silence other instances.""" - blocked = _api() - other = _api() - responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked for 30 seconds"), - _FakeAiohttpResponse(200, b"{}", {"ok": True}), - ] - calls: list[int] = [] - - async def run() -> Any: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls(responses, calls), - ), patch("ariston.ariston_api.asyncio.sleep"): - return await blocked._async_get("https://example/api") - - self.assertEqual(asyncio.run(run()), {"ok": True}) - - self.assertGreater(blocked._blocked_until, 0) - self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 - - -if __name__ == "__main__": - unittest.main() + await self.api._async_get(PATH) + with self.assertRaises(ConnectionException): + await self.api._async_get(PATH) + self.assertEqual(session.request.await_count, 2) + sleep.assert_awaited_once_with(5) + self.now += 70 + self.assertEqual(await self.api._async_get(PATH), {"ok": True}) + + asyncio.run(exercise()) + + def test_concurrent_429_responses_do_not_shorten_deadline_or_repeat_warning(self): + async def exercise(): + entered = asyncio.Event() + release = asyncio.Event() + slow = async_response(429, retry_after="10") + + async def read_body(): + entered.set() + await release.wait() + return b"" + + slow.content.read.side_effect = read_body + session = AsyncMock() + session.__aenter__.return_value = session + + async def first_request(*args, **kwargs): + # Both HTTP requests have started before either publishes a block. + await entered.wait() + return async_response(429, retry_after="90") + + async def concurrent_response(*args, **kwargs): + if session.request.await_count == 1: + return await first_request() + return slow + + session.request.side_effect = concurrent_response + with ( + patch("ariston.ariston_api.aiohttp.ClientSession", return_value=session), + self.assertLogs("ariston.ariston_api", level="WARNING") as logs, + ): + first = asyncio.create_task(self.api._async_get(PATH)) + second = asyncio.create_task(self.api._async_get(PATH)) + await entered.wait() + self.assert_rate_limited(lambda: self.api._get(PATH)) + release.set() + errors = await asyncio.gather(first, second, return_exceptions=True) + + self.assertEqual([error.args[0] for error in errors], [429, 429]) + self.assertEqual(self.api._rate_limit.deadline, 190) + self.assertEqual(len(logs.output), 1) + self.assertEqual(session.request.await_count, 2) + + asyncio.run(exercise())