diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index d383445..7003f8e 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -49,7 +49,6 @@ _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 @@ -76,20 +75,6 @@ def _parse_retry_after_seconds(headers: Any) -> Optional[int]: 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 %ss wait", - _UNPARSABLE_INITIAL_WAIT_SECONDS, - ) - 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,): @@ -147,6 +132,11 @@ def _menu_items_path(api_url: str, gw_id: str, menu_items_query: str) -> str: class ConnectionException(Exception): """When can not connect to Ariston cloud""" + def __init__(self, *args: Any, retry_after: Optional[float] = None) -> None: + """Initialize the connection exception with optional rate-limit delay.""" + super().__init__(*args) + self.retry_after = retry_after + class AristonAPI: """Ariston API class""" @@ -182,8 +172,18 @@ def __init__( # 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: + def _rate_limit_exception(self, payload: Any) -> ConnectionException: + """Build a 429 ConnectionException carrying the remaining block delay.""" + remaining = self._blocked_until - time.time() + return ConnectionException( + 429, + payload, + retry_after=remaining if remaining > 0 else None, + ) + + def _bump_rate_limit_cooldown(self, now: Optional[float] = None) -> None: """Advance unparsable-429 streak and extend the shared block window.""" + current_time = time.time() if now is None else now self._rate_limit_streak += 1 cooldown = min( _UNPARSABLE_COOLDOWN_MAX_SECONDS, @@ -196,10 +196,10 @@ def _bump_rate_limit_cooldown(self) -> None: self._rate_limit_streak, cooldown, ) - self._blocked_until = max(self._blocked_until, time.time() + cooldown) + self._blocked_until = max(self._blocked_until, current_time + cooldown) def _prepare_rate_limit_retry( - self, content: bytes, headers: Any, is_retry: bool + self, content: bytes, headers: Any, is_rate_limit_retry: bool ) -> Optional[tuple[int, int]]: """Update rate-limit state and return the wait and epoch for a retry.""" now = time.time() @@ -207,19 +207,18 @@ def _prepare_rate_limit_retry( 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() + if parsed is None: + if not is_rate_limit_retry and ( + self._rate_limit_retry_in_flight or now < self._blocked_until + ): + return None + self._bump_rate_limit_cooldown(now) return None - else: - wait_seconds = _rate_limit_wait_seconds(content) + wait_seconds = parsed + 1 + _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, wait_seconds) self._blocked_until = max(self._blocked_until, now + wait_seconds) - if is_retry or self._rate_limit_retry_in_flight: + if is_rate_limit_retry or self._rate_limit_retry_in_flight: return None return (math.ceil(self._blocked_until - now), self._rate_limit_retry_epoch) @@ -258,6 +257,8 @@ def connect(self) -> bool: return True + except ConnectionException: + raise except Exception as error: raise ConnectionException() from error @@ -782,12 +783,12 @@ def __request( params: Optional[dict[str, Any]] = None, body: Any = None, is_retry: bool = False, + rate_limit_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", + if not rate_limit_retry and time.time() < self._blocked_until: + raise self._rate_limit_exception( + "Rate limited; skipping request until the block window ends" ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, @@ -815,7 +816,7 @@ def __request( return None case 429: return self.__handle_rate_limit( - response, is_retry, method, path, params, body + response, rate_limit_retry, method, path, params, body ) case _: if not is_retry: @@ -823,7 +824,8 @@ def __request( return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) - self._rate_limit_streak = 0 + if time.time() >= self._blocked_until: + self._rate_limit_streak = 0 if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -838,7 +840,7 @@ def _post(self, path: str, body: Any) -> Any: def __handle_rate_limit( self, response, - is_retry: bool, + is_rate_limit_retry: bool, method: str, path: str, params: Optional[dict[str, Any]], @@ -847,16 +849,18 @@ def __handle_rate_limit( """Sleep out the 429 block window, retry once, per-instance deadline.""" content = response.content headers = getattr(response, "headers", None) - retry_plan = self._prepare_rate_limit_retry(content, headers, is_retry) + retry_plan = self._prepare_rate_limit_retry( + content, headers, is_rate_limit_retry + ) if retry_plan is not None: wait_seconds, epoch = retry_plan time.sleep(wait_seconds) if self._claim_rate_limit_retry(epoch): try: - return self.__request(method, path, params, body, True) + return self.__request(method, path, params, body, True, True) finally: self._rate_limit_retry_in_flight = False - raise ConnectionException(response.status_code, content.decode()) + raise self._rate_limit_exception(content.decode()) def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" @@ -991,6 +995,8 @@ async def async_connect(self) -> bool: return True + except ConnectionException: + raise except Exception as error: raise ConnectionException() from error @@ -1749,12 +1755,12 @@ async def __async_request( body: Any = None, is_retry: bool = False, timeout_seconds: int = 30, + rate_limit_retry: bool = False, ) -> 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", + if not rate_limit_retry and time.time() < self._blocked_until: + raise self._rate_limit_exception( + "Rate limited; skipping request until the block window ends" ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, @@ -1791,7 +1797,13 @@ async def __async_request( return None case 429: return await self.__async_handle_rate_limit( - response, is_retry, method, path, params, body, timeout_seconds + response, + rate_limit_retry, + method, + path, + params, + body, + timeout_seconds, ) case _: if not is_retry: @@ -1801,7 +1813,8 @@ async def __async_request( ) raise ConnectionException(response.status) - self._rate_limit_streak = 0 + if time.time() >= self._blocked_until: + self._rate_limit_streak = 0 if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1820,7 +1833,7 @@ async def _async_post( async def __async_handle_rate_limit( self, response, - is_retry: bool, + is_rate_limit_retry: bool, method: str, path: str, params: Optional[dict[str, Any]], @@ -1830,18 +1843,20 @@ async def __async_handle_rate_limit( """Sleep out the 429 block window, retry once, share the deadline.""" content = await response.content.read() headers = getattr(response, "headers", None) - retry_plan = self._prepare_rate_limit_retry(content, headers, is_retry) + retry_plan = self._prepare_rate_limit_retry( + content, headers, is_rate_limit_retry + ) if retry_plan is not None: wait_seconds, epoch = retry_plan await asyncio.sleep(wait_seconds) if self._claim_rate_limit_retry(epoch): try: return await self.__async_request( - method, path, params, body, True, timeout_seconds + method, path, params, body, True, timeout_seconds, True ) finally: self._rate_limit_retry_in_flight = False - raise ConnectionException(response.status, content) + raise self._rate_limit_exception(content) async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 1354213..37a93fc 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -120,17 +120,18 @@ def test_429_parses_wait_seconds(self): 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) + http = MagicMock(return_value=_sync_response(429, b"Too many requests")) + api = _api() with patch("ariston.ariston_api.requests.request", http): - result = _api()._get("https://example/api") + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") - self.assertEqual(result, {"ok": True}) - self.assertEqual(self.clock.sleeps, [5]) # documented fallback - self.assertEqual(http.call_count, 2) + self.assertEqual(ctx.exception.args, (429, "Too many requests")) + self.assertEqual(ctx.exception.retry_after, 60.0) + self.assertEqual(self.clock.sleeps, []) # immediate cooldown, no blind 5s retry + self.assertEqual(http.call_count, 1) + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(api._blocked_until, self.clock.time() + 60) def test_429_twice_raises(self): body = b"Requests are blocked for 10 seconds" @@ -236,31 +237,31 @@ def test_429_without_duration_escalates_cooldown_and_resets_on_ok(self): 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): + with self.assertRaises(ConnectionException) as first_err: api._get("https://example/api") - first_cooldown = api._blocked_until - self.clock.time() - self.assertGreater(first_cooldown, 50) + self.assertEqual(first_err.exception.retry_after, 60.0) + self.assertEqual(api._blocked_until - self.clock.time(), 60.0) self.assertEqual(api._rate_limit_streak, 1) - self.assertEqual(self.clock.sleeps, [5]) + self.assertEqual(self.clock.sleeps, []) - api._blocked_until = 0.0 - with self.assertRaises(ConnectionException): + self.clock.now += 60 + with self.assertRaises(ConnectionException) as second_err: api._get("https://example/api") - second_cooldown = api._blocked_until - self.clock.time() - self.assertGreater(second_cooldown, 110) + self.assertEqual(second_err.exception.retry_after, 120.0) + self.assertEqual(api._blocked_until - self.clock.time(), 120.0) self.assertEqual(api._rate_limit_streak, 2) - self.assertEqual(self.clock.sleeps, [5]) + self.assertEqual(self.clock.sleeps, []) - api._blocked_until = 0.0 + self.clock.now += 120 self.assertEqual(api._get("https://example/api"), {"ok": True}) self.assertEqual(api._rate_limit_streak, 0) + self.assertEqual(http.call_count, 3) def test_async_429_without_duration_sets_cooldown_and_retry_after_header(self): api = _api() @@ -270,7 +271,6 @@ def test_async_429_without_duration_sets_cooldown_and_retry_after_header(self): resp_with_header, _FakeAiohttpResponse(200, b"{}", {"ok": True}), _FakeAiohttpResponse(429, b"Requests are blocked"), - _FakeAiohttpResponse(429, b"Requests are blocked"), ] calls: list[int] = [] @@ -281,20 +281,25 @@ async def run(): ): ok = await api._async_get("https://example/api") api._blocked_until = 0.0 - with self.assertRaises(ConnectionException): + with self.assertRaises(ConnectionException) as ctx: await api._async_get("https://example/api") - return ok - - self.assertEqual(asyncio.run(run()), {"ok": True}) - self.assertEqual(self.clock.sleeps, [13, 5]) + return ok, ctx.exception + + ok, exc = asyncio.run(run()) + self.assertEqual(ok, {"ok": True}) + self.assertEqual(exc.args, (429, b"Requests are blocked")) + self.assertEqual(exc.retry_after, 60.0) + self.assertEqual(len(calls), 3) + self.assertEqual(self.clock.sleeps, [13]) self.assertEqual(api._rate_limit_streak, 1) - self.assertGreater(api._blocked_until - self.clock.time(), 50) + self.assertEqual(api._blocked_until - self.clock.time(), 60.0) def test_async_overlapping_429_sends_single_retry(self): api = _api() + body = b"Requests are blocked for 5 seconds" responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked"), - _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, body), + _FakeAiohttpResponse(429, body), _FakeAiohttpResponse(429, b"Requests are blocked"), ] calls: list[int] = [] @@ -314,10 +319,51 @@ async def run(): 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(self.clock.sleeps, [6, 6]) self.assertEqual(api._rate_limit_streak, 1) self.assertTrue(all(isinstance(res, ConnectionException) for res in results)) + async def _run_overlapping_gets( + self, api: AristonAPI, responses: list, calls: list[int] + ) -> list[Any]: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + self._overlapping_session_cls(responses, calls, self.real_sleep), + ): + return await asyncio.gather( + api._async_get("https://example/api/a"), + api._async_get("https://example/api/b"), + return_exceptions=True, + ) + + def test_async_overlapping_unparsable_429_escalates_cooldown_once(self): + for initial_streak, expected_streak, expected_cooldown in ( + (0, 1, 60.0), + (1, 2, 120.0), + ): + with self.subTest(initial_streak=initial_streak): + api = _api() + api._rate_limit_streak = initial_streak + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ] + calls: list[int] = [] + self.clock.sleeps.clear() + + results = asyncio.run( + self._run_overlapping_gets(api, responses, calls) + ) + self.assertEqual(len(calls), 2) + self.assertEqual(self.clock.sleeps, []) + self.assertEqual(api._rate_limit_streak, expected_streak) + self.assertEqual( + api._blocked_until - self.clock.time(), expected_cooldown + ) + for res in results: + self.assertIsInstance(res, ConnectionException) + self.assertEqual(res.retry_after, expected_cooldown) + async def _overlapping_sleep(self, seconds: int) -> None: self.clock.sleeps.append(seconds) wake_at = self.clock.now + seconds @@ -504,6 +550,162 @@ async def run() -> None: asyncio.run(run()) self.assertEqual(len(calls), 1) + async def _async_get_expecting_connection_error( + self, api: AristonAPI, url: str = "https://example/api" + ) -> ConnectionException: + with self.assertRaises(ConnectionException) as ctx: + await api._async_get(url) + return ctx.exception + + def test_short_circuit_rate_limit_exposes_retry_after(self): + for is_async in (False, True): + with self.subTest(is_async=is_async): + api = _api() + api._blocked_until = self.clock.time() + 45.5 + + if not is_async: + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + exc = ctx.exception + else: + exc = asyncio.run( + self._async_get_expecting_connection_error(api) + ) + + self.assertEqual(exc.args[0], 429) + self.assertEqual(exc.retry_after, 45.5) + + def test_repeated_parsed_429_exposes_retry_after(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): + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + self.assertEqual(ctx.exception.args[0], 429) + self.assertEqual(ctx.exception.retry_after, 11.0) + + def test_ok_response_during_active_block_preserves_streak(self): + api = _api() + api._rate_limit_streak = 2 + api._blocked_until = self.clock.time() + 60.0 + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(200, b"{}", {"ok": True}), + ): + result = api._AristonAPI__request( + "GET", "https://example/api", rate_limit_retry=True + ) + self.assertEqual(result, {"ok": True}) + self.assertEqual(api._rate_limit_streak, 2) + + async_api = _api() + async_api._rate_limit_streak = 1 + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + results = asyncio.run( + self._run_overlapping_gets(async_api, responses, calls) + ) + self.assertIsInstance(results[0], ConnectionException) + self.assertEqual(results[1], {"ok": True}) + self.assertEqual(async_api._rate_limit_streak, 2) + + def test_async_5xx_retry_respects_active_rate_limit_block(self): + api = _api() + calls: list[str] = [] + sleep_started = asyncio.Event() + block_active = asyncio.Event() + + async def fake_sleep(seconds: int) -> None: + self.clock.sleeps.append(seconds) + sleep_started.set() + await block_active.wait() + self.clock.now += seconds + + async def request(_method: str, url: str, **kwargs: Any): + calls.append(url) + if url.endswith("/five-hundred"): + return _FakeAiohttpResponse(500) + return _FakeAiohttpResponse(429, b"Requests are blocked") + + async def run(): + with patch("ariston.ariston_api.aiohttp.ClientSession") as session, patch( + "ariston.ariston_api.asyncio.sleep", side_effect=fake_sleep + ): + session.return_value.__aenter__.return_value.request = AsyncMock( + side_effect=request + ) + task_500 = asyncio.create_task( + api._async_get("https://example/api/five-hundred") + ) + await sleep_started.wait() + with self.assertRaises(ConnectionException) as err_429: + await api._async_get("https://example/api/four-two-nine") + block_active.set() + with self.assertRaises(ConnectionException) as err_500: + await task_500 + return err_429.exception, err_500.exception + + err_429, err_500 = asyncio.run(asyncio.wait_for(run(), timeout=5)) + self.assertEqual( + calls, + [ + "https://example/api/five-hundred", + "https://example/api/four-two-nine", + ], + ) # 500 retry did not hit server during active 429 block + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(err_429.retry_after, 60.0) + self.assertEqual(err_500.args[0], 429) + self.assertEqual(err_500.retry_after, 55.0) + + def test_connect_preserves_rate_limit_exception_and_retry_after(self): + sync_api = _api() + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(429, b"Requests are blocked"), + ): + with self.assertRaises(ConnectionException) as sync_ctx: + sync_api.connect() + self.assertEqual(sync_ctx.exception.args, (429, "Requests are blocked")) + self.assertEqual(sync_ctx.exception.retry_after, 60.0) + + async_api = _api() + calls: list[int] = [] + + async def run_connect() -> ConnectionException: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls( + [_FakeAiohttpResponse(429, b"Requests are blocked")], calls + ), + ): + with self.assertRaises(ConnectionException) as ctx: + await async_api.async_connect() + return ctx.exception + + async_exc = asyncio.run(run_connect()) + self.assertEqual(async_exc.args, (429, b"Requests are blocked")) + self.assertEqual(async_exc.retry_after, 60.0) + + def test_bare_429_while_retry_in_flight_does_not_escalate_streak(self): + api = _api() + api._rate_limit_retry_in_flight = True + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(429, b"Requests are blocked"), + ): + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + self.assertEqual(ctx.exception.args, (429, "Requests are blocked")) + self.assertIsNone(ctx.exception.retry_after) + self.assertEqual(api._rate_limit_streak, 0) + if __name__ == "__main__": unittest.main()