-
-
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
Closed
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
da9468a
fix!: ensure that generator clean up is correctly propagated
winstxnhdw 2c8fd96
feat: allow user to handle disconnect with `athrow`
winstxnhdw e8028dd
refactor: remove redundant flag synchronisation
winstxnhdw 08b5607
style: make `Event` a class attribute
winstxnhdw 011f50f
chore: always break after `athrow`
winstxnhdw 6874f49
fix: use `hasattr` to check if `content_async_iterator` exists
winstxnhdw 85ff626
refactor: handle `athrow` edge cases at the same site
winstxnhdw 3663919
test/refactor: use subprocess client
winstxnhdw 6bff665
fix: avoid strange timeout in `pytest`
winstxnhdw 12ef3f3
test: add tests for `AsyncIteratorWrapper`
winstxnhdw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
|
||
| self.iterator = iter(iterator) | ||
| self.generator = self._async_generator() | ||
|
|
||
| def _call_next(self) -> T: | ||
|
|
@@ -78,8 +102,28 @@ 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 typ(val, tb), | ||
| ) | ||
| except StopIteration as e: | ||
| raise StopAsyncIteration from e | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: | ||
| for _ in range(10): | ||
| yield data.file_content | ||
| await sleep(0.1) | ||
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.