Debian Codegraph @

src/quart_trio/utils.py

raw
1 from contextvars import copy_context
2 from functools import partial, wraps
3 from inspect import isgenerator
4 from typing import Any, AsyncGenerator, Callable, Coroutine, Generator
5
6 import trio
7
8
9 def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
10 """Ensure that the sync function is run without blocking.
11
12 If the *func* is not a coroutine it will be wrapped such that it
13 runs on a thread. This ensures that synchronous functions do not
14 block the event loop.
15 """
16
17 @wraps(func)
18 async def _wrapper(*args: Any, **kwargs: Any) -> Any:
19 result = await trio.to_thread.run_sync(copy_context().run, partial(func, *args, **kwargs))
20 if isgenerator(result):
21 return run_sync_iterable(result) # type: ignore
22 else:
23 return result
24
25 _wrapper._quart_async_wrapper = True # type: ignore
26 return _wrapper
27
28
29 def run_sync_iterable(iterable: Generator[Any, None, None]) -> AsyncGenerator[Any, None]:
30 async def _gen_wrapper() -> AsyncGenerator[Any, None]:
31 # Wrap the generator such that each iteration runs
32 # in the executor. Then rationalise the raised
33 # errors so that it ends.
34 def _inner() -> Any:
35 # https://bugs.python.org/issue26221
36 # StopIteration errors are swallowed by the
37 # run_in_exector method
38 try:
39 return next(iterable)
40 except StopIteration:
41 raise StopAsyncIteration()
42
43 while True:
44 try:
45 yield await trio.to_thread.run_sync(partial(copy_context().run, _inner))
46 except StopAsyncIteration:
47 return
48
49 return _gen_wrapper()