Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 49 additions & 41 deletions ariston/ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -76,20 +75,6 @@
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,):
Expand Down Expand Up @@ -147,6 +132,11 @@
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"""
Expand Down Expand Up @@ -182,8 +172,18 @@
# 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,
Expand All @@ -196,7 +196,7 @@
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
Expand All @@ -207,17 +207,13 @@
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 now >= self._blocked_until:
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:
return None
Expand Down Expand Up @@ -259,6 +255,8 @@
return True

except Exception as error:
if isinstance(error, ConnectionException) and error.args[:1] == (429,):
raise
raise ConnectionException() from error

def get_detailed_devices(self) -> list[Any]:
Expand Down Expand Up @@ -782,12 +780,12 @@
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,
Expand Down Expand Up @@ -823,7 +821,8 @@
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)
Expand Down Expand Up @@ -853,10 +852,10 @@
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"""
Expand Down Expand Up @@ -992,6 +991,8 @@
return True

except Exception as error:
if isinstance(error, ConnectionException) and error.args[:1] == (429,):
raise
raise ConnectionException() from error

async def async_get_detailed_devices(self) -> list[Any]:
Expand Down Expand Up @@ -1741,7 +1742,7 @@
return list(bus_errors)
return []

async def __async_request(

Check failure on line 1745 in ariston/ariston_api.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=fustom_python-ariston-api&issues=AaIdnW1JS3t7O7lNw3G2&open=AaIdnW1JS3t7O7lNw3G2&pullRequest=213
self,
method: str,
path: str,
Expand All @@ -1749,12 +1750,12 @@
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,
Expand Down Expand Up @@ -1791,7 +1792,13 @@
return None
case 429:
return await self.__async_handle_rate_limit(
response, is_retry, method, path, params, body, timeout_seconds
response,
is_retry,
method,
path,
params,
body,
timeout_seconds,
)
case _:
if not is_retry:
Expand All @@ -1801,7 +1808,8 @@
)
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)
Expand Down Expand Up @@ -1837,11 +1845,11 @@
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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies = [
]
requires-python = ">=3.11"
license = { file = "LICENSE" }
version = "0.19.22"
version = "0.19.23"
dynamic = ['description']

[project.urls]
Expand Down
Loading