107 lines
3.8 KiB
Python
107 lines
3.8 KiB
Python
|
|
"""应用组装边界:仅在 lifespan 中创建外部资源,退出时按顺序回收。"""
|
||
|
|
|
||
|
|
from contextlib import asynccontextmanager
|
||
|
|
import logging
|
||
|
|
from fastapi import FastAPI
|
||
|
|
from fastapi.responses import JSONResponse
|
||
|
|
from sqlalchemy.exc import SQLAlchemyError
|
||
|
|
from app.api.router import router as api_router
|
||
|
|
from app.core.config import Settings
|
||
|
|
from app.core.database import Database
|
||
|
|
from app.services.auth import bootstrap_admin
|
||
|
|
from app.services.orchestration.coordinator import Coordinator
|
||
|
|
|
||
|
|
|
||
|
|
def create_app(settings=None, *, provider=None):
|
||
|
|
|
||
|
|
@asynccontextmanager
|
||
|
|
async def lifespan(app):
|
||
|
|
configuration = settings or Settings.from_env()
|
||
|
|
for root in (
|
||
|
|
configuration.asset_root,
|
||
|
|
configuration.job_work_root,
|
||
|
|
configuration.state_root,
|
||
|
|
):
|
||
|
|
root.mkdir(parents=True, exist_ok=True)
|
||
|
|
db = Database(configuration)
|
||
|
|
app.state.settings, app.state.db = (configuration, db)
|
||
|
|
live_provider = provider
|
||
|
|
if live_provider is None:
|
||
|
|
from app.adapters.provider.client import Provider
|
||
|
|
|
||
|
|
live_provider = Provider(configuration)
|
||
|
|
app.state.provider = live_provider
|
||
|
|
coordinator = Coordinator(configuration, db, live_provider)
|
||
|
|
app.state.coordinator = coordinator
|
||
|
|
app.state.draining = False
|
||
|
|
|
||
|
|
async def after_tick():
|
||
|
|
from app.services.orchestration.workflow_engine import advance_workflows
|
||
|
|
|
||
|
|
await advance_workflows(db, configuration, live_provider)
|
||
|
|
|
||
|
|
coordinator.after_tick = after_tick
|
||
|
|
try:
|
||
|
|
await db.initialize()
|
||
|
|
await bootstrap_admin(db, configuration)
|
||
|
|
from app.core.public_preflight import require_public_ready
|
||
|
|
|
||
|
|
await require_public_ready(db, configuration)
|
||
|
|
if configuration.run_coordinator:
|
||
|
|
await coordinator.start()
|
||
|
|
yield
|
||
|
|
finally:
|
||
|
|
app.state.draining = True
|
||
|
|
await coordinator.close()
|
||
|
|
await live_provider.aclose()
|
||
|
|
await db.close()
|
||
|
|
|
||
|
|
app = FastAPI(title="CMVR Visual", lifespan=lifespan)
|
||
|
|
from app.api.middleware.upload_guard import UploadGuard
|
||
|
|
|
||
|
|
app.add_middleware(UploadGuard)
|
||
|
|
|
||
|
|
@app.middleware("http")
|
||
|
|
async def maintenance_writes(request, call_next):
|
||
|
|
from app.core.maintenance import maintenance_active
|
||
|
|
|
||
|
|
configuration = getattr(request.app.state, "settings", None)
|
||
|
|
if (
|
||
|
|
configuration
|
||
|
|
and request.method in {"POST", "PUT", "PATCH", "DELETE"}
|
||
|
|
and request.url.path.startswith("/api/")
|
||
|
|
and (request.url.path not in {"/api/auth/login", "/api/auth/logout"})
|
||
|
|
and maintenance_active(configuration)
|
||
|
|
):
|
||
|
|
return JSONResponse(
|
||
|
|
status_code=503,
|
||
|
|
content={
|
||
|
|
"detail": {
|
||
|
|
"code": "maintenance",
|
||
|
|
"message": "系统维护中,任务和草稿已保留,请稍后重试",
|
||
|
|
}
|
||
|
|
},
|
||
|
|
)
|
||
|
|
return await call_next(request)
|
||
|
|
|
||
|
|
@app.exception_handler(SQLAlchemyError)
|
||
|
|
async def database_failure(request, exc):
|
||
|
|
logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__)
|
||
|
|
return JSONResponse(
|
||
|
|
status_code=503,
|
||
|
|
content={
|
||
|
|
"detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"}
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
@app.exception_handler(Exception)
|
||
|
|
async def internal_failure(request, exc):
|
||
|
|
logging.getLogger(__name__).exception("Unhandled application error")
|
||
|
|
return JSONResponse(
|
||
|
|
status_code=500,
|
||
|
|
content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}},
|
||
|
|
)
|
||
|
|
|
||
|
|
app.include_router(api_router, prefix="/api")
|
||
|
|
return app
|