Coverage for src/robot_dispatch/main.py: 62%
76 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 17:18 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 17:18 +0000
1from __future__ import annotations
3import uuid
4from contextlib import asynccontextmanager
5from typing import Any
7from fastapi import FastAPI, Request, status
8from fastapi.middleware.cors import CORSMiddleware
9from fastapi.responses import JSONResponse
11from robot_dispatch.api.routers import health, robots, stats, tasks
12from robot_dispatch.config import Settings, get_settings
13from robot_dispatch.db.session import create_engine, create_session_factory
14from robot_dispatch.db.uow import make_sql_uow_factory
15from robot_dispatch.logging_setup import configure_logging, get_logger
16from robot_dispatch.messaging.broker import Broker
17from robot_dispatch.services.errors import RobotNotFound, TaskConflict, TaskNotFound
19logger = get_logger("api")
22@asynccontextmanager
23async def lifespan(app: FastAPI):
24 settings: Settings = app.state.settings
25 configure_logging(settings.log_level, settings.log_json)
27 engine = create_engine(settings.database_url)
28 app.state.engine = engine
29 app.state.uow_factory = make_sql_uow_factory(create_session_factory(engine))
31 broker: Broker | None = None
32 try:
33 broker = Broker(
34 settings.rabbitmq_url,
35 prefetch=settings.consumer_prefetch,
36 connect_retries=3,
37 connect_delay=1.0,
38 )
39 await broker.connect()
40 for robot in await _known_robots(app.state.uow_factory):
41 await broker.ensure_robot_queue(robot)
42 except Exception as exc: # noqa: BLE001 - API must start even if the broker is down
43 logger.warning("rabbitmq is not available for the API process", error=str(exc))
44 broker = None
45 app.state.broker = broker
47 logger.info("api started", environment=settings.environment)
48 try:
49 yield
50 finally:
51 if broker is not None:
52 await broker.close()
53 await engine.dispose()
54 logger.info("api stopped")
57async def _known_robots(uow_factory) -> list[uuid.UUID]:
58 try:
59 async with uow_factory() as uow:
60 robots = await uow.robots.list()
61 return [robot.id for robot in robots]
62 except Exception: # noqa: BLE001 - database may not be migrated yet
63 return []
66def create_app(settings: Settings | None = None) -> FastAPI:
67 settings = settings or get_settings()
68 app = FastAPI(
69 title="Robot Dispatch Service",
70 version="0.1.0",
71 description=(
72 "Fault-tolerant task dispatch for a ROS2 robot fleet: task queue, "
73 "assignment to idle robots, lease-based failure recovery, "
74 "transactional outbox and RabbitMQ integration."
75 ),
76 lifespan=lifespan,
77 )
78 app.state.settings = settings
80 app.add_middleware(
81 CORSMiddleware,
82 allow_origins=["*"],
83 allow_methods=["*"],
84 allow_headers=["*"],
85 )
87 @app.middleware("http")
88 async def request_context(request: Request, call_next):
89 request_id = request.headers.get("X-Request-ID") or uuid.uuid4().hex
90 response = await call_next(request)
91 response.headers["X-Request-ID"] = request_id
92 return response
94 @app.exception_handler(TaskNotFound)
95 async def _task_not_found(_: Request, exc: TaskNotFound) -> JSONResponse:
96 return JSONResponse(
97 status_code=status.HTTP_404_NOT_FOUND,
98 content={"detail": str(exc), "task_id": str(exc.task_id)},
99 )
101 @app.exception_handler(RobotNotFound)
102 async def _robot_not_found(_: Request, exc: RobotNotFound) -> JSONResponse:
103 return JSONResponse(
104 status_code=status.HTTP_404_NOT_FOUND,
105 content={"detail": str(exc), "robot_id": str(exc.robot_id)},
106 )
108 @app.exception_handler(TaskConflict)
109 async def _task_conflict(_: Request, exc: TaskConflict) -> JSONResponse:
110 return JSONResponse(
111 status_code=status.HTTP_409_CONFLICT,
112 content={"detail": exc.reason, "status": exc.status, "task_id": str(exc.task_id)},
113 )
115 api_prefix = "/api/v1"
116 app.include_router(tasks.router, prefix=api_prefix)
117 app.include_router(robots.router, prefix=api_prefix)
118 app.include_router(stats.router, prefix=api_prefix)
119 app.include_router(health.router)
121 @app.get("/", include_in_schema=False)
122 async def root() -> dict[str, Any]:
123 return {"service": settings.app_name, "docs": "/docs", "api": api_prefix}
125 return app
128app = create_app()