diff --git a/plugin/adapter.py b/plugin/adapter.py index 2c0af49..2f69ce3 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -451,6 +451,9 @@ class DDPClient: except Exception: break self.connected = False + # B1: Reader loop exited — cancel all pending Futures so callers + # (e.g. PulseController) get DDPNotConnected and can fall back to REST. + self._cancel_pending_results() logger.debug("DDP reader thread exited") def is_alive(self, max_silence: float = 300.0) -> bool: @@ -768,6 +771,21 @@ class DDPClient: len(stale_ids), ) + def _cancel_pending_results(self) -> None: + """B1: Resolve all pending Futures with DDPNotConnected and clear the store. + + Called on disconnect and reader-loop exit to prevent memory leaks + from Futures that would otherwise hang forever waiting for a result + message that will never arrive. + """ + with self._result_lock: + for msg_id, future in list(self._pending_results.items()): + if not future.done(): + future.set_exception( + DDPNotConnected("DDP connection closed — pending result cancelled") + ) + self._pending_results.clear() + def disconnect(self): self._running = False if self.sock: @@ -777,6 +795,9 @@ class DDPClient: pass self.sock = None self.connected = False + # B1: Cancel all pending Futures so callers (e.g. PulseController) + # get DDPNotConnected and can fall back to REST instead of hanging. + self._cancel_pending_results() self._sub_rooms.clear() # Bug 7: reconnect_and_restore() ist deprecated — sie umgeht M13 GC. diff --git a/tests/test_ddp_await.py b/tests/test_ddp_await.py index fc7f6f7..9df86c1 100644 --- a/tests/test_ddp_await.py +++ b/tests/test_ddp_await.py @@ -481,3 +481,61 @@ class TestLegacyTimerSetStatusRemainsSync: adapter.ddp.set_status("away") mock_ddp.set_status.assert_called_with("away") + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 11: B1 — disconnect clears pending Futures with DDPNotConnected +# ═══════════════════════════════════════════════════════════════════════════ + +class TestDisconnectClearsPendingFutures: + """B1: disconnect() löst alle pending Futures mit DDPNotConnected auf.""" + + def test_disconnect_clears_pending_futures(self): + """Engine erstellt, set_status_async aufrufen, disconnect() → DDPNotConnected.""" + client = _make_ddp_client(connected=True) + client._send_json = MagicMock() + + async def _run(): + # Starte set_status_async — registriert einen Future + task = asyncio.create_task(client.set_status_async("online", timeout=5.0)) + await asyncio.sleep(0.05) + + # Verifiziere: Future ist registriert + with client._result_lock: + assert len(client._pending_results) == 1 + + # Disconnect — muss den Future mit DDPNotConnected auflösen + client.disconnect() + + # Der Task sollte jetzt DDPNotConnected werfen + with pytest.raises(DDPNotConnected) as exc_info: + await task + assert "connection closed" in str(exc_info.value).lower() + + # _pending_results muss leer sein + with client._result_lock: + assert len(client._pending_results) == 0 + + asyncio.run(_run()) + + def test_reader_loop_exit_clears_pending_futures(self): + """Simuliere reader-loop exit: _cancel_pending_results wird aufgerufen.""" + client = _make_ddp_client(connected=True) + client._send_json = MagicMock() + + # Registriere einen pending Future manuell + future = concurrent.futures.Future() + with client._result_lock: + client._pending_results["st9999999999_1"] = future + + # Simuliere reader-loop exit (wie in _reader_loop nach while-Schleife) + client._cancel_pending_results() + + # Future muss DDPNotConnected haben + assert future.done() + with pytest.raises(DDPNotConnected): + future.result() + + # Store muss leer sein + with client._result_lock: + assert len(client._pending_results) == 0