136 lines
6.4 KiB
Python
136 lines
6.4 KiB
Python
"""Nex Animation Studio · 长视频编导平台 API 入口。
|
||
|
||
启动顺序:建表 → 播种模型注册表 → 启动内联守护调度器(仅 TASK_EXECUTOR=inline)。
|
||
生产模式(TASK_EXECUTOR=celery)请另外运行 celery worker 与 celery beat。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from contextlib import asynccontextmanager
|
||
from pathlib import Path
|
||
|
||
from fastapi import FastAPI, HTTPException, Request
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
from starlette.middleware.base import BaseHTTPMiddleware
|
||
|
||
from app.api import api_router
|
||
from app.api.auth import auth_middleware
|
||
from app.config import settings
|
||
from app.db import SessionLocal, init_db
|
||
from app.providers import registry as model_registry
|
||
from app.services import agent, auth as auth_service, daemon, execution, ffmpeg as ff
|
||
from app.services.auth import AuthError
|
||
|
||
logging.basicConfig(level=getattr(logging, settings.log_level.upper(), logging.INFO),
|
||
format="%(asctime)s %(levelname)-7s %(name)s | %(message)s")
|
||
logger = logging.getLogger("nex.main")
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
init_db()
|
||
db = SessionLocal()
|
||
try:
|
||
model_registry.seed_specs(db)
|
||
if auth_service.bootstrap(db) is not None:
|
||
logger.warning("平台已完成账号初始化:请用 %s / 默认密码 登录并立即修改",
|
||
settings.bootstrap_username)
|
||
purged = auth_service.purge_expired(db)
|
||
if purged:
|
||
logger.info("清理过期登录会话 %d 条", purged)
|
||
finally:
|
||
db.close()
|
||
logger.info("执行后端=%s ffmpeg=%s 登录鉴权=%s media_root=%s", execution.backend_name(),
|
||
ff.available(), "开" if settings.auth_enabled else "关",
|
||
Path(settings.media_root).resolve())
|
||
if execution.backend_name() == "inline":
|
||
db = SessionLocal()
|
||
try:
|
||
agent.recover_interrupted_runs(db, auto_resume=True)
|
||
finally:
|
||
db.close()
|
||
daemon.start()
|
||
try:
|
||
yield
|
||
finally:
|
||
daemon.stop()
|
||
execution.shutdown()
|
||
|
||
|
||
app = FastAPI(title=settings.app_name, version="1.0.0", lifespan=lifespan,
|
||
description="长视频编导平台:资产库 → 分镜脚本 → 模型调度 → 质检审核 → 时间线合成导出")
|
||
# 先注册鉴权、后注册 CORS:Starlette 里**后注册的中间件在最外层**,
|
||
# 这样 401/403 也会带上 CORS 头,前端才能读到「未登录」而不是一个笼统的网络错误。
|
||
app.add_middleware(BaseHTTPMiddleware, dispatch=auth_middleware)
|
||
app.add_middleware(CORSMiddleware,
|
||
allow_origins=settings.cors_origin_list or ["*"],
|
||
allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
||
app.include_router(api_router)
|
||
|
||
|
||
@app.exception_handler(AuthError)
|
||
async def _auth_error(_request: Request, exc: AuthError) -> JSONResponse:
|
||
"""把服务层的业务错误翻译成正确的状态码。
|
||
|
||
「账号已存在 409」「口令太弱 400」「已停用 403」如果被 FastAPI 当成未捕获异常
|
||
统一吐 500,前端就只能显示「服务器错误」,用户不知道该改什么。
|
||
"""
|
||
return JSONResponse(status_code=exc.status, content={"detail": str(exc)})
|
||
|
||
Path(settings.media_root).mkdir(parents=True, exist_ok=True)
|
||
app.mount(settings.media_url_prefix, StaticFiles(directory=settings.media_root), name="media")
|
||
|
||
|
||
# ------------------------------------------------------------------ 前端产物托管
|
||
# 判定逻辑在 app/config.py:Settings.frontend_dist —— 鉴权中间件要问同一个问题,
|
||
# 而 api 是被本模块反向导入的,放这里会撞循环导入。
|
||
|
||
|
||
def spa_target(dist: Path, full_path: str) -> Path:
|
||
"""把 URL 路径映射成构建目录里真正要吐出去的文件。
|
||
|
||
React Router 用的是 browser history:`/projects/3/storyboard` 这类深链在磁盘上
|
||
没有对应文件,必须回落 index.html 交给前端路由,否则用户刷新一次就 404。
|
||
单独拆成函数(而不是写在路由里)有两个原因:
|
||
① 关着 SERVE_FRONTEND 时下面那段注册代码根本不执行,路由体无法被自检覆盖,
|
||
纯函数则随时能测——路径穿越那一条只能这么验;
|
||
② `/api/xxx` 写错时不该被「回落」骗过去:不排掉 API 前缀的话,
|
||
一个不存在的接口会返回 200 + 一坨 HTML,前端 res.json() 直接报解析错误,
|
||
用户看到的是「Unexpected token '<'」而不是「404 接口不存在」。
|
||
"""
|
||
prefix = settings.api_prefix.strip("/")
|
||
if full_path == prefix or full_path.startswith(f"{prefix}/"):
|
||
# full_path 里本来就带着 api/,别再拼一遍前缀
|
||
raise HTTPException(status_code=404, detail=f"接口不存在:/{full_path}")
|
||
target = (dist / full_path).resolve()
|
||
# 只允许落在构建目录内:挡掉 "/assets/../../etc/passwd" 这类路径穿越。
|
||
if full_path and target.is_file() and target.is_relative_to(dist):
|
||
return target
|
||
return dist / "index.html"
|
||
|
||
|
||
FRONTEND_DIST = settings.frontend_dist()
|
||
if settings.serve_frontend_enabled() and FRONTEND_DIST is None:
|
||
logger.warning("SERVE_FRONTEND=%s 但 frontend/dist 里没有 index.html:本次只对外提供 API"
|
||
"(先跑 ./scripts/server.sh build)", settings.serve_frontend)
|
||
if FRONTEND_DIST is not None:
|
||
# 不能把整个目录挂到 "/":那会遮住已经注册的 /api、/media、/docs。所以拆成两条:
|
||
# 哈希资源走目录挂载,其余路径交给下面的 catch-all 做 history 回落。
|
||
# React Router 用的是 history 模式(browser history),/projects/3 这类深链在磁盘上没有对应文件,
|
||
# 必须回 index.html 交给前端路由,否则用户刷新一次就 404。
|
||
if (FRONTEND_DIST / "assets").is_dir():
|
||
app.mount("/assets", StaticFiles(directory=FRONTEND_DIST / "assets"), name="spa-assets")
|
||
|
||
@app.get("/{full_path:path}", include_in_schema=False)
|
||
async def spa(full_path: str) -> FileResponse:
|
||
return FileResponse(spa_target(FRONTEND_DIST, full_path))
|
||
|
||
logger.info("前端产物已托管:%s(SERVE_FRONTEND=%s)", FRONTEND_DIST, settings.serve_frontend)
|
||
|
||
|
||
@app.get("/")
|
||
def index() -> dict:
|
||
return {"app": settings.app_name, "docs": "/docs", "health": "/health", "meta": "/api/meta"}
|