"""Wait until http://127.0.0.1:/health responds or timeout. Usage: wait_health.py [timeout_seconds] Exit: 0 healthy, 1 timeout, 2 bad args. """ from __future__ import annotations import socket import sys import time def healthy(port: int, timeout: float = 1.0) -> bool: try: with socket.create_connection(("127.0.0.1", port), timeout=timeout) as sock: req = f"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n" sock.sendall(req.encode("ascii")) sock.settimeout(timeout) data = b"" while True: try: chunk = sock.recv(256) except socket.timeout: break if not chunk: break data += chunk if b"\r\n\r\n" in data and len(data) > 32: break return b"200" in data.split(b"\r\n", 1)[0] except OSError: return False def main() -> int: if len(sys.argv) not in (2, 3): print("usage: wait_health.py [timeout]", file=sys.stderr) return 2 try: port = int(sys.argv[1]) except ValueError: print(f"bad port: {sys.argv[1]}", file=sys.stderr) return 2 timeout = 30.0 if len(sys.argv) == 3: try: timeout = float(sys.argv[2]) except ValueError: print(f"bad timeout: {sys.argv[2]}", file=sys.stderr) return 2 deadline = time.time() + timeout while time.time() < deadline: if healthy(port): print("OK") return 0 time.sleep(0.35) print("TIMEOUT") return 1 if __name__ == "__main__": raise SystemExit(main())