From 0192bdf2dd8b505f3df04f6d3a8f11f13b9f6ceb Mon Sep 17 00:00:00 2001 From: Walt Howd Date: Tue, 10 Nov 2026 04:41:31 +0000 Subject: [PATCH 1/2] Pass subscription errors to an on_error callback The server ends a subscription with an `error` message when it fails, for example when the vehicle refuses a command the subscription waits on. The web socket only logged those at debug, so a caller waiting on the subscription could only time out. Subscriptions can now take an `on_error` callback that gets the error message; existing callers are unchanged. --- src/rivian/rivian.py | 5 ++++- src/rivian/ws_monitor.py | 29 ++++++++++++++++++++++++----- tests/test_ws_monitor.py | 22 +++++++++++++++++++++- 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/src/rivian/rivian.py b/src/rivian/rivian.py index c9cd86d..c4854de 100644 --- a/src/rivian/rivian.py +++ b/src/rivian/rivian.py @@ -1136,6 +1136,7 @@ async def _start_subscription( payload: dict[str, Any], callback: Callable[[dict[str, Any]], None], description: str, + on_error: Callable[[dict[str, Any]], None] | None = None, ) -> Callable[[], Awaitable[None]] | None: """Connect the web socket if needed and start a subscription. @@ -1146,7 +1147,9 @@ async def _start_subscription( ws_monitor = await self._ws_connect() # Ends early if the connection closes, e.g. when rate limited if await ws_monitor.wait_for_ack() and ( - unsubscribe := await ws_monitor.start_subscription(payload, callback) + unsubscribe := await ws_monitor.start_subscription( + payload, callback, on_error=on_error + ) ): _LOGGER.debug("Subscribed to %s", description) return unsubscribe diff --git a/src/rivian/ws_monitor.py b/src/rivian/ws_monitor.py index 6e6e77e..bf0a339 100644 --- a/src/rivian/ws_monitor.py +++ b/src/rivian/ws_monitor.py @@ -98,8 +98,14 @@ def __init__( self._monitor_task: asyncio.Task | None = None self._receiver_task: asyncio.Task | None = None self._last_received: datetime | None = None + # id -> (callback, payload, error callback) self._subscriptions: dict[ - str, tuple[Callable[[dict[str, Any]], None], dict[str, Any]] + str, + tuple[ + Callable[[dict[str, Any]], None], + dict[str, Any], + Callable[[dict[str, Any]], None] | None, + ], ] = {} @property @@ -211,13 +217,20 @@ async def wait_for_ack(self) -> bool: return self._connection_ack.is_set() async def start_subscription( - self, payload: dict[str, Any], callback: Callable[[dict[str, Any]], None] + self, + payload: dict[str, Any], + callback: Callable[[dict[str, Any]], None], + on_error: Callable[[dict[str, Any]], None] | None = None, ) -> Callable[[], Awaitable[None]] | None: - """Start a subscription.""" + """Start a subscription. + + `on_error` gets the subscription's error messages, which are otherwise + only logged. + """ if not self.connected: return None _id = str(uuid4()) - self._subscriptions[_id] = (callback, payload) + self._subscriptions[_id] = (callback, payload, on_error) await self._subscribe(_id, payload) async def unsubscribe() -> None: @@ -247,7 +260,7 @@ async def _resubscribe_all(self) -> None: except TimeoutError: _LOGGER.error("A timeout occurred while attempting to resubscribe") return - for _id, (_, payload) in self._subscriptions.items(): + for _id, (_, payload, _) in self._subscriptions.items(): await self._subscribe(_id, payload) async def _receiver(self) -> None: @@ -305,6 +318,12 @@ async def _receive(self, websocket: ClientWebSocketResponse[bool]) -> None: _fn(data) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error in a subscription callback") + elif ( + data_type == "error" + and (subscription := self._subscriptions.get(data.get("id"))) + and subscription[2] + ): + subscription[2](data) else: self._log_message(msg) elif msg.type == WSMsgType.ERROR: diff --git a/tests/test_ws_monitor.py b/tests/test_ws_monitor.py index 7f5a4bd..88d7a52 100644 --- a/tests/test_ws_monitor.py +++ b/tests/test_ws_monitor.py @@ -31,6 +31,7 @@ def __init__(self) -> None: self.ping_once_connections = 0 self.connections = 0 self.next_on_subscribe = False + self.error_on_subscribe = False self.url = "" async def handler(self, request: web.Request) -> web.WebSocketResponse: @@ -72,6 +73,10 @@ async def handler(self, request: web.Request) -> web.WebSocketResponse: data = msg.json() if self.next_on_subscribe and data.get("type") == "subscribe": await ws.send_json({"id": data["id"], "type": "next"}) + if self.error_on_subscribe and data.get("type") == "subscribe": + await ws.send_json( + {"id": data["id"], "type": "error", "payload": [{}]} + ) return ws @@ -159,7 +164,7 @@ async def fake_sleep(delay: float) -> None: def add_subscription(monitor: WebSocketMonitor) -> None: """Give the monitor a subscription to resume, so it keeps reconnecting.""" - monitor._subscriptions["sub"] = (lambda _: None, {"query": "subscription"}) + monitor._subscriptions["sub"] = (lambda _: None, {"query": "subscription"}, None) async def wait_for(condition: Any, timeout: float = 5) -> None: @@ -594,3 +599,18 @@ async def test_monitor_stops_when_the_session_closes( await wait_for(monitor.monitor.done) assert server.connections == 1 assert not [r for r in caplog.records if r.levelname == "ERROR"] + + +async def test_subscription_errors_reach_on_error( + server: FakeServer, monitor: WebSocketMonitor +) -> None: + """A subscription's error message goes to its on_error, if it has one.""" + server.error_on_subscribe = True + await monitor.new_connection(start_monitor=True) + await wait_for(lambda: monitor.connection_ack.is_set()) + errors: list[dict[str, Any]] = [] + await monitor.start_subscription({"query": "a"}, lambda _: None, errors.append) + await monitor.start_subscription({"query": "b"}, lambda _: None) + await wait_for(lambda: errors) + assert errors[0]["type"] == "error" + assert monitor.connected From e8fe7d97e8eb1c4e59ba5e81f4f0da88a2a4c3f7 Mon Sep 17 00:00:00 2001 From: Walt Howd Date: Sun, 15 Nov 2026 18:17:39 +0000 Subject: [PATCH 2/2] Guard the on_error callback like the next callback An `on_error` that raised escaped the receive loop and ended the receiver task. Both callbacks now run through `_run_callback`, which logs a failure instead of raising and awaits coroutine callbacks. --- src/rivian/ws_monitor.py | 28 ++++++++++++++++++---------- tests/test_ws_monitor.py | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/rivian/ws_monitor.py b/src/rivian/ws_monitor.py index bf0a339..dd2578d 100644 --- a/src/rivian/ws_monitor.py +++ b/src/rivian/ws_monitor.py @@ -55,6 +55,22 @@ class _Backoff: rate_limited: bool = False # whether the backoff until retry_at is a rate limit +async def _run_callback( + callback: Callable[[dict[str, Any]], None], data: dict[str, Any] +) -> None: + """Run a subscription callback, logging instead of raising if it fails. + + A failing callback shouldn't take the connection down. + """ + try: + if inspect.iscoroutinefunction(callback): + await callback(data) + else: + callback(data) + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Error in a subscription callback") + + class WebSocketMonitor: """Web socket monitor for a vehicle.""" @@ -309,21 +325,13 @@ async def _receive(self, websocket: ClientWebSocketResponse[bool]) -> None: elif data_type == "next": self._reset_backoff() if (_id := data.get("id")) in self._subscriptions: - _fn = self._subscriptions[_id][0] - # A failing callback shouldn't take the connection down - try: - if inspect.iscoroutinefunction(_fn): - await _fn(data) - else: - _fn(data) - except Exception: # pylint: disable=broad-except - _LOGGER.exception("Error in a subscription callback") + await _run_callback(self._subscriptions[_id][0], data) elif ( data_type == "error" and (subscription := self._subscriptions.get(data.get("id"))) and subscription[2] ): - subscription[2](data) + await _run_callback(subscription[2], data) else: self._log_message(msg) elif msg.type == WSMsgType.ERROR: diff --git a/tests/test_ws_monitor.py b/tests/test_ws_monitor.py index 88d7a52..3ea5bbe 100644 --- a/tests/test_ws_monitor.py +++ b/tests/test_ws_monitor.py @@ -614,3 +614,26 @@ async def test_subscription_errors_reach_on_error( await wait_for(lambda: errors) assert errors[0]["type"] == "error" assert monitor.connected + + +async def test_failing_on_error_keeps_connection( + server: FakeServer, + monitor: WebSocketMonitor, + caplog: pytest.LogCaptureFixture, +) -> None: + """An on_error that raises is logged, and later messages still arrive.""" + server.error_on_subscribe = True + await monitor.new_connection(start_monitor=True) + await wait_for(lambda: monitor.connection_ack.is_set()) + + def failing(_: dict[str, Any]) -> None: + raise ValueError("on_error failed") + + errors: list[dict[str, Any]] = [] + await monitor.start_subscription({"query": "a"}, lambda _: None, failing) + await monitor.start_subscription({"query": "b"}, lambda _: None, errors.append) + await wait_for(lambda: errors) + + assert "Error in a subscription callback" in caplog.text + assert monitor.connected + assert server.connections == 1