[Refactor] P0.2: Migrate API server helpers out of api_server (#5453)

Signed-off-by: herotai214 <herotai214@gmail.com>
This commit is contained in:
herotai214 authored and GitHub committed 2026-09-10 15:03:21 +08:00
1 parent aff7d64948
commit bbac4df7d3
47 files changed
+2437 -1744

No files matched your search

@@ -0,0 +1,23 @@
# Serve Utilities
This directory is for server/app utilities shared by Omni entrypoints.
## Put Here
- FastAPI app/router mutation helpers (`routes.remove_route_from_app`,
`routes._remove_route_from_router`).
- Server exception-handler registration.
- Engine-failure helpers that are not owned by one endpoint family.
## Do Not Put Here
- Endpoint restriction *policy* (which routes a pipeline shuts down, and why).
That stays in `vllm_omni.config.endpoint_policy`; the policy module should
*call* `remove_route_from_app` from here, not redefine it.
- OpenAI response-shape adapters. Those belong under
`vllm_omni.entrypoints.openai`.
- Modality validation or payload parsing.
- Generic helpers without a clear server/app responsibility.
Keep this directory aligned with the spirit of upstream
`vllm.entrypoints.serve.utils`. Broader utility cleanup is tracked by #5227.
Whitespace-only changes.
@@ -0,0 +1,92 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Server-level error helpers for vLLM-Omni entrypoints.
Use this module for FastAPI/app exception handling and engine-failure response
construction that is not owned by a single OpenAI endpoint family."""
from typing import Any
from fastapi import Request
from fastapi.responses import JSONResponse
from vllm.entrypoints.launchers.launcher import terminate_if_errored
from vllm.entrypoints.serve import create_error_response
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
logger = init_logger(__name__)
def _get_request_id_from_request(req: Request) -> str | None:
return req.state.request_metadata.request_id if hasattr(req.state, "request_metadata") else None
def _build_engine_error_payload(
exc: EngineDeadError | EngineGenerateError,
*,
request_id: str | None,
) -> tuple[dict[str, Any], int]:
err = create_error_response(exc)
payload = err.model_dump()
error_body = payload.get("error", {})
error_body["request_id"] = request_id
error_body["error_stage_id"] = getattr(exc, "error_stage_id", None)
return payload, err.error.code
def _create_engine_error_json_response(
req: Request,
exc: EngineDeadError | EngineGenerateError,
) -> JSONResponse:
request_id = _get_request_id_from_request(req)
error_stage_id = getattr(exc, "error_stage_id", None)
engine = req.app.state.engine_client
if isinstance(exc, EngineDeadError):
# Log Omni-specific diagnostic information for dead engines.
orchestrator_alive = engine.engine.is_alive() if hasattr(engine, "engine") else "N/A"
logger.error(
"EngineDeadError: orchestrator_alive=%s, errored=%s, request_id=%s, error_stage_id=%s",
orchestrator_alive,
engine.errored,
request_id,
error_stage_id,
)
terminate_if_errored(
server=req.app.state.server,
engine=engine,
)
payload, status_code = _build_engine_error_payload(exc, request_id=request_id)
return JSONResponse(content=payload, status_code=status_code)
def _register_omni_exception_handlers(app) -> None:
"""Override upstream vLLM exception handlers with Omni-aware versions.
The upstream ``engine_error_handler`` is designed for ``AsyncLLM`` (single
EngineCore process). Omni uses a multi-stage orchestrator with different
health semantics, so we register our own handlers that:
- Log multi-stage diagnostic info (orchestrator liveness, per-stage health)
when an ``EngineDeadError`` is caught.
- Call ``terminate_if_errored``
- Return an OpenAI-compatible error JSON response.
"""
async def omni_engine_error_handler(
req: Request,
exc: EngineDeadError | EngineGenerateError,
):
request_id = _get_request_id_from_request(req)
if req.app.state.args.log_error_stack:
logger.exception("Engine Exception caught. Request id: %s", request_id)
return _create_engine_error_json_response(req, exc)
app.exception_handler(EngineGenerateError)(omni_engine_error_handler)
app.exception_handler(EngineDeadError)(omni_engine_error_handler)
@@ -0,0 +1,45 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Route-table helpers for Omni server assembly.
Owns FastAPI app **and** router mutation used during server construction.
``endpoint_policy`` imports app-level removal from here; it does not own
route-table helpers itself.
"""
from collections.abc import Set
from fastapi import APIRouter, FastAPI
from starlette.routing import Route
def remove_route_from_app(
app: FastAPI,
path: str,
methods: Set[str],
) -> None:
"""Remove app routes matching a path and one of the given HTTP methods."""
routes_to_remove = [
route
for route in app.routes
if isinstance(route, Route) and route.path == path and route.methods is not None and route.methods & methods
]
for route in routes_to_remove:
app.routes.remove(route)
def _remove_route_from_router(
router: APIRouter,
path: str,
methods: set[str] | None = None,
) -> None:
"""Remove routes from an ``APIRouter`` by path and optionally by methods."""
methods_set = {method.upper() for method in methods} if methods else None
for route in list(router.routes):
if getattr(route, "path", None) != path:
continue
if methods_set is not None:
route_methods = {method.upper() for method in (getattr(route, "methods", None) or set())}
if not (route_methods & methods_set):
continue
router.routes.remove(route)