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..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.""" @@ -98,8 +114,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 +233,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 +276,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: @@ -296,15 +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] + ): + 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 7f5a4bd..3ea5bbe 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,41 @@ 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 + + +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