Debian Codegraph @

debian/vendor/hypercorn/asyncio/udp_server.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 from typing import Optional, Tuple, TYPE_CHECKING
5
6 from .task_group import TaskGroup
7 from .worker_context import WorkerContext
8 from ..config import Config
9 from ..events import Event, RawData
10 from ..typing import AppWrapper
11 from ..utils import parse_socket_addr
12
13 if TYPE_CHECKING:
14 # h3/Quic is an optional part of Hypercorn
15 from ..protocol.quic import QuicProtocol # noqa: F401
16
17
18 class UDPServer(asyncio.DatagramProtocol):
19 def __init__(
20 self,
21 app: AppWrapper,
22 loop: asyncio.AbstractEventLoop,
23 config: Config,
24 context: WorkerContext,
25 ) -> None:
26 self.app = app
27 self.config = config
28 self.context = context
29 self.loop = loop
30 self.protocol: "QuicProtocol"
31 self.protocol_queue: asyncio.Queue = asyncio.Queue(10)
32 self.transport: Optional[asyncio.DatagramTransport] = None
33
34 def connection_made(self, transport: asyncio.DatagramTransport) -> None: # type: ignore
35 self.transport = transport
36
37 def datagram_received(self, data: bytes, address: Tuple[bytes, str]) -> None: # type: ignore
38 try:
39 self.protocol_queue.put_nowait(RawData(data=data, address=address)) # type: ignore
40 except asyncio.QueueFull:
41 pass # Just throw the data away, is UDP
42
43 async def run(self) -> None:
44 # h3/Quic is an optional part of Hypercorn
45 from ..protocol.quic import QuicProtocol # noqa: F811
46
47 socket = self.transport.get_extra_info("socket")
48 server = parse_socket_addr(socket.family, socket.getsockname())
49 async with TaskGroup(self.loop) as task_group:
50 self.protocol = QuicProtocol(
51 self.app, self.config, self.context, task_group, server, self.protocol_send
52 )
53
54 while not self.context.terminated.is_set() or not self.protocol.idle:
55 event = await self.protocol_queue.get()
56 await self.protocol.handle(event)
57
58 async def protocol_send(self, event: Event) -> None:
59 if isinstance(event, RawData):
60 self.transport.sendto(event.data, event.address)