nex_animation/backend/app/main.py

286 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""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.datastructures import Headers
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.gzip import GZipMiddleware, GZipResponder
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="长视频编导平台:资产库 → 分镜脚本 → 模型调度 → 质检审核 → 时间线合成导出")
# ------------------------------------------------------------------ 交付面:按 content-type 压缩
# 立项依据是阶段 29 的两把实测尺(`reports/ui_evidence/nex-p29/apigzip.log`):
# 首访过网 1 292 834 B 里 `/api` 占 773 646 B,比全部 JS+CSS 之和(512 744 B)还大,
# 而它是当时唯一没压的一族。同一把尺(gzip level 6)离线量过:
# · JSON 21 条 866 745 → 143 900 B,**省 83.4 %**;
# · 挂在同一个 `/api` 前缀下的 `/api/media/thumb/*.png` 24 条 51 768 → 52 320 B,
# **反而 +1.1 %**(PNG 自己就是压过的)。
# ⇒ 判据不能是路径前缀。所以这里不直接用 `GZipMiddleware` 挂全站:它只看
# `Accept-Encoding` 和体积,**不看 content-type**,挂上去会把下面两样东西压坏——
# · `/api/media/thumb/*.png`:白烧 CPU 还变大;
# · `/api/exports/{id}/download` 的 `video/mp4`:Starlette 压完顺手删掉
# `Content-Length`,而播放器要靠它算 Range 进度条,seek 直接废。
# 做法:复用 Starlette 那套已经被验证过的流式 gzip 状态机(`GZipResponder`:
# 缓冲到 minimum_size 再决定、边压边发、合并 `Vary`、压完才删 `Content-Length`),
# 只在 `http.response.start` 那一步多问一句「这个 media type 值不值得压」。
# `GZIP_MINIMUM` 管不管得住,取决于这一层坐在鉴权中间件的哪一侧。阶段 30 为此翻过一次,
# A/B 读数在 `reports/ui_evidence/nex-p30/servecheck.log`:
# · starlette 0.46.2 `gzip.py` 的体积阈值只在「一条 body 消息且 `more_body=False`」时判定。
# 路由返回 `JSONResponse`、`StaticFiles` 发小文件 ⇒ 都是一条完整 body ⇒ 阈值管得住。
# · `BaseHTTPMiddleware` 会把下游响应转成分块转发(首块 `more_body=True`)⇒ 阈值整体失效。
# 把它压在这一层外面那次实测:4 个 <1 kB 的哈希 chunk(`ProjectDetail` /
# `kit-icons-extra` / `use-auto-refresh` / `use-local-storage`)与 742 B 的导出元数据
# 全被压,跟项目自己声明的 1 kB 底线(`SPA_GZIP_MINIMUM`、nginx `gzip_min_length`)对不上。
# ⇒ 所以顺序是「压缩层最内 → 鉴权 → CORS 最外」,见下面三条 `add_middleware`。
# 代价:鉴权自己吐的 401/403 JSON(实测 25 B)不被覆盖——它本来就在阈值以下。
# 收益:阈值名副其实,静态面与 API 面同一把尺,servecheck 那条「<1 kB 的小文件不压」
# 两侧都过(是实现对上判据,不是把判据改松)。
# · 仍然成立的那半:流式端点不看体积(`StreamingResponse` 首块就压)⇒
# 二进制的安全由 media type 判据负责,不由阈值负责。
# (钉在 `tests/test_api_content_gzip.py::test_streaming_webp_thumbnail_is_still_untouched`)
GZIP_MINIMUM = 1024 # 与 SPA_GZIP_MINIMUM / nginx `gzip_min_length` 同一把尺
GZIP_LEVEL = 6 # 与 SPA_GZIP_LEVEL / nginx `gzip_comp_level` 同一把尺
# 文本族之外的类型一律不压。`text/*` 在函数里单列,这里只登记非 text/ 的:
GZIP_TYPES = frozenset({
"application/json", "application/geo+json", "application/ld+json", "application/ndjson",
"application/x-ndjson", "application/javascript", "text/javascript", "application/ecmascript",
"application/xml", "text/xml", "image/svg+xml", "application/yaml", "application/x-yaml",
})
def gzip_eligible(content_type: str) -> bool:
"""这个响应的 media type 值不值得 gzip。"""
main = (content_type or "").split(";", 1)[0].strip().lower()
if not main:
return False # 没声明类型的空响应 / 204:不压
if main.startswith("text/"):
# SSE 是长连接上的逐条推送,gzip 会把它攒成块(Starlette 自己也排除它)
return main != "text/event-stream"
return main in GZIP_TYPES
class _GzipByContentType(GZipResponder):
"""`GZipResponder` + 一条 content-type 判据。
父类在 `http.response.start` 时只把 `text/event-stream` 当例外;这里把「例外」的定义
换成「不在文本族里」,其余流程(缓冲、流式、`Vary`、`Content-Length`)一个字不改,
所以不会另起一套实现。已经带 `Content-Encoding` 的也归入例外:上游压过就透传,
不叠第二层(`/assets` 那一层 gzip 与这一层并存靠的就是这条)。
"""
async def send_with_compression(self, message):
await super().send_with_compression(message)
if message["type"] == "http.response.start":
headers = Headers(raw=message["headers"])
self.content_type_is_excluded = (self.content_type_is_excluded
or self.content_encoding_set
or not gzip_eligible(headers.get("content-type", "")))
class ContentTypeGZipMiddleware(GZipMiddleware):
"""按 content-type 过滤的 gzip。它是三条用户中间件里最内的一条,
所以看到的是路由与挂载点自己发出的响应(体积阈值管得住,见上面的说明);
异常处理器在路由内侧,5xx 的 JSON 一样被覆盖。"""
async def __call__(self, scope, receive, send):
if scope["type"] != "http" or \
"gzip" not in Headers(scope=scope).get("accept-encoding", "").lower():
await self.app(scope, receive, send) # 客户端不收 gzip ⇒ 原样给,绝不冒充
return
await _GzipByContentType(self.app, self.minimum_size,
compresslevel=self.compresslevel)(scope, receive, send)
# 三条用户中间件从外到内:CORS → 鉴权 → 按 content-type 的 gzip。
# `add_middleware` 把自己插到最外层 ⇒ 压缩层必须**最先**注册,晚一行就跑到了鉴权外面
# (那一版把 `GZIP_MINIMUM` 整个架空了,见上面)。gzip 只影响响应编码:不改状态码、
# 不改 body、不改任何业务契约,解压后与原来逐字节相同
# (`backend/tests/test_api_content_gzip.py` 就是这么断言的)。
app.add_middleware(ContentTypeGZipMiddleware, minimum_size=GZIP_MINIMUM, compresslevel=GZIP_LEVEL)
# 鉴权排第二、CORS 最后注册坐在最外 ⇒ 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")
# ------------------------------------------------------------------ 交付面:SPA 静态资源
# 三条口径放在一起说清楚,免得下一轮又去后端中间件上试:
# ① 带哈希的 chunk 与内容一一对应 ⇒ 让浏览器缓存一年;`index.html` 反过来必须每次回源
# 校验,否则发版后老标签页拿着旧壳去引已经消失的哈希文件,用户看到的是白屏。
# ② 文本资源要压:首屏闭包 1 469 kB(`scripts/ui/chunkinfo.mjs`)里 1 144 kB 是一个
# JS chunk,原文直出等于把已经量好的 gzip 450 kB 按 raw 再发一遍。
# `compresslevel` 取 6 不取 9——同级产物只差千分之几,CPU 便宜一半(实测见
# `reports/ui_evidence/nex-p29/serve-ab.log`)。
# ③ 压缩判据是**响应自己声明的 media type**,不是它挂在哪个路径前缀下:见上面
# 「交付面:按 content-type 压缩」那一节。`/assets` 这一层仍然自带 gzip
# (阶段 29 的产物证据与 pytest 都钉在它上面;本目录只有 js/css,没有二进制),
# 上面那一层看到已经带 `Content-Encoding` 的响应会原样透传,不会压两遍。
SPA_ASSET_CACHE = "public, max-age=31536000, immutable"
SPA_SHELL_CACHE = "no-cache"
SPA_GZIP_MINIMUM = 1024 # 小于 1 kB 不值得压(压完加头反而更大)
SPA_GZIP_LEVEL = 6
def with_cache_control(asgi, value: str):
"""给子应用的每个响应补一个 `Cache-Control`,上游已经给了就不覆盖。
没用 `StaticFiles(headers=...)`:那个构造参数在 starlette 0.3x 就被删了,
本项目锁的是 0.46.2,写死之后整个 `/assets` 挂载直接 TypeError。
包一层只读 ASGI 的 `http.response.start` 消息,与版本无关,
也不碰 StaticFiles 自己的 ETag / Range 逻辑。
"""
async def wrapped(scope, receive, send):
if scope["type"] != "http":
await asgi(scope, receive, send)
return
async def send_headers(message):
if message["type"] == "http.response.start":
raw = list(message["headers"])
if not any(k.lower() == b"cache-control" for k, _ in raw):
raw.append((b"cache-control", value.encode("latin-1")))
message = {**message, "headers": raw}
await send(message)
await asgi(scope, receive, send_headers)
return wrapped
def spa_assets_app(dist: Path):
"""`/assets` 的 ASGI 子应用:StaticFiles + 长期缓存 + gzip。
和 `spa_target()` 一样单独成函数:这段只在 `SERVE_FRONTEND` 打开时注册,
纯 API 模式的自检一次都跑不到它,测试只能拿函数自己拼一个壳来验。
"""
files = with_cache_control(StaticFiles(directory=dist / "assets"), SPA_ASSET_CACHE)
return GZipMiddleware(files, minimum_size=SPA_GZIP_MINIMUM, compresslevel=SPA_GZIP_LEVEL)
# ------------------------------------------------------------------ 前端产物托管
# 判定逻辑在 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", spa_assets_app(FRONTEND_DIST), name="spa-assets")
@app.get("/{full_path:path}", include_in_schema=False)
async def spa(full_path: str) -> FileResponse:
# 壳每次回源校验(见 §交付面 ①);带哈希的 chunk 走上面那条挂载长期缓存。
return FileResponse(spa_target(FRONTEND_DIST, full_path),
headers={"Cache-Control": SPA_SHELL_CACHE})
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"}