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
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import asyncio
import functools
import inspect

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.

medium

To optimize startup performance and avoid importing the heavy inspect module, we can import collections.abc instead and use isinstance(..., collections.abc.Awaitable).

Suggested change
import inspect
import collections.abc

import sys
import time
from typing import (
Expand Down Expand Up @@ -123,13 +124,10 @@ async def retry_target_stream(
target_output: AsyncIterable[_Y] | Awaitable[AsyncIterable[_Y]] = target(
*init_args, **init_kwargs
)
try:
if inspect.isawaitable(target_output):

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.

medium

Use isinstance(target_output, collections.abc.Awaitable) instead of inspect.isawaitable(target_output) to avoid the overhead of importing the inspect module.

Suggested change
if inspect.isawaitable(target_output):
if isinstance(target_output, collections.abc.Awaitable):

# gapic functions return the generator behind an awaitable
# unwrap the awaitable so we can work with the generator directly
target_output = await target_output # type: ignore
except TypeError:
# was not awaitable, continue
pass
target_output = await target_output
target_iterator = cast(AsyncIterable["_Y"], target_output).__aiter__()

if target_is_generator is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,49 @@ def push_sleep_value(err):
sleep.assert_called_once_with(inserted_sleep)


@pytest.mark.asyncio
@pytest.mark.parametrize("custom_awaitable", [False, True])
@pytest.mark.parametrize("retryable", [False, True])
async def test_retry_streaming_factory_type_error(custom_awaitable, retryable):
error = TypeError("stream setup failed")
attempts = []

async def values():
yield 42

async def factory():
attempts.append(None)
if len(attempts) == 1:
raise error
return values()

class Awaitable:
def __await__(self):
return factory().__await__()

on_error = mock.Mock()
target = Awaitable if custom_awaitable else factory
stream = retry_streaming_async.retry_target_stream(
target,
predicate=lambda exc: retryable and isinstance(exc, TypeError),
sleep_generator=[0],
on_error=on_error,
)
with mock.patch("asyncio.sleep", new_callable=mock.AsyncMock) as sleep:
if retryable:
assert [item async for item in stream] == [42]
assert len(attempts) == 2
on_error.assert_called_once_with(error)
sleep.assert_awaited_once_with(0)
else:
with pytest.raises(TypeError) as exc_info:
await stream.__anext__()
assert exc_info.value is error
assert len(attempts) == 1
on_error.assert_not_called()
sleep.assert_not_awaited()


class TestAsyncStreamingRetry(Test_BaseRetry):
def _make_one(self, *args, **kwargs):
return retry_streaming_async.AsyncStreamingRetry(*args, **kwargs)
Expand Down
Loading