Debian Codegraph @

debian/vendor/hypercorn/asyncio/run.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import platform
5 import signal
6 import ssl
7 from functools import partial
8 from multiprocessing.synchronize import Event as EventType
9 from os import getpid
10 from socket import socket
11 from typing import Any, Awaitable, Callable, Optional, Set
12
13 from .lifespan import Lifespan
14 from .statsd import StatsdLogger
15 from .tcp_server import TCPServer
16 from .udp_server import UDPServer
17 from .worker_context import WorkerContext
18 from ..config import Config, Sockets
19 from ..typing import AppWrapper
20 from ..utils import (
21 check_multiprocess_shutdown_event,
22 load_application,
23 raise_shutdown,
24 repr_socket_addr,
25 ShutdownError,
26 )
27
28 try:
29 from asyncio import Runner
30 except ImportError:
31 from taskgroup import Runner # type: ignore
32
33
34 def _share_socket(sock: socket) -> socket:
35 # Windows requires the socket be explicitly shared across
36 # multiple workers (processes).
37 from socket import fromshare # type: ignore
38
39 sock_data = sock.share(getpid()) # type: ignore
40 return fromshare(sock_data)
41
42
43 async def worker_serve(
44 app: AppWrapper,
45 config: Config,
46 *,
47 sockets: Optional[Sockets] = None,
48 shutdown_trigger: Optional[Callable[..., Awaitable]] = None,
49 ) -> None:
50 config.set_statsd_logger_class(StatsdLogger)
51
52 loop = asyncio.get_event_loop()
53
54 if shutdown_trigger is None:
55 signal_event = asyncio.Event()
56
57 def _signal_handler(*_: Any) -> None: # noqa: N803
58 signal_event.set()
59
60 for signal_name in {"SIGINT", "SIGTERM", "SIGBREAK"}:
61 if hasattr(signal, signal_name):
62 try:
63 loop.add_signal_handler(getattr(signal, signal_name), _signal_handler)
64 except NotImplementedError:
65 # Add signal handler may not be implemented on Windows
66 signal.signal(getattr(signal, signal_name), _signal_handler)
67
68 shutdown_trigger = signal_event.wait # type: ignore
69
70 lifespan = Lifespan(app, config, loop)
71
72 lifespan_task = loop.create_task(lifespan.handle_lifespan())
73 await lifespan.wait_for_startup()
74 if lifespan_task.done():
75 exception = lifespan_task.exception()
76 if exception is not None:
77 raise exception
78
79 if sockets is None:
80 sockets = config.create_sockets()
81
82 ssl_handshake_timeout = None
83 if config.ssl_enabled:
84 ssl_context = config.create_ssl_context()
85 ssl_handshake_timeout = config.ssl_handshake_timeout
86
87 context = WorkerContext()
88 server_tasks: Set[asyncio.Task] = set()
89
90 async def _server_callback(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
91 nonlocal server_tasks
92
93 task = asyncio.current_task(loop)
94 server_tasks.add(task)
95 task.add_done_callback(server_tasks.discard)
96 await TCPServer(app, loop, config, context, reader, writer)
97
98 servers = []
99 for sock in sockets.secure_sockets:
100 if config.workers > 1 and platform.system() == "Windows":
101 sock = _share_socket(sock)
102
103 servers.append(
104 await asyncio.start_server(
105 _server_callback,
106 backlog=config.backlog,
107 ssl=ssl_context,
108 sock=sock,
109 ssl_handshake_timeout=ssl_handshake_timeout,
110 )
111 )
112 bind = repr_socket_addr(sock.family, sock.getsockname())
113 await config.log.info(f"Running on https://{bind} (CTRL + C to quit)")
114
115 for sock in sockets.insecure_sockets:
116 if config.workers > 1 and platform.system() == "Windows":
117 sock = _share_socket(sock)
118
119 servers.append(
120 await asyncio.start_server(_server_callback, backlog=config.backlog, sock=sock)
121 )
122 bind = repr_socket_addr(sock.family, sock.getsockname())
123 await config.log.info(f"Running on http://{bind} (CTRL + C to quit)")
124
125 for sock in sockets.quic_sockets:
126 if config.workers > 1 and platform.system() == "Windows":
127 sock = _share_socket(sock)
128
129 _, protocol = await loop.create_datagram_endpoint(
130 lambda: UDPServer(app, loop, config, context), sock=sock
131 )
132 task = loop.create_task(protocol.run())
133 server_tasks.add(task)
134 task.add_done_callback(server_tasks.discard)
135 bind = repr_socket_addr(sock.family, sock.getsockname())
136 await config.log.info(f"Running on https://{bind} (QUIC) (CTRL + C to quit)")
137
138 try:
139 await raise_shutdown(shutdown_trigger)
140 except (ShutdownError, KeyboardInterrupt):
141 pass
142 finally:
143 await context.terminated.set()
144
145 for server in servers:
146 server.close()
147 await server.wait_closed()
148
149 try:
150 gathered_server_tasks = asyncio.gather(*server_tasks)
151 await asyncio.wait_for(gathered_server_tasks, config.graceful_timeout)
152 except asyncio.TimeoutError:
153 pass
154 finally:
155 # Retrieve the Gathered Tasks Cancelled Exception, to
156 # prevent a warning that this hasn't been done.
157 gathered_server_tasks.exception()
158
159 await lifespan.wait_for_shutdown()
160 lifespan_task.cancel()
161 await lifespan_task
162
163
164 def asyncio_worker(
165 config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
166 ) -> None:
167 app = load_application(config.application_path, config.wsgi_max_body_size)
168
169 shutdown_trigger = None
170 if shutdown_event is not None:
171 shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)
172
173 if config.workers > 1 and platform.system() == "Windows":
174 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # type: ignore
175
176 _run(
177 partial(worker_serve, app, config, sockets=sockets),
178 debug=config.debug,
179 shutdown_trigger=shutdown_trigger,
180 )
181
182
183 def uvloop_worker(
184 config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
185 ) -> None:
186 try:
187 import uvloop
188 except ImportError as error:
189 raise Exception("uvloop is not installed") from error
190 else:
191 asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
192
193 app = load_application(config.application_path, config.wsgi_max_body_size)
194
195 shutdown_trigger = None
196 if shutdown_event is not None:
197 shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)
198
199 _run(
200 partial(worker_serve, app, config, sockets=sockets),
201 debug=config.debug,
202 shutdown_trigger=shutdown_trigger,
203 )
204
205
206 def _run(
207 main: Callable,
208 *,
209 debug: bool = False,
210 shutdown_trigger: Optional[Callable[..., Awaitable[None]]] = None,
211 ) -> None:
212 with Runner(debug=debug) as runner:
213 runner.get_loop().set_exception_handler(_exception_handler)
214 runner.run(main(shutdown_trigger=shutdown_trigger))
215
216
217 def _exception_handler(loop: asyncio.AbstractEventLoop, context: dict) -> None:
218 exception = context.get("exception")
219 if isinstance(exception, ssl.SSLError):
220 pass # Handshake failure
221 else:
222 loop.default_exception_handler(context)