Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<!-- Here goes notes on how to upgrade from previous versions, including deprecations and what they should be replaced with -->

- `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

<!-- Here goes the main new features and examples or instructions on how to use them -->
Expand Down
18 changes: 11 additions & 7 deletions src/frequenz/client/base/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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")
Expand Down
32 changes: 29 additions & 3 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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:
Expand All @@ -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"

Expand Down