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
54 changes: 32 additions & 22 deletions ariston/ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,11 +837,14 @@ async def async_get_properties(
properties = await self._async_request_properties(
path, items, features, culture, False
)
except ConnectionException as error:
if error.args[:1] != (500,) or not items:
except (ConnectionException, asyncio.TimeoutError) as error:
if (
isinstance(error, ConnectionException)
and error.args[:1] != (500,)
) or not items:
raise
_LOGGER.warning(
"GALEVO properties batch returned HTTP 500; retrying in pairs"
"GALEVO properties batch failed with HTTP 500 or timed out; retrying in pairs"
)
properties = await self._async_recover_properties(
path, items, features, culture, error
Expand All @@ -867,6 +870,7 @@ async def _async_request_properties(
"features": features,
"culture": culture,
},
timeout_seconds=90,
)

async def _async_cached_property(
Expand All @@ -876,9 +880,9 @@ async def _async_cached_property(
features: dict[str, Any],
culture: str,
) -> Any:
"""Retry a property with the provider cache after HTTP 500."""
"""Retry a property with the provider cache after a server error or timeout."""
_LOGGER.warning(
"GALEVO property %s returned HTTP 500; trying cached value",
"GALEVO property %s failed or timed out; trying cached value",
item["id"],
)
try:
Expand All @@ -900,13 +904,13 @@ async def _async_recover_property(
features: dict[str, Any],
culture: str,
) -> Any:
"""Retry one property fresh, then cached on HTTP 500."""
"""Retry one property fresh, then cached on server error or timeout."""
try:
return await self._async_request_properties(
path, [item], features, culture, False
)
except ConnectionException as error:
if error.args[:1] != (500,):
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)

Expand All @@ -917,13 +921,13 @@ async def _async_recover_property_chunk(
features: dict[str, Any],
culture: str,
) -> list[dict[str, Any]]:
"""Retry a pair, splitting only when the pair returns HTTP 500."""
"""Retry a pair, splitting on server error or timeout."""
try:
response = await self._async_request_properties(
path, chunk, features, culture, False
)
except ConnectionException as error:
if error.args[:1] != (500,):
except (ConnectionException, asyncio.TimeoutError) as error:
if isinstance(error, ConnectionException) and error.args[:1] != (500,):
raise
if len(chunk) == 1:
response = await self._async_cached_property(
Expand All @@ -946,7 +950,7 @@ async def _async_recover_properties(
items: list[dict[str, Any]],
features: dict[str, Any],
culture: str,
initial_error: ConnectionException,
initial_error: ConnectionException | asyncio.TimeoutError,
) -> dict[str, Any]:
"""Collect pair retries, preserving the original error if none succeed."""
properties = {"features": features, "items": []}
Expand Down Expand Up @@ -1456,6 +1460,7 @@ async def __async_request(
params: Optional[dict[str, Any]] = None,
body: Any = None,
is_retry: bool = False,
timeout_seconds: int = 30,
) -> Optional[dict[str, Any]]:
"""Async request with aiohttp"""
if not is_retry and time.time() < self._blocked_until:
Expand All @@ -1475,10 +1480,8 @@ async def __async_request(
params,
)

# Apply an explicit total timeout so a stalled request fails fast
# instead of relying on aiohttp's 5 minute default. This mirrors the
# 30 second timeout used by the synchronous `requests` path.
timeout = aiohttp.ClientTimeout(total=30)
# GALEVO property batches can take longer than other API requests.
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
async with aiohttp.ClientSession(timeout=timeout) as session:
response = await session.request(
method, path, params=params, json=body, headers=headers
Expand All @@ -1490,7 +1493,7 @@ async def __async_request(
if not is_retry:
if await self.async_connect():
return await self.__async_request(
method, path, params, body, True
method, path, params, body, True, timeout_seconds
)
raise ConnectionException(
"Login failed (password changed?)"
Expand All @@ -1500,13 +1503,13 @@ async def __async_request(
return None
case 429:
return await self.__async_handle_rate_limit(
response, is_retry, method, path, params, body
response, is_retry, method, path, params, body, timeout_seconds
)
case _:
if not is_retry:
await asyncio.sleep(5)
return await self.__async_request(
method, path, params, body, True
method, path, params, body, True, timeout_seconds
)
raise ConnectionException(response.status)

Expand All @@ -1517,9 +1520,13 @@ async def __async_request(

return None

async def _async_post(self, path: str, body: Any) -> Any:
async def _async_post(
self, path: str, body: Any, timeout_seconds: int = 30
) -> Any:
"""Async POST request"""
return await self.__async_request("POST", path, None, body)
return await self.__async_request(
"POST", path, None, body, timeout_seconds=timeout_seconds
)

async def __async_handle_rate_limit(
self,
Expand All @@ -1529,14 +1536,17 @@ async def __async_handle_rate_limit(
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)
return await self.__async_request(
method, path, params, body, True, timeout_seconds
)
raise ConnectionException(response.status, content)

async def _async_get(
Expand Down
5 changes: 2 additions & 3 deletions ariston/galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
CustomDeviceFeatures,
DeviceFeatures,
DeviceProperties,
GalevoDeviceAttribute,
GasEnergyUnit,
GasType,
HOLIDAY_DATE_FORMAT,
Expand Down Expand Up @@ -125,7 +124,7 @@ def update_state(self) -> None:
self.menu_items = self.api.get_menu_items(
self.gw,
include_hybrid_items=(
self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True
self.features.get(DeviceFeatures.HYBRID_SYS) is True
),
)
except ConnectionException as error:
Expand All @@ -147,7 +146,7 @@ async def async_update_state(self) -> None:
),
self._async_get_menu_items(
include_hybrid_items=(
self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True
self.features.get(DeviceFeatures.HYBRID_SYS) is True
)
),
)
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.14"
version = "0.19.15"
dynamic = ['description']

[project.urls]
Expand Down
99 changes: 59 additions & 40 deletions tests/test_ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,55 +439,74 @@ async def exercise():
["124,119", "123,125,115", "123", "125", "115", "349,348", "127"],
)

def test_async_properties_recovers_from_batch_500_with_small_requests(self):
api = AristonAPI("user", "password", api_url="https://example.test/api/")
features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]}
items = [{"id": name, "zn": 0} for name in ("A", "B", "PlantMode")]
requests = []

async def post(path, body):
requests.append(body)
requested = [item["id"] for item in body["items"]]
if len(requested) > 2 or (
requested == ["PlantMode"] and not body["useCache"]
):
raise ConnectionException(500)
return {
"features": features,
"items": [{"id": name} for name in requested],
}
def test_async_properties_recovers_from_batch_errors_with_small_requests(self):
scenarios = (
(
"HTTP 500",
ConnectionException(500),
[{"id": name, "zn": 0} for name in ("A", "B", "PlantMode")],
[
(["A", "B", "PlantMode"], False),
(["A", "B"], False),
(["PlantMode"], False),
(["PlantMode"], True),
],
),
(
"timeout",
asyncio.TimeoutError(),
[{"id": name, "zn": 0} for name in ("A", "B", "C")],
[
(["A", "B", "C"], False),
(["A", "B"], False),
(["C"], False),
],
),
)

async def exercise():
with patch.object(api, "get_items", return_value=items), patch.object(
api, "_async_post", new=AsyncMock(side_effect=post)
):
return await api.async_get_properties("gw-1", features, "en", "si")
for scenario, failure, items, expected_requests in scenarios:
with self.subTest(scenario=scenario):
api = AristonAPI("user", "password", api_url="https://example.test/api/")
features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]}
requests = []

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"]
):
raise failure
return {
"features": features,
"items": [{"id": name} for name in requested],
}

async def exercise():
with patch.object(api, "get_items", return_value=items), patch.object(
api, "_async_post", new=AsyncMock(side_effect=post)
):
return await api.async_get_properties(
"gw-1", features, "en", "si"
)

result = asyncio.run(exercise())
self.assertEqual(
[item["id"] for item in result["items"]], ["A", "B", "PlantMode"]
)
self.assertEqual(result["features"], features)
self.assertEqual(
[
([item["id"] for item in body["items"]], body["useCache"])
for body in requests
],
[
(["A", "B", "PlantMode"], False),
(["A", "B"], False),
(["PlantMode"], False),
(["PlantMode"], True),
],
)
result = asyncio.run(exercise())
self.assertEqual(
[item["id"] for item in result["items"]],
[item["id"] for item in items],
)
self.assertEqual(result["features"], features)
self.assertEqual(requests, expected_requests)

def test_async_properties_splits_failing_pair_before_using_cache(self):
api = AristonAPI("user", "password")
features = {DeviceFeatures.ZONES: []}
items = [{"id": name, "zn": 0} for name in ("A", "B", "C", "D")]
requests = []

async def post(path, body):
async def post(path, body, **kwargs):
requested = [item["id"] for item in body["items"]]
requests.append((requested, body["useCache"]))
if len(requested) > 2 or requested == ["A", "B"]:
Expand Down
Loading
Loading