Skip to content
Merged
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
11 changes: 4 additions & 7 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,17 @@

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

<!-- Here goes the main new features and examples or instructions on how to use them -->

## 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.
36 changes: 35 additions & 1 deletion src/frequenz/client/dispatch/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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.
Comment on lines +139 to +142

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was really confused by this __aexit__ and the mention to an non-existent disconnect().

Damn this is ugly!!! I think we should change BaseApiClient to do the reverse, make __aexit__ call disconnect() instead of the other way around 😒


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."""
Expand Down
31 changes: 31 additions & 0 deletions tests/test_client_timeouts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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