From 91a99b76bec00f9b2775a671f30e88999889ec79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E8=BE=89?= Date: Thu, 12 Mar 2026 16:16:40 +0800 Subject: [PATCH] fix: initialize SQL storage on first request in serverless runtime Vercel serverless deployments could start serving requests without reliably executing FastAPI lifespan startup, so config.load() was not always called during cold start. Because SQL schema creation is triggered through storage-backed config/tokens access, PostgreSQL/MySQL tables (for example app_config and tokens) were never initialized even when SERVER_STORAGE_TYPE and SERVER_STORAGE_URL were configured. Add a minimal lazy-init guard in Config with ensure_loaded(), protected by an asyncio lock and a success flag to keep initialization idempotent under concurrent first requests. Wire this guard into an HTTP middleware so initialization is guaranteed before handling requests, and reuse ensure_loaded() in lifespan to preserve existing startup behavior. This keeps the fix small, safe, and backward-compatible while restoring deterministic DB bootstrapping on Vercel. --- app/core/config.py | 14 ++++++++++++++ main.py | 11 ++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/app/core/config.py b/app/core/config.py index c849f01e..8d6335f2 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -6,6 +6,7 @@ """ from copy import deepcopy +import asyncio from pathlib import Path from typing import Any, Dict import tomllib @@ -244,6 +245,8 @@ class Config: self._defaults = {} self._code_defaults = {} self._defaults_loaded = False + self._loaded = False + self._load_lock = asyncio.Lock() def register_defaults(self, defaults: Dict[str, Any]): """注册代码中定义的默认值""" @@ -330,9 +333,20 @@ class Config: ) self._config = merged + self._loaded = True except Exception as e: logger.error(f"Error loading config: {e}") self._config = {} + self._loaded = False + + async def ensure_loaded(self): + """确保配置至少成功加载一次(按需懒加载,线程安全)""" + if self._loaded: + return + async with self._load_lock: + if self._loaded: + return + await self.load() def get(self, key: str, default: Any = None) -> Any: """ diff --git a/main.py b/main.py index f62c12e6..9e7c70e6 100644 --- a/main.py +++ b/main.py @@ -23,12 +23,12 @@ env_file = BASE_DIR / ".env" if env_file.exists(): load_dotenv(env_file) -from fastapi import FastAPI # noqa: E402 +from fastapi import FastAPI, Request # noqa: E402 from fastapi.middleware.cors import CORSMiddleware # noqa: E402 from fastapi import Depends # noqa: E402 from app.core.auth import verify_api_key # noqa: E402 -from app.core.config import get_config # noqa: E402 +from app.core.config import config, get_config # noqa: E402 from app.core.logger import logger, setup_logging # noqa: E402 from app.core.exceptions import register_exception_handlers # noqa: E402 from app.core.response_middleware import ResponseLoggerMiddleware # noqa: E402 @@ -61,7 +61,7 @@ async def lifespan(app: FastAPI): register_defaults(get_grok_defaults()) # 2. 加载配置 - await config.load() + await config.ensure_loaded() # 3. 启动服务显示 logger.info("Starting Grok2API...") @@ -131,6 +131,11 @@ def create_app() -> FastAPI: # 请求日志和 ID 中间件 app.add_middleware(ResponseLoggerMiddleware) + @app.middleware("http") + async def ensure_config_loaded(request: Request, call_next): + await config.ensure_loaded() + return await call_next(request) + # 注册异常处理器 register_exception_handlers(app)