INNER CODE UNIT · Python
bind_server_socket
omnirexflora-labs/omnicoreagent · src/omnicoreagent/serve/server.py:209
def bind_server_socket(host: str, port: int) -> socket.socket:
"""Take the port before the server starts up.
uvicorn runs the app's startup, then binds; a startup that took 26-110 s
(the 0.5.0rc2 gate) found a taken port only at the end, while clients
polling it reached whatever held it.
"""
family = socket.AF_INET6 if ":" in host else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
# Listening, not only bound: two sockets may both bind with
# SO_REUSEADDR, and a second server starting meanwhile did (the
# 0.5.0rc3 gate); only one can listen.
sock.listen(2048)
except OSError as exc:
sock.close()