| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from functools import partial |
| 5 |
from types import TracebackType |
| 6 |
from typing import Any, Awaitable, Callable, Optional |
| 7 |
|
| 8 |
from ..config import Config |
| 9 |
from ..typing import AppWrapper, ASGIReceiveCallable, ASGIReceiveEvent, ASGISendEvent, Scope |
| 10 |
|
| 11 |
try: |
| 12 |
from asyncio import TaskGroup as AsyncioTaskGroup |
| 13 |
except ImportError: |
| 14 |
from taskgroup import TaskGroup as AsyncioTaskGroup # type: ignore |
| 15 |
|
| 16 |
|
| 17 |
async def _handle( |
| 18 |
app: AppWrapper, |
| 19 |
config: Config, |
| 20 |
scope: Scope, |
| 21 |
receive: ASGIReceiveCallable, |
| 22 |
send: Callable[[Optional[ASGISendEvent]], Awaitable[None]], |
| 23 |
sync_spawn: Callable, |
| 24 |
call_soon: Callable, |
| 25 |
) -> None: |
| 26 |
try: |
| 27 |
await app(scope, receive, send, sync_spawn, call_soon) |
| 28 |
except asyncio.CancelledError: |
| 29 |
raise |
| 30 |
except Exception: |
| 31 |
await config.log.exception("Error in ASGI Framework") |
| 32 |
finally: |
| 33 |
await send(None) |
| 34 |
|
| 35 |
|
| 36 |
class TaskGroup: |
| 37 |
def __init__(self, loop: asyncio.AbstractEventLoop) -> None: |
| 38 |
self._loop = loop |
| 39 |
self._task_group = AsyncioTaskGroup() |
| 40 |
|
| 41 |
async def spawn_app( |
| 42 |
self, |
| 43 |
app: AppWrapper, |
| 44 |
config: Config, |
| 45 |
scope: Scope, |
| 46 |
send: Callable[[Optional[ASGISendEvent]], Awaitable[None]], |
| 47 |
) -> Callable[[ASGIReceiveEvent], Awaitable[None]]: |
| 48 |
app_queue: asyncio.Queue[ASGIReceiveEvent] = asyncio.Queue(config.max_app_queue_size) |
| 49 |
|
| 50 |
def _call_soon(func: Callable, *args: Any) -> Any: |
| 51 |
future = asyncio.run_coroutine_threadsafe(func(*args), self._loop) |
| 52 |
return future.result() |
| 53 |
|
| 54 |
self.spawn( |
| 55 |
_handle, |
| 56 |
app, |
| 57 |
config, |
| 58 |
scope, |
| 59 |
app_queue.get, |
| 60 |
send, |
| 61 |
partial(self._loop.run_in_executor, None), |
| 62 |
_call_soon, |
| 63 |
) |
| 64 |
return app_queue.put |
| 65 |
|
| 66 |
def spawn(self, func: Callable, *args: Any) -> None: |
| 67 |
self._task_group.create_task(func(*args)) |
| 68 |
|
| 69 |
async def __aenter__(self) -> "TaskGroup": |
| 70 |
await self._task_group.__aenter__() |
| 71 |
return self |
| 72 |
|
| 73 |
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None: |
| 74 |
await self._task_group.__aexit__(exc_type, exc_value, tb) |