diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 8e15817..d383445 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import math import re import time from typing import Any, Optional @@ -47,6 +48,11 @@ _LOGGER = logging.getLogger(__name__) _RATE_LIMIT_RE = re.compile(rb"blocked for (\d+) seconds", re.IGNORECASE) +_RATE_LIMIT_WAIT_LOG = "Rate limited (429) for %s seconds; waiting it out" +_UNPARSABLE_INITIAL_WAIT_SECONDS = 5 +_UNPARSABLE_COOLDOWN_BASE_SECONDS = 60 +_UNPARSABLE_COOLDOWN_MAX_SECONDS = 600 +_INCOMPLETE_MENU_CACHE_TTL_SECONDS = 3600 def _parse_block_seconds(content: bytes) -> Optional[int]: @@ -57,19 +63,87 @@ def _parse_block_seconds(content: bytes) -> Optional[int]: return int(match.group(1)) +def _parse_retry_after_seconds(headers: Any) -> Optional[int]: + """Extract an integer Retry-After delay in seconds from response headers.""" + if not headers or not hasattr(headers, "get"): + return None + raw = headers.get("Retry-After") + if not isinstance(raw, str): + return None + raw = raw.strip() + if raw.isdigit(): + return max(1, int(raw)) + 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" + "falling back to %ss wait", + _UNPARSABLE_INITIAL_WAIT_SECONDS, ) - return 5 - _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) + return _UNPARSABLE_INITIAL_WAIT_SECONDS + _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, parsed + 1) return parsed + 1 +def _raise_unless_http_500(error: ConnectionException) -> None: + """Re-raise ConnectionException unless its status code is HTTP 500.""" + if error.args[:1] != (500,): + raise error + + +def _record_menu_item_response( + additional_items: list[dict[str, Any]], + group_ids: list[int], + group_queries: list[str], + menu_item: MenuItemNames, + item_response: list[dict[str, Any]] | None, +) -> None: + """Collect a single split menu-item payload into the current group results.""" + if item_response: + additional_items.extend(item_response) + group_ids.extend(_collect_menu_item_ids(item_response, (menu_item,))) + group_queries.append(str(menu_item.value)) + + +def _record_menu_group_result( + items: list[dict[str, Any]], + discovered_ids: list[int], + working_queries: list[str], + additional_items: list[dict[str, Any]], + group_ids: list[int], + group_queries: list[str], +) -> None: + """Append discovered menu-group items and queries when non-empty.""" + if additional_items: + items.extend(additional_items) + discovered_ids.extend(group_ids) + working_queries.extend(group_queries) + + +def _collect_menu_item_ids( + items: list[Any], fallback_group: tuple[MenuItemNames, ...] | None = None +) -> list[int]: + """Extract integer item IDs from a menu-items payload.""" + found = [ + item["id"] + for item in items + if isinstance(item, dict) and isinstance(item.get("id"), int) + ] + if found or not items or fallback_group is None: + return found + return [menu_item.value for menu_item in fallback_group] + + +def _menu_items_path(api_url: str, gw_id: str, menu_items_query: str) -> str: + """Build the menuItems endpoint URL for a gateway and comma-joined IDs.""" + return f"{api_url}{ARISTON_MENU_ITEMS}/{gw_id}?menuItems={menu_items_query}" + + class ConnectionException(Exception): """When can not connect to Ariston cloud""" @@ -98,9 +172,70 @@ def __init__( # API URLs must not silence each other; the three coordinators for # one account still share one API instance. self._blocked_until = 0.0 + self._rate_limit_streak = 0 + self._rate_limit_retry_epoch = 0 + self._rate_limit_retry_in_flight = False + # Cached menu item query strings per gateway once hybrid discovery succeeds. + self._hybrid_menu_items: dict[str, tuple[str, ...]] = {} + self._hybrid_menu_grouped_mode: set[str] = set() + self._hybrid_menu_items_expires_at: dict[str, float] = {} # Sync (requests) R2 web-app session; created lazily on first use. self.__r2_requests_session: Optional[requests.Session] = None + def _bump_rate_limit_cooldown(self) -> None: + """Advance unparsable-429 streak and extend the shared block window.""" + self._rate_limit_streak += 1 + cooldown = min( + _UNPARSABLE_COOLDOWN_MAX_SECONDS, + _UNPARSABLE_COOLDOWN_BASE_SECONDS + * (2 ** min(self._rate_limit_streak - 1, 4)), + ) + _LOGGER.warning( + "Rate limited (429) without parsable block duration (streak %s); " + "cooling down for %s seconds", + self._rate_limit_streak, + cooldown, + ) + self._blocked_until = max(self._blocked_until, time.time() + cooldown) + + def _prepare_rate_limit_retry( + self, content: bytes, headers: Any, is_retry: bool + ) -> Optional[tuple[int, int]]: + """Update rate-limit state and return the wait and epoch for a retry.""" + now = time.time() + parsed = _parse_block_seconds(content) + if parsed is None: + parsed = _parse_retry_after_seconds(headers) + + if parsed is not None: + wait_seconds = parsed + 1 + _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, wait_seconds) + elif self._rate_limit_retry_in_flight and not is_retry: + return None + elif is_retry or self._rate_limit_streak: + self._bump_rate_limit_cooldown() + return None + else: + wait_seconds = _rate_limit_wait_seconds(content) + + self._blocked_until = max(self._blocked_until, now + wait_seconds) + if is_retry or self._rate_limit_retry_in_flight: + return None + + return (math.ceil(self._blocked_until - now), self._rate_limit_retry_epoch) + + def _claim_rate_limit_retry(self, epoch: int) -> bool: + """Claim the single post-sleep retry once the shared deadline has elapsed.""" + if ( + self._rate_limit_retry_in_flight + or self._rate_limit_retry_epoch != epoch + or time.time() < self._blocked_until + ): + return False + self._rate_limit_retry_epoch += 1 + self._rate_limit_retry_in_flight = True + return True + def _r2_cookies(self) -> aiohttp.CookieJar: """Lazily create the R2 cookie jar (requires a running loop).""" if self.__r2_cookies is None: @@ -249,48 +384,129 @@ def get_velis_plant_settings( return settings return {} + @staticmethod + def _build_hybrid_menu_query( + core_items: list[Any], discovered_ids: list[int] + ) -> str: + """Build a deduplicated comma-separated query preserving core menu items.""" + core_ids = [ + int(item_id) for item_id in MenuItemNames.core_values().split(",") + ] + ordered = list( + dict.fromkeys( + [*core_ids, *_collect_menu_item_ids(core_items), *discovered_ids] + ) + ) + return ",".join(str(item_id) for item_id in ordered) + + def _get_cached_menu_queries( + self, gw_id: str, include_hybrid_items: bool + ) -> Optional[tuple[str, ...]]: + """Return unexpired cached menu-item queries for a gateway, if any.""" + if not include_hybrid_items: + return None + expires_at = self._hybrid_menu_items_expires_at.get(gw_id) + if expires_at is not None and time.time() >= expires_at: + self._hybrid_menu_items.pop(gw_id, None) + self._hybrid_menu_items_expires_at.pop(gw_id, None) + return None + return self._hybrid_menu_items.get(gw_id) + + def _handle_cached_menu_error( + self, gw_id: str, error: ConnectionException + ) -> None: + """Invalidate cached menu queries on 500/550 and lock grouped mode if needed.""" + status = error.args[0] if error.args else None + if status not in (500, 550): + raise error + cached = self._hybrid_menu_items.pop(gw_id, None) + self._hybrid_menu_items_expires_at.pop(gw_id, None) + if cached is not None and len(cached) == 1: + self._hybrid_menu_grouped_mode.add(gw_id) + + def _store_discovered_menu_items( + self, + gw_id: str, + core_items: list[Any], + discovered_ids: list[int], + working_queries: list[str], + incomplete: bool, + ) -> None: + """Persist menu queries and set TTL when any item had a transient 500.""" + if gw_id in self._hybrid_menu_grouped_mode: + self._hybrid_menu_items[gw_id] = tuple(dict.fromkeys(working_queries)) + else: + self._hybrid_menu_items[gw_id] = ( + self._build_hybrid_menu_query(core_items, discovered_ids), + ) + if incomplete: + self._hybrid_menu_items_expires_at[gw_id] = ( + time.time() + _INCOMPLETE_MENU_CACHE_TTL_SECONDS + ) + else: + self._hybrid_menu_items_expires_at.pop(gw_id, None) + def get_menu_items( self, gw_id: str, include_hybrid_items: bool = False ) -> list[dict[str, Any]]: """Get core menu items and, when requested, optional hybrid values.""" - items = self._get( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={MenuItemNames.core_values()}" - ) + cached_queries = self._get_cached_menu_queries(gw_id, include_hybrid_items) + if cached_queries is not None: + try: + cached_items: list[dict[str, Any]] = [] + for query in cached_queries: + part = self._get(_menu_items_path(self.__api_url, gw_id, query)) + if part: + cached_items.extend(part) + except ConnectionException as error: + self._handle_cached_menu_error(gw_id, error) + else: + return cached_items + + core_query = MenuItemNames.core_values() + items = self._get(_menu_items_path(self.__api_url, gw_id, core_query)) if items is None or not include_hybrid_items: return items or [] + core_snapshot = list(items) + discovered_ids: list[int] = [] + working_queries: list[str] = [core_query] + incomplete = False for group in MenuItemNames.hybrid_groups(): - group_ids = ",".join(str(item.value) for item in group) - path = ( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={group_ids}" - ) + group_query = ",".join(str(item.value) for item in group) try: - additional_items = self._get(path) + additional_items = self._get( + _menu_items_path(self.__api_url, gw_id, group_query) + ) + group_ids = _collect_menu_item_ids(additional_items or [], group) + group_queries = [group_query] if additional_items else [] except ConnectionException as error: - if error.args[:1] != (500,): - raise - additional_items = [] + _raise_unless_http_500(error) + additional_items, group_ids, group_queries = [], [], [] for menu_item in group: - item_path = ( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={menu_item.value}" + item_path = _menu_items_path( + self.__api_url, gw_id, str(menu_item.value) ) try: item_response = self._get(item_path) except ConnectionException as item_error: - if item_error.args[:1] != (500,): - raise + _raise_unless_http_500(item_error) + incomplete = True _LOGGER.debug( "Skipping unsupported GALEVO menu item %s", menu_item.value, ) continue - if item_response: - additional_items.extend(item_response) - if additional_items: - items.extend(additional_items) + _record_menu_item_response( + additional_items, group_ids, group_queries, menu_item, item_response + ) + _record_menu_group_result( + items, discovered_ids, working_queries, additional_items, group_ids, group_queries + ) + + self._store_discovered_menu_items( + gw_id, core_snapshot, discovered_ids, working_queries, incomplete + ) return items def set_property( @@ -607,6 +823,7 @@ def __request( return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) + self._rate_limit_streak = 0 if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -629,11 +846,16 @@ def __handle_rate_limit( ) -> 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: + headers = getattr(response, "headers", None) + retry_plan = self._prepare_rate_limit_retry(content, headers, is_retry) + if retry_plan is not None: + wait_seconds, epoch = retry_plan time.sleep(wait_seconds) - return self.__request(method, path, params, body, True) + if self._claim_rate_limit_retry(epoch): + try: + return self.__request(method, path, params, body, True) + finally: + self._rate_limit_retry_in_flight = False raise ConnectionException(response.status_code, content.decode()) def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: @@ -1021,44 +1243,65 @@ async def async_get_menu_items( self, gw_id: str, include_hybrid_items: bool = False ) -> list[dict[str, Any]]: """Async get core menu items and optional hybrid values.""" - items = await self._async_get( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={MenuItemNames.core_values()}" - ) + cached_queries = self._get_cached_menu_queries(gw_id, include_hybrid_items) + if cached_queries is not None: + try: + cached_items: list[dict[str, Any]] = [] + for query in cached_queries: + part = await self._async_get( + _menu_items_path(self.__api_url, gw_id, query) + ) + if part: + cached_items.extend(part) + except ConnectionException as error: + self._handle_cached_menu_error(gw_id, error) + else: + return cached_items + + core_query = MenuItemNames.core_values() + items = await self._async_get(_menu_items_path(self.__api_url, gw_id, core_query)) if items is None or not include_hybrid_items: return items or [] + core_snapshot = list(items) + discovered_ids: list[int] = [] + working_queries: list[str] = [core_query] + incomplete = False for group in MenuItemNames.hybrid_groups(): - group_ids = ",".join(str(item.value) for item in group) - path = ( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={group_ids}" - ) + group_query = ",".join(str(item.value) for item in group) try: - additional_items = await self._async_get(path) + additional_items = await self._async_get( + _menu_items_path(self.__api_url, gw_id, group_query) + ) + group_ids = _collect_menu_item_ids(additional_items or [], group) + group_queries = [group_query] if additional_items else [] except ConnectionException as error: - if error.args[:1] != (500,): - raise - additional_items = [] + _raise_unless_http_500(error) + additional_items, group_ids, group_queries = [], [], [] for menu_item in group: - item_path = ( - f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}" - f"?menuItems={menu_item.value}" + item_path = _menu_items_path( + self.__api_url, gw_id, str(menu_item.value) ) try: item_response = await self._async_get(item_path) except ConnectionException as item_error: - if item_error.args[:1] != (500,): - raise + _raise_unless_http_500(item_error) + incomplete = True _LOGGER.debug( "Skipping unsupported GALEVO menu item %s", menu_item.value, ) continue - if item_response: - additional_items.extend(item_response) - if additional_items: - items.extend(additional_items) + _record_menu_item_response( + additional_items, group_ids, group_queries, menu_item, item_response + ) + _record_menu_group_result( + items, discovered_ids, working_queries, additional_items, group_ids, group_queries + ) + + self._store_discovered_menu_items( + gw_id, core_snapshot, discovered_ids, working_queries, incomplete + ) return items async def async_set_property( @@ -1558,6 +1801,7 @@ async def __async_request( ) raise ConnectionException(response.status) + self._rate_limit_streak = 0 if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1585,13 +1829,18 @@ async def __async_handle_rate_limit( ) -> 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: + headers = getattr(response, "headers", None) + retry_plan = self._prepare_rate_limit_retry(content, headers, is_retry) + if retry_plan is not None: + wait_seconds, epoch = retry_plan await asyncio.sleep(wait_seconds) - return await self.__async_request( - method, path, params, body, True, timeout_seconds - ) + if self._claim_rate_limit_retry(epoch): + try: + return await self.__async_request( + method, path, params, body, True, timeout_seconds + ) + finally: + self._rate_limit_retry_in_flight = False raise ConnectionException(response.status, content) async def _async_get( diff --git a/tests/test_ariston_api.py b/tests/test_ariston_api.py index 1df0e8a..9c45d5d 100644 --- a/tests/test_ariston_api.py +++ b/tests/test_ariston_api.py @@ -459,6 +459,155 @@ async def exercise(): ], ) + def test_menu_items_cache_supported_ids_and_recover_on_500_or_550(self): + expected = [124, 119, 349, 348, 337, 340, 341] + expected_requests = [ + "124,119", + "123,125,115", + "349,348", + "337,340,341", + "127", + "124,119,349,348,337,340,341", + "124,119,349,348,337,340,341", + "124,119", + "123,125,115", + "349,348", + "337,340,341", + "127", + "124,119", + "349,348", + "337,340,341", + "124,119", + "349,348", + "124,119", + "123,125,115", + "349,348", + "337,340,341", + "127", + "124,119", + "349,348", + "337,340,341", + ] + + def run_case(is_async, failure_status): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + requests = [] + fail_combined = False + fail_group_once = False + + def handle(path): + nonlocal fail_group_once + requested = path.split("menuItems=", 1)[1] + requests.append(requested) + if requested in ("123,125,115", "127"): + return [] + if fail_combined and requested == "124,119,349,348,337,340,341": + raise ConnectionException(failure_status) + if fail_group_once and requested == "349,348": + fail_group_once = False + raise ConnectionException(failure_status) + return [{"id": int(item_id)} for item_id in requested.split(",")] + + if not is_async: + with patch.object(api, "_get", side_effect=handle): + results = [api.get_menu_items("gw-1", include_hybrid_items=True)] + results.append(api.get_menu_items("gw-1", include_hybrid_items=True)) + fail_combined = True + results.append(api.get_menu_items("gw-1", include_hybrid_items=True)) + results.append(api.get_menu_items("gw-1", include_hybrid_items=True)) + fail_group_once = True + results.append(api.get_menu_items("gw-1", include_hybrid_items=True)) + results.append(api.get_menu_items("gw-1", include_hybrid_items=True)) + else: + async def async_handle(path): + return handle(path) + + async def exercise(): + nonlocal fail_combined, fail_group_once + with patch.object(api, "_async_get", new=AsyncMock(side_effect=async_handle)): + out = [await api.async_get_menu_items("gw-1", include_hybrid_items=True)] + out.append(await api.async_get_menu_items("gw-1", include_hybrid_items=True)) + fail_combined = True + out.append(await api.async_get_menu_items("gw-1", include_hybrid_items=True)) + out.append(await api.async_get_menu_items("gw-1", include_hybrid_items=True)) + fail_group_once = True + out.append(await api.async_get_menu_items("gw-1", include_hybrid_items=True)) + out.append(await api.async_get_menu_items("gw-1", include_hybrid_items=True)) + return out + + results = asyncio.run(exercise()) + + for result in results: + self.assertEqual([item["id"] for item in result], expected) + self.assertEqual(requests, expected_requests) + self.assertIn("gw-1", api._hybrid_menu_grouped_mode) + + for is_async in (False, True): + for failure_status in (500, 550): + with self.subTest(is_async=is_async, failure_status=failure_status): + run_case(is_async, failure_status) + + def test_incomplete_menu_discovery_expires_and_recovers_skipped_id(self): + for is_async in (False, True): + with self.subTest(is_async=is_async): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + fail_125 = True + + def handle(path): + requested = path.split("menuItems=", 1)[1] + if requested == "123,125,115": + raise ConnectionException(500) + if fail_125 and requested == "125": + raise ConnectionException(500) + return [{"id": int(item_id)} for item_id in requested.split(",")] + + if not is_async: + with patch.object(api, "_get", side_effect=handle): + first = api.get_menu_items("gw-1", include_hybrid_items=True) + cached = api.get_menu_items("gw-1", include_hybrid_items=True) + self.assertIn("gw-1", api._hybrid_menu_items_expires_at) + fail_125 = False + api._hybrid_menu_items_expires_at["gw-1"] = 0.0 + refreshed = api.get_menu_items("gw-1", include_hybrid_items=True) + else: + async def async_handle(path): + return handle(path) + + async def exercise(): + nonlocal fail_125 + with patch.object(api, "_async_get", new=AsyncMock(side_effect=async_handle)): + r1 = await api.async_get_menu_items("gw-1", include_hybrid_items=True) + r2 = await api.async_get_menu_items("gw-1", include_hybrid_items=True) + self.assertIn("gw-1", api._hybrid_menu_items_expires_at) + fail_125 = False + api._hybrid_menu_items_expires_at["gw-1"] = 0.0 + r3 = await api.async_get_menu_items("gw-1", include_hybrid_items=True) + return r1, r2, r3 + + first, cached, refreshed = asyncio.run(exercise()) + + self.assertNotIn(125, [item["id"] for item in first]) + self.assertNotIn(125, [item["id"] for item in cached]) + self.assertIn(125, [item["id"] for item in refreshed]) + self.assertNotIn("gw-1", api._hybrid_menu_items_expires_at) + + def test_async_menu_items_do_not_cache_partial_discovery_on_429(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + + async def get(path): + requested = path.split("menuItems=", 1)[1] + if requested == "349,348": + raise ConnectionException(429, b"Requests are blocked") + return [{"id": int(item_id)} for item_id in requested.split(",")] + + async def exercise(): + with self.assertRaises(ConnectionException): + await api.async_get_menu_items("gw-1", include_hybrid_items=True) + + with patch.object(api, "_async_get", new=AsyncMock(side_effect=get)): + asyncio.run(exercise()) + self.assertNotIn("gw-1", api._hybrid_menu_items) + def test_async_properties_recovers_from_batch_errors_with_small_requests(self): scenarios = ( ( diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 951952e..1354213 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -1,10 +1,9 @@ """Unit tests for the 429 rate-limit handling in ariston.ariston_api.""" import asyncio -import time import unittest -from typing import Any, Optional -from unittest.mock import MagicMock, patch +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch from ariston.ariston_api import ( AristonAPI, @@ -67,9 +66,33 @@ async def request(self, *args: Any, **kwargs: Any): return _Session +class _FakeClock: + def __init__(self) -> None: + self.now = 1000.0 + self.sleeps: list[int] = [] + + def time(self) -> float: + return self.now + + def sleep(self, seconds: int) -> None: + self.sleeps.append(seconds) + self.now += seconds + + class RateLimitTests(unittest.TestCase): """429 handling: parse, sleep-out with a single retry, per-instance window.""" + def setUp(self) -> None: + self.clock = _FakeClock() + self.real_sleep = asyncio.sleep + self.enterContext(patch("ariston.ariston_api.time", self.clock)) + self.enterContext( + patch( + "ariston.ariston_api.asyncio.sleep", + side_effect=lambda seconds: self.clock.sleep(seconds), + ) + ) + # -- parse helper -- def test_parse_block_seconds(self): @@ -87,16 +110,13 @@ def test_429_parses_wait_seconds(self): _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 - ): + with patch("ariston.ariston_api.requests.request", http): 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.assertEqual(self.clock.sleeps, [67]) # parsed 66 + 1s margin self.assertGreater(api._blocked_until, 0) # block window was set def test_429_without_parsable_body(self): @@ -105,14 +125,11 @@ def test_429_without_parsable_body(self): _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 - ): + with patch("ariston.ariston_api.requests.request", http): result = _api()._get("https://example/api") self.assertEqual(result, {"ok": True}) - self.assertEqual(sleeps, [5]) # documented fallback + self.assertEqual(self.clock.sleeps, [5]) # documented fallback self.assertEqual(http.call_count, 2) def test_429_twice_raises(self): @@ -121,9 +138,7 @@ def test_429_twice_raises(self): 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 patch("ariston.ariston_api.requests.request", http): with self.assertRaises(ConnectionException): api._get("https://example/api") @@ -131,7 +146,7 @@ def test_429_twice_raises(self): def test_blocked_until_short_circuits(self): api = _api() - api._blocked_until = time.time() + 30 + api._blocked_until = self.clock.time() + 30 http = MagicMock() with patch("ariston.ariston_api.requests.request", http): with self.assertRaises(ConnectionException): @@ -149,9 +164,7 @@ def test_block_window_is_per_instance(self): _sync_response(200, b"{}", {"ok": True}), ] ) - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep" - ): + with patch("ariston.ariston_api.requests.request", http): self.assertEqual(blocked._get("https://example/api"), {"ok": True}) self.assertGreater(blocked._blocked_until, 0) @@ -165,14 +178,11 @@ def test_async_429_parses_and_retries(self): _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") @@ -180,12 +190,12 @@ async def run() -> Any: self.assertEqual(result, {"ok": True}) self.assertEqual(len(calls), 2) # exactly one retry - self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + self.assertEqual(self.clock.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 + api._blocked_until = self.clock.time() + 30 async def run() -> None: with patch( @@ -213,7 +223,7 @@ 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}) @@ -221,6 +231,279 @@ async def run() -> Any: self.assertGreater(blocked._blocked_until, 0) self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 + def test_429_without_duration_escalates_cooldown_and_resets_on_ok(self): + api = _api() + body = b"Requests are blocked" + http = MagicMock( + side_effect=[ + _sync_response(429, body), + _sync_response(429, body), + _sync_response(429, body), + _sync_response(200, b"{}", {"ok": True}), + ] + ) + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + first_cooldown = api._blocked_until - self.clock.time() + self.assertGreater(first_cooldown, 50) + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(self.clock.sleeps, [5]) + + api._blocked_until = 0.0 + with self.assertRaises(ConnectionException): + api._get("https://example/api") + second_cooldown = api._blocked_until - self.clock.time() + self.assertGreater(second_cooldown, 110) + self.assertEqual(api._rate_limit_streak, 2) + self.assertEqual(self.clock.sleeps, [5]) + + api._blocked_until = 0.0 + self.assertEqual(api._get("https://example/api"), {"ok": True}) + self.assertEqual(api._rate_limit_streak, 0) + + def test_async_429_without_duration_sets_cooldown_and_retry_after_header(self): + api = _api() + resp_with_header = _FakeAiohttpResponse(429, b"Requests are blocked") + resp_with_header.headers = {"Retry-After": "12"} + responses = [ + resp_with_header, + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ] + calls: list[int] = [] + + async def run(): + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ): + ok = await api._async_get("https://example/api") + api._blocked_until = 0.0 + with self.assertRaises(ConnectionException): + await api._async_get("https://example/api") + return ok + + self.assertEqual(asyncio.run(run()), {"ok": True}) + self.assertEqual(self.clock.sleeps, [13, 5]) + self.assertEqual(api._rate_limit_streak, 1) + self.assertGreater(api._blocked_until - self.clock.time(), 50) + + def test_async_overlapping_429_sends_single_retry(self): + api = _api() + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ] + calls: list[int] = [] + + async def run(): + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + self._overlapping_session_cls(responses, calls, self.real_sleep), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=self._overlapping_sleep + ): + return await asyncio.gather( + api._async_get("https://example/api/a"), + api._async_get("https://example/api/b"), + return_exceptions=True, + ) + + results = asyncio.run(run()) + self.assertEqual(len(calls), 3) # 2 initial calls + 1 single claimed retry + self.assertEqual(self.clock.sleeps, [5, 5]) + self.assertEqual(api._rate_limit_streak, 1) + self.assertTrue(all(isinstance(res, ConnectionException) for res in results)) + + async def _overlapping_sleep(self, seconds: int) -> None: + self.clock.sleeps.append(seconds) + wake_at = self.clock.now + seconds + await self.real_sleep(0) + self.clock.now = max(self.clock.now, wake_at) + + @staticmethod + def _overlapping_session_cls(responses: list, calls: list, real_sleep: Any): + 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) + await real_sleep(0) + return responses.pop(0) + + return _Session + + def test_retry_after_still_retries_when_streak_is_nonzero(self): + for is_async in (False, True): + with self.subTest(is_async=is_async): + api = _api() + api._rate_limit_streak = 1 + self.clock.sleeps.clear() + if not is_async: + r1 = _sync_response(429, b"Requests are blocked") + r1.headers = {"Retry-After": "8"} + http = MagicMock( + side_effect=[r1, _sync_response(200, b"{}", {"ok": True})] + ) + with patch("ariston.ariston_api.requests.request", http): + result = api._get("https://example/api") + self.assertEqual(http.call_count, 2) + else: + r1 = _FakeAiohttpResponse(429, b"Requests are blocked") + r1.headers = {"Retry-After": "8"} + responses = [r1, _FakeAiohttpResponse(200, b"{}", {"ok": True})] + calls: list[int] = [] + + async def run_async(): + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ): + return await api._async_get("https://example/api") + + result = asyncio.run(run_async()) + self.assertEqual(len(calls), 2) + + self.assertEqual(result, {"ok": True}) + self.assertEqual(self.clock.sleeps, [9]) + self.assertEqual(api._rate_limit_streak, 0) + + def test_async_overlapping_429_respects_longest_shared_deadline(self): + for order in ("long_first", "short_first"): + with self.subTest(order=order): + api = _api() + r_long = _FakeAiohttpResponse(429, b"Requests are blocked") + r_long.headers = {"Retry-After": "60"} + r_short = _FakeAiohttpResponse(429, b"Requests are blocked") + r_short.headers = {"Retry-After": "1"} + responses = ( + [r_long, r_short, _FakeAiohttpResponse(200, b"{}", {"ok": True})] + if order == "long_first" + else [r_short, r_long, _FakeAiohttpResponse(200, b"{}", {"ok": True})] + ) + calls: list[int] = [] + self.clock.sleeps.clear() + + async def run(): + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + self._overlapping_session_cls(responses, calls, self.real_sleep), + ), patch( + "ariston.ariston_api.asyncio.sleep", + side_effect=self._overlapping_sleep, + ): + return await asyncio.gather( + api._async_get("https://example/api/a"), + api._async_get("https://example/api/b"), + return_exceptions=True, + ) + + results = asyncio.run(run()) + self.assertEqual(len(calls), 3) + if order == "long_first": + self.assertEqual(self.clock.sleeps, [61, 61]) + self.assertEqual(results[0], {"ok": True}) + self.assertIsInstance(results[1], ConnectionException) + else: + self.assertEqual(self.clock.sleeps, [2, 61]) + self.assertIsInstance(results[0], ConnectionException) + self.assertEqual(results[1], {"ok": True}) + + def test_async_late_retry_after_preserves_block_after_successful_retry(self): + api = _api() + owner_url = "https://example/api/owner" + late_url = "https://example/api/late" + next_url = "https://example/api/next" + first_response = _FakeAiohttpResponse(429, b"Requests are blocked for 1 seconds") + late_response = _FakeAiohttpResponse(429, b"Requests are blocked") + late_response.headers = {"Retry-After": "60"} + ok = _FakeAiohttpResponse(200, b"{}", {"ok": True}) + calls: list[str] = [] + + async def run() -> None: + late_request_started = asyncio.Event() + retry_started = asyncio.Event() + + async def request(_method: str, url: str, **kwargs: Any): + calls.append(url) + if url == late_url: + late_request_started.set() + await retry_started.wait() + return late_response + if url == owner_url: + if calls.count(owner_url) == 1: + return first_response + retry_started.set() + with self.assertRaises(ConnectionException): + await late_request + return ok + + with patch("ariston.ariston_api.aiohttp.ClientSession") as session: + session.return_value.__aenter__.return_value.request = AsyncMock( + side_effect=request + ) + late_request = asyncio.create_task(api._async_get(late_url)) + await late_request_started.wait() + self.assertEqual(await api._async_get(owner_url), {"ok": True}) + + self.clock.now += 60.75 + with self.assertRaises(ConnectionException): + await api._async_get(next_url) + self.clock.now += 0.25 + self.assertEqual(await api._async_get(next_url), {"ok": True}) + + asyncio.run(asyncio.wait_for(run(), timeout=5)) + self.assertEqual(calls, [late_url, owner_url, owner_url, next_url]) + + def test_retry_waits_for_shared_deadline(self): + url = "https://example/api" + body = b"Requests are blocked for 1 seconds" + + def wake_early(seconds: int) -> None: + self.assertEqual(seconds, 2) + self.clock.now += 0.25 + + with patch.object(self.clock, "sleep", side_effect=wake_early): + with self.subTest(transport="sync"): + http = MagicMock( + side_effect=[ + _sync_response(429, body), + _sync_response(200, b"{}", {"ok": True}), + ] + ) + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(ConnectionException): + _api()._get(url) + http.assert_called_once() + + with self.subTest(transport="async"): + calls: list[int] = [] + responses = [ + _FakeAiohttpResponse(429, body), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ): + with self.assertRaises(ConnectionException): + await _api()._async_get(url) + + asyncio.run(run()) + self.assertEqual(len(calls), 1) + if __name__ == "__main__": unittest.main()