diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index cc806ad..a36ebd5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,8 +2,19 @@ ## 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__()`. +- `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 + + ## 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..035af4d 100644 --- a/src/frequenz/client/base/client.py +++ b/src/frequenz/client/base/client.py @@ -238,58 +238,79 @@ 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. 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 +324,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..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,13 +174,77 @@ 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) 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 +265,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 +279,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"