From 12b634b7e06860157594671252501c11812ac53b Mon Sep 17 00:00:00 2001 From: Bobby Date: Fri, 27 Nov 2026 17:00:51 -0500 Subject: [PATCH] new: `hapi serve` runs the API and probes in one event loop (#74) Two uvicorn servers, the public API on :8000 and the internal probe listener on :8081, share one event loop (ADR-0009), so a wedged loop fails liveness. SIGINT/SIGTERM stops both; if one listener stops or fails to start, the other stops with it. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + justfile | 4 ++ pyproject.toml | 5 +++ src/hapi/__main__.py | 3 ++ src/hapi/cli.py | 34 ++++++++++++++ src/hapi/platform/server.py | 60 +++++++++++++++++++++++++ tests/test_serve.py | 78 ++++++++++++++++++++++++++++++++ uv.lock | 89 ++++++++++++++++++++++++++++++++++++- 8 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 src/hapi/__main__.py create mode 100644 src/hapi/cli.py create mode 100644 src/hapi/platform/server.py create mode 100644 tests/test_serve.py diff --git a/README.md b/README.md index 5b23f42..82866f8 100644 --- a/README.md +++ b/README.md @@ -8,4 +8,5 @@ The only tool needed outside the project is [uv](https://docs.astral.sh/uv/). Ev uv sync # create .venv with all dev tools uv run just lint # Ruff, pyright strict uv run just test # pytest +uv run just dev # API on :8000, probes on :8081 ``` diff --git a/justfile b/justfile index ebe7010..c6b85bd 100644 --- a/justfile +++ b/justfile @@ -2,6 +2,10 @@ default: @just --list +# Run hAPI locally: the API on :8000 and probes on :8081. +dev: + uv run hapi serve + # Run the test suite. test *args: uv run pytest {{args}} diff --git a/pyproject.toml b/pyproject.toml index d555f04..305d268 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,8 +6,13 @@ readme = "README.md" requires-python = ">=3.14" dependencies = [ "fastapi>=0.165.0", + "typer>=0.29.3", + "uvicorn>=0.54.0", ] +[project.scripts] +hapi = "hapi.cli:main" + [build-system] requires = ["hatchling"] build-backend = "hatchling.build" diff --git a/src/hapi/__main__.py b/src/hapi/__main__.py new file mode 100644 index 0000000..cece0e9 --- /dev/null +++ b/src/hapi/__main__.py @@ -0,0 +1,3 @@ +from hapi.cli import main + +main() diff --git a/src/hapi/cli.py b/src/hapi/cli.py new file mode 100644 index 0000000..9867413 --- /dev/null +++ b/src/hapi/cli.py @@ -0,0 +1,34 @@ +"""The `hapi` command line.""" + +from typing import Annotated + +import typer + +from hapi.app import create_api_app, create_probe_app +from hapi.platform.server import Listener, serve + +app = typer.Typer(no_args_is_help=True) + + +@app.callback() +def _root() -> None: + """hAPI: a personal API for one Household and its automations.""" + + +@app.command("serve") +def serve_command( + host: Annotated[str, typer.Option(help="Interface to bind both listeners to.")] = "127.0.0.1", + api_port: Annotated[int, typer.Option(help="Public API port.")] = 8000, + probe_port: Annotated[int, typer.Option(help="Internal probe port, never routed.")] = 8081, +) -> None: + """Serve the public API and the internal probe listener in one event loop.""" + serve( + [ + Listener(create_api_app(), host, api_port), + Listener(create_probe_app(), host, probe_port), + ] + ) + + +def main() -> None: + app() diff --git a/src/hapi/platform/server.py b/src/hapi/platform/server.py new file mode 100644 index 0000000..6b05023 --- /dev/null +++ b/src/hapi/platform/server.py @@ -0,0 +1,60 @@ +"""Run several ASGI apps as uvicorn listeners in one process and one event loop. + +Sharing the loop is deliberate (ADR-0009): if the API wedges the loop, the +probe listener stops answering too, so liveness fails. +""" + +import asyncio +import signal +from collections.abc import Generator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass + +import uvicorn +from starlette.types import ASGIApp + +_STOP_SIGNALS = (signal.SIGINT, signal.SIGTERM) + + +@dataclass(frozen=True) +class Listener: + app: ASGIApp + host: str + port: int + + +class _Server(uvicorn.Server): + """A uvicorn server that leaves signal handling to `serve`.""" + + @contextmanager + def capture_signals(self) -> Generator[None]: + yield + + +async def _serve(listeners: Sequence[Listener]) -> None: + servers = [ + _Server(uvicorn.Config(listener.app, host=listener.host, port=listener.port)) + for listener in listeners + ] + + def stop_all() -> None: + for server in servers: + server.should_exit = True + + loop = asyncio.get_running_loop() + for sig in _STOP_SIGNALS: + loop.add_signal_handler(sig, stop_all) + try: + tasks = [asyncio.create_task(server.serve()) for server in servers] + # If any listener stops (or fails to start), stop the rest with it. + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + stop_all() + await asyncio.gather(*tasks) + finally: + for sig in _STOP_SIGNALS: + loop.remove_signal_handler(sig) + + +def serve(listeners: Sequence[Listener]) -> None: + """Serve every listener until SIGINT or SIGTERM, then shut all of them down.""" + asyncio.run(_serve(listeners)) diff --git a/tests/test_serve.py b/tests/test_serve.py new file mode 100644 index 0000000..563150f --- /dev/null +++ b/tests/test_serve.py @@ -0,0 +1,78 @@ +"""`hapi serve` runs the public API and the internal probe listener in one process. + +Unlike other CLI tests, these run `hapi serve` as a real subprocess: binding real +ports and receiving SIGTERM are the behaviour under test. +""" + +import signal +import socket +import subprocess +import sys +import time +from collections.abc import Iterator +from typing import NamedTuple + +import httpx +import pytest + + +def _free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _wait_until_listening(url: str, process: subprocess.Popen[bytes]) -> None: + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if process.poll() is not None: + pytest.fail(f"hapi serve exited early with {process.returncode}") + try: + httpx.get(url, timeout=0.5) + except httpx.TransportError: + time.sleep(0.05) + else: + return + pytest.fail(f"nothing listening at {url}") + + +class Served(NamedTuple): + process: subprocess.Popen[bytes] + api_port: int + probe_port: int + + +@pytest.fixture +def served() -> Iterator[Served]: + api_port, probe_port = _free_port(), _free_port() + process = subprocess.Popen( + [ + sys.executable, + "-m", + "hapi", + "serve", + "--api-port", + str(api_port), + "--probe-port", + str(probe_port), + ], + ) + try: + _wait_until_listening(f"http://127.0.0.1:{api_port}/", process) + _wait_until_listening(f"http://127.0.0.1:{probe_port}/", process) + yield Served(process, api_port, probe_port) + finally: + if process.poll() is None: + process.kill() + process.wait() + + +def test_probes_answer_on_the_probe_port_only(served: Served) -> None: + assert httpx.get(f"http://127.0.0.1:{served.probe_port}/livez").status_code == 200 + assert httpx.get(f"http://127.0.0.1:{served.api_port}/livez").status_code == 404 + + +def test_sigterm_stops_both_listeners_cleanly(served: Served) -> None: + served.process.send_signal(signal.SIGTERM) + + assert served.process.wait(timeout=10) == 0 diff --git a/uv.lock b/uv.lock index ef1302e..bc42ed9 100644 --- a/uv.lock +++ b/uv.lock @@ -42,6 +42,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, ] +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + [[package]] name = "colorama" version = "0.4.6" @@ -84,6 +93,8 @@ version = "0.1.0" source = { editable = "." } dependencies = [ { name = "fastapi" }, + { name = "typer" }, + { name = "uvicorn" }, ] [package.dev-dependencies] @@ -97,7 +108,11 @@ dev = [ ] [package.metadata] -requires-dist = [{ name = "fastapi", specifier = ">=0.165.0" }] +requires-dist = [ + { name = "fastapi", specifier = ">=0.165.0" }, + { name = "typer", specifier = ">=0.29.3" }, + { name = "uvicorn", specifier = ">=0.54.0" }, +] [package.metadata.requires-dev] dev = [ @@ -155,6 +170,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, ] +[[package]] +name = "markdown-it-py" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/fc/cee2c45553c9a9bf77d8b0c391560c556d7ed756b1f0bb35eb5d48db09ea/markdown_it_py-4.3.0.tar.gz", hash = "sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa", size = 242701, upload-time = "2026-11-10T16:18:30.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/31/5f0ac2f1a1c67423c995c731a11cd4ad05d081a2be969d74f868bdb9cc70/markdown_it_py-4.3.0-py3-none-any.whl", hash = "sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa", size = 96951, upload-time = "2026-11-10T16:18:28.975Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + [[package]] name = "nodeenv" version = "1.12.0" @@ -331,6 +367,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/27/2d/e600d8f47597a803641704aba367c7266cd621f86561ec36da9888f160ec/pytest_asyncio-1.5.0-py3-none-any.whl", hash = "sha256:557f255ee03cc84f84a8d5f438bc9c6e0f714bf86970ae743c7ecb5a38d7e07d", size = 17215, upload-time = "2026-11-12T16:35:48.446Z" }, ] +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + [[package]] name = "ruff" version = "0.17.6" @@ -380,6 +429,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/29/81112f1180a156306bf36ab0ffd3e6ec35259ed40cefd8774c24560ce857/rust_just-1.59.0-py3-none-win_amd64.whl", hash = "sha256:75bde89d36bb0c7b35fb9cecefb303f154dc320d4b5b8c832c5ad0bf1904077b", size = 2413475, upload-time = "2026-10-16T03:59:55.345Z" }, ] +[[package]] +name = "shellingham" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, +] + [[package]] name = "starlette" version = "1.10.0" @@ -392,6 +450,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, ] +[[package]] +name = "typer" +version = "0.29.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "pydantic" }, + { name = "rich" }, + { name = "shellingham" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f4/8f/4583099c74623e04610d9df01ff58a9217935e88fdbd4b14167ebe99c134/typer-0.29.3.tar.gz", hash = "sha256:8189a53bb9684dc551e0b61e71904b323214884f2eb14bfe71aa859ae980d10a", size = 205982, upload-time = "2026-11-26T08:20:50.693Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/43/a3e7ce867dc4fa852f4223ada99d29bc9ba5faf32496b63ec587cd10a0d7/typer-0.29.3-py3-none-any.whl", hash = "sha256:1fd37275046faecc86caa2e0e313978c10db71533fc0fe1a48f4e03a60efc23c", size = 121082, upload-time = "2026-11-26T08:20:49.527Z" }, +] + [[package]] name = "typing-extensions" version = "4.16.0" @@ -412,3 +486,16 @@ sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab7 wheels = [ { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, ] + +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +]