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
20 changes: 20 additions & 0 deletions pyintesishome/intesisbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ def __init__(
self._receive_task: asyncio.Task = None
self._error_message = None
self._last_successful_update = None
# Set when the API rejects the credentials themselves, as opposed
# to failing for a reason a retry might survive. Consumers read it
# to start a reauthentication flow; Home Assistant turns it into
# ConfigEntryAuthFailed, whose reload is what clears it.
self._authentication_failed = False
# How long state cached from the last successful update stays
# trustworthy. Governs is_available, which is what consumers should
# gate entity availability on. Subclasses that know their own update
Expand Down Expand Up @@ -675,6 +680,10 @@ def is_available(self) -> bool:
is_connected flap, so long as HTTP polling is still getting
through.
"""
if self._authentication_failed:
# Cached state may still be inside _stale_after, but nothing
# is going to refresh it until the credentials are fixed.
return False
if self._connected:
return True
if self._last_successful_update is None:
Expand All @@ -684,6 +693,17 @@ def is_available(self) -> bool:
).total_seconds()
return elapsed < self._stale_after

@property
def authentication_failed(self) -> bool:
"""Returns true if the API rejected the credentials.

Distinct from is_available being false: this one will not fix
itself. The controller has to be rebuilt with working credentials,
which for Home Assistant means a reauth flow and a config entry
reload.
"""
return self._authentication_failed

@property
def connection_retries(self) -> int:
"""Returns the number of connection retries."""
Expand Down
59 changes: 55 additions & 4 deletions pyintesishome/intesishome.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ class _PendingSet(NamedTuple):
future: asyncio.Future


# errorCodes from /api.php/get/control that mean the credentials
# themselves were rejected, as opposed to a failure a retry might survive.
# Observed: 3 / WRONG_USERNAME_PASSWORD. The full table is not published,
# so anything not listed here is treated as transient - see
# _raise_api_error for why that is the safe direction to be wrong in.
AUTH_ERROR_CODES = frozenset({3})

_LOGGER = logging.getLogger("pyintesishome")

# The official app builds its socket frames with String.format, so they carry
Expand Down Expand Up @@ -281,7 +288,12 @@ async def _run_poller(self):
try:
await self.poll_status(sendcallback=True)
except IHAuthenticationError as exc:
# Rejected credentials will not fix themselves.
# Rejected credentials will not fix themselves, and
# _raise_api_error only classifies a failure this way
# when the API named the credentials. Retiring is safe
# because authentication_failed is now set: the
# consumer sees an unavailable controller, reauthenticates,
# and rebuilds this object with a fresh poller.
_LOGGER.error(
"Authentication with %s was rejected while polling; "
"stopping: %s",
Expand Down Expand Up @@ -469,6 +481,45 @@ async def poll_status(self, sendcallback=False):
async with self._poll_lock:
return await self._poll_status(sendcallback)

def _raise_api_error(self, status_response):
"""Turn an errorCode response into the exception it deserves.

The cloud answers every failure the same way - HTTP 200 carrying
an errorCode - so this is the only place the two kinds can be told
apart, and getting it wrong is expensive in both directions. Every
errorCode used to raise IHAuthenticationError, which retires the
poller permanently, so one transient error from the backend left
the controller dead until the consumer restarted.

Only the codes known to mean rejected credentials are treated as
such; the rest default to transient. That asymmetry is deliberate,
because the full code table is not published: guessing transient
costs one poll interval and a retry, while guessing auth costs the
user a controller that has stopped polling for good. An unknown
code logs the number it saw, so adding it here is a one-line
change once its meaning is known.
"""
self._error_message = status_response.get("errorMessage")
code = status_response.get("errorCode")

if code in AUTH_ERROR_CODES:
_LOGGER.error(
"%s rejected the credentials (code %s): %s",
self._device_type,
code,
self._error_message,
)
self._authentication_failed = True
raise IHAuthenticationError(self._error_message)

_LOGGER.warning(
"%s returned error code %s: %s. Treating it as transient",
self._device_type,
code,
self._error_message,
)
raise IHConnectionError(self._error_message)

def _apply_config(self, config):
"""Store the socket address and token, and register known devices."""
if not config:
Expand Down Expand Up @@ -560,13 +611,13 @@ async def _poll_status(self, sendcallback=False):

if status_response:
if "errorCode" in status_response:
self._error_message = status_response["errorMessage"]
_LOGGER.error("Error from API %s", repr(self._error_message))
raise IHAuthenticationError()
self._raise_api_error(status_response)

self._apply_config(status_response.get("config"))
updated_devices = self._apply_statuses(status_response)
self._error_message = None
# Credentials that work now supersede an earlier rejection.
self._authentication_failed = False

# Only an answer that actually carried device state counts as a
# successful update. When every device on the account is
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

setup(
name="pyintesishome",
version="2.4.0",
version="2.5.0",
description="A python3 library for running asynchronus communications with IntesisHome Smart AC Controllers",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
112 changes: 112 additions & 0 deletions tests/test_pyintesishome.py
Original file line number Diff line number Diff line change
Expand Up @@ -1104,3 +1104,115 @@ async def test_stop_clears_the_cached_portal_login(
# stop() disposed of, which used to raise AttributeError.
assert await cloud_controller._set_value(MOCK_DEVICE_ID, 9, 220) is True
assert cloud_controller._portal_session is not None


@pytest.mark.asyncio
async def test_transient_api_error_does_not_retire_the_poller(cloud_controller):
"""The cloud reports every failure as a 200 with an errorCode, so a
backend hiccup used to be indistinguishable from bad credentials - and
the poller retired on both, leaving the controller dead until the
consumer restarted."""
error_payload = {"errorCode": 20, "errorMessage": "INTERNAL_SERVER_ERROR"}

with patch.object(
cloud_controller._web_session,
"post",
return_value=_json_response(error_payload),
):
with pytest.raises(IHConnectionError):
await cloud_controller.poll_status()

assert cloud_controller.authentication_failed is False
# A transient error is one the poller rides out, so it must still be
# running and must not have declared an unrecoverable failure.
assert not cloud_controller._poll_task.done()
assert cloud_controller.error_message == "INTERNAL_SERVER_ERROR"


@pytest.mark.asyncio
async def test_rejected_credentials_are_reported_as_authentication_failure(
cloud_controller,
):
"""Bad credentials are the one failure a retry cannot survive, so they
have to reach the consumer as something it can act on rather than as
another unavailable controller."""
# Shape taken from a real /api.php/get/control response to a bad
# password.
error_payload = {"errorCode": 3, "errorMessage": "WRONG_USERNAME_PASSWORD"}

with patch.object(
cloud_controller._web_session,
"post",
return_value=_json_response(error_payload),
):
with pytest.raises(IHAuthenticationError):
await cloud_controller.poll_status()

assert cloud_controller.authentication_failed is True
# Cached state is still fresh, but nothing will refresh it again until
# the credentials are fixed, so the controller must not claim to be
# available on the strength of it.
assert cloud_controller.is_available is False


@pytest.mark.asyncio
async def test_a_working_poll_clears_an_earlier_authentication_failure(
cloud_controller,
):
"""Reauthentication normally rebuilds the controller, but credentials
can also start working again on their own (an account restored at the
far end). A stale flag would pin the controller unavailable forever."""
cloud_controller._authentication_failed = True
assert cloud_controller.is_available is False

await cloud_controller.poll_status()

assert cloud_controller.authentication_failed is False
assert cloud_controller.is_available is True


@pytest.mark.asyncio
async def test_credential_rejection_retires_the_poller(cloud_controller):
"""Retiring is still right for real credential failures - it stops the
controller hammering the API with a password it knows is wrong."""
error_payload = {"errorCode": 3, "errorMessage": "WRONG_USERNAME_PASSWORD"}

with patch.object(
cloud_controller._web_session,
"post",
return_value=_json_response(error_payload),
):
cloud_controller._poll_interval = 0.05
await cloud_controller._cancel_task_if_exists(cloud_controller._poll_task)
cloud_controller._poll_task = None
cloud_controller._start_poller()

await wait_until(lambda: cloud_controller._poll_task.done(), timeout=2.0)

assert cloud_controller.authentication_failed is True
assert cloud_controller.is_available is False


@pytest.mark.asyncio
async def test_error_classification_reads_the_code_not_the_message(cloud_controller):
"""errorMessage is a human-facing label and not something to branch
on. An unrecognised code stays transient however much its text sounds
like an auth failure, because retiring the poller in error is the
expensive mistake and only the code can be checked reliably."""
# Synthetic: no such response has been observed. It exists to pin the
# classification to the code, so a future change cannot quietly go
# back to matching text.
error_payload = {
"errorCode": 99,
"errorMessage": "PASSWORD_SERVICE_TEMPORARILY_UNAVAILABLE",
}

with patch.object(
cloud_controller._web_session,
"post",
return_value=_json_response(error_payload),
):
with pytest.raises(IHConnectionError):
await cloud_controller.poll_status()

assert cloud_controller.authentication_failed is False
Loading