扩展 HTTP API#

您可以向 lmcache server HTTP 前端添加新端点,无需修改任何现有代码。端点只需是放置在 lmcache/v1/multiprocess/http_apis/ 中的 Python 模块,并公开一个 FastAPI APIRouterHTTPAPIRegistry 会在启动时自动发现并挂载它——与 L2 adapters 所采用的零修改模式相同。

自动发现机制#

启动时,http_server.py 将 FastAPI 应用实例传递给 HTTPAPIRegistrylmcache/v1/multiprocess/http_api_registry.py)。该注册器使用 pkgutil 扫描 http_apis/ 目录,导入所有名称以 _api 结尾的模块,并将其中定义的模块级 router 注册到应用中。内置模块均遵循此模式:

模块

端点

方法

描述

root_api.py

/

GET

基本存活检查

healthcheck_api.py

/healthcheck

GET

Kubernetes 探针端点

cache_api.py

/clear-cache

POST

强制清除 L1 缓存

status_api.py

/status

GET

内部状态报告

添加端点#

lmcache/v1/multiprocess/http_apis/ 中创建一个文件,文件名以 _api.py 结尾,并公开一个 router

# lmcache/v1/multiprocess/http_apis/metrics_api.py
# SPDX-License-Identifier: Apache-2.0
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

router = APIRouter()


@router.get("/metrics")
async def metrics(request: Request):
    """Return cache hit/miss metrics."""
    engine = getattr(request.app.state, "engine", None)
    if engine is None:
        return JSONResponse(
            status_code=503,
            content={"error": "engine not initialized"},
        )
    return {"hits": 42, "misses": 7}

就这些 —— HTTPAPIRegistry 会在下次服务器启动时自动发现并挂载该模块,无需修改其他文件。

模块契约#

API 模块 必须

  • 位于 lmcache/v1/multiprocess/http_apis/ 目录下,文件名以 _api.py 结尾;

  • 公开一个模块级的 router,类型为 fastapi.APIRouter

API 模块 应该

  • 通过检查 request.app.state.engine 防范引擎未初始化的情况,并在其为 None 时返回 503

  • 使用 lmcache.logging.init_logger(__name__) 进行日志记录;

  • 使用 async 处理函数,避免阻塞式 I/O。

API 模块 不得 导入或修改 http_server.py 中的 app 对象。

访问共享状态#

app.state 是服务器启动时填充的共享上下文,可通过请求对象访问:

@router.get("/my-endpoint")
async def my_endpoint(request: Request):
    engine = request.app.state.engine          # main cache engine
    zmq_server = request.app.state.zmq_server   # underlying ZMQ server
    ...

完整的设计说明请参见源码树中的 docs/design/v1/multiprocess/http_api_extension.md