| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from functools import partial |
| 5 |
from typing import Callable, Dict |
| 6 |
|
| 7 |
from ..asyncio.task_group import TaskGroup |
| 8 |
from ..typing import ASGIFramework, Scope |
| 9 |
|
| 10 |
MAX_QUEUE_SIZE = 10 |
| 11 |
|
| 12 |
|
| 13 |
class _DispatcherMiddleware: |
| 14 |
def __init__(self, mounts: Dict[str, ASGIFramework]) -> None: |
| 15 |
self.mounts = mounts |
| 16 |
|
| 17 |
async def __call__(self, scope: Scope, receive: Callable, send: Callable) -> None: |
| 18 |
if scope["type"] == "lifespan": |
| 19 |
await self._handle_lifespan(scope, receive, send) |
| 20 |
else: |
| 21 |
for path, app in self.mounts.items(): |
| 22 |
if scope["path"].startswith(path): |
| 23 |
scope["path"] = scope["path"][len(path) :] or "/" |
| 24 |
return await app(scope, receive, send) |
| 25 |
await send( |
| 26 |
{ |
| 27 |
"type": "http.response.start", |
| 28 |
"status": 404, |
| 29 |
"headers": [(b"content-length", b"0")], |
| 30 |
} |
| 31 |
) |
| 32 |
await send({"type": "http.response.body"}) |
| 33 |
|
| 34 |
async def _handle_lifespan(self, scope: Scope, receive: Callable, send: Callable) -> None: |
| 35 |
pass |
| 36 |
|
| 37 |
|
| 38 |
class AsyncioDispatcherMiddleware(_DispatcherMiddleware): |
| 39 |
async def _handle_lifespan(self, scope: Scope, receive: Callable, send: Callable) -> None: |
| 40 |
self.app_queues: Dict[str, asyncio.Queue] = { |
| 41 |
path: asyncio.Queue(MAX_QUEUE_SIZE) for path in self.mounts |
| 42 |
} |
| 43 |
self.startup_complete = {path: False for path in self.mounts} |
| 44 |
self.shutdown_complete = {path: False for path in self.mounts} |
| 45 |
|
| 46 |
async with TaskGroup(asyncio.get_event_loop()) as task_group: |
| 47 |
for path, app in self.mounts.items(): |
| 48 |
task_group.spawn( |
| 49 |
app, |
| 50 |
scope, |
| 51 |
self.app_queues[path].get, |
| 52 |
partial(self.send, path, send), |
| 53 |
) |
| 54 |
|
| 55 |
while True: |
| 56 |
message = await receive() |
| 57 |
for queue in self.app_queues.values(): |
| 58 |
await queue.put(message) |
| 59 |
if message["type"] == "lifespan.shutdown": |
| 60 |
break |
| 61 |
|
| 62 |
async def send(self, path: str, send: Callable, message: dict) -> None: |
| 63 |
if message["type"] == "lifespan.startup.complete": |
| 64 |
self.startup_complete[path] = True |
| 65 |
if all(self.startup_complete.values()): |
| 66 |
await send({"type": "lifespan.startup.complete"}) |
| 67 |
elif message["type"] == "lifespan.shutdown.complete": |
| 68 |
self.shutdown_complete[path] = True |
| 69 |
if all(self.shutdown_complete.values()): |
| 70 |
await send({"type": "lifespan.shutdown.complete"}) |
| 71 |
|
| 72 |
|
| 73 |
class TrioDispatcherMiddleware(_DispatcherMiddleware): |
| 74 |
async def _handle_lifespan(self, scope: Scope, receive: Callable, send: Callable) -> None: |
| 75 |
import trio |
| 76 |
|
| 77 |
self.app_queues = {path: trio.open_memory_channel(MAX_QUEUE_SIZE) for path in self.mounts} |
| 78 |
self.startup_complete = {path: False for path in self.mounts} |
| 79 |
self.shutdown_complete = {path: False for path in self.mounts} |
| 80 |
|
| 81 |
async with trio.open_nursery() as nursery: |
| 82 |
for path, app in self.mounts.items(): |
| 83 |
nursery.start_soon( |
| 84 |
app, |
| 85 |
scope, |
| 86 |
self.app_queues[path][1].receive, |
| 87 |
partial(self.send, path, send), |
| 88 |
) |
| 89 |
|
| 90 |
while True: |
| 91 |
message = await receive() |
| 92 |
for channels in self.app_queues.values(): |
| 93 |
await channels[0].send(message) |
| 94 |
if message["type"] == "lifespan.shutdown": |
| 95 |
break |
| 96 |
|
| 97 |
async def send(self, path: str, send: Callable, message: dict) -> None: |
| 98 |
if message["type"] == "lifespan.startup.complete": |
| 99 |
self.startup_complete[path] = True |
| 100 |
if all(self.startup_complete.values()): |
| 101 |
await send({"type": "lifespan.startup.complete"}) |
| 102 |
elif message["type"] == "lifespan.shutdown.complete": |
| 103 |
self.shutdown_complete[path] = True |
| 104 |
if all(self.shutdown_complete.values()): |
| 105 |
await send({"type": "lifespan.shutdown.complete"}) |
| 106 |
|
| 107 |
|
| 108 |
DispatcherMiddleware = AsyncioDispatcherMiddleware # Remove with version 0.11 |