Repository navigation
fix(api): honour 429 retry-after instead of failing immediately - #187
Conversation
The API returns the block duration in the response body but the client discarded it and raised straight away, so the next poll often landed inside the same window. Parse the value, wait it out, and share the blocked-until deadline across all callers. Closes: AGENTS_ariston-429-holiday.md
The app exposes holiday mode for Velis water heaters but the library had
no method for it. POST velis/slpPlantData/{gw}/holiday with {"new": date}
to enable (ISO midnight format) and {"new": null} to cancel, mirroring the
existing Galevo holiday API. Date format centralized in a shared constant.
Proven against the live API: POST returns {"success":true} and the field
holidayUntil appears in velis/slpPlantData afterwards.
Closes: AGENTS_ariston-429-holiday.md
The +patchN version suffix is only needed for our local wheel deployment; release versioning belongs to the maintainer, so the PR diff no longer touches pyproject.toml (this also clears the Sonar S8565 lock-file finding from new code). Tests now use the monkeypatch fixture for the shared _blocked_until state and keep a single invocation inside pytest.raises blocks (S8997, S5778).
- Replace dict()/list() constructor calls with {}/[] literals
across ariston_api, galevo_device, velis_device (Sonar S7498)
- Extract the 429 branch from __request/__async_request into
__handle_rate_limit/__async_handle_rate_limit helpers plus a
module-level _rate_limit_wait_seconds() (Sonar S3776)
No behavior change; full suite 10/10 green (ariston-test:py313).
…ode drops value 0 Review-fixes: - [Important] R2 read retry caught only ConnectionException; expired forms-auth session surfaces as ContentTypeError/KeyError (login-HTML as JSON) -> read+parse now wrapped, surfaces as ConnectionException so the fresh-login retry fires
Round-2 review remark: the expired-session path fixed in 853b5a4 was executed by no test. Two hermetic guards: bad GetData body (KeyError/ ValueError) surfaces ConnectionException; one failed read triggers exactly one fresh login and one retry read. Suite 17/17.
|
@flupkede I will review this. I'm making test suite for this repo before that. :) |
astrinh0
left a comment
There was a problem hiding this comment.
Request changes: please address the three required inline findings. The final inline comment is a suggestion.
| operativeMode route silently drops value 0 (proven 2026-10-18). | ||
| """ | ||
| mode = NuosSplitOperativeMode[operation_mode] | ||
| if mode is NuosSplitOperativeMode.GREEN: |
There was a problem hiding this comment.
Required: This change routes only the async setter through R2. The synchronous sibling set_water_heater_operation_mode() still calls set_nuos_mode() for GREEN (0), which this PR says the api/v2 route silently ignores. Synchronous callers therefore still cannot set GREEN. Add the equivalent sync R2 path or handle GREEN in the sync setter.
There was a problem hiding this comment.
Fixed in f173bcb: added the sync twin — set_nuos_mode_via_r2() (requests-based R2 login/read/POST with the same one-fresh-login retry on a failed read), and the sync set_water_heater_operation_mode() now routes GREEN through it while COMFORT/FAST keep the direct route. The sync local echo also went into MODE before; it now writes OP_MODE like the async setter (mode is the plant-mode field and never changes on an operativeMode write). Covered by 4 new tests: full sync flow (login form → read → envelope with opMode 0), fresh-login retry, and GREEN/COMFORT routing.
|
|
||
| # Shared across all instances: one 429 silences every caller (all three | ||
| # HA coordinators) until the block window has passed. | ||
| _blocked_until: float = 0.0 |
There was a problem hiding this comment.
Required: This is a class attribute, so every AristonAPI instance shares the same deadline. A 429 for one account or API URL will make all other instances raise local 429 errors until the deadline expires. Keep the deadline on the instance or key it by account/API URL; the three coordinators for one account can still share one API instance.
There was a problem hiding this comment.
Fixed in f173bcb: _blocked_until is now a per-instance attribute set in __init__; both the sync and async handlers read/write self._blocked_until. The three coordinators for one account still share a single API instance, so they keep the shared short-circuit. Added per-instance isolation tests for both paths (a 429 on one instance leaves other instances untouched).
|
|
||
|
|
||
| class _FakeResponse: | ||
| def __init__(self, status: int, json_err: Exception | None = None) -> None: |
There was a problem hiding this comment.
Required: This test module evaluates the union annotation at import time. On Python 3.9, Exception | None raises TypeError; pyproject.toml supports Python >=3.9. Use Optional[Exception] or add from future import annotations.
There was a problem hiding this comment.
Fixed in f173bcb: added from __future__ import annotations to the test module and verified on a py3.9 interpreter (the Exception | None TypeError reproduces without it, clean with it).
Related finding while verifying: ariston/__init__.py uses match/case, so the package import itself fails on Python 3.9 despite requires-python = ">=3.9" — that one I left untouched since it predates this PR and bumping the floor vs. replacing the match is your call.
| async with session.post( | ||
| ARISTON_R2_SLP_SET_DATA.format(gw_id), json=payload | ||
| ) as response: | ||
| if response.status != 200: |
There was a problem hiding this comment.
Optional: This treats any HTTP 200 as a successful write. If SetData returns success:false, or follows an expired-session redirect to a 200 login page, this method returns normally and the caller updates local opMode. Validate the response body or detect authentication responses and retry or raise.
There was a problem hiding this comment.
Done in f173bcb (both sync and async SetData POSTs now validate the response): a non-JSON 200 body (expired-session redirect to the login page) and a JSON body with success: false raise ConnectionException instead of reporting success. Two tests cover both shapes. I did not add an automatic POST retry: the GetData immediately before the write already validated the session, so an auth failure at the POST surfaces honestly to the caller (HA's write-verify marks it write_failed) rather than silently re-sending a state change.
… SetData validation, py3.9 test annotations - _blocked_until: class attribute -> instance attribute; a 429 on one account must not silence other AristonAPI instances (the three HA coordinators for one account still share one instance) - sync set_nuos_mode_via_r2 (requests twin of the async R2 flow); the sync device setter now routes GREEN through it and echoes into opMode like the async setter (was MODE) - R2 SetData response validated (sync + async): non-JSON body (expired session redirect to the login page) and success:false raise ConnectionException instead of reporting success; no POST retry — the read just before the write already validated the session - test module: from __future__ import annotations (py3.9 import TypeError); verified on a py3.9 interpreter Note: ariston/__init__.py uses match/case, so the package itself does not import on py3.9 despite requires-python = ">=3.9" (pre-existing, flagged in the PR thread). Suite 25/25.
|
@flupkede please fix the conflicts I will merge it :) |
Done! and thank you so much for all the nice work ! |
Conflict resolution: - const.py: keep AUTO=3 (review-accepted rename of IMEMORY) and add main's GREEN_PLUS=6 in the same enum - test_device_models.py: keep the OP_MODE echo contract (sync + async, FAST and GREEN_PLUS asserts — mode is the plant-mode field, opMode the live operative state) and main's Nuos target-temperature cache fix (assert 60) - holiday: main's set_velis_slp_holiday and this branch's set_velis_holiday coexist (distinct names, same endpoint) - version follows main (0.19.12) Suite: 83 tests + 150 subtests green.
|
Conflicts are now actually resolved in 3071974 (merge of upstream/main): kept the AUTO rename alongside your GREEN_PLUS=6, kept the OP_MODE echo contract in the tests ( |
… set_velis_slp_holiday main gained set_velis_slp_holiday/async_set_velis_slp_holiday (same velis/slpPlantData holiday endpoint) after this branch introduced set_velis_holiday/async_set_velis_holiday. Keep main's pair as the canonical API; this branch keeps only the device-level wrapper (AristonVelisDevice.set_velis_holiday, which adds HOLIDAY_DATE_FORMAT date handling and is what the HA integration calls) and now delegates to main's methods. Suite 83 tests + 150 subtests green.
|
While resolving the merge I noticed main now carries Deduplicated in ace3bb8, in favour of yours: your pair stays the canonical API, ours is removed. The branch keeps only the device-level wrapper ( |
|
Preserve the existing Nuos mode name or make the break explicit. Replacing IMEMORY with AUTO removes an existing public enum member. Callers using that member or passing "IMEMORY" to the string-based setter will now fail. Retain a compatibility alias or handle this as a documented breaking API change. |
The Tests workflow installs only locked runtime deps (no pytest) and runs 'coverage run -m unittest discover'. Two of this branch's test modules imported pytest (ModuleNotFoundError in CI) and the third used module-level functions, which unittest discovery silently skips. Converted test_rate_limit.py, test_nuos_green_r2.py and test_velis_holiday.py to stdlib unittest.TestCase style; the pytest parametrize became a subTest loop, pytest.raises became assertRaises/assertRaisesRegex. No test logic changed. Verified with the exact CI commands on a pytest-less interpreter: 82 tests OK, coverage 99% (gate is 90%). Suite also still passes under pytest.
|
Fixed in 52a017e. The three test modules this branch adds were written pytest-style, but the Tests workflow installs only the locked runtime deps (no pytest) and runs Verified on a pytest-less interpreter with the exact workflow commands: 82 tests OK, coverage 99% (gate is 90%). One thing on your side: the new run on 52a017e is sitting in "action_required" (needs your approval to start) — presumably from the workflow-approval setting you touched while configuring required checks. Once you approve it, it should go green. |
|
Check only the last comment |
Renaming the mislabeled IMEMORY=3 to AUTO removed an existing public enum member: callers using NuosSplitOperativeMode.IMEMORY or passing "IMEMORY" to the string-based setter would break. AUTO stays the canonical name; IMEMORY is retained as an enum alias (same value 3), so attribute access and NuosSplitOperativeMode["IMEMORY"] keep working. Iteration and the mode options only expose AUTO — no duplicate value in water_heater_mode_options. The @unique decorator was dropped for this enum only (an alias is a duplicate value by definition); all other enums keep it. Tests: alias identity, string lookup, no duplicate option value, and the device setter accepting "IMEMORY". Suite: 84 tests + 152 subtests green under both unittest (CI, coverage 99%) and pytest.
|
Fair point — fixed in 9ab0a1a. |
|
merged @flupkede I will update this next week on the home assistant integration |
|
Already on 0.20.5 ! |
Problem
When the Ariston cloud rate-limits a request it returns HTTP 429 with the block duration in the body (
Requests are blocked for 66 seconds), but the client discarded that body and raised immediately. Home Assistant setups typically run multiple DataUpdateCoordinators against the same API (main state, bus errors, energy), so after the exception every coordinator kept polling on its normal interval — often still inside the block window — causing a storm of repeated 429s. The coordinators had no shared knowledge of a running block.Solution
blocked for (\d+) seconds).is_retrymechanism. A second 429 raises — no loop.AristonAPI._blocked_until(review round 2026-11-12): a 429 seen by one instance fails fast locally until the window passes, without silencing instances for other accounts; the three coordinators for one account share one API instance, so they keep the shared short-circuit. The deliberate post-sleep retry (is_retry=True) bypasses the guard so it cannot deadlock against its own deadline.The second commit adds Velis holiday support, mirroring the existing Galevo holiday API:
set_velis_holiday/async_set_velis_holidayonAristonAPIandAristonVelisDevice.POST velis/slpPlantData/{gw}/holidaywith{"new": "YYYY-MM-DDT00:00:00"}to enable and{"new": null}to cancel. Verified against the live API:{"success":true}, and theholidayUntilfield invelis/slpPlantDatareflects the change on the next read.HOLIDAY_DATE_FORMATconstant, now shared with the Galevo implementation.Nuos Split GREEN via the R2 web-app endpoint (new)
api/v2 velis/slpPlantData/{gw}/operativeModesilently drops value 0 (GREEN): HTTP 200, no effect — a classic falsy-zero bug (upstream issues #407/#461; GreenPlus=6 is also missing from the enum, #185). Values 1+ apply fine.The official web app sets GREEN through the R2 route
POST /R2/PlantHomeSlp/SetData/{gw}with an envelope{plantData: <echo>, viewModel: {opMode: 0, ...}}, which does apply value 0 (verified live:opMode=0in api/v2 and on the device tile).async_set_nuos_mode_via_r2: lazy R2 forms-auth login (GET login page → parse__RequestVerificationToken→ form POST), shared cookie jar created lazily inside the event loop, and one fresh-login retry when a read fails (an expired forms-auth session surfaces as login-page HTML / missingplantData, now wrapped intoConnectionExceptionso the retry fires).NuosSplitOperativeMode.GREENroutes through R2 (async and sync); COMFORT/FAST keep the proven direct api/v2 POST.IMEMORY→AUTO(value 3), matching the official app's range (Green=0 / Comfort=1 / Fast=2 / Auto=3 / HcHp=4 / Electric=5 / GreenPlus=6).opMode(the live state the device reports), notmode(the plant-mode field, Manual=2/Program=1) — both setters.const.py.Tests
25 unit tests added by this PR (the branch additionally carries the maintainer-merged CI suite; combined on the branch: 74 tests + 144 subtests, all green): duration parsing, the N+1 wait with a single retry, the 5s fallback, second-429 raise, the shared
_blocked_untilshort-circuit (no network call inside the window), their async equivalents, the holiday URL/payload/date-format contract, and the R2 GREEN set (payload shape, GREEN→R2 routing, COMFORT direct routing, official enum range, bad-body→ConnectionExceptionparametrized, fresh-login retry). All hermetic, no network.Note:
pyproject.tomlstays at0.19.9(kept clean for the Sonar gate); our deployment installs this from a locally built wheel — happy to rebase onto whatever versioning you prefer.