Debian Codegraph @

debian/vendor/hypercorn/middleware/wsgi.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 from functools import partial
5 from typing import Any, Callable, Iterable
6
7 from ..app_wrappers import WSGIWrapper
8 from ..typing import ASGIReceiveCallable, ASGISendCallable, Scope, WSGIFramework
9
10 MAX_BODY_SIZE = 2**16
11
12 WSGICallable = Callable[[dict, Callable], Iterable[bytes]]
13
14
15 class InvalidPathError(Exception):
16 pass
17
18
19 class _WSGIMiddleware:
20 def __init__(self, wsgi_app: WSGIFramework, max_body_size: int = MAX_BODY_SIZE) -> None:
21 self.wsgi_app = WSGIWrapper(wsgi_app, max_body_size)
22 self.max_body_size = max_body_size
23
24 async def __call__(
25 self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
26 ) -> None:
27 pass
28
29
30 class AsyncioWSGIMiddleware(_WSGIMiddleware):
31 async def __call__(
32 self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
33 ) -> None:
34 loop = asyncio.get_event_loop()
35
36 def _call_soon(func: Callable, *args: Any) -> Any:
37 future = asyncio.run_coroutine_threadsafe(func(*args), loop)
38 return future.result()
39
40 await self.wsgi_app(scope, receive, send, partial(loop.run_in_executor, None), _call_soon)
41
42
43 class TrioWSGIMiddleware(_WSGIMiddleware):
44 async def __call__(
45 self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
46 ) -> None:
47 import trio
48
49 await self.wsgi_app(scope, receive, send, trio.to_thread.run_sync, trio.from_thread.run)