-
-
Notifications
You must be signed in to change notification settings - Fork 535
fix!: ensure that generator clean up is correctly propagated #4394
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 8 commits
da9468a
2c8fd96
e8028dd
08b5607
011f50f
6874f49
85ff626
3663919
6bff665
12ef3f3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
|
winstxnhdw marked this conversation as resolved.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,38 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import AsyncGenerator, Awaitable, Iterable, Iterator | ||
| from collections.abc import AsyncGenerator, Awaitable, Generator, Iterable | ||
| from typing import ( | ||
| TYPE_CHECKING, | ||
| Callable, | ||
| Generic, | ||
| TypeVar, | ||
| overload, | ||
| ) | ||
|
|
||
| from typing_extensions import ParamSpec | ||
| from typing_extensions import ParamSpec, TypeVar | ||
|
|
||
| from litestar.concurrency import sync_to_thread | ||
| from litestar.utils.predicates import is_async_callable | ||
|
|
||
| if TYPE_CHECKING: | ||
| from types import TracebackType | ||
|
|
||
| __all__ = ("AsyncCallable", "AsyncIteratorWrapper", "ensure_async_callable", "is_async_callable") | ||
|
|
||
|
|
||
| P = ParamSpec("P") | ||
| T = TypeVar("T") | ||
| S = TypeVar("S", default=None) | ||
|
|
||
|
|
||
| def iterable_to_generator(iterable: Iterable[T]) -> Generator[T, S, None]: | ||
| """Convert an iterable to a generator. | ||
|
|
||
| Args: | ||
| iterable: An iterable. | ||
|
|
||
| Returns: | ||
| A generator. | ||
| """ | ||
| yield from iterable | ||
|
|
||
|
|
||
| @overload | ||
|
|
@@ -51,18 +66,27 @@ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Awaitable[T]: # type: | |
| return sync_to_thread(self.func, *args, **kwargs) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| class AsyncIteratorWrapper(Generic[T]): | ||
| class AsyncIteratorWrapper(AsyncGenerator[T, S]): | ||
| """Asynchronous generator, wrapping an iterable or iterator.""" | ||
|
|
||
| __slots__ = ("generator", "iterator") | ||
| __slots__ = ("_original_generator", "generator", "iterator") | ||
|
|
||
| def __init__(self, iterator: Iterator[T] | Iterable[T]) -> None: | ||
| """Take a sync iterator or iterable and yields values from it asynchronously. | ||
| def __init__(self, iterator: Iterable[T]) -> None: | ||
| """Take a sync iterable and yields values from it asynchronously. | ||
|
|
||
| Args: | ||
| iterator: A sync iterator or iterable. | ||
| iterator: A sync iterable. | ||
| """ | ||
| self.iterator = iterator if isinstance(iterator, Iterator) else iter(iterator) | ||
| self._original_generator: Generator[T, S, None] | ||
|
|
||
| if isinstance(iterator, Generator): | ||
| self._original_generator = iterator | ||
| elif isinstance(iterator, AsyncIteratorWrapper): | ||
| self._original_generator = iterator._original_generator | ||
|
Comment on lines
+84
to
+85
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This fundamentally changes the functionality of |
||
| else: | ||
| self._original_generator = iterable_to_generator(iterator) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line is still necessary for |
||
|
|
||
| self.iterator = iter(iterator) | ||
| self.generator = self._async_generator() | ||
|
|
||
| def _call_next(self) -> T: | ||
|
|
@@ -78,8 +102,29 @@ async def _async_generator(self) -> AsyncGenerator[T, None]: | |
| except ValueError: | ||
| return | ||
|
|
||
| def __aiter__(self) -> AsyncIteratorWrapper[T]: | ||
| def __aiter__(self) -> AsyncIteratorWrapper[T, S]: | ||
| return self | ||
|
|
||
| async def __anext__(self) -> T: | ||
| return await self.generator.__anext__() | ||
|
|
||
| async def aclose(self) -> None: | ||
| await sync_to_thread(self._original_generator.close) | ||
|
|
||
| async def asend(self, value: S) -> T: | ||
| return await sync_to_thread(self._original_generator.send, value) | ||
|
|
||
| async def athrow( | ||
| self, | ||
| typ: BaseException | type[BaseException], | ||
| val: BaseException | object = None, | ||
| tb: TracebackType | None = None, | ||
| ) -> T: | ||
| try: | ||
| return ( | ||
| await sync_to_thread(self._original_generator.throw, typ) | ||
| if isinstance(typ, BaseException) | ||
| else await sync_to_thread(self._original_generator.throw, typ, val, tb) | ||
| ) | ||
| except StopIteration as e: | ||
| raise StopAsyncIteration from e | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| from collections.abc import AsyncIterator | ||
|
|
||
| from anyio import Path, open_file, sleep | ||
| from msgspec import Struct | ||
|
|
||
| from litestar import Litestar, post | ||
| from litestar.response import ServerSentEvent | ||
| from litestar.response.streaming import ClientDisconnectError | ||
|
|
||
|
|
||
| class CleanupRequest(Struct): | ||
| file_path: str | ||
| file_content: str | ||
|
|
||
|
|
||
| @post("/cleanup") | ||
| async def get_notified(data: CleanupRequest) -> ServerSentEvent: | ||
| async with await open_file(data.file_path, "w") as file: | ||
| await file.write(data.file_content) | ||
|
|
||
| async def generator() -> AsyncIterator[str]: | ||
| try: | ||
| while True: | ||
| yield data.file_content | ||
| await sleep(0.1) | ||
|
Comment on lines
22
to
25
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Finally found the issue with the test. The SSE needs to continuously yield something otherwise the generator cannot handle the |
||
| except ClientDisconnectError: | ||
| await Path(data.file_path).unlink() | ||
|
|
||
| return ServerSentEvent(generator()) | ||
|
|
||
|
|
||
| def create_test_app() -> Litestar: | ||
| return Litestar(route_handlers=[get_notified]) | ||
|
|
||
|
|
||
| app = create_test_app() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Again, I do not understand why you have to be so over specific here. It should be good enough to simply check:
athrowbreakUh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The issue here is how
_ServerSentEventIteratoris designed. The content is kept inself.content_async_iterator, which means to close the original generator from the handler, we need to specifically throwself.iterator.content_async_iteratorbecauseself.iteratorwill only contain the header chunks likeevent_id,event_type, etc.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_ServerSentEventIteratorshould handle that though, not the code that's calling it. It knows about its internal state, and is best suited to decide where to throw what exception. From the outside, it should be treated as any other async iterator / generator.