From 3ac91926966e36a185a4c105676b2dc8876c4e86 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 30 Nov 2026 11:29:52 +0000 Subject: [PATCH 1/2] 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 | 14 +++++++++++-- src/frequenz/client/base/client.py | 19 +++++++++++------- tests/test_client.py | 32 +++++++++++++++++++++++++++--- 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index cc806ad..cc76802 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,8 +2,18 @@ ## Summary -This release makes stream error logs easier to read by keeping each error on a single line. + + +## Upgrading + + + +- `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 + + ## Bug Fixes -- `GrpcStreamBroadcaster` now logs stream errors on a single line, leaving out the debug string when it only repeats the code and details. + diff --git a/src/frequenz/client/base/client.py b/src/frequenz/client/base/client.py index 5935c5a..ee2bf1c 100644 --- a/src/frequenz/client/base/client.py +++ b/src/frequenz/client/base/client.py @@ -288,8 +288,17 @@ 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. For example, stop and clear any stream broadcasters, + then await `super().disconnect()` to close the channel. 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 +312,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" From 749d7f718169aad46e617ee8a67e4dc632491b3b Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 30 Nov 2026 13:06:54 +0000 Subject: [PATCH 2/2] Require disconnect before changing settings Changing the URL or credentials in connect() replaces the channel without closing it or running subclass cleanup. Require callers to disconnect first, while keeping repeated calls with the same settings a no-op. Store the requested settings only after creating the channel and stub, so a failed connection doesn't overwrite the settings for the next call. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 1 + src/frequenz/client/base/client.py | 68 ++++++++++++++----------- tests/test_client.py | 79 +++++++++++++++++++++++++++--- 3 files changed, 113 insertions(+), 35 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index cc76802..a36ebd5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -9,6 +9,7 @@ - `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__()`. +- `BaseApiClient.connect()` raises `RuntimeError` if the client is already connected and the requested URL, API key, or signing secret would change. To apply new settings, await `client.disconnect()` before calling `client.connect()` with the new settings. Calling `connect()` again with the same settings still does nothing. ## New Features diff --git a/src/frequenz/client/base/client.py b/src/frequenz/client/base/client.py index ee2bf1c..035af4d 100644 --- a/src/frequenz/client/base/client.py +++ b/src/frequenz/client/base/client.py @@ -238,51 +238,63 @@ def connect( auth_key: str | None | EllipsisType = ..., sign_secret: str | None | EllipsisType = ..., ) -> None: - """Connect to the server, possibly using a new URL. + """Connect to the server with the given settings. - If the client is already connected and the URL is the same as the previous URL, - this method does nothing. If you want to force a reconnection, you can call - [disconnect()][frequenz.client.base.client.BaseApiClient.disconnect] first. + If the client is already connected with the requested settings, this method + does nothing. To change the settings, await + [`disconnect()`][frequenz.client.base.client.BaseApiClient.disconnect] first. Args: server_url: The URL of the server to connect to. If not provided, the previously used URL is used. - auth_key: The API key to use when connecting to the service. If an Ellipsis - is provided, the previously used auth_key is used. - sign_secret: The secret to use when creating message HMAC. If an Ellipsis is - provided, + auth_key: The API key to use. Omit to keep the current key or pass `None` + to clear it. + sign_secret: The secret to use when signing messages. Omit to keep the + current secret or pass `None` to clear it. + + Raises: + RuntimeError: If the client is already connected and the URL, API key, or + signing secret would change. + ValueError: If the server URL cannot be used to create a channel. """ - reconnect = False - if server_url is not None and server_url != self._server_url: # URL changed - self._server_url = server_url - reconnect = True - if auth_key is not ... and auth_key != self._auth_key: - self._auth_key = auth_key - reconnect = True - if sign_secret is not ... and sign_secret != self._sign_secret: - self._sign_secret = sign_secret - reconnect = True - if self.is_connected and not reconnect: # Desired connection already exists + new_server_url = self._server_url if server_url is None else server_url + new_auth_key = self._auth_key if auth_key is ... else auth_key + new_sign_secret = self._sign_secret if sign_secret is ... else sign_secret + + if self.is_connected: + if (new_server_url, new_auth_key, new_sign_secret) != ( + self._server_url, + self._auth_key, + self._sign_secret, + ): + raise RuntimeError( + "Call and await disconnect() before changing connection settings." + ) return interceptors: list[ClientInterceptor] = [] - if self._auth_key is not None: + if new_auth_key is not None: interceptors += [ - AuthenticationInterceptorUnaryUnary(self._auth_key), # type: ignore [list-item] - AuthenticationInterceptorUnaryStream(self._auth_key), # type: ignore [list-item] + AuthenticationInterceptorUnaryUnary(new_auth_key), # type: ignore [list-item] + AuthenticationInterceptorUnaryStream(new_auth_key), # type: ignore [list-item] ] - if self._sign_secret is not None: + if new_sign_secret is not None: interceptors += [ - SigningInterceptorUnaryUnary(self._sign_secret), # type: ignore [list-item] - SigningInterceptorUnaryStream(self._sign_secret), # type: ignore [list-item] + SigningInterceptorUnaryUnary(new_sign_secret), # type: ignore [list-item] + SigningInterceptorUnaryStream(new_sign_secret), # type: ignore [list-item] ] - self._channel = parse_grpc_uri( - self._server_url, + channel = parse_grpc_uri( + new_server_url, interceptors, defaults=self._channel_defaults, ) - self._stub = self._create_stub(self._channel) + stub = self._create_stub(channel) + self._server_url = new_server_url + self._auth_key = new_auth_key + self._sign_secret = new_sign_secret + self._channel = channel + self._stub = stub async def disconnect(self) -> None: """Disconnect from the server. diff --git a/tests/test_client.py b/tests/test_client.py index c16b6eb..85ab98e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -145,24 +145,26 @@ def test_base_api_client_connect( mocks.parse_grpc_uri.reset_mock() mocks.create_stub.reset_mock() - client.connect(new_server_url) + same_url = new_server_url is None or new_server_url == _DEFAULT_SERVER_URL + if auto_connect and not same_url: + with pytest.raises(RuntimeError, match=r"await disconnect\(\)"): + client.connect(new_server_url) + else: + client.connect(new_server_url) assert client.channel is mocks.channel assert client._stub is mocks.stub # pylint: disable=protected-access assert client.is_connected - same_url = new_server_url is None or new_server_url == _DEFAULT_SERVER_URL - - if same_url: + if auto_connect or same_url: assert client.server_url == _DEFAULT_SERVER_URL else: assert client.server_url == new_server_url - # If we were previously connected and the URL didn't change, the client should not - # reconnect - if auto_connect and same_url: + if auto_connect: mocks.parse_grpc_uri.assert_not_called() mocks.create_stub.assert_not_called() + mocks.channel.close.assert_not_awaited() else: mocks.parse_grpc_uri.assert_called_once_with( client.server_url, @@ -172,6 +174,69 @@ def test_base_api_client_connect( mocks.create_stub.assert_called_once_with(mocks.channel) +@pytest.mark.parametrize("credential", ["auth_key", "sign_secret"]) +@pytest.mark.parametrize("new_value", ["new", None]) +def test_connect_rejects_credential_changes( + credential: str, new_value: str | None, mocker: pytest_mock.MockFixture +) -> None: + """Keep the current connection and credentials after a rejected change.""" + client, mocks = create_client_with_mocks( + mocker, auth_key="original", sign_secret="original" + ) + + with pytest.raises(RuntimeError, match=r"await disconnect\(\)"): + client.connect(**{credential: new_value}) + + client.connect(auth_key="original", sign_secret="original") + client.connect() + assert client.channel is mocks.channel + mocks.channel.close.assert_not_awaited() + assert mocks.parse_grpc_uri.call_count == 1 + assert mocks.create_stub.call_count == 1 + + +async def test_connect_applies_new_settings_after_disconnect( + mocker: pytest_mock.MockFixture, +) -> None: + """Create a new channel with new settings after closing the previous one.""" + client, mocks = create_client_with_mocks( + mocker, auth_key="original", sign_secret="original" + ) + next_channel = mock.MagicMock(spec=grpc.aio.Channel) + mocks.parse_grpc_uri.return_value = next_channel + + await client.disconnect() + client.connect("grpc://localhost:50051", auth_key=None, sign_secret=None) + + mocks.channel.close.assert_awaited_once_with(grace=None) + assert client.server_url == "grpc://localhost:50051" + assert client.channel is next_channel + mocks.parse_grpc_uri.assert_called_with( + client.server_url, [], defaults=ChannelOptions() + ) + mocks.create_stub.assert_called_with(next_channel) + + +@pytest.mark.parametrize("fail_at", ["parse_grpc_uri", "create_stub"]) +def test_connect_keeps_settings_after_failure( + fail_at: str, mocker: pytest_mock.MockFixture +) -> None: + """Retain the last settings if the new channel or stub cannot be created.""" + client, mocks = create_client_with_mocks(mocker, auto_connect=False) + failing_mock = getattr(mocks, fail_at) + failing_mock.side_effect = ValueError("cannot connect") + + with pytest.raises(ValueError, match="cannot connect"): + client.connect("grpc://localhost:50051", auth_key="new", sign_secret="new") + + _assert_is_disconnected(client) + failing_mock.side_effect = None + client.connect() + mocks.parse_grpc_uri.assert_called_with( + _DEFAULT_SERVER_URL, [], defaults=ChannelOptions() + ) + + async def test_base_api_client_disconnect(mocker: pytest_mock.MockFixture) -> None: """Test disconnecting the BaseApiClient.""" client, mocks = create_client_with_mocks(mocker, auto_connect=True)