diff --git a/teslemetry_stream/vehicle.py b/teslemetry_stream/vehicle.py index 0d1eef1..eee88ec 100644 --- a/teslemetry_stream/vehicle.py +++ b/teslemetry_stream/vehicle.py @@ -98,6 +98,10 @@ def __init__(self, stream: TeslemetryStream, vin: str): # listeners (e.g. HA integration setup) discovering an unpopulated # vehicle joins one GET instead of each starting its own. self._populate_flight = None + # Callbacks told when the server refuses a config update. + self._config_refused_listeners: dict[ + object, Callable[[str, str | None], None] + ] = {} # Registered from birth, not lazily, so no connection can ever # predate this listener and miss a config event. Safe outside a # running loop: `internal=True` makes async_add_listener's @@ -254,8 +258,16 @@ async def _flush(self) -> None: if error := data.get("error"): LOGGER.error( - "Error updating streaming config for %s: %s", self.vin, error + "Error updating streaming config for %s: %s", + self.vin, + data.get("error_description") or error, ) + description = data.get("error_description") + if error == "streaming_allowance_exceeded": + # The account is over its streaming allowance, so replaying + # this config on the next trigger would be refused again. + self._config.clear() + self._notify_config_refused(str(error), description) return ignored = data.get("ignoredFields") or [] @@ -279,6 +291,36 @@ async def _flush(self) -> None: self.fields = {**self.fields, **applied} self._config.clear() + def _notify_config_refused(self, error: str, description: str | None) -> None: + """Tell each config-refused listener; one failing must not stop the rest.""" + for callback in list(self._config_refused_listeners.values()): + try: + callback(error, description) + except Exception: + LOGGER.exception( + "Config refused listener failed for %s", self.vin + ) + + def listen_config_refused( + self, callback: Callable[[str, str | None], None] + ) -> Callable[[], None]: + """Call back with (error, description) when the server refuses a config. + + Fires for every error-shaped response to a config update, for example + ``streaming_allowance_exceeded``; the caller filters on ``error``. + Returns a function that removes the listener. + """ + # Each registration has its own identity, so registering the same + # callback twice gives two independent removers, and a repeated + # remove() only ever removes its own registration. + key = object() + self._config_refused_listeners[key] = callback + + def remove() -> None: + self._config_refused_listeners.pop(key, None) + + return remove + async def _patch_with_bounded_retry( self, config: dict[str, Any] ) -> dict[str, Any] | None: diff --git a/tests/test_config_update.py b/tests/test_config_update.py index f44d7e0..dc651e7 100644 --- a/tests/test_config_update.py +++ b/tests/test_config_update.py @@ -10,7 +10,7 @@ import logging from typing import Any -from teslemetry_stream.vehicle import TeslemetryStreamVehicle +from teslemetry_stream.vehicle import LOGGER, TeslemetryStreamVehicle VIN_A = "TESTVIN0000000001" VIN_B = "TESTVIN0000000002" @@ -67,6 +67,17 @@ def emit(self, record: logging.LogRecord) -> None: self.messages.append(record.getMessage()) +class CaptureErrors(logging.Handler): + """Collect formatted ERROR records emitted by the library.""" + + def __init__(self) -> None: + super().__init__(level=logging.ERROR) + self.messages: list[str] = [] + + def emit(self, record: logging.LogRecord) -> None: + self.messages.append(record.getMessage()) + + def check(label: str, ok: bool, detail: str = "") -> bool: print(f"{label:<56} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}") return ok @@ -191,6 +202,102 @@ async def main() -> None: ) ) + # A streaming allowance refusal logs the description and drops the batch. + over = { + "response": None, + "error": "streaming_allowance_exceeded", + "error_description": "This streaming configuration uses 120% of your allowance", + } + vehicle = make_vehicle(VIN_A, [over]) + captured = CaptureErrors() + LOGGER.addHandler(captured) + try: + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + finally: + LOGGER.removeHandler(captured) + results.append( + check( + "allowance refusal logs the error description", + any("120% of your allowance" in m for m in captured.messages) + and not any("streaming_allowance_exceeded" in m for m in captured.messages), + f"logged {captured.messages}", + ) + ) + results.append( + check( + "allowance refusal clears the pending config", + vehicle._config == {} and vehicle.fields == {}, + f"pending {vehicle._config}, fields {sorted(vehicle.fields)}", + ) + ) + + # The config-refused listener gets (error, description) once; a removed + # listener is not called; a raising listener does not block the others. + vehicle = make_vehicle(VIN_A, [over, FAILED, over]) + calls: list[tuple[str, str | None]] = [] + later: list[tuple[str, str | None]] = [] + + def boom(error: str, description: str | None) -> None: + raise RuntimeError("listener bug") + + vehicle.listen_config_refused(boom) + vehicle.listen_config_refused(lambda e, d: calls.append((e, d))) + remove_later = vehicle.listen_config_refused(lambda e, d: later.append((e, d))) + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + results.append( + check( + "config-refused listener called once with error and description", + calls == [(over["error"], over["error_description"])] + and later == calls, + f"calls {calls}", + ) + ) + remove_later() + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + results.append( + check( + "removed listener not called; other errors reach listeners", + len(later) == 1 and calls[-1] == ("upstream internal error", None), + f"calls {calls}, later {later}", + ) + ) + vehicle = make_vehicle(VIN_A, [ACCEPTED]) + seen: list[Any] = [] + vehicle.listen_config_refused(lambda e, d: seen.append(e)) + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + results.append(check("success does not call the listener", seen == [])) + + # The same callback registered twice has independent, idempotent removers. + vehicle = make_vehicle(VIN_A, [over, over]) + twice: list[str] = [] + + def same(error: str, description: str | None) -> None: + twice.append(error) + + remove_first = vehicle.listen_config_refused(same) + vehicle.listen_config_refused(same) + remove_first() + remove_first() + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + results.append( + check( + "repeated remove only removes its own registration", + len(twice) == 1, + f"calls {twice}", + ) + ) + + # Any other error keeps the pending config for the next explicit trigger. + vehicle = make_vehicle(VIN_A, [FAILED]) + await vehicle.update_config({"fields": {"BatteryLevel": None}}) + results.append( + check( + "other errors keep the pending config", + vehicle._config == {"fields": {"BatteryLevel": None}}, + f"pending {vehicle._config}", + ) + ) + # Pending config must not be shared between vehicles. first = make_vehicle(VIN_A, [FAILED]) second = make_vehicle(VIN_B, [ACCEPTED])