| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import errno |
| 5 |
import functools |
| 6 |
import socket |
| 7 |
import sys |
| 8 |
import typing |
| 9 |
|
| 10 |
import anyio.abc |
| 11 |
import anyio.to_thread |
| 12 |
import hypercorn |
| 13 |
import hypercorn.config |
| 14 |
import hypercorn.trio |
| 15 |
import hypercorn.typing |
| 16 |
import trio |
| 17 |
from quart_trio import QuartTrio |
| 18 |
|
| 19 |
from urllib3.util.url import parse_url |
| 20 |
|
| 21 |
|
| 22 |
class Config(hypercorn.Config): |
| 23 |
def create_sockets(self) -> hypercorn.config.Sockets: |
| 24 |
assert len(self.bind) == 1 |
| 25 |
secure_sockets, insecure_sockets = [], [] |
| 26 |
if self.ssl_enabled: |
| 27 |
secure_sockets = self._retry_create_urllib3_sockets(self.bind[0]) |
| 28 |
else: |
| 29 |
insecure_sockets = self._retry_create_urllib3_sockets(self.bind[0]) |
| 30 |
return hypercorn.config.Sockets( |
| 31 |
secure_sockets, insecure_sockets, quic_sockets=[] |
| 32 |
) |
| 33 |
|
| 34 |
def _retry_create_urllib3_sockets(self, bind: str) -> list[socket.socket]: |
| 35 |
# When we request a socket with host localhost and port zero, Hypercorn |
| 36 |
# only binds to IPv4. But we want to bind to IPv6 too, otherwise we |
| 37 |
# waste about 2 second for each test on Windows since urllib3 tries |
| 38 |
# IPv6 first as it does not implement Happy Eyeballs. |
| 39 |
# We want to use the same port for IPv4 and IPv6, so we first get a |
| 40 |
# free port in IPv4 and request the same port in IPv6. But that port |
| 41 |
# could easily be taken with IPv6 already, especially on crowded CI |
| 42 |
# environments, which would fail the run. For this reason we retry |
| 43 |
# _create_urllib3_sockets up to 10 times, which completely eliminates |
| 44 |
# this failure mode. |
| 45 |
for i in range(10): |
| 46 |
try: |
| 47 |
return self._create_urllib3_sockets(bind) |
| 48 |
except OSError as e: |
| 49 |
if e.errno == errno.EADDRINUSE: |
| 50 |
print( |
| 51 |
f"Retrying binding to {bind} after EADDRINUSE", file=sys.stderr |
| 52 |
) |
| 53 |
raise OSError("failed to bind socket") |
| 54 |
|
| 55 |
def _create_urllib3_sockets(self, bind: str) -> list[socket.socket]: |
| 56 |
sockets = [] |
| 57 |
|
| 58 |
bind = bind.replace("[", "").replace("]", "") |
| 59 |
host = bind.rsplit(":", 1)[0] |
| 60 |
port = 0 # Get a random port |
| 61 |
family = socket.AF_INET6 if ":" in host else socket.AF_UNSPEC |
| 62 |
|
| 63 |
for res in socket.getaddrinfo( |
| 64 |
host, port, family, socket.SOCK_STREAM, 0, socket.AI_PASSIVE |
| 65 |
): |
| 66 |
af, socktype, proto, canonname, sockadddr = res |
| 67 |
|
| 68 |
sock = socket.socket(af, socket.SOCK_STREAM, proto) |
| 69 |
|
| 70 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 71 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 72 |
|
| 73 |
sock.setblocking(False) |
| 74 |
sock.bind((host, port)) |
| 75 |
port = sock.getsockname()[1] |
| 76 |
sock.set_inheritable(True) |
| 77 |
sockets.append(sock) |
| 78 |
|
| 79 |
return sockets |
| 80 |
|
| 81 |
|
| 82 |
async def _start_server( |
| 83 |
config: Config, |
| 84 |
app: QuartTrio, |
| 85 |
shutdown_event: trio.Event, |
| 86 |
*, |
| 87 |
task_status: anyio.abc.TaskStatus[list[str]] = anyio.TASK_STATUS_IGNORED, |
| 88 |
) -> None: |
| 89 |
async with trio.open_nursery() as nursery: |
| 90 |
with trio.fail_after(5): |
| 91 |
config_bind: list[str] |
| 92 |
config_bind = await nursery.start( |
| 93 |
functools.partial( |
| 94 |
hypercorn.trio.serve, |
| 95 |
app, |
| 96 |
config, |
| 97 |
shutdown_trigger=shutdown_event.wait, |
| 98 |
) |
| 99 |
) |
| 100 |
task_status.started(config_bind) |
| 101 |
|
| 102 |
|
| 103 |
@contextlib.contextmanager |
| 104 |
def run_hypercorn_in_thread( |
| 105 |
host: str, certs: dict[str, typing.Any] | None, app: hypercorn.typing.ASGIFramework |
| 106 |
) -> typing.Iterator[int]: |
| 107 |
config = Config() |
| 108 |
if certs: |
| 109 |
config.certfile = certs["certfile"] |
| 110 |
config.keyfile = certs["keyfile"] |
| 111 |
if "cert_reqs" in certs: |
| 112 |
config.verify_mode = certs["cert_reqs"] |
| 113 |
if "ca_certs" in certs: |
| 114 |
config.ca_certs = certs["ca_certs"] |
| 115 |
if "alpn_protocols" in certs: |
| 116 |
config.alpn_protocols = certs["alpn_protocols"] |
| 117 |
config.bind = [f"{host}:0"] |
| 118 |
|
| 119 |
shutdown_event = trio.Event() |
| 120 |
|
| 121 |
with anyio.from_thread.start_blocking_portal(backend="trio") as portal: |
| 122 |
future, config_bind = portal.start_task( |
| 123 |
_start_server, config, app, shutdown_event |
| 124 |
) |
| 125 |
try: |
| 126 |
port = parse_url(config_bind[0]).port |
| 127 |
assert port is not None |
| 128 |
yield port |
| 129 |
finally: |
| 130 |
portal.call(shutdown_event.set) |
| 131 |
future.result() |
| 132 |
|
| 133 |
|
| 134 |
def main() -> int: |
| 135 |
# For debugging dummyserver itself - PYTHONPATH=src python -m dummyserver.hypercornserver |
| 136 |
from .app import hypercorn_app |
| 137 |
|
| 138 |
config = Config() |
| 139 |
config.bind = ["localhost:0"] |
| 140 |
shutdown_event = trio.Event() |
| 141 |
trio.run(_start_server, config, hypercorn_app, shutdown_event) |
| 142 |
return 0 |
| 143 |
|
| 144 |
|
| 145 |
if __name__ == "__main__": |
| 146 |
sys.exit(main()) |