"""Minimal HTTP health endpoint using raw asyncio. No external dependencies — just a bare TCP server that speaks enough HTTP to return JSON status. Runs on a separate port from the NTCP2 transport (default 9701). """ from __future__ import annotations import asyncio import json import logging logger = logging.getLogger(__name__) async def start_health_server( get_status_fn, host: str = "0.0.0.0", port: int = 9701, ) -> asyncio.Server: """Start a minimal HTTP health server. Parameters ---------- get_status_fn: Callable that returns a dict with router status. host: Bind address. port: Listen port (default 9701). Returns ------- asyncio.Server The running server instance. """ async def handle_request( reader: asyncio.StreamReader, writer: asyncio.StreamWriter, ) -> None: try: # Read the request line (we don't care about the path) await asyncio.wait_for(reader.readline(), timeout=5.0) # Drain remaining headers while True: line = await asyncio.wait_for(reader.readline(), timeout=5.0) if line in (b"\r\n", b"\n", b""): break status = get_status_fn() body = json.dumps(status, indent=2).encode() response = ( b"HTTP/1.1 200 OK\r\n" b"Content-Type: application/json\r\n" b"Connection: close\r\n" b"Content-Length: " + str(len(body)).encode() + b"\r\n" b"\r\n" + body ) writer.write(response) await writer.drain() except Exception: pass finally: writer.close() try: await writer.wait_closed() except Exception: pass server = await asyncio.start_server(handle_request, host, port) logger.info("Health server started on %s:%d", host, port) return server