diff --git a/pyhilo/signalr.py b/pyhilo/signalr.py index 74b85bd..40cc815 100644 --- a/pyhilo/signalr.py +++ b/pyhilo/signalr.py @@ -4,6 +4,8 @@ import asyncio from collections import defaultdict +from collections.abc import Sequence +import contextlib from dataclasses import dataclass, field from datetime import datetime from enum import IntEnum @@ -11,6 +13,7 @@ from typing import Any, Callable, Optional, Tuple from pysignalr.client import SignalRClient +from pysignalr.messages import Message from pyhilo.const import LOG @@ -75,6 +78,9 @@ class SignalRHub: ``disconnect()`` — cancel the task awaiting ``run()`` to stop cleanly """ + # Azure SignalR sends PingMessage every ~15s; 60s catches silent dead links. + _SERVER_TIMEOUT: float = 60.0 + def __init__( self, negotiate_callback: Callable[[], Any], @@ -86,6 +92,7 @@ def __init__( self._negotiate = negotiate_callback self._client: Optional[SignalRClient] = None self._task: Optional[asyncio.Task] = None + self._connected: bool = False self._connect_callbacks: list[Callable[..., Any]] = [] self._disconnect_callbacks: list[Callable[..., Any]] = [] self._event_callbacks: list[Callable[..., Any]] = [] @@ -96,8 +103,8 @@ def __init__( @property def connected(self) -> bool: - """Return True if a client is currently running.""" - return self._client is not None + """Return True if the SignalR connection is currently open.""" + return self._connected def add_connect_callback(self, callback: Callable[..., Any]) -> Callable[..., None]: """Register a callback to fire after a successful connection.""" @@ -131,8 +138,9 @@ def remove() -> None: async def run(self) -> None: """Negotiate, create the SignalR client, and block until it disconnects. - Raises on hard errors (auth failure, negotiation failure, etc.). - Returns normally on a clean server-side disconnect. + Raises on hard errors (auth failure, negotiation failure, server timeout, + or close before open). Returns normally on a clean server-side + disconnect after the connection has opened. """ azure_url, access_token = await self._negotiate() LOG.info("SignalRHub: negotiate succeeded, connecting to %s", azure_url) @@ -142,12 +150,22 @@ async def run(self) -> None: None, ssl.create_default_context ) - self._client = SignalRClient( + client = SignalRClient( url=azure_url, headers={"Authorization": f"Bearer {access_token}"}, retry_count=0, ssl=ssl_context, ) + self._client = client + + activity_event = asyncio.Event() + orig_callback = client._transport._callback + + async def _tracked_on_message(message: Message) -> None: + activity_event.set() + await orig_callback(message) + + client._transport._callback = _tracked_on_message # Install catch-all handler — must be set AFTER __init__ and BEFORE run() (Lesson ❹) hub_self = self @@ -171,19 +189,78 @@ async def _handler(arguments: Any) -> None: self_dict[target] = [_handler] return [_handler] - self._client._message_handlers = _CatchAllDict(list) + client._message_handlers = _CatchAllDict(list) + + was_connected = False + server_closed = False + server_timed_out = False + watchdog_task: asyncio.Task[None] | None = None + client_task: asyncio.Task[None] + + def _on_timeout() -> None: + nonlocal server_timed_out + server_timed_out = True + + async def _on_open() -> None: + nonlocal was_connected, watchdog_task + self._connected = True + was_connected = True + watchdog_task = asyncio.create_task( + self._watch_server_timeout(activity_event, client_task, _on_timeout) + ) + LOG.info("SignalRHub: connected") + await self._fire_callbacks(self._connect_callbacks, "connect") + + async def _on_close() -> None: + nonlocal server_closed + self._connected = False + # pysignalr's WebsocketTransport loops forever in websockets.connect() with + # the already-negotiated URL/token; cancel client_task so run() exits + # and callers can re-negotiate a fresh Azure SignalR token. + server_closed = True + if not client_task.done(): + client_task.cancel() # Wire connect/disconnect/error hooks - self._client.on_open(self._on_open) - self._client.on_close(self._on_close) - self._client.on_error(self._on_error) + client.on_open(_on_open) + client.on_close(_on_close) + client.on_error(self._on_error) self._task = asyncio.current_task() + client_task = asyncio.create_task(client.run()) try: - await self._client.run() + await client_task + except asyncio.CancelledError: + current_task = asyncio.current_task() + outer_cancelled = current_task is not None and current_task.cancelling() > 0 + if not outer_cancelled: + if server_closed: + if was_connected: + return + raise ConnectionError( + "SignalR connection closed before open" + ) from None + if server_timed_out: + raise TimeoutError( + f"SignalR server timeout ({self._SERVER_TIMEOUT}s without messages)" + ) from None + raise finally: + self._connected = False + if watchdog_task is not None: + if not watchdog_task.done(): + watchdog_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await watchdog_task + if not client_task.done(): + client_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await client_task self._client = None self._task = None + if was_connected: + LOG.info("SignalRHub: disconnected") + await self._fire_callbacks(self._disconnect_callbacks, "disconnect") async def invoke(self, method: str, args: list[Any]) -> None: """Invoke a hub method on the server. @@ -191,7 +268,7 @@ async def invoke(self, method: str, args: list[Any]) -> None: :param method: Hub method name :param args: Positional arguments for the method """ - if self._client is None: + if not self._connected or self._client is None: LOG.warning("SignalRHub: invoke(%s) called while disconnected", method) return LOG.debug("SignalRHub: invoke method=%s args=%s", method, args) @@ -220,25 +297,41 @@ async def disconnect(self) -> None: # Internal pysignalr hooks # ------------------------------------------------------------------ - async def _on_open(self) -> None: - LOG.info("SignalRHub: connected") - for cb in self._connect_callbacks: + async def _fire_callbacks( + self, callbacks: Sequence[Callable[..., object]], label: str + ) -> None: + for cb in list(callbacks): try: result = cb() if asyncio.iscoroutine(result): await result except Exception as exc: - LOG.error("SignalRHub: connect callback error: %s", exc) + LOG.error("SignalRHub: %s callback error: %s", label, exc) - async def _on_close(self) -> None: - LOG.info("SignalRHub: disconnected") - for cb in self._disconnect_callbacks: + async def _watch_server_timeout( + self, + activity_event: asyncio.Event, + client_task: asyncio.Task[None], + on_timeout: Callable[[], None], + ) -> None: + while not client_task.done(): + activity_event.clear() try: - result = cb() - if asyncio.iscoroutine(result): - await result - except Exception as exc: - LOG.error("SignalRHub: disconnect callback error: %s", exc) + await asyncio.wait_for( + activity_event.wait(), timeout=self._SERVER_TIMEOUT + ) + except TimeoutError: + if not self._connected: + return + LOG.warning( + "SignalRHub: server timeout (%ss without inbound messages)", + self._SERVER_TIMEOUT, + ) + self._connected = False + on_timeout() + if not client_task.done(): + client_task.cancel() + return async def _on_error(self, message: str) -> None: LOG.error("SignalRHub: error: %s", message) diff --git a/tests/test_signalr.py b/tests/test_signalr.py index 1effeab..96af4a6 100644 --- a/tests/test_signalr.py +++ b/tests/test_signalr.py @@ -1,5 +1,12 @@ +from __future__ import annotations + import asyncio +from collections.abc import AsyncIterator, Awaitable, Callable +import contextlib +import ssl +from pysignalr.client import SignalRClient +from pysignalr.messages import Message, PingMessage import pytest from pyhilo.signalr import SignalRHub @@ -9,53 +16,113 @@ async def _fake_negotiate() -> tuple[str, str]: return ("wss://example.invalid/hub", "fake-token") -@pytest.mark.asyncio -async def test_disconnect_cancels_running_task(monkeypatch: pytest.MonkeyPatch) -> None: - """disconnect() must cancel the task running run(), not call client.stop(). +class _FakeTransport: + def __init__(self, callback: Callable[[Message], Awaitable[object]]) -> None: + self._callback = callback - pysignalr.SignalRClient has no stop()/close() method -- its run() - coroutine blocks until cancelled. Calling a nonexistent stop() method - raised AttributeError on every Home Assistant shutdown. - """ - client_connected = asyncio.Event() +class _FakeSignalRClient: + on_run: Callable[[_FakeSignalRClient], Awaitable[None]] | None = None + instances: list[_FakeSignalRClient] = [] + + def __init__( + self, + url: str, + headers: dict[str, str] | None = None, + retry_count: int = 0, + ssl: ssl.SSLContext | None = None, + ) -> None: + self._message_handlers: dict[str, list[Callable[..., Awaitable[None]]]] = {} + self.open_callback: Callable[[], Awaitable[None]] | None = None + self.close_callback: Callable[[], Awaitable[None]] | None = None + self.error_callback: Callable[[str], Awaitable[None]] | None = None + self.sent: list[tuple[str, list[object]]] = [] + self._transport = _FakeTransport(self._default_message_callback) + self.__class__.instances.append(self) - class FakeSignalRClient: - def __init__(self, *args: object, **kwargs: object) -> None: - self._message_handlers: dict = {} + async def _default_message_callback(self, message: Message) -> None: + return None - def on_open(self, callback: object) -> None: - pass + def on_open(self, callback: Callable[[], Awaitable[None]]) -> None: + self.open_callback = callback - def on_close(self, callback: object) -> None: - pass + def on_close(self, callback: Callable[[], Awaitable[None]]) -> None: + self.close_callback = callback - def on_error(self, callback: object) -> None: - pass + def on_error(self, callback: Callable[[str], Awaitable[None]]) -> None: + self.error_callback = callback - async def run(self) -> None: - # Block forever, like the real pysignalr transport's reconnect loop. - client_connected.set() - await asyncio.Event().wait() + async def send(self, method: str, arguments: list[object]) -> None: + self.sent.append((method, arguments)) - monkeypatch.setattr("pyhilo.signalr.SignalRClient", FakeSignalRClient) + async def run(self) -> None: + runner = self.__class__.on_run + assert runner is not None + await runner(self) + + +def _patch_client( + monkeypatch: pytest.MonkeyPatch, + runner: Callable[[_FakeSignalRClient], Awaitable[None]], +) -> list[_FakeSignalRClient]: + clients: list[_FakeSignalRClient] = [] + monkeypatch.setattr(_FakeSignalRClient, "instances", clients) + monkeypatch.setattr(_FakeSignalRClient, "on_run", runner) + monkeypatch.setattr("pyhilo.signalr.SignalRClient", _FakeSignalRClient) monkeypatch.setattr("pyhilo.signalr.ssl.create_default_context", lambda: object()) + return clients + + +async def _server_close_runner(client: _FakeSignalRClient) -> None: + assert client.open_callback is not None + assert client.close_callback is not None + await client.open_callback() + await client.close_callback() + # Simulate pysignalr's WebsocketTransport looping on stale credentials. + await asyncio.Event().wait() + + +async def _silent_runner(client: _FakeSignalRClient) -> None: + assert client.open_callback is not None + await client.open_callback() + await asyncio.Event().wait() + + +@contextlib.asynccontextmanager +async def _running_hub(hub: SignalRHub) -> AsyncIterator[asyncio.Task[None]]: + task = asyncio.create_task(hub.run()) + try: + yield task + finally: + await hub.disconnect() + +@pytest.mark.asyncio +async def test_disconnect_cancels_running_task( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """disconnect() cancels the task awaiting run(), updates connected, and notifies once.""" + client_connected = asyncio.Event() + disconnects = 0 + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, _silent_runner) hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_connect_callback(client_connected.set) + hub.add_disconnect_callback(on_disconnect) task = asyncio.create_task(hub.run()) - # Wait until run() has reached the blocking await inside - # FakeSignalRClient.run() (negotiation and the executor hop for the SSL - # context are real awaits, so a fixed number of sleep(0)s is fragile). await asyncio.wait_for(client_connected.wait(), timeout=5) assert hub.connected - # Must not raise -- this previously called the nonexistent - # SignalRClient.stop() and raised AttributeError. await hub.disconnect() assert task.done() assert not hub.connected + assert disconnects == 1 @pytest.mark.asyncio @@ -64,3 +131,267 @@ async def test_disconnect_without_a_running_task_is_a_no_op() -> None: hub = SignalRHub(negotiate_callback=_fake_negotiate) await hub.disconnect() assert not hub.connected + + +@pytest.mark.asyncio +async def test_connected_is_false_until_on_open_fires( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """hub.connected remains False until pysignalr invokes on_open.""" + before_open = asyncio.Event() + proceed_open = asyncio.Event() + after_open = asyncio.Event() + connected_in_callback: list[bool] = [] + + async def runner(client: _FakeSignalRClient) -> None: + before_open.set() + await proceed_open.wait() + assert client.open_callback is not None + await client.open_callback() + after_open.set() + await asyncio.Event().wait() + + _patch_client(monkeypatch, runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_connect_callback(lambda: connected_in_callback.append(hub.connected)) + async with _running_hub(hub): + await asyncio.wait_for(before_open.wait(), timeout=5) + assert not hub.connected + + proceed_open.set() + await asyncio.wait_for(after_open.wait(), timeout=5) + assert hub.connected + assert connected_in_callback == [True] + + +@pytest.mark.asyncio +async def test_invoke_is_ignored_while_not_connected( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """invoke() does not call client.send() before on_open marks the hub connected.""" + before_open = asyncio.Event() + + async def runner(_client: _FakeSignalRClient) -> None: + before_open.set() + await asyncio.Event().wait() + + clients = _patch_client(monkeypatch, runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + async with _running_hub(hub): + await asyncio.wait_for(before_open.wait(), timeout=5) + await hub.invoke("SubscribeToLocation", [42]) + + assert len(clients) == 1 + assert clients[0].sent == [] + + +@pytest.mark.asyncio +async def test_invoke_forwards_when_connected( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """invoke() delegates to client.send() once on_open has fired.""" + opened = asyncio.Event() + + clients = _patch_client(monkeypatch, _silent_runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_connect_callback(opened.set) + async with _running_hub(hub): + await asyncio.wait_for(opened.wait(), timeout=5) + await hub.invoke("SubscribeToLocation", [42]) + + assert len(clients) == 1 + assert clients[0].sent == [("SubscribeToLocation", [42])] + + +@pytest.mark.asyncio +async def test_on_close_exits_run_cleanly_and_fires_disconnect_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Server close exits hub.run() cleanly even if pysignalr keeps retrying afterwards.""" + disconnects = 0 + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, _server_close_runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_disconnect_callback(on_disconnect) + + await asyncio.wait_for(hub.run(), timeout=5) + + assert not hub.connected + assert disconnects == 1 + + +@pytest.mark.asyncio +async def test_on_close_before_open_raises_connection_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Server close before on_open raises ConnectionError so callers back off.""" + disconnects = 0 + + async def runner(client: _FakeSignalRClient) -> None: + assert client.close_callback is not None + await client.close_callback() + await asyncio.Event().wait() + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_disconnect_callback(on_disconnect) + + with pytest.raises(ConnectionError, match="closed before open"): + await asyncio.wait_for(hub.run(), timeout=5) + + assert not hub.connected + assert disconnects == 0 + + +@pytest.mark.asyncio +async def test_client_error_after_open_marks_disconnected_and_notifies_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A client failure after open propagates while cleaning up and firing disconnect once.""" + disconnects = 0 + + async def runner(client: _FakeSignalRClient) -> None: + assert client.open_callback is not None + await client.open_callback() + raise RuntimeError("server close") + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_disconnect_callback(on_disconnect) + + with pytest.raises(RuntimeError, match="server close"): + await hub.run() + + assert not hub.connected + assert disconnects == 1 + + +@pytest.mark.asyncio +async def test_client_error_before_open_does_not_fire_disconnect( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failure before on_open must not trigger disconnect callbacks.""" + disconnects = 0 + + async def runner(_client: _FakeSignalRClient) -> None: + raise RuntimeError("auth failed") + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, runner) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_disconnect_callback(on_disconnect) + + with pytest.raises(RuntimeError, match="auth failed"): + await hub.run() + + assert not hub.connected + assert disconnects == 0 + + +@pytest.mark.asyncio +async def test_server_timeout_aborts_silent_connection( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A silent connection raises TimeoutError after _SERVER_TIMEOUT and notifies once.""" + disconnects = 0 + + def on_disconnect() -> None: + nonlocal disconnects + disconnects += 1 + + _patch_client(monkeypatch, _silent_runner) + monkeypatch.setattr(SignalRHub, "_SERVER_TIMEOUT", 0.05) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + hub.add_disconnect_callback(on_disconnect) + + with pytest.raises(TimeoutError): + await asyncio.wait_for(hub.run(), timeout=5) + + assert not hub.connected + assert disconnects == 1 + + +@pytest.mark.asyncio +async def test_inbound_messages_reset_server_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Inbound SignalR messages (including PingMessage) reset the keepalive deadline.""" + keepalives_done = asyncio.Event() + + async def runner(client: _FakeSignalRClient) -> None: + assert client.open_callback is not None + await client.open_callback() + for _ in range(5): + await asyncio.sleep(0.025) + await client._transport._callback(PingMessage()) + keepalives_done.set() + await asyncio.Event().wait() + + _patch_client(monkeypatch, runner) + monkeypatch.setattr(SignalRHub, "_SERVER_TIMEOUT", 0.08) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + async with _running_hub(hub) as task: + await asyncio.wait_for(keepalives_done.wait(), timeout=5) + assert hub.connected + assert not task.done() + + +@pytest.mark.parametrize( + ("first_runner", "expected_first_exc"), + [ + pytest.param( + _server_close_runner, + contextlib.nullcontext(), + id="after-server-close", + ), + pytest.param( + _silent_runner, + pytest.raises(TimeoutError), + id="after-server-timeout", + ), + ], +) +@pytest.mark.asyncio +async def test_run_resets_state_across_reconnect_cycles( + monkeypatch: pytest.MonkeyPatch, + first_runner: Callable[[_FakeSignalRClient], Awaitable[None]], + expected_first_exc: contextlib.AbstractContextManager[object], +) -> None: + """Subsequent run() calls on the same SignalRHub reset close/timeout state cleanly.""" + reconnected = asyncio.Event() + monkeypatch.setattr(SignalRHub, "_SERVER_TIMEOUT", 0.05) + hub = SignalRHub(negotiate_callback=_fake_negotiate) + + _patch_client(monkeypatch, first_runner) + with expected_first_exc: + await asyncio.wait_for(hub.run(), timeout=5) + assert not hub.connected + + _patch_client(monkeypatch, _silent_runner) + hub.add_connect_callback(reconnected.set) + async with _running_hub(hub): + await asyncio.wait_for(reconnected.wait(), timeout=5) + assert hub.connected + + +@pytest.mark.asyncio +async def test_pysignalr_exposes_transport_callback() -> None: + """Guard SignalRHub's assumption that pysignalr exposes _transport._callback.""" + client = SignalRClient("wss://example.invalid/hub", retry_count=0) + assert callable(client._transport._callback) + await client._transport._callback(PingMessage())