From 71efc6217ab76c8063b2c9f87b8b9961597dcce2 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 30 Nov 2026 11:29:52 +0000 Subject: [PATCH] Call disconnect on async context exit Let subclasses release resources in disconnect() regardless of how the caller closes the client. Close the channel without a grace period as gRPC does on context exit, and let exceptions from the block propagate. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ src/frequenz/client/base/client.py | 18 ++++++++++------- tests/test_client.py | 32 +++++++++++++++++++++++++++--- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 3722bb9..c9b64a6 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,6 +8,8 @@ +- `BaseApiClient.disconnect()` no longer calls `__aexit__()`. If your client overrides `__aexit__()` to clean up resources, move that cleanup to `disconnect()` and await `super().disconnect()`. The cleanup will then run on explicit disconnect and when leaving an `async with` block. Keep logic that needs the block's exception in `__aexit__()`. + ## New Features diff --git a/src/frequenz/client/base/client.py b/src/frequenz/client/base/client.py index 5935c5a..885df8a 100644 --- a/src/frequenz/client/base/client.py +++ b/src/frequenz/client/base/client.py @@ -288,8 +288,16 @@ async def disconnect(self) -> None: """Disconnect from the server. If the client is not connected, this method does nothing. + + Override this method to release resources on explicit disconnect and on + `async with` exit. Make sure it is safe to call the override more than + once. """ - await self.__aexit__(None, None, None) + if self._channel is None: + return + await self._channel.close(grace=None) + self._channel = None + self._stub = None async def __aenter__(self) -> Self: """Enter a context manager.""" @@ -303,12 +311,8 @@ async def __aexit__( _exc_tb: Any | None, ) -> bool | None: """Exit a context manager.""" - if self._channel is None: - return None - result = await self._channel.__aexit__(_exc_type, _exc_val, _exc_tb) - self._channel = None - self._stub = None - return result + await self.disconnect() + return None StubOutT = TypeVar("StubOutT") diff --git a/tests/test_client.py b/tests/test_client.py index 8850b9c..c16b6eb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -178,7 +178,8 @@ async def test_base_api_client_disconnect(mocker: pytest_mock.MockFixture) -> No await client.disconnect() - mocks.channel.__aexit__.assert_called_once_with(None, None, None) + await client.disconnect() + mocks.channel.close.assert_awaited_once_with(grace=None) assert client.server_url == _DEFAULT_SERVER_URL _assert_is_disconnected(client) @@ -199,7 +200,7 @@ async def test_base_api_client_async_context_manager( assert client.channel is mocks.channel assert client._stub is mocks.stub # pylint: disable=protected-access assert client.is_connected - mocks.channel.__aexit__.assert_not_called() + mocks.channel.close.assert_not_awaited() # If we were previously connected, the client should not reconnect when entering # the context manager if auto_connect: @@ -213,11 +214,36 @@ async def test_base_api_client_async_context_manager( ) mocks.create_stub.assert_called_once_with(mocks.channel) - mocks.channel.__aexit__.assert_called_once_with(None, None, None) + mocks.channel.close.assert_awaited_once_with(grace=None) assert client.server_url == _DEFAULT_SERVER_URL _assert_is_disconnected(client) +async def test_disconnect_override(mocker: pytest_mock.MockFixture) -> None: + """Run subclass cleanup for explicit disconnect and exceptional context exit.""" + calls: list[bool] = [] + + class Client(BaseApiClient[object]): + """Record each call to the cleanup override.""" + + async def disconnect(self) -> None: + calls.append(self.is_connected) + await super().disconnect() + + channel = mocker.patch("frequenz.client.base.client.parse_grpc_uri").return_value + channel.close = mock.AsyncMock() + client = Client(_DEFAULT_SERVER_URL, create_stub=lambda _: object()) + client.connect() + await client.disconnect() + with pytest.raises(ValueError, match="body failed"): + async with client: + raise ValueError("body failed") + + assert calls == [True, True] + assert channel.close.await_count == 2 + _assert_is_disconnected(client) + + def _transform_name(transform: bool) -> str: return "transform" if transform else "no_transform"