2023-08-11 19:26:49 +08:00
|
|
|
# @Time : 2023/8/9 23:23
|
|
|
|
|
# @Author : Lan
|
|
|
|
|
# @File : main.py
|
|
|
|
|
# @Software: PyCharm
|
2023-08-15 22:37:54 +08:00
|
|
|
import asyncio
|
2024-11-23 16:43:58 +08:00
|
|
|
import time
|
2025-12-18 23:08:40 +08:00
|
|
|
from contextlib import asynccontextmanager
|
2023-08-15 17:23:30 +08:00
|
|
|
|
2026-09-09 17:25:42 +08:00
|
|
|
from fastapi import FastAPI
|
2024-06-15 20:04:48 +08:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2026-09-09 17:25:42 +08:00
|
|
|
from fastapi.responses import JSONResponse
|
2025-12-18 23:08:40 +08:00
|
|
|
from tortoise import Tortoise
|
2026-10-23 09:18:30 +00:00
|
|
|
from tortoise.contrib.fastapi import tortoise_exception_handlers
|
2023-08-15 17:23:30 +08:00
|
|
|
|
2025-12-18 23:08:40 +08:00
|
|
|
from apps.admin.views import admin_api
|
2026-09-09 17:00:42 +08:00
|
|
|
from apps.base.config import (
|
2026-06-16 00:49:43 +08:00
|
|
|
ensure_security_settings,
|
|
|
|
|
ensure_settings_row,
|
|
|
|
|
is_runtime_initialized,
|
|
|
|
|
refresh_settings,
|
|
|
|
|
)
|
2026-09-09 17:25:42 +08:00
|
|
|
from apps.base.models import KeyValue
|
2026-09-20 02:01:08 +08:00
|
|
|
from apps.base.pages import not_found_handler, router as pages_router
|
2026-09-09 17:25:42 +08:00
|
|
|
from apps.base.setup_wizard import build_setup_page, is_setup_path, setup_response, wants_html_response
|
2026-09-09 17:00:42 +08:00
|
|
|
from apps.base.tasks import (
|
2026-07-11 17:50:26 +08:00
|
|
|
clean_expired_presign_sessions,
|
|
|
|
|
clean_incomplete_uploads,
|
|
|
|
|
delete_expire_files,
|
|
|
|
|
)
|
2026-09-09 17:25:42 +08:00
|
|
|
from apps.base.views import share_api, chunk_api, presign_api
|
2026-10-10 18:52:28 +08:00
|
|
|
from apps.base.mcp import router as mcp_router
|
2026-10-23 09:18:30 +00:00
|
|
|
from core.database import db_startup_lock, init_db
|
2026-09-09 17:25:42 +08:00
|
|
|
from core.errors import StorageError
|
|
|
|
|
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
|
|
|
|
from core.settings import settings
|
2026-06-03 12:22:12 +08:00
|
|
|
from core.version import APP_VERSION
|
2026-06-03 02:15:15 +08:00
|
|
|
|
|
|
|
|
|
2024-10-06 16:43:49 +08:00
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI):
|
2025-02-23 20:49:51 +08:00
|
|
|
logger.info("正在初始化应用...")
|
2024-10-06 16:43:49 +08:00
|
|
|
# 初始化数据库
|
|
|
|
|
await init_db()
|
|
|
|
|
|
2026-02-13 23:30:48 +08:00
|
|
|
# 加载配置(多进程下串行化启动写操作)
|
|
|
|
|
async with db_startup_lock():
|
|
|
|
|
await load_config()
|
2025-02-08 22:41:32 +08:00
|
|
|
# 启动后台任务
|
|
|
|
|
task = asyncio.create_task(delete_expire_files())
|
2025-12-01 15:13:33 +08:00
|
|
|
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
2026-07-11 17:50:26 +08:00
|
|
|
presign_cleanup_task = asyncio.create_task(clean_expired_presign_sessions())
|
2025-02-23 20:49:51 +08:00
|
|
|
logger.info("应用初始化完成")
|
2025-02-08 22:41:32 +08:00
|
|
|
|
2024-10-06 17:14:16 +08:00
|
|
|
try:
|
|
|
|
|
yield
|
|
|
|
|
finally:
|
|
|
|
|
task.cancel()
|
2025-12-01 15:13:33 +08:00
|
|
|
chunk_cleanup_task.cancel()
|
2026-07-11 17:50:26 +08:00
|
|
|
presign_cleanup_task.cancel()
|
|
|
|
|
await asyncio.gather(
|
|
|
|
|
task,
|
|
|
|
|
chunk_cleanup_task,
|
|
|
|
|
presign_cleanup_task,
|
|
|
|
|
return_exceptions=True,
|
|
|
|
|
)
|
2024-10-06 17:14:16 +08:00
|
|
|
await Tortoise.close_connections()
|
2025-02-23 20:49:51 +08:00
|
|
|
logger.info("应用已关闭")
|
2024-10-06 17:14:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def load_config():
|
2026-02-13 23:45:44 +08:00
|
|
|
await ensure_settings_row()
|
2025-02-15 22:00:53 +08:00
|
|
|
await KeyValue.update_or_create(
|
|
|
|
|
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
|
|
|
|
)
|
2026-09-07 23:43:50 +08:00
|
|
|
# refresh_settings already syncs every rate limiter (error/metadata/upload/login)
|
|
|
|
|
# via _sync_ip_limits; do not hand-sync a subset here — that once drifted by
|
|
|
|
|
# missing the metadata limiter.
|
2026-09-09 18:47:40 +08:00
|
|
|
await refresh_settings(force=True)
|
2026-06-16 00:49:43 +08:00
|
|
|
await ensure_security_settings()
|
2026-01-07 20:36:59 +08:00
|
|
|
|
2026-09-09 17:37:06 +08:00
|
|
|
# Rate limiters keep per-process state (apps.base.dependencies.IPRateLimit).
|
|
|
|
|
# With multiple workers each process counts independently, so the effective
|
|
|
|
|
# threshold scales with the worker count and resets on restart.
|
2026-09-09 18:09:02 +08:00
|
|
|
if settings.server_workers > 1:
|
2026-09-09 17:37:06 +08:00
|
|
|
logger.warning(
|
2026-09-09 18:09:02 +08:00
|
|
|
"server_workers=%s:进程内限流在多 worker 下各自独立,阈值将按 worker 数放大;"
|
2026-09-09 17:37:06 +08:00
|
|
|
"如需完整限流请使用单 worker(默认)或改造为共享存储限流",
|
2026-09-09 18:09:02 +08:00
|
|
|
settings.server_workers,
|
2026-09-09 17:37:06 +08:00
|
|
|
)
|
|
|
|
|
|
2026-09-09 17:25:42 +08:00
|
|
|
|
2026-10-23 09:18:30 +00:00
|
|
|
# Tortoise 的 ORM 异常映射(DoesNotExist → 404、IntegrityError → 422)。
|
|
|
|
|
# 只注册处理器;连接初始化统一由 lifespan 里的 init_db() 负责,
|
|
|
|
|
# 避免 register_tortoise 合并 lifespan 造成的双重初始化。
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
lifespan=lifespan,
|
|
|
|
|
version=APP_VERSION,
|
|
|
|
|
exception_handlers=tortoise_exception_handlers(),
|
|
|
|
|
)
|
2023-08-15 17:23:30 +08:00
|
|
|
|
2026-09-09 17:07:43 +08:00
|
|
|
|
|
|
|
|
@app.exception_handler(StorageError)
|
|
|
|
|
async def storage_error_handler(request, exc: StorageError):
|
|
|
|
|
# Render StorageError exactly like FastAPI renders HTTPException so the
|
|
|
|
|
# framework-free storage layer keeps identical client-visible responses.
|
|
|
|
|
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
|
|
|
|
|
|
|
|
|
|
2026-02-13 23:45:44 +08:00
|
|
|
@app.middleware("http")
|
|
|
|
|
async def refresh_settings_middleware(request, call_next):
|
|
|
|
|
await refresh_settings()
|
2026-06-16 00:49:43 +08:00
|
|
|
if not is_runtime_initialized() and not is_setup_path(request.url.path):
|
|
|
|
|
if wants_html_response(request):
|
|
|
|
|
return setup_response(build_setup_page())
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=428,
|
|
|
|
|
content={
|
|
|
|
|
"code": 428,
|
|
|
|
|
"message": "系统未初始化,请先完成初始化",
|
|
|
|
|
"msg": "系统未初始化,请先完成初始化",
|
|
|
|
|
"detail": {"setup": "/setup"},
|
|
|
|
|
},
|
|
|
|
|
)
|
2026-02-13 23:45:44 +08:00
|
|
|
return await call_next(request)
|
|
|
|
|
|
2023-08-11 19:26:49 +08:00
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=["*"],
|
2026-07-23 19:38:50 +08:00
|
|
|
# 前端使用 Bearer Token,不依赖 Cookie credentials。
|
|
|
|
|
# allow_origins=["*"] 与 allow_credentials=True 组合不符合 CORS 规范。
|
|
|
|
|
allow_credentials=False,
|
2023-08-11 19:26:49 +08:00
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
2023-08-15 17:23:30 +08:00
|
|
|
|
2023-08-14 17:52:53 +08:00
|
|
|
app.include_router(share_api)
|
2025-02-23 20:49:51 +08:00
|
|
|
app.include_router(chunk_api)
|
2025-12-31 03:25:09 +08:00
|
|
|
app.include_router(presign_api)
|
2026-06-03 02:57:29 +08:00
|
|
|
app.include_router(presign_api, prefix="/api")
|
2023-08-14 17:52:53 +08:00
|
|
|
app.include_router(admin_api)
|
2026-09-09 17:25:42 +08:00
|
|
|
app.include_router(pages_router)
|
2026-10-10 18:52:28 +08:00
|
|
|
app.include_router(mcp_router)
|
2023-08-14 13:30:10 +08:00
|
|
|
|
2026-09-09 17:25:42 +08:00
|
|
|
# 404 时返回主题首页(index 兼任 exception handler 与 GET / 路由)
|
2026-09-20 02:01:08 +08:00
|
|
|
app.add_exception_handler(404, not_found_handler)
|
2024-06-15 17:27:28 +08:00
|
|
|
|
|
|
|
|
|
2025-02-15 22:00:53 +08:00
|
|
|
if __name__ == "__main__":
|
2023-08-14 18:27:39 +08:00
|
|
|
import uvicorn
|
|
|
|
|
|
2025-02-15 22:00:53 +08:00
|
|
|
uvicorn.run(
|
2026-01-07 20:36:59 +08:00
|
|
|
app="main:app",
|
2026-09-09 18:09:02 +08:00
|
|
|
host=settings.server_host,
|
|
|
|
|
port=settings.server_port,
|
2026-01-07 20:36:59 +08:00
|
|
|
reload=False,
|
2026-09-09 18:09:02 +08:00
|
|
|
workers=settings.server_workers,
|
2026-09-01 23:56:08 +08:00
|
|
|
log_level=get_log_level_name(),
|
|
|
|
|
access_log=is_access_log_enabled(),
|
2025-02-15 22:00:53 +08:00
|
|
|
)
|