From 3873fd98aea663eaab489ba06648f8712e817ce8 Mon Sep 17 00:00:00 2001 From: "Mathias L. Baumann" Date: Mon, 30 Nov 2026 10:36:03 +0100 Subject: [PATCH] Stop running streams on disconnect DispatchApiClient.stream() starts a background task per microgrid to retry the gRPC stream forever. disconnect() (and leaving the client as an async context manager) only closed the channel, so those tasks kept running and kept failing once the channel was gone. Override __aexit__ to stop every stream before closing the channel, since both disconnect() and the context manager exit through it. Signed-off-by: Mathias L. Baumann --- RELEASE_NOTES.md | 11 +++----- src/frequenz/client/dispatch/_client.py | 36 ++++++++++++++++++++++++- tests/test_client_timeouts.py | 31 +++++++++++++++++++++ 3 files changed, 70 insertions(+), 8 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 65a73c2..6004714 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,14 +2,11 @@ ## Summary -Dispatch streams now have no deadline by default and rely on gRPC keepalive to -detect dead connections. +Dispatch streams now have no deadline by default and rely on gRPC keepalive to detect dead connections. ## Upgrading -- `DispatchApiClient` no longer sets a five-minute stream deadline by default. - Pass a `timedelta` as `stream_timeout` to keep a finite deadline. The public - `stream_timeout` property now returns `None` when no deadline is configured. +- `DispatchApiClient` no longer sets a five-minute stream deadline by default. Pass a `timedelta` as `stream_timeout` to keep a finite deadline. The public `stream_timeout` property now returns `None` when no deadline is configured. ## New Features @@ -17,5 +14,5 @@ detect dead connections. ## Bug Fixes -- Remove the default stream deadline that forced healthy subscriptions to reconnect - every five minutes. Explicit stream timeouts remain supported. +- Remove the default stream deadline that forced healthy subscriptions to reconnect every five minutes. Explicit stream timeouts remain supported. +- `DispatchApiClient.disconnect()` (and exiting the client as an async context manager) now stops every stream started with `stream()`, instead of leaving their background tasks running and retrying forever. diff --git a/src/frequenz/client/dispatch/_client.py b/src/frequenz/client/dispatch/_client.py index ce88903..610419c 100644 --- a/src/frequenz/client/dispatch/_client.py +++ b/src/frequenz/client/dispatch/_client.py @@ -7,7 +7,15 @@ import warnings from datetime import datetime, timedelta -from typing import Any, AsyncIterator, Awaitable, Iterable, Iterator, Literal, cast +from typing import ( + Any, + AsyncIterator, + Awaitable, + Iterable, + Iterator, + Literal, + cast, +) # pylint: disable-next=no-name-in-module from frequenz.api.common.v1alpha8.pagination.pagination_params_pb2 import ( @@ -120,6 +128,32 @@ def __init__( stream_timeout.total_seconds() if stream_timeout is not None else None ) + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: Any | None, + ) -> bool | None: + """Disconnect from the server, stopping any running streams first. + + `BaseApiClient.disconnect()` and the async context manager (`async with`) + both exit through this method, so streams started with `stream()` are + always stopped, whether the client is disconnected explicitly or by + leaving a `with` block. + + Args: + exc_type: The type of the exception raised, if any. + exc_val: The exception raised, if any. + exc_tb: The traceback of the exception raised, if any. + + Returns: + Whatever the base class returns for the same arguments. + """ + for broadcaster in self._streams.values(): + await broadcaster.stop() + self._streams.clear() + return await super().__aexit__(exc_type, exc_val, exc_tb) + @property def call_timeout(self) -> timedelta: """Get the call timeout.""" diff --git a/tests/test_client_timeouts.py b/tests/test_client_timeouts.py index d1dab15..27c0559 100644 --- a/tests/test_client_timeouts.py +++ b/tests/test_client_timeouts.py @@ -121,3 +121,34 @@ async def open_stream() -> AsyncIterator[StreamMicrogridDispatchesResponse]: broadcaster = client._streams[MicrogridId(1)] # pylint: disable=protected-access await broadcaster.stop() + + +async def test_disconnect_stops_streams(mocker: MockerFixture) -> None: + """Test that disconnecting the client stops any streams still running.""" + stream_open = asyncio.Event() + + async def open_stream() -> AsyncIterator[StreamMicrogridDispatchesResponse]: + stream_open.set() + # Block forever, like a real stream would while the connection is alive. + await asyncio.Event().wait() + yield StreamMicrogridDispatchesResponse() # pragma: no cover + + stub = MagicMock() + stub.StreamMicrogridDispatches.return_value = open_stream() + mocker.patch.object( + DispatchApiClient, "stub", new_callable=PropertyMock, return_value=stub + ) + client = DispatchApiClient( + server_url="grpc://example.com", auth_key="key", connect=False + ) + + client.stream(MicrogridId(1)) + await asyncio.wait_for(stream_open.wait(), timeout=1) + + broadcaster = client._streams[MicrogridId(1)] # pylint: disable=protected-access + assert broadcaster.is_running + + await asyncio.wait_for(client.disconnect(), timeout=5) + + assert not broadcaster.is_running + assert not client._streams # pylint: disable=protected-access