diff --git a/README.md b/README.md index cdef7f2..bc759c0 100644 --- a/README.md +++ b/README.md @@ -290,8 +290,9 @@ class StreamingGreeterApiClient(BaseApiClient[hsw_pb2_grpc.MultiGreeterStub]): def say_hello_stream(self, name: str, *, buffer_size: int = 50) -> Receiver[str]: """Stream greetings from the server. - This method reuses the underlying stream if called multiple times with the - same name. + This method reuses the stream for the same name. If every receiver of + that stream was closed, the next call starts the stream again. A stream + that has ended is not started again. Args: name: The name to greet. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 4bd60ba..2170177 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,10 +8,22 @@ +- The retry count of `GrpcStreamBroadcaster` is now reset when a message arrives. A limit in `retry_strategy` now counts only the retries in a row that receive no message, so a limit above 0 no longer stops a stream that gets a message on every connection. With `ExponentialBackoff`, the wait also starts again from `initial_interval`. +- `GrpcStreamBroadcaster` now stops its stream once every receiver it handed out is closed or garbage-collected, and `is_running` is then False. Keep a receiver referenced for as long as you read from it. Calling `new_receiver()` again starts the stream again, unless `stop()` was called. +- `GrpcStreamBroadcaster.new_receiver()` now returns a plain `Receiver` that wraps the channel receiver. `len()` on it and `Merger.stop()` no longer work; use `close()` to stop receiving. + ## New Features +- `GrpcStreamBroadcaster` takes an `idle_timeout`, which must be positive. A call that receives no message for that long is cancelled and retried according to `retry_strategy`. The `StreamRetrying` event, or the `StreamFatalError` event once retries run out, then carries a `StreamIdleTimeoutError`. +- `GrpcStreamBroadcaster` stops, and cancels its call, once every receiver it handed out is closed or garbage-collected. This also happens while the stream is stalled or retrying, so an abandoned stream no longer retries forever. +- A `GrpcStreamBroadcaster` that never handed out a receiver is not stopped for lack of receivers. It runs until its stream ends, gives up or fails, or `stop()` is called. + ## Bug Fixes + +- `GrpcStreamBroadcaster` now ends its receivers when the stream fails with an unexpected error, and sends `StreamFatalError` to receivers with events. Before, they waited forever. +- `GrpcStreamBroadcaster.stop()` no longer swallows a cancellation of the task that awaits it. +- `GrpcStreamBroadcaster.new_receiver(include_events=True)` now returns a receiver that ends at once when called after `stop()`, or after the stream ended or gave up. If no receiver with events was created before, it used to wait forever. diff --git a/src/frequenz/client/base/streaming.py b/src/frequenz/client/base/streaming.py index c7f2ea7..c1a43dc 100644 --- a/src/frequenz/client/base/streaming.py +++ b/src/frequenz/client/base/streaming.py @@ -4,11 +4,21 @@ """Implementation of the grpc streaming helper.""" import asyncio +import contextlib +import functools import logging -from collections.abc import Callable +import weakref +from collections.abc import AsyncGenerator, Callable from dataclasses import dataclass from datetime import timedelta -from typing import AsyncIterable, Generic, Literal, TypeAlias, TypeVar, overload +from typing import ( + AsyncIterable, + Generic, + Literal, + TypeAlias, + TypeVar, + overload, +) import grpc.aio @@ -25,6 +35,9 @@ OutputT = TypeVar("OutputT") """The output type of the stream.""" +_T = TypeVar("_T") +"""The message type of a tracked receiver.""" + @dataclass(frozen=True) class StreamStarted: @@ -54,6 +67,27 @@ class StreamFatalError: """The exception that caused the stream to stop.""" +class StreamIdleTimeoutError(TimeoutError): + """The stream received no message within its idle timeout. + + It is not an `ApiClientError`, because the broadcaster does not know the + server URL. + """ + + def __init__(self, stream_name: str, idle_timeout: timedelta) -> None: + """Initialize the error. + + Args: + stream_name: The name of the stream. + idle_timeout: The idle timeout that expired. + """ + super().__init__(f"no message received for {idle_timeout}") + self.stream_name = stream_name + """The name of the stream.""" + self.idle_timeout = idle_timeout + """The idle timeout that expired.""" + + StreamEvent: TypeAlias = StreamStarted | StreamRetrying | StreamFatalError """Type alias for the events that can be sent over the stream.""" @@ -66,9 +100,15 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]): when the connection is lost, and broadcasting the received messages to multiple receivers. - The stream is started when the class is initialized, and can be stopped - with the `stop` method. New receivers can be created with the - `new_receiver` method, which will receive the streamed messages. + The stream starts when the broadcaster is created. It stops when `stop()` is + called, or when the stream ends, gives up or fails. New receivers can be + created with the `new_receiver` method, which will receive the streamed + messages. + + Once receivers were handed out, the stream also stops by itself when every + one of them is closed or garbage-collected, and a later `new_receiver()` + call starts it again, unless `stop()` was called. Keep a receiver referenced + while it is in use. If `include_events=True` is passed to `new_receiver`, the receiver will also get state change messages (`StreamStarted`, `StreamRetrying`, @@ -160,6 +200,7 @@ def __init__( # pylint: disable=too-many-arguments,too-many-positional-argument transform: Callable[[InputT], OutputT], retry_strategy: retry.Strategy | None = None, retry_on_exhausted_stream: bool = False, + idle_timeout: timedelta | None = None, ): """Initialize the streaming helper. @@ -170,26 +211,48 @@ def __init__( # pylint: disable=too-many-arguments,too-many-positional-argument transform: A function to transform the input type to the output type. retry_strategy: The retry strategy to use, when the connection is lost. Defaults to retries every 3 seconds, with a jitter of 1 second, indefinitely. + The retry count is reset when a message arrives, so a limit counts + the retries in a row that receive no message. So a limit above 0 + never stops a stream that receives a message on every + connection. With `ExponentialBackoff`, the wait also starts again + from its initial interval. retry_on_exhausted_stream: Whether to retry when the stream is exhausted, i.e. when the server closes the stream. Defaults to False. + idle_timeout: If set, a call that receives no message for this long is + cancelled and handled like a failed call: it is retried according to + `retry_strategy`, with a `StreamIdleTimeoutError` as the error. + + Raises: + ValueError: If `idle_timeout` is not positive. """ + if idle_timeout is not None and idle_timeout <= timedelta(0): + raise ValueError(f"idle_timeout must be positive, not {idle_timeout}") self._stream_name = stream_name self._stream_method = stream_method self._transform = transform self._retry_strategy = ( - retry.LinearBackoff() if retry_strategy is None else retry_strategy.copy() + retry.LinearBackoff() if retry_strategy is None else retry_strategy ) self._retry_on_exhausted_stream = retry_on_exhausted_stream + self._idle_timeout = idle_timeout + self._stop_requested = False + self._runs: set[_Run[OutputT]] = set() + self._current_run = self._start_run() - # Channel for transformed data messages (OutputT) - self._data_channel: channels.Broadcast[OutputT] = channels.Broadcast( - name=f"GrpcStreamBroadcaster-{stream_name}-Data" - ) + def _start_run(self) -> "_Run[OutputT]": + """Start streaming with new channels and a fresh retry strategy. - # Channel for stream events (StreamEvent), created on demand - self._event_channel: channels.Broadcast[StreamEvent] | None = None - self._event_sender: channels.Sender[StreamEvent] | None = None - self._task = asyncio.create_task(self._run()) + Returns: + The new run. + """ + run = _Run[OutputT]( + f"GrpcStreamBroadcaster-{self._stream_name}", + self._retry_strategy.copy(), + asyncio.get_running_loop(), + ) + run.task = asyncio.create_task(self._run(run)) + self._runs = {r for r in self._runs if not r.task.done()} | {run} + return run @overload def new_receiver( @@ -209,7 +272,8 @@ def new_receiver( include_events: bool, ) -> channels.Receiver[StreamEvent | OutputT]: ... - def new_receiver( + # `pydoclint` counts the `raise` that passes on an error of `subscribe()`. + def new_receiver( # noqa: DOC501, DOC503 self, *, maxsize: int = 50, @@ -218,6 +282,11 @@ def new_receiver( ) -> channels.Receiver[StreamEvent | OutputT]: """Create a new receiver for the stream. + If the stream stopped because every earlier receiver was closed or + garbage-collected, it is started again, unless `stop()` was called. + Otherwise, if the stream has ended, given up or failed, or `stop()` was + called, the receiver ends at once without data. + Args: maxsize: The maximum number of messages to buffer in underlying receivers. warn_on_overflow: Whether to log a warning when a receiver's @@ -230,115 +299,410 @@ def new_receiver( A new receiver. If `include_events` is True, the receiver will yield both `OutputT` and `StreamEvent` types. Otherwise, only `OutputT`. """ - if not include_events: - return self._data_channel.new_receiver( - limit=maxsize, warn_on_overflow=warn_on_overflow - ) - - if self._event_channel is None: + run = self._current_run + # Count the receiver before subscribing: a garbage collection while + # subscribing could otherwise release the run's last receiver and stop + # the run under the new one. + release = run.receiver_counter.acquire() + if run.receivers_gone and not run.ended and not self._stop_requested: + release() + _logger.info("%s: restarting for a new receiver", self._stream_name) + run = self._current_run = self._start_run() + release = run.receiver_counter.acquire() + + if include_events and run.event_sender is None and not run.closed: _logger.debug( "%s: First request for events, creating event channel.", self._stream_name, ) - self._event_channel = channels.Broadcast[StreamEvent]( - name=f"GrpcStreamBroadcaster-{self._stream_name}-Events" - ) - self._event_sender = self._event_channel.new_sender() - - data_rx = self._data_channel.new_receiver( - limit=maxsize, warn_on_overflow=warn_on_overflow - ) - event_rx = self._event_channel.new_receiver( - limit=maxsize, warn_on_overflow=warn_on_overflow - ) - return channels.merge(data_rx, event_rx) + try: + receiver = run.subscribe(maxsize, warn_on_overflow, include_events) + except BaseException: + release() + raise + return _TrackedReceiver(receiver, release) @property def is_running(self) -> bool: """Return whether the streaming helper is running. + This is False after `stop()`, and once the stream has ended, given up or + failed. It is also False once every receiver handed out was closed or + garbage-collected, until `new_receiver()` starts the stream again. + Returns: Whether the streaming helper is running. """ - return not self._task.done() + run = self._current_run + return not (run.task.done() or run.receivers_gone) async def stop(self) -> None: """Stop the streaming helper.""" _logger.info("%s: stopping the stream", self._stream_name) - if self._task.done(): - return - self._task.cancel() + self._stop_requested = True + tasks = [run.task for run in self._runs if not run.task.done()] + for task in tasks: + task.cancel() try: - await self._task - except asyncio.CancelledError: - pass - await self._data_channel.aclose() - if self._event_channel is not None: - await self._event_channel.aclose() + # Collects the runs' cancellations; a cancellation of the caller still + # propagates. + await asyncio.gather(*tasks, return_exceptions=True) + finally: + # A run cancelled before its first step never closes its own channels. + for run in self._runs: + await run.close() - async def _run(self) -> None: - """Run the streaming helper.""" - data_sender = self._data_channel.new_sender() + async def _run(self, run: "_Run[OutputT]") -> None: + """Run the stream until it ends, gives up, fails or is cancelled. + Args: + run: The run to stream for. + """ + try: + await self._stream(run) + except Exception as err: # pylint: disable=broad-exception-caught + # Once every receiver is gone, the run is being cancelled. An error + # now, e.g. from the call's cleanup, does not mark the run as ended, + # so a new receiver can restart it. + if not run.receivers_gone: + run.ended = True + _logger.exception("%s: unexpected error, stopping", self._stream_name) + await run.send_event(StreamFatalError(err)) + finally: + if run.receivers_gone: + _logger.info("%s: all receivers are gone, stopping", self._stream_name) + await run.close() + + async def _stream(self, run: "_Run[OutputT]") -> None: + """Stream, retrying according to the retry strategy. + + Args: + run: The run to stream for. + """ while True: error: Exception | None = None _logger.info("%s: starting to stream", self._stream_name) try: call = self._stream_method() - if self._event_sender: - await self._event_sender.send(StreamStarted()) + await run.send_event(StreamStarted()) + + async with contextlib.aclosing(self._call_messages(call)) as messages: + async for msg in messages: + run.retry_strategy.reset() + try: + transformed = self._transform(msg) + except Exception: # pylint: disable=broad-exception-caught + _logger.exception( + "%s: error transforming message: %s", + self._stream_name, + msg, + ) + continue + + await run.data_sender.send(transformed) - async for msg in call: - try: - transformed = self._transform(msg) - except Exception: # pylint: disable=broad-exception-caught - _logger.exception( - "%s: error transforming message: %s", - self._stream_name, - msg, - ) - continue - - await data_sender.send(transformed) - - except grpc.aio.AioRpcError as err: + except (grpc.aio.AioRpcError, StreamIdleTimeoutError) as err: error = err + if run.receivers_gone: + return if error is None and not self._retry_on_exhausted_stream: + run.ended = True _logger.info( "%s: connection closed, stream exhausted", self._stream_name ) - await self._data_channel.aclose() - if self._event_channel is not None: - await self._event_channel.aclose() - break + return - interval = self._retry_strategy.next_interval() + interval = run.retry_strategy.next_interval() error_str = f"Error: {error}" if error else "Stream exhausted" if interval is None: + run.ended = True _logger.error( "%s: connection ended, retry limit exceeded (%s), giving up. %s.", self._stream_name, - self._retry_strategy.get_progress(), + run.retry_strategy.get_progress(), error_str, ) - if error is not None and self._event_sender: - await self._event_sender.send(StreamFatalError(error)) - await self._data_channel.aclose() - if self._event_channel is not None: - await self._event_channel.aclose() - break + if error is not None: + await run.send_event(StreamFatalError(error)) + return _logger.warning( "%s: connection ended, retrying %s in %0.3f seconds. %s.", self._stream_name, - self._retry_strategy.get_progress(), + run.retry_strategy.get_progress(), interval, error_str, ) - if self._event_sender: - await self._event_sender.send( - StreamRetrying(timedelta(seconds=interval), error) - ) + await run.send_event(StreamRetrying(timedelta(seconds=interval), error)) await asyncio.sleep(interval) + + async def _call_messages( + self, call: AsyncIterable[InputT] + ) -> AsyncGenerator[InputT, None]: + """Yield the messages of a call, enforcing the idle timeout. + + When this generator is closed before the call ends, e.g. on an idle + timeout or when the broadcaster is stopped, the call is cancelled if it + has a `cancel()` method. gRPC calls also cancel themselves when the + cancellation reaches them while they wait for a message. + + Args: + call: The call returned by the stream method. + + Yields: + The messages of the call. + + Raises: + StreamIdleTimeoutError: If no message arrives within the idle timeout. + TimeoutError: If the call itself raises it. + """ + idle_timeout = self._idle_timeout + exhausted = False + try: + if idle_timeout is None: + async for msg in call: + yield msg + exhausted = True + return + iterator = aiter(call) + while True: + timer = asyncio.timeout(idle_timeout.total_seconds()) + try: + async with timer: + msg = await anext(iterator) + except StopAsyncIteration: + exhausted = True + return + except TimeoutError as err: + if not timer.expired(): + raise + raise StreamIdleTimeoutError( + self._stream_name, idle_timeout + ) from err + yield msg + finally: + if not exhausted: + _cancel_call(call) + + +def _cancel_call(call: object) -> None: + """Cancel a gRPC call, if the object supports it. + + Args: + call: The object returned by the stream method. + """ + cancel = getattr(call, "cancel", None) + if callable(cancel): + cancel() + + +# pylint: disable-next=too-many-instance-attributes +class _Run(Generic[OutputT]): + """The channels, receiver counter and task of one run of a broadcaster's stream. + + A broadcaster starts its first run when it is created. It starts a new run + when a receiver is requested after the current run stopped because every + receiver was gone, unless `stop()` was called or the run ended by itself. + Each run only closes its own channels, so a run that is still winding down + cannot end the next run's receivers. + """ + + def __init__( + self, + name: str, + retry_strategy: retry.Strategy, + loop: asyncio.AbstractEventLoop, + ) -> None: + """Initialize the run. + + Args: + name: The name prefix for the run's channels. + retry_strategy: The retry strategy of this run. + loop: The event loop the run streams on. + """ + self._name = name + self.retry_strategy = retry_strategy + """The retry strategy of this run.""" + self._data_channel = channels.Broadcast[OutputT](name=f"{name}-Data") + self.data_sender = self._data_channel.new_sender() + """The sender of the data channel.""" + self._event_channel: channels.Broadcast[StreamEvent] | None = None + self.event_sender: channels.Sender[StreamEvent] | None = None + """The sender of the event channel, created on demand.""" + self.receiver_counter = _ReceiverCounter(self._on_receivers_gone, loop) + """Counts the receivers handed out for this run.""" + self.receivers_gone = False + """Whether every receiver was closed or dropped, which stops the run.""" + self.ended = False + """Whether the stream ended, gave up or failed by itself. + + Not set when the run stopped because every receiver was gone. A run + with this set is not restarted. + """ + self.task: asyncio.Task[None] + """The task streaming for this run.""" + + def _on_receivers_gone(self) -> None: + """Stop streaming, as every receiver handed out was closed or dropped.""" + if self.task.done() or self.receivers_gone: + return + self.receivers_gone = True + self.task.cancel() + + def subscribe( + self, maxsize: int, warn_on_overflow: bool, include_events: bool + ) -> channels.Receiver[StreamEvent | OutputT]: + """Create a receiver for the run's data, and its events if asked. + + Once the run is closed, only the data receiver is returned, and it ends at + once. + + Args: + maxsize: The maximum number of messages to buffer per channel. + warn_on_overflow: Whether to log a warning when a message is dropped. + include_events: Whether to also receive the stream events. + + Returns: + The new receiver. + """ + data_rx = self._data_channel.new_receiver( + limit=maxsize, warn_on_overflow=warn_on_overflow + ) + # An event channel created after `close()` would never be closed. + if not include_events or self.closed: + return data_rx + if self._event_channel is None: + self._event_channel = channels.Broadcast[StreamEvent]( + name=f"{self._name}-Events" + ) + self.event_sender = self._event_channel.new_sender() + event_rx = self._event_channel.new_receiver( + limit=maxsize, warn_on_overflow=warn_on_overflow + ) + return channels.merge(data_rx, event_rx) + + @property + def closed(self) -> bool: + """Whether the run's channels were closed.""" + return self._data_channel.is_closed + + async def send_event(self, event: StreamEvent) -> None: + """Send an event to the event receivers, if there are any. + + Args: + event: The event to send. + """ + if self.event_sender is not None: + await self.event_sender.send(event) + + async def close(self) -> None: + """Close the channels, which ends the receivers.""" + await self._data_channel.aclose() + if self._event_channel is not None: + await self._event_channel.aclose() + + +class _ReceiverCounter: + """Counts the receivers handed out that are not yet closed or dropped.""" + + def __init__( + self, on_all_gone: Callable[[], None], loop: asyncio.AbstractEventLoop + ) -> None: + """Initialize the counter. + + Args: + on_all_gone: A bound method to call, on `loop`, when the last receiver + is gone. It is held weakly, so receivers do not keep its object + alive. + loop: The event loop to count on. + """ + self._on_all_gone = weakref.WeakMethod(on_all_gone) + self._loop = loop + self._open = 0 + + def acquire(self) -> Callable[[], None]: + """Count a new receiver. + + Returns: + The function to call, once and from any thread, when the receiver is + gone. + """ + self._open += 1 + return functools.partial(_call_on_loop, self._loop, self._release) + + def _release(self) -> None: + """Count a receiver as gone.""" + self._open -= 1 + on_all_gone = self._on_all_gone() + if self._open == 0 and on_all_gone is not None: + on_all_gone() + + +class _TrackedReceiver(channels.Receiver[_T]): + """A receiver that reports when it is closed or garbage-collected.""" + + def __init__(self, receiver: channels.Receiver[_T], release: Callable[[], None]): + """Initialize the receiver. + + Args: + receiver: The receiver to wrap. + release: The function to call once the receiver is closed or dropped. + """ + self._receiver = receiver + self._release = weakref.finalize(self, release) + # typeshed gives `finalize` empty `__slots__`, so mypy rejects this. + self._release.atexit = False # type: ignore[misc] + + async def ready(self) -> bool: + """Wait until a message is ready. + + Returns: + Whether a message is ready; False once the receiver has stopped. + """ + return await self._receiver.ready() + + def consume(self) -> _T: + """Return the message that is ready. + + Returns: + The message. + """ + return self._receiver.consume() + + def close(self) -> None: + """Close the receiver.""" + try: + self._receiver.close() + finally: + self._release() + + def __str__(self) -> str: + """Return a string representation of the wrapped receiver.""" + return str(self._receiver) + + def __repr__(self) -> str: + """Return a representation of the wrapped receiver.""" + return repr(self._receiver) + + +def _call_on_loop(loop: asyncio.AbstractEventLoop, func: Callable[[], None]) -> None: + """Call a function on an event loop, from any thread. + + The call is immediate when made from the loop itself, and is dropped when the + loop is already closed. + + Args: + loop: The event loop to call the function on. + func: The function to call. + """ + try: + running = asyncio.get_running_loop() + except RuntimeError: + running = None + if running is loop: + func() + return + with contextlib.suppress(RuntimeError): # The loop is closed. + loop.call_soon_threadsafe(func) diff --git a/tests/streaming/test_grpc_stream_broadcaster.py b/tests/streaming/test_grpc_stream_broadcaster.py index ff74b5f..eef9e19 100644 --- a/tests/streaming/test_grpc_stream_broadcaster.py +++ b/tests/streaming/test_grpc_stream_broadcaster.py @@ -4,16 +4,20 @@ """Tests for GrpcStreamBroadcaster class.""" import asyncio +import gc +import itertools import logging -from collections.abc import AsyncIterator +import threading +from collections.abc import AsyncIterator, Callable from contextlib import AsyncExitStack from datetime import timedelta +from typing import Any from unittest import mock import grpc import grpc.aio import pytest -from frequenz.channels import Receiver +from frequenz.channels import Receiver, ReceiverStoppedError from frequenz.client.base import retry, streaming from frequenz.client.base.streaming import ( @@ -382,16 +386,17 @@ async def test_messages_on_retry( receiver_ready_event: asyncio.Event, # pylint: disable=redefined-outer-name include_events: bool, ) -> None: - """Test that messages are sent on retry.""" + """Test that messages are sent on retry, and reset the retry count.""" # We need to use a specific instance for all the test here because 2 errors created # with the same arguments don't compare equal (grpc.aio.AioRpcError doesn't seem to # provide a __eq__ method). error = make_error() + successes = [2, 2, 0] helper = streaming.GrpcStreamBroadcaster( stream_name="test_helper", stream_method=lambda: _ErroringAsyncIter( - error, receiver_ready_event, num_successes=2 + error, receiver_ready_event, num_successes=successes.pop(0) ), transform=_transformer, retry_strategy=retry.LinearBackoff(limit=1, interval=0.0, jitter=0.0), @@ -413,8 +418,11 @@ async def test_messages_on_retry( "transformed_0", "transformed_1", ] + assert not successes if include_events: assert events == [ + StreamStarted(), + StreamRetrying(timedelta(seconds=0.0), error), StreamStarted(), StreamRetrying(timedelta(seconds=0.0), error), StreamStarted(), @@ -422,3 +430,861 @@ async def test_messages_on_retry( ] else: assert events == [] + + +class _HangingCall(AsyncIterator[int]): + """Async iterator that never yields, like a server stream that stalls.""" + + def __init__(self) -> None: + self.cancelled = 0 + + async def __anext__(self) -> int: + await asyncio.Event().wait() + raise AssertionError("unreachable") + + def cancel(self) -> bool: + """Record a cancellation, as a gRPC call would accept one.""" + self.cancelled += 1 + return True + + +async def _slow_stream() -> AsyncIterator[int]: + """Yield 5 messages, 10 ms apart.""" + for i in range(5): + await asyncio.sleep(0.01) + yield i + + +async def _endless_stream() -> AsyncIterator[int]: + """Yield a message every 10 ms, forever.""" + for i in itertools.count(): + yield i + await asyncio.sleep(0.01) + + +def _collect_garbage_before( + monkeypatch: pytest.MonkeyPatch, cls: type, name: str +) -> None: + """Make `cls.name` run a full garbage collection before it does its work.""" + original = getattr(cls, name) + + def collecting(*args: Any, **kwargs: Any) -> Any: + gc.collect() + return original(*args, **kwargs) + + monkeypatch.setattr(cls, name, collecting) + + +def _drop_in_a_cycle(receiver: Any) -> None: + """Drop a receiver so that only a garbage collection can free it.""" + cycle: list[Any] = [receiver] + cycle.append(cycle) + + +class _SlowToCancel(_HangingCall): + """A call that takes 0.1 s to clean up when it is cancelled.""" + + def __init__(self, cleanups: list[str], finished: asyncio.Event) -> None: + super().__init__() + self._cleanups = cleanups + self._finished = finished + + async def __anext__(self) -> int: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + try: + await asyncio.sleep(0.1) + except asyncio.CancelledError: + self._cleanups.append("interrupted") + raise + finally: + self._finished.set() + self._cleanups.append("done") + raise + raise AssertionError("unreachable") + + +class _AlwaysFailing: + """Stream method whose calls always fail, counting how often it is called.""" + + def __init__(self) -> None: + self.calls = 0 + self._ready_event = asyncio.Event() + self._ready_event.set() + + def __call__(self) -> AsyncIterator[int]: + self.calls += 1 + return _ErroringAsyncIter(make_error(), self._ready_event) + + +def _helper( + stream_method: Callable[[], AsyncIterator[int]], **kwargs: Any +) -> streaming.GrpcStreamBroadcaster[int, str]: + """Create a broadcaster for the tests below.""" + return streaming.GrpcStreamBroadcaster( + stream_name="test_helper", + stream_method=stream_method, + transform=_transformer, + **kwargs, + ) + + +async def test_idle_timeout_retries_then_gives_up() -> None: + """A stalled stream is cancelled, retried, and given up after the limit.""" + calls: list[_HangingCall] = [] + + def stream_method() -> _HangingCall: + calls.append(_HangingCall()) + return calls[-1] + + helper = _helper( + stream_method, + retry_strategy=retry.LinearBackoff(limit=1, interval=0.0, jitter=0.0), + idle_timeout=timedelta(seconds=0.05), + ) + async with AsyncExitStack() as stack: + stack.push_async_callback(helper.stop) + receiver = helper.new_receiver(include_events=True) + items, events = await asyncio.wait_for(_split_message(receiver), timeout=5) + + assert items == [] + assert [type(e) for e in events] == [ + StreamStarted, + StreamRetrying, + StreamStarted, + StreamFatalError, + ] + for event in (events[1], events[3]): + assert isinstance(event, (StreamRetrying, StreamFatalError)) + assert isinstance(event.exception, streaming.StreamIdleTimeoutError) + assert event.exception.idle_timeout == timedelta(seconds=0.05) + assert [call.cancelled for call in calls] == [1, 1] + + +async def test_idle_timeout_measures_gaps_between_messages( + no_retry: mock.MagicMock, # pylint: disable=redefined-outer-name +) -> None: + """A stream that keeps sending within the idle timeout is never cut off.""" + helper = _helper( + _slow_stream, retry_strategy=no_retry, idle_timeout=timedelta(seconds=0.03) + ) + async with AsyncExitStack() as stack: + stack.push_async_callback(helper.stop) + receiver = helper.new_receiver(include_events=True) + items, events = await asyncio.wait_for(_split_message(receiver), timeout=5) + + assert items == [f"transformed_{i}" for i in range(5)] + assert events == [StreamStarted()] + + +async def test_stop_during_idle_wait() -> None: + """Stopping while waiting for a message cancels the call cleanly.""" + call = _HangingCall() + helper = _helper(lambda: call, idle_timeout=timedelta(seconds=10)) + receiver = helper.new_receiver(include_events=True) + await asyncio.sleep(0.01) + await helper.stop() + items, events = await asyncio.wait_for(_split_message(receiver), timeout=5) + + assert items == [] + assert events == [StreamStarted()] + assert call.cancelled == 1 + assert not helper.is_running + + +async def test_no_idle_timeout_by_default() -> None: + """Without an idle timeout a silent stream is left waiting.""" + call = _HangingCall() + helper = _helper(lambda: call) + try: + receiver = helper.new_receiver() + await asyncio.sleep(0.1) + assert helper.is_running + assert call.cancelled == 0 + receiver.close() + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +def test_idle_timeout_must_be_positive() -> None: + """A zero or negative idle timeout is rejected.""" + for idle_timeout in (timedelta(0), timedelta(seconds=-1)): + with pytest.raises(ValueError, match="idle_timeout"): + _helper(_HangingCall, idle_timeout=idle_timeout) + + +async def test_stops_when_all_receivers_closed_while_retrying() -> None: + """A retrying stream stops once its only receiver is closed.""" + stream_method = _AlwaysFailing() + helper = _helper( + stream_method, + retry_strategy=retry.LinearBackoff(limit=None, interval=0.01, jitter=0.0), + ) + try: + receiver = helper.new_receiver() + await asyncio.sleep(0.05) + receiver.close() + await asyncio.sleep(0.05) + assert not helper.is_running + calls = stream_method.calls + await asyncio.sleep(0.05) + assert stream_method.calls == calls + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stops_when_all_receivers_closed_while_stalled() -> None: + """A stalled stream stops and cancels its call once its receiver is closed.""" + call = _HangingCall() + helper = _helper(lambda: call) + try: + receiver = helper.new_receiver() + await asyncio.sleep(0.01) + receiver.close() + assert not helper.is_running + await asyncio.sleep(0.05) + assert call.cancelled == 1 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stops_when_receiver_is_garbage_collected() -> None: + """A retrying stream stops once its only receiver is dropped.""" + helper = _helper( + _AlwaysFailing(), + retry_strategy=retry.LinearBackoff(limit=None, interval=0.01, jitter=0.0), + ) + try: + receiver = helper.new_receiver() + del receiver + gc.collect() + await asyncio.sleep(0.05) + assert not helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stops_when_events_receiver_is_garbage_collected() -> None: + """A stalled stream stops once its only receiver, with events, is dropped.""" + call = _HangingCall() + helper = _helper(lambda: call) + try: + receiver = helper.new_receiver(include_events=True) + await asyncio.sleep(0.01) + del receiver + gc.collect() + await asyncio.sleep(0.05) + assert not helper.is_running + assert call.cancelled == 1 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_keeps_running_while_a_receiver_is_open( + no_retry: mock.MagicMock, # pylint: disable=redefined-outer-name +) -> None: + """Closing one receiver leaves the stream running for the others.""" + helper = _helper(_slow_stream, retry_strategy=no_retry) + async with AsyncExitStack() as stack: + stack.push_async_callback(helper.stop) + closed = helper.new_receiver() + kept = helper.new_receiver() + closed.close() + first = await asyncio.wait_for(kept.receive(), timeout=5) + assert helper.is_running + rest, _ = await asyncio.wait_for(_split_message(kept), timeout=5) + + assert [first, *rest] == [f"transformed_{i}" for i in range(5)] + + +async def test_events_receiver_keeps_the_stream_running() -> None: + """A receiver with events keeps the stream alive until it is closed.""" + helper = _helper(_HangingCall) + try: + receiver = helper.new_receiver(include_events=True) + await asyncio.sleep(0.05) + assert helper.is_running + receiver.close() + await asyncio.sleep(0.05) + assert not helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_new_receiver_restarts_after_receivers_gone() -> None: + """A stream stopped for lack of receivers restarts for a new receiver.""" + stream = _CountingStream() + helper = _helper(stream) + try: + first = helper.new_receiver() + assert await asyncio.wait_for(first.receive(), timeout=5) == "transformed_1" + first.close() + await asyncio.sleep(0.05) + assert not helper.is_running + + second = helper.new_receiver() + assert helper.is_running + assert await asyncio.wait_for(second.receive(), timeout=5) == "transformed_2" + assert stream.calls == 2 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +@pytest.mark.parametrize("include_events", [False, True]) +async def test_new_receiver_after_stop_is_stopped(include_events: bool) -> None: + """After stop(), a new receiver ends without data.""" + helper = _helper(_HangingCall) + await helper.stop() + receiver = helper.new_receiver(include_events=include_events) + assert not helper.is_running + assert await asyncio.wait_for(_split_message(receiver), timeout=5) == ([], []) + + +class _CountingStream: + """Stream method whose calls yield their number, then hang.""" + + def __init__(self) -> None: + self.calls = 0 + + async def __call__(self) -> AsyncIterator[int]: + self.calls += 1 + yield self.calls + await asyncio.Event().wait() + + +async def test_close_then_new_receiver_in_the_same_tick() -> None: + """A receiver requested right after the last one closed gets data.""" + helper = _helper(_CountingStream()) + try: + first = helper.new_receiver() + assert await asyncio.wait_for(first.receive(), timeout=5) == "transformed_1" + first.close() + second = helper.new_receiver() + assert await asyncio.wait_for(second.receive(), timeout=5) == "transformed_2" + assert helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_new_receiver_after_breaking_out_of_a_loop() -> None: + """A loop that breaks out and drops its receiver does not starve the next one.""" + helper = _helper(_endless_stream) + received = [] + + async def first_item() -> None: + async for item in helper.new_receiver(): + received.append(item) + break + + try: + for _ in range(2): + await asyncio.wait_for(first_item(), timeout=5) + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + assert len(received) == 2 + + +async def test_close_before_the_stream_started() -> None: + """Closing the only receiver before the stream ran does not hang the next one.""" + helper = _helper(_CountingStream()) + try: + helper.new_receiver().close() + receiver = helper.new_receiver() + assert await asyncio.wait_for(receiver.receive(), timeout=5) == "transformed_1" + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stop_after_receivers_gone_stays_stopped() -> None: + """After stop(), a new receiver does not restart a stream whose receivers left.""" + helper = _helper(_HangingCall) + receiver = helper.new_receiver() + await asyncio.sleep(0.01) + receiver.close() + await helper.stop() + late = helper.new_receiver() + assert not helper.is_running + assert await asyncio.wait_for(_split_message(late), timeout=5) == ([], []) + + +async def test_closing_events_receiver_keeps_data_flowing( + no_retry: mock.MagicMock, # pylint: disable=redefined-outer-name +) -> None: + """Closing the only receiver with events does not stop the data receivers.""" + helper = _helper(_slow_stream, retry_strategy=no_retry) + async with AsyncExitStack() as stack: + stack.push_async_callback(helper.stop) + events = helper.new_receiver(include_events=True) + data = helper.new_receiver() + events.close() + items = await asyncio.wait_for(_split_message(data), timeout=5) + + assert items == ([f"transformed_{i}" for i in range(5)], []) + + +async def test_messages_before_the_first_receiver_do_not_stop_the_stream() -> None: + """Messages sent before any receiver exists do not stop the stream.""" + calls: list[int] = [] + sent = asyncio.Event() + + async def stream() -> AsyncIterator[int]: + calls.append(len(calls)) + yield 0 + sent.set() + await asyncio.sleep(0.01) + yield 1 + await asyncio.Event().wait() + + helper = _helper(stream) + try: + await asyncio.wait_for(sent.wait(), timeout=5) + receiver = helper.new_receiver() + assert await asyncio.wait_for(receiver.receive(), timeout=5) == "transformed_1" + assert calls == [0] + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_restart_gets_a_fresh_retry_budget() -> None: + """A restarted stream does not inherit the retries the previous run used.""" + stream_method = _AlwaysFailing() + helper = _helper( + stream_method, + retry_strategy=retry.LinearBackoff(limit=1, interval=0.0, jitter=0.0), + ) + try: + first = helper.new_receiver() + await asyncio.sleep(0) + first.close() + await asyncio.sleep(0.01) + second = helper.new_receiver(include_events=True) + _, events = await asyncio.wait_for(_split_message(second), timeout=5) + assert [type(e) for e in events] == [ + StreamStarted, + StreamRetrying, + StreamStarted, + StreamFatalError, + ] + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_unexpected_error_ends_the_receivers() -> None: + """An unexpected error from the call ends the receivers instead of hanging them.""" + + async def stream() -> AsyncIterator[int]: + yield 1 + raise ValueError("unexpected") + + helper = _helper(stream) + receiver = helper.new_receiver(include_events=True) + items, events = await asyncio.wait_for(_split_message(receiver), timeout=5) + assert items == ["transformed_1"] + assert [type(e) for e in events] == [StreamStarted, StreamFatalError] + assert isinstance(events[1], StreamFatalError) + assert isinstance(events[1].exception, ValueError) + await helper.stop() + + +async def test_receiver_dropped_in_another_thread() -> None: + """A receiver collected in another thread stops the stream on the loop.""" + call = _HangingCall() + helper = _helper(lambda: call) + try: + holder = [helper.new_receiver()] + await asyncio.sleep(0.01) + thread = threading.Thread(target=holder.clear) + thread.start() + thread.join() + await asyncio.wait_for(_wait_until_stopped(helper), timeout=5) + assert call.cancelled == 1 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def _wait_until_stopped( + helper: streaming.GrpcStreamBroadcaster[int, str], +) -> None: + """Wait until the broadcaster is no longer running.""" + while helper.is_running: + await asyncio.sleep(0.01) + + +async def test_stop_before_the_stream_started() -> None: + """A receiver handed out right before stop() ends instead of hanging.""" + helper = _helper(_HangingCall) + receiver = helper.new_receiver() + await helper.stop() + assert await asyncio.wait_for(_split_message(receiver), timeout=5) == ([], []) + + +async def test_garbage_collection_while_subscribing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A receiver collected while a new one subscribes does not end the new one.""" + helper = _helper(_endless_stream) + gc.disable() + try: + first = helper.new_receiver() + await asyncio.wait_for(first.receive(), timeout=5) + _drop_in_a_cycle(first) + del first + _collect_garbage_before( + monkeypatch, streaming._Run, "subscribe" # pylint: disable=protected-access + ) + second = helper.new_receiver() + await asyncio.wait_for(second.receive(), timeout=5) + assert helper.is_running + finally: + gc.enable() + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_closed_receiver_stops_while_others_continue() -> None: + """A closed receiver ends even while the stream keeps running for others.""" + helper = _helper(_endless_stream) + try: + closed = helper.new_receiver() + kept = helper.new_receiver() + await asyncio.wait_for(kept.receive(), timeout=5) + closed.close() + with pytest.raises(ReceiverStoppedError): + await asyncio.wait_for(closed.receive(), timeout=5) + await asyncio.wait_for(kept.receive(), timeout=5) + assert helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_call_timeout_error_is_not_an_idle_timeout() -> None: + """A TimeoutError raised by the call is a failure, not an idle timeout.""" + calls = 0 + + async def stream() -> AsyncIterator[int]: + nonlocal calls + calls += 1 + raise TimeoutError("from the call") + yield 0 # pylint: disable=unreachable + + helper = _helper(stream, idle_timeout=timedelta(seconds=10)) + try: + receiver = helper.new_receiver(include_events=True) + _, events = await asyncio.wait_for(_split_message(receiver), timeout=5) + assert [type(e) for e in events] == [StreamStarted, StreamFatalError] + assert isinstance(events[1], StreamFatalError) + # pylint: disable-next=unidiomatic-typecheck + assert type(events[1].exception) is TimeoutError + assert calls == 1 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stop_does_not_swallow_the_callers_cancellation() -> None: + """Cancelling the task that awaits stop() cancels it.""" + helper = _helper(lambda: _SlowToCancel([], asyncio.Event())) + receiver = helper.new_receiver() + await asyncio.sleep(0.01) + stopper = asyncio.create_task(helper.stop()) + await asyncio.sleep(0.01) + stopper.cancel() + with pytest.raises(asyncio.CancelledError): + await stopper + assert await asyncio.wait_for(_split_message(receiver), timeout=5) == ([], []) + + +async def test_stop_closes_receivers_when_its_caller_is_cancelled() -> None: + """A cancelled stop() still ends the receivers of a run that never started.""" + receivers: list[Receiver[str]] = [] + + async def make_and_stop() -> None: + helper = _helper(_HangingCall) + receivers.append(helper.new_receiver()) + await helper.stop() + + stopper = asyncio.create_task(make_and_stop()) + await asyncio.sleep(0) + stopper.cancel() + with pytest.raises(asyncio.CancelledError): + await stopper + assert await asyncio.wait_for(_split_message(receivers[0]), timeout=5) == ( + [], + [], + ) + + +async def test_closing_a_receiver_twice_counts_it_once() -> None: + """A receiver closed twice, then collected, leaves the others running.""" + helper = _helper(_endless_stream) + try: + closed = helper.new_receiver() + kept = helper.new_receiver() + await asyncio.wait_for(kept.receive(), timeout=5) + closed.close() + closed.close() + del closed + gc.collect() + await asyncio.sleep(0.02) + assert helper.is_running + await asyncio.wait_for(kept.receive(), timeout=5) + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_failed_new_receiver_is_not_counted() -> None: + """A new_receiver() call that raises does not keep the stream running.""" + helper = _helper(_HangingCall) + try: + receiver = helper.new_receiver() + with pytest.raises(ValueError): + helper.new_receiver(maxsize=-1) + receiver.close() + assert not helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_failed_close_still_counts_the_receiver_as_gone( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A receiver whose close() raises no longer keeps the stream running.""" + + def failing_close() -> None: + raise RuntimeError("close failed") + + helper = _helper(_HangingCall) + try: + receiver = helper.new_receiver() + monkeypatch.setattr(getattr(receiver, "_receiver"), "close", failing_close) + with pytest.raises(RuntimeError, match="close failed"): + receiver.close() + assert not helper.is_running + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_restart_after_release_inside_the_stream_step( + caplog: pytest.LogCaptureFixture, +) -> None: + """A stream whose last receiver goes away in its own step restarts later.""" + caplog.set_level(logging.WARNING) + receivers: list[Receiver[str]] = [] + + async def stream() -> AsyncIterator[int]: + if not receivers: + raise AssertionError("no receiver yet") + if len(receivers) == 1: + receivers[0].close() + raise make_error() + yield 1 + await asyncio.Event().wait() + + helper = _helper(stream, retry_strategy=retry.LinearBackoff(interval=0.0)) + try: + receivers.append(helper.new_receiver()) + await asyncio.wait_for(_wait_until_stopped(helper), timeout=5) + assert not [r for r in caplog.records if r.name == streaming.__name__] + receivers.append(helper.new_receiver()) + assert await asyncio.wait_for(receivers[1].receive(), timeout=5) == ( + "transformed_1" + ) + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_runs_do_not_pile_up() -> None: + """Receivers closed right after they are created do not leave runs behind.""" + helper = _helper(_CountingStream()) + try: + for _ in range(20): + helper.new_receiver().close() + await asyncio.sleep(0) + helper.new_receiver() + assert len(helper._runs) <= 2 # pylint: disable=protected-access + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_garbage_collection_while_counting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A receiver collected while a new one is counted makes the stream restart.""" + helper = _helper(_CountingStream()) + gc.disable() + try: + first = helper.new_receiver() + assert await asyncio.wait_for(first.receive(), timeout=5) == "transformed_1" + _drop_in_a_cycle(first) + del first + _collect_garbage_before( + monkeypatch, + streaming._ReceiverCounter, # pylint: disable=protected-access + "acquire", + ) + second = helper.new_receiver() + assert await asyncio.wait_for(second.receive(), timeout=5) == "transformed_2" + finally: + gc.enable() + await asyncio.wait_for(helper.stop(), timeout=5) + + +@pytest.mark.parametrize("fails", [False, True], ids=["ended", "gave-up"]) +async def test_finished_stream_stays_finished(fails: bool) -> None: + """A stream that ended or gave up on its own is not restarted.""" + calls = 0 + + async def stream() -> AsyncIterator[int]: + nonlocal calls + calls += 1 + yield 1 + if fails: + raise make_error() + + helper = _helper( + stream, retry_strategy=retry.LinearBackoff(limit=0, interval=0.0, jitter=0.0) + ) + try: + first = helper.new_receiver() + assert await asyncio.wait_for(_split_message(first), timeout=5) == ( + ["transformed_1"], + [], + ) + first.close() + late = helper.new_receiver() + assert await asyncio.wait_for(_split_message(late), timeout=5) == ([], []) + late_events = helper.new_receiver(include_events=True) + assert await asyncio.wait_for(_split_message(late_events), timeout=5) == ( + [], + [], + ) + assert calls == 1 + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_restart_lets_the_old_call_finish_its_cleanup() -> None: + """Starting a new run does not interrupt the old call's cleanup.""" + cleanups: list[str] = [] + finished = asyncio.Event() + calls: list[_SlowToCancel] = [] + + def stream_method() -> _SlowToCancel: + calls.append( + _SlowToCancel(cleanups, finished if not calls else asyncio.Event()) + ) + return calls[-1] + + helper = _helper(stream_method) + try: + first = helper.new_receiver() + await asyncio.sleep(0.01) + first.close() + await asyncio.sleep(0.01) + second = helper.new_receiver() + await asyncio.wait_for(finished.wait(), timeout=5) + assert cleanups == ["done"] + assert helper.is_running + second.close() + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +async def test_stop_waits_for_older_runs() -> None: + """stop() waits until the calls of earlier runs have finished their cleanup.""" + finished = asyncio.Event() + calls: list[_HangingCall] = [] + + def stream_method() -> _HangingCall: + calls.append(_SlowToCancel([], finished) if not calls else _HangingCall()) + return calls[-1] + + helper = _helper(stream_method) + first = helper.new_receiver() + await asyncio.sleep(0.01) + first.close() + second = helper.new_receiver() + await asyncio.sleep(0.01) + await asyncio.wait_for(helper.stop(), timeout=5) + assert finished.is_set() + second.close() + + +async def test_restart_after_a_failed_cleanup() -> None: + """A stream that fails while it stops for lack of receivers still restarts.""" + calls = 0 + + async def stream() -> AsyncIterator[int]: + nonlocal calls + calls += 1 + yield calls + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + raise RuntimeError("cleanup failed") from None + + helper = _helper(stream) + try: + first = helper.new_receiver() + assert await asyncio.wait_for(first.receive(), timeout=5) == "transformed_1" + first.close() + await asyncio.sleep(0.05) + second = helper.new_receiver() + assert await asyncio.wait_for(second.receive(), timeout=5) == "transformed_2" + finally: + await asyncio.wait_for(helper.stop(), timeout=5) + + +class _CollectGarbage(logging.Filter): + """A log filter that runs a full garbage collection for every record.""" + + def filter(self, record: logging.LogRecord) -> bool: + """Collect garbage and keep the record.""" + gc.collect() + return True + + +@pytest.mark.parametrize( + "error", + [None, make_error(), ValueError("unexpected")], + ids=["ended", "gave-up", "failed"], +) +async def test_receiver_collected_as_the_stream_finishes( + error: Exception | None, + caplog: pytest.LogCaptureFixture, +) -> None: + """A stream whose last receiver is collected after it ended stays finished.""" + caplog.set_level(logging.INFO, logger=streaming.__name__) + calls = 0 + finish = asyncio.Event() + + async def stream() -> AsyncIterator[int]: + nonlocal calls + calls += 1 + yield 1 + await finish.wait() + if error is not None: + raise error + + helper = _helper( + stream, retry_strategy=retry.LinearBackoff(limit=0, interval=0.0, jitter=0.0) + ) + logger = logging.getLogger(streaming.__name__) + collect = _CollectGarbage() + gc.disable() + try: + first = helper.new_receiver() + assert await asyncio.wait_for(first.receive(), timeout=5) == "transformed_1" + _drop_in_a_cycle(first) + del first + logger.addFilter(collect) + finish.set() + await asyncio.wait_for(_wait_until_stopped(helper), timeout=5) + await asyncio.sleep(0.01) + logger.removeFilter(collect) + late = helper.new_receiver() + assert await asyncio.wait_for(_split_message(late), timeout=5) == ([], []) + assert calls == 1 + finally: + logger.removeFilter(collect) + gc.enable() + await asyncio.wait_for(helper.stop(), timeout=5)