| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import trio |
| 4 |
|
| 5 |
from .task_group import TaskGroup |
| 6 |
from .worker_context import WorkerContext |
| 7 |
from ..config import Config |
| 8 |
from ..events import Event, RawData |
| 9 |
from ..typing import AppWrapper |
| 10 |
from ..utils import parse_socket_addr |
| 11 |
|
| 12 |
MAX_RECV = 2**16 |
| 13 |
|
| 14 |
|
| 15 |
class UDPServer: |
| 16 |
def __init__( |
| 17 |
self, |
| 18 |
app: AppWrapper, |
| 19 |
config: Config, |
| 20 |
context: WorkerContext, |
| 21 |
socket: trio.socket.socket, |
| 22 |
) -> None: |
| 23 |
self.app = app |
| 24 |
self.config = config |
| 25 |
self.context = context |
| 26 |
self.socket = trio.socket.from_stdlib_socket(socket) |
| 27 |
|
| 28 |
async def run( |
| 29 |
self, task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED |
| 30 |
) -> None: |
| 31 |
from ..protocol.quic import QuicProtocol # h3/Quic is an optional part of Hypercorn |
| 32 |
|
| 33 |
task_status.started() |
| 34 |
server = parse_socket_addr(self.socket.family, self.socket.getsockname()) |
| 35 |
async with TaskGroup() as task_group: |
| 36 |
self.protocol = QuicProtocol( |
| 37 |
self.app, self.config, self.context, task_group, server, self.protocol_send |
| 38 |
) |
| 39 |
|
| 40 |
while not self.context.terminated.is_set() or not self.protocol.idle: |
| 41 |
data, address = await self.socket.recvfrom(MAX_RECV) |
| 42 |
await self.protocol.handle(RawData(data=data, address=address)) |
| 43 |
|
| 44 |
async def protocol_send(self, event: Event) -> None: |
| 45 |
if isinstance(event, RawData): |
| 46 |
await self.socket.sendto(event.data, event.address) |