Debian Codegraph @

debian/vendor/hypercorn/trio/task_group.py

raw
1 from __future__ import annotations
2
3 import sys
4 from types import TracebackType
5 from typing import Any, Awaitable, Callable, Optional
6
7 import trio
8
9 from ..config import Config
10 from ..typing import AppWrapper, ASGIReceiveCallable, ASGIReceiveEvent, ASGISendEvent, Scope
11
12 if sys.version_info < (3, 11):
13 from exceptiongroup import BaseExceptionGroup
14
15
16 async def _handle(
17 app: AppWrapper,
18 config: Config,
19 scope: Scope,
20 receive: ASGIReceiveCallable,
21 send: Callable[[Optional[ASGISendEvent]], Awaitable[None]],
22 sync_spawn: Callable,
23 call_soon: Callable,
24 ) -> None:
25 try:
26 await app(scope, receive, send, sync_spawn, call_soon)
27 except trio.Cancelled:
28 raise
29 except BaseExceptionGroup as error:
30 _, other_errors = error.split(trio.Cancelled)
31 if other_errors is not None:
32 await config.log.exception("Error in ASGI Framework")
33 await send(None)
34 else:
35 raise
36 except Exception:
37 await config.log.exception("Error in ASGI Framework")
38 finally:
39 await send(None)
40
41
42 class TaskGroup:
43 def __init__(self) -> None:
44 self._nursery: Optional[trio._core._run.Nursery] = None
45 self._nursery_manager: Optional[trio._core._run.NurseryManager] = None
46
47 async def spawn_app(
48 self,
49 app: AppWrapper,
50 config: Config,
51 scope: Scope,
52 send: Callable[[Optional[ASGISendEvent]], Awaitable[None]],
53 ) -> Callable[[ASGIReceiveEvent], Awaitable[None]]:
54 app_send_channel, app_receive_channel = trio.open_memory_channel(config.max_app_queue_size)
55 self._nursery.start_soon(
56 _handle,
57 app,
58 config,
59 scope,
60 app_receive_channel.receive,
61 send,
62 trio.to_thread.run_sync,
63 trio.from_thread.run,
64 )
65 return app_send_channel.send
66
67 def spawn(self, func: Callable, *args: Any) -> None:
68 self._nursery.start_soon(func, *args)
69
70 async def __aenter__(self) -> TaskGroup:
71 self._nursery_manager = trio.open_nursery()
72 self._nursery = await self._nursery_manager.__aenter__()
73 return self
74
75 async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
76 await self._nursery_manager.__aexit__(exc_type, exc_value, tb)
77 self._nursery_manager = None
78 self._nursery = None