"""Run the API: ``python -m core.serve [--host 0.0.0.0] [--port 8000]``. Uses a selector event loop on every platform; psycopg's async mode cannot run on Windows' default Proactor loop, which ``uvicorn`` would otherwise pick. Graceful deploys (Phase 18): on SIGTERM/SIGINT the server first asks every in-flight agent run to stop at its next step boundary (``AgentRuntime.request_drain``; state is checkpointed), and only then lets uvicorn stop accepting connections and wait up to ``--graceful-timeout`` seconds for open requests. Without this, uvicorn would wait for long runs to finish and call the lifespan's drain only afterwards, when the platform may already be killing the process. """ from __future__ import annotations import argparse import asyncio import logging import selectors from types import FrameType from typing import Any import uvicorn log = logging.getLogger(__name__) def drain_app(app: Any, reason: str = "shutdown") -> bool: """Request a drain of the app's agent runtime, if it has one. Returns True if requested.""" services = getattr(getattr(app, "state", None), "services", None) runtime = getattr(services, "runtime", None) if runtime is None: return False runtime.request_drain(reason) return True class DrainingServer(uvicorn.Server): """``uvicorn.Server`` that drains agent runs as soon as a shutdown signal arrives.""" def __init__(self, config: uvicorn.Config, app: Any) -> None: super().__init__(config) self.drain_target = app self.drained = False def handle_exit(self, sig: int, frame: FrameType | None) -> None: if not self.drained: self.drained = True try: if drain_app(self.drain_target, "shutdown"): log.info("signal %s: draining in-flight agent runs", sig) except Exception: # never block shutdown on the drain hook log.exception("drain on signal %s failed", sig) super().handle_exit(sig, frame) def main(argv: list[str] | None = None) -> None: p = argparse.ArgumentParser() p.add_argument("--host", default="127.0.0.1") p.add_argument("--port", type=int, default=8000) p.add_argument("--proxy-headers", action="store_true") p.add_argument( "--graceful-timeout", type=int, default=None, help="seconds to wait for open requests after SIGTERM (default WP_GRACEFUL_SHUTDOWN_S)", ) p.add_argument( "--app", default="core.api.main:app", help="ASGI app as module:attribute (tests serve an app with scripted models)", ) a = p.parse_args(argv) from uvicorn.importer import import_from_string from core.config import get_settings from core.ops.preflight import production_problems problems = production_problems(get_settings()) if problems: raise SystemExit("refusing to start (WP_ENV=production): " + "; ".join(problems)) graceful = ( a.graceful_timeout if a.graceful_timeout is not None else get_settings().graceful_shutdown_s ) app = import_from_string(a.app) config = uvicorn.Config( app, host=a.host, port=a.port, proxy_headers=a.proxy_headers, timeout_graceful_shutdown=graceful, ) server = DrainingServer(config, app) asyncio.run( server.serve(), loop_factory=lambda: asyncio.SelectorEventLoop(selectors.DefaultSelector()), ) if __name__ == "__main__": main()