2026-07-22 17:32:59 +08:00
|
|
|
import asyncio
|
|
|
|
|
from contextlib import suppress
|
|
|
|
|
|
2026-07-16 13:47:37 +08:00
|
|
|
from fastapi import FastAPI
|
2026-07-21 11:06:34 +08:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2026-07-16 13:47:37 +08:00
|
|
|
|
2026-08-21 10:15:08 +08:00
|
|
|
from app.core.cache_paths import setup_local_caches
|
|
|
|
|
|
|
|
|
|
# 在任何 docling / tiktoken 模块被实例化之前设置缓存路径,避免首调用走到 ~/.cache。
|
|
|
|
|
setup_local_caches()
|
|
|
|
|
|
|
|
|
|
from app.api.v1.router import api_router # noqa: E402
|
|
|
|
|
from app.core.config import docs_kwargs, get_settings # noqa: E402
|
|
|
|
|
from app.core.logging import configure_logging, setup_request_logging # noqa: E402
|
|
|
|
|
from app.workers.compute_poller import run_compute_poller # noqa: E402
|
2026-07-16 13:47:37 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
|
|
|
settings = get_settings()
|
|
|
|
|
configure_logging(settings)
|
|
|
|
|
|
2026-08-07 09:24:35 +08:00
|
|
|
app = FastAPI(title=settings.app_name, **docs_kwargs(settings.enable_docs))
|
2026-07-21 11:06:34 +08:00
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=settings.cors_allow_origins,
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
2026-07-16 13:47:37 +08:00
|
|
|
setup_request_logging(app)
|
2026-07-21 10:09:36 +08:00
|
|
|
app.include_router(api_router, prefix=settings.route_prefix)
|
2026-07-22 17:32:59 +08:00
|
|
|
|
|
|
|
|
@app.on_event("startup")
|
|
|
|
|
async def start_workers() -> None:
|
|
|
|
|
app.state.compute_poller_task = asyncio.create_task(run_compute_poller())
|
|
|
|
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
|
|
|
async def stop_workers() -> None:
|
|
|
|
|
task = getattr(app.state, "compute_poller_task", None)
|
|
|
|
|
if task:
|
|
|
|
|
task.cancel()
|
|
|
|
|
with suppress(asyncio.CancelledError):
|
|
|
|
|
await task
|
|
|
|
|
|
2026-07-16 13:47:37 +08:00
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app = create_app()
|