Skip to content
Closed
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
100 changes: 81 additions & 19 deletions ariston/ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,18 @@ def _parse_block_seconds(content: bytes) -> Optional[int]:
return int(match.group(1))


def _rate_limit_wait_seconds(content: bytes) -> int:
"""Effective wait for a 429: parsed duration + 1s margin, else 5s."""
# Ariston answers "Requests are blocked" without a duration once an account
# exceeds its request budget. Retrying keeps the block alive, so every request
# of the instance pauses instead, doubling the pause while the block persists.
RATE_LIMIT_BACKOFF_START_SECONDS = 15 * 60
RATE_LIMIT_BACKOFF_MAX_SECONDS = 2 * 60 * 60


def _rate_limit_wait_seconds(content: bytes) -> Optional[int]:
"""Effective wait for a 429: parsed duration + 1s margin, else None."""
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
return None
_LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1)
return parsed + 1

Expand Down Expand Up @@ -98,6 +101,8 @@ 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
# Current pause for 429s without a block duration; 0 after a success.
self._rate_limit_backoff_seconds = 0
# Sync (requests) R2 web-app session; created lazily on first use.
self.__r2_requests_session: Optional[requests.Session] = None

Expand Down Expand Up @@ -566,9 +571,12 @@ def __request(
params: Optional[dict[str, Any]] = None,
body: Any = None,
is_retry: bool = False,
waited_out_block: bool = False,
) -> Optional[dict[str, Any]]:
"""Request with requests"""
if not is_retry and time.time() < self._blocked_until:
# Retries are checked too: a 405/5xx retry must not slip through a
# pause that another in-flight response started meanwhile.
if not waited_out_block and time.time() < self._blocked_until:
raise ConnectionException(
429,
"Rate limited; skipping request until the block window ends",
Expand Down Expand Up @@ -607,6 +615,7 @@ def __request(
return self.__request(method, path, params, body, True)
raise ConnectionException(response.status_code)

self._reset_rate_limit_backoff()
if len(response.content) > 0:
json = response.json()
_LOGGER.debug("Response %s", json)
Expand All @@ -618,6 +627,45 @@ def _post(self, path: str, body: Any) -> Any:
"""POST request"""
return self.__request("POST", path, None, body)

def _start_rate_limit_backoff(self) -> None:
"""Pause all requests of this instance after a 429 without a duration."""
if self._rate_limit_backoff_seconds and time.time() < self._blocked_until:
# Sent before the current pause started: same block, keep the pause.
return
self._rate_limit_backoff_seconds = (
min(self._rate_limit_backoff_seconds * 2, RATE_LIMIT_BACKOFF_MAX_SECONDS)
if self._rate_limit_backoff_seconds
else RATE_LIMIT_BACKOFF_START_SECONDS
)
self._blocked_until = max(
self._blocked_until, time.time() + self._rate_limit_backoff_seconds
)
_LOGGER.warning(
"Rate limited (429) without block duration; pausing requests for %s seconds",
self._rate_limit_backoff_seconds,
)

def _reset_rate_limit_backoff(self) -> None:
"""Forget the backoff after a success, unless a pause is still active.

A success that was in flight when a pause started does not prove the
block is over, so it must not reset the doubling.
"""
if time.time() >= self._blocked_until:
self._rate_limit_backoff_seconds = 0

def _start_rate_limit_wait(self, wait_seconds: int) -> Optional[float]:
"""Block until a parsed 429 window ends, without shortening a longer pause.

Returns the end of the window to wait out, or None when a longer pause
is already active and the request must not be retried.
"""
until = time.time() + wait_seconds
if self._blocked_until > until:
return None
self._blocked_until = until
return until

def __handle_rate_limit(
self,
response,
Expand All @@ -627,13 +675,18 @@ def __handle_rate_limit(
params: Optional[dict[str, Any]],
body: Any,
) -> Optional[dict[str, Any]]:
"""Sleep out the 429 block window, retry once, per-instance deadline."""
"""Sleep out a short 429 block window and retry once; back off otherwise."""
content = response.content
wait_seconds = _rate_limit_wait_seconds(content)
self._blocked_until = time.time() + wait_seconds
if not is_retry:
if wait_seconds is None:
self._start_rate_limit_backoff()
raise ConnectionException(response.status_code, content.decode())
until = self._start_rate_limit_wait(wait_seconds)
if until is not None and not is_retry:
time.sleep(wait_seconds)
return self.__request(method, path, params, body, True)
# Retry only if no longer pause started while waiting.
if self._blocked_until <= until:
return self.__request(method, path, params, body, True, True)
raise ConnectionException(response.status_code, content.decode())

def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any:
Expand Down Expand Up @@ -1506,9 +1559,12 @@ async def __async_request(
body: Any = None,
is_retry: bool = False,
timeout_seconds: int = 30,
waited_out_block: bool = False,
) -> Optional[dict[str, Any]]:
"""Async request with aiohttp"""
if not is_retry and time.time() < self._blocked_until:
# Retries are checked too: a 405/5xx retry must not slip through a
# pause that another in-flight response started meanwhile.
if not waited_out_block and time.time() < self._blocked_until:
raise ConnectionException(
429,
"Rate limited; skipping request until the block window ends",
Expand Down Expand Up @@ -1558,6 +1614,7 @@ async def __async_request(
)
raise ConnectionException(response.status)

self._reset_rate_limit_backoff()
if response.content_length and response.content_length > 0:
json = await response.json()
_LOGGER.debug("Response %s", json)
Expand All @@ -1583,15 +1640,20 @@ async def __async_handle_rate_limit(
body: Any,
timeout_seconds: int,
) -> Optional[dict[str, Any]]:
"""Sleep out the 429 block window, retry once, share the deadline."""
"""Sleep out a short 429 block window and retry once; back off otherwise."""
content = await response.content.read()
wait_seconds = _rate_limit_wait_seconds(content)
self._blocked_until = time.time() + wait_seconds
if not is_retry:
if wait_seconds is None:
self._start_rate_limit_backoff()
raise ConnectionException(response.status, content)
Comment thread
rudelafuente marked this conversation as resolved.
Resolved
until = self._start_rate_limit_wait(wait_seconds)
if until is not None and not is_retry:
await asyncio.sleep(wait_seconds)
return await self.__async_request(
method, path, params, body, True, timeout_seconds
)
# Retry only if no longer pause started while waiting.
if self._blocked_until <= until:
return await self.__async_request(
method, path, params, body, True, timeout_seconds, True
)
raise ConnectionException(response.status, content)

async def _async_get(
Expand Down
74 changes: 63 additions & 11 deletions ariston/galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import logging
import math
import time
from datetime import date
from typing import Any, Optional

Expand All @@ -29,6 +30,15 @@
)
from .device import AristonDevice

# Hybrid and heat pump menu items cost up to four extra requests per refresh
# (more when the per-item fallback runs). Refreshing them on every poll exhausts
# Ariston's per-account request budget, so they are refreshed less often and the
# last values are kept in between.
HYBRID_MENU_ITEMS_REFRESH_SECONDS = 30 * 60
HYBRID_MENU_ITEM_IDS = frozenset(
item.value for group in MenuItemNames.hybrid_groups() for item in group
)

_LOGGER = logging.getLogger(__name__)
_MENU_ITEM_UNAVAILABLE_VALUES = frozenset({3276.0, 3276.7, -3276.8, -3277.0})
_CH_RETURN_TEMP_UNAVAILABLE_VALUES = _MENU_ITEM_UNAVAILABLE_VALUES | {0.0}
Expand All @@ -50,6 +60,8 @@ def __init__(
self.consumptions_settings: dict[str, Any] = {}
self.energy_account: dict[str, Any] = {}
self.menu_items: list[dict[str, Any]] = []
# When the hybrid menu items were last fetched successfully.
self._hybrid_menu_items_fetched_at: Optional[float] = None

@property
def consumption_type(self) -> str:
Expand Down Expand Up @@ -121,6 +133,35 @@ def _should_include_hybrid_menu_items(self) -> bool:
or self.features.get(DeviceFeatures.HP_SYS) is True
)

def _hybrid_menu_items_due(self) -> bool:
"""Return True if this refresh should request the hybrid menu items."""
if not self._should_include_hybrid_menu_items():
return False
last = self._hybrid_menu_items_fetched_at
return last is None or time.monotonic() - last >= HYBRID_MENU_ITEMS_REFRESH_SECONDS

def _mark_hybrid_menu_items_fetched(self, include_hybrid_items: bool) -> None:
"""Start the refresh window only once the hybrid items really arrived.

A request skipped by a 429 pause or failed by a server error must not
delay the next attempt by a whole window.
"""
if include_hybrid_items:
self._hybrid_menu_items_fetched_at = time.monotonic()

def _with_cached_hybrid_menu_items(
self, items: list[dict[str, Any]], include_hybrid_items: bool
) -> list[dict[str, Any]]:
"""Keep the last hybrid menu items when this refresh skipped them."""
if include_hybrid_items or not self._should_include_hybrid_menu_items():
return items
ids = {item.get("id") for item in items}
return items + [
item
for item in self.menu_items
if item.get("id") in HYBRID_MENU_ITEM_IDS and item.get("id") not in ids
]

def update_state(self) -> None:
"""Update the device states from the cloud"""
if len(self.features) == 0:
Expand All @@ -132,11 +173,15 @@ def update_state(self) -> None:
self.language_tag,
self.umsys,
)
include_hybrid_items = self._hybrid_menu_items_due()
try:
self.menu_items = self.api.get_menu_items(
self.gw,
include_hybrid_items=self._should_include_hybrid_menu_items(),
self.menu_items = self._with_cached_hybrid_menu_items(
self.api.get_menu_items(
self.gw, include_hybrid_items=include_hybrid_items
),
include_hybrid_items,
)
self._mark_hybrid_menu_items_fetched(include_hybrid_items)
except ConnectionException as error:
if not self._should_retain_menu_items_after_error(error):
raise
Expand All @@ -147,31 +192,38 @@ async def async_update_state(self) -> None:
if len(self.features) == 0:
await self.async_get_features()

(self.data, self.menu_items) = await asyncio.gather(
include_hybrid_items = self._hybrid_menu_items_due()
(self.data, (self.menu_items, fetched)) = await asyncio.gather(
self.api.async_get_properties(
self.gw,
self.features,
self.language_tag,
self.umsys,
),
self._async_get_menu_items(
include_hybrid_items=self._should_include_hybrid_menu_items()
),
self._async_get_menu_items(include_hybrid_items=include_hybrid_items),
)
# Only once both results are stored: a failed properties request
# discards the menu items, so they must be fetched again.
self._mark_hybrid_menu_items_fetched(include_hybrid_items and fetched)
self._update_state()

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."""
) -> tuple[list[dict[str, Any]], bool]:
"""Get menu items while retaining the last values for server errors.

Returns the items and whether they were fetched (False when the last
values were retained after a server error).
"""
try:
return await self.api.async_get_menu_items(
items = 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
return self.menu_items, False
return self._with_cached_hybrid_menu_items(items, include_hybrid_items), True

def _should_retain_menu_items_after_error(
self, error: ConnectionException
Expand Down
Loading