Update app/main.py
Browse files- app/main.py +126 -116
app/main.py
CHANGED
|
@@ -8,48 +8,37 @@ import asyncio
|
|
| 8 |
import os
|
| 9 |
import platform
|
| 10 |
import sys
|
| 11 |
-
import base64
|
| 12 |
from contextlib import asynccontextmanager
|
| 13 |
from pathlib import Path
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
from fastapi.staticfiles import StaticFiles
|
| 21 |
-
|
| 22 |
-
from app.platform.logging.logger import logger, setup_logging, reload_logging
|
| 23 |
-
from app.platform.config.snapshot import config as _config
|
| 24 |
-
from app.platform.errors import AppError
|
| 25 |
-
from app.platform.meta import get_project_version
|
| 26 |
-
from app.platform.paths import data_path
|
| 27 |
-
from app.platform.storage import reconcile_local_media_cache_async
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
load_dotenv()
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def generic_cipher(data: bytes, key: str) -> bytes:
|
| 37 |
-
import hashlib
|
| 38 |
-
key_hash = hashlib.sha256(key.encode()).digest()
|
| 39 |
-
result = bytearray(len(data))
|
| 40 |
-
for i in range(len(data)):
|
| 41 |
-
if i % 32 == 0 and i > 0:
|
| 42 |
-
key_hash = hashlib.sha256(key_hash).digest()
|
| 43 |
-
result[i] = data[i] ^ key_hash[i % 32]
|
| 44 |
-
return bytes(result)
|
| 45 |
-
|
| 46 |
|
| 47 |
-
|
| 48 |
-
# 🌟 核心改进:通过 Python 内存劫持(Monkey-Patching)强行接管系统配置
|
| 49 |
-
# ---------------------------------------------------------------------------
|
| 50 |
_orig_get_str = _config.get_str
|
| 51 |
def _patched_get_str(key: str, default: str = "") -> str:
|
| 52 |
-
# 强制
|
| 53 |
if key in ("app.app_key", "app.api_key", "app.webui_key"):
|
| 54 |
return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
|
| 55 |
if key == "app.app_url":
|
|
@@ -59,7 +48,7 @@ _config.get_str = _patched_get_str
|
|
| 59 |
|
| 60 |
_orig_get_bool = _config.get_bool
|
| 61 |
def _patched_get_bool(key: str, default: bool = False) -> bool:
|
| 62 |
-
# 强
|
| 63 |
if key == "app.webui_enabled":
|
| 64 |
return True
|
| 65 |
if key == "features.temporary":
|
|
@@ -68,6 +57,22 @@ def _patched_get_bool(key: str, default: bool = False) -> bool:
|
|
| 68 |
return True
|
| 69 |
return _orig_get_bool(key, default)
|
| 70 |
_config.get_bool = _patched_get_bool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
# ---------------------------------------------------------------------------
|
|
@@ -82,6 +87,7 @@ def _try_acquire_scheduler_lock() -> bool:
|
|
| 82 |
global _lock_fd
|
| 83 |
try:
|
| 84 |
import fcntl
|
|
|
|
| 85 |
_LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 86 |
fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY)
|
| 87 |
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
@@ -99,6 +105,7 @@ def _release_scheduler_lock() -> None:
|
|
| 99 |
return
|
| 100 |
try:
|
| 101 |
import fcntl
|
|
|
|
| 102 |
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
|
| 103 |
os.close(_lock_fd)
|
| 104 |
except (ImportError, OSError):
|
|
@@ -106,9 +113,14 @@ def _release_scheduler_lock() -> None:
|
|
| 106 |
_lock_fd = None
|
| 107 |
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
setup_logging(
|
| 110 |
level=os.getenv("LOG_LEVEL", "INFO"),
|
| 111 |
-
file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower()
|
|
|
|
| 112 |
)
|
| 113 |
|
| 114 |
|
|
@@ -116,34 +128,9 @@ setup_logging(
|
|
| 116 |
# Lifespan
|
| 117 |
# ---------------------------------------------------------------------------
|
| 118 |
|
|
|
|
| 119 |
@asynccontextmanager
|
| 120 |
async def lifespan(app: FastAPI):
|
| 121 |
-
target_db = data_path("accounts.db")
|
| 122 |
-
enc_file = Path(__file__).resolve().parent.parent / "accounts.db.enc"
|
| 123 |
-
secret_key = os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
|
| 124 |
-
|
| 125 |
-
# 🌟 核心改进:引入 SQLite 特征幻数检测,防止坏文件导致系统锁死
|
| 126 |
-
if secret_key and enc_file.exists() and (not target_db.exists() or target_db.stat().st_size == 0):
|
| 127 |
-
try:
|
| 128 |
-
logger.info("[🔒 自动化自愈] 检测到加密备份卷,正在安全核验并恢复...")
|
| 129 |
-
raw_data = base64.b64decode(enc_file.read_text().strip())
|
| 130 |
-
|
| 131 |
-
# 智能判定:兼容纯 base64 或者是密文流
|
| 132 |
-
if raw_data.startswith(b"SQLite format 3\x00"):
|
| 133 |
-
dec_data = raw_data
|
| 134 |
-
else:
|
| 135 |
-
dec_data = generic_cipher(raw_data, secret_key)
|
| 136 |
-
|
| 137 |
-
# 只有通过头部校验的合法数据库才允许写入,否则放行以确保安全进入后台
|
| 138 |
-
if dec_data.startswith(b"SQLite format 3\x00"):
|
| 139 |
-
target_db.parent.mkdir(parents=True, exist_ok=True)
|
| 140 |
-
target_db.write_bytes(dec_data)
|
| 141 |
-
logger.info("[🎉 自动化自愈] 585 个账号历史数据库满血恢复成功!")
|
| 142 |
-
else:
|
| 143 |
-
logger.error("[⚠️ 自愈保护启动] 解密数据未通过 SQLite 校验,已自动放行空库,确保你能够安全登录后台重新导入。")
|
| 144 |
-
except Exception as e:
|
| 145 |
-
logger.error("[❌ 自动化自愈失败] 遭遇异常: {}", e)
|
| 146 |
-
|
| 147 |
# 1. Load configuration.
|
| 148 |
await _config.load()
|
| 149 |
reload_logging(
|
|
@@ -157,22 +144,42 @@ async def lifespan(app: FastAPI):
|
|
| 157 |
platform.system(),
|
| 158 |
)
|
| 159 |
|
| 160 |
-
# 2. Initialise account repository
|
| 161 |
-
from app.control.account.backends.factory import
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
from app.control.account.scheduler import get_account_refresh_scheduler
|
| 164 |
from app.dataplane.account import get_account_directory
|
| 165 |
|
| 166 |
storage_backend, storage_target = describe_repository_target()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
repo = create_repository()
|
| 168 |
await repo.initialize()
|
| 169 |
|
|
|
|
| 170 |
from app.platform.startup import run_startup_migrations
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
await _config.load()
|
| 173 |
await reconcile_local_media_cache_async()
|
| 174 |
|
| 175 |
directory = await get_account_directory(repo)
|
|
|
|
| 176 |
app.state.repository = repo
|
| 177 |
app.state.directory = directory
|
| 178 |
|
|
@@ -184,7 +191,11 @@ async def lifespan(app: FastAPI):
|
|
| 184 |
async def _sync_loop() -> None:
|
| 185 |
idle_streak = 0
|
| 186 |
while True:
|
| 187 |
-
interval =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
await asyncio.sleep(interval)
|
| 189 |
try:
|
| 190 |
changed = await directory.sync_if_changed()
|
|
@@ -199,7 +210,9 @@ async def lifespan(app: FastAPI):
|
|
| 199 |
|
| 200 |
# 4. Account refresh scheduler
|
| 201 |
from app.control.account.refresh import AccountRefreshService
|
|
|
|
| 202 |
refresh_enabled = _config.get_bool("account.refresh.enabled", False)
|
|
|
|
| 203 |
refresh_svc = AccountRefreshService(repo)
|
| 204 |
set_refresh_service(refresh_svc)
|
| 205 |
app.state.refresh_service = refresh_svc
|
|
@@ -208,21 +221,26 @@ async def lifespan(app: FastAPI):
|
|
| 208 |
scheduler = get_account_refresh_scheduler(refresh_svc)
|
| 209 |
set_refresh_scheduler(scheduler)
|
| 210 |
set_refresh_scheduler_leader(is_leader)
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
| 213 |
|
| 214 |
# 5. Initialise proxy directory
|
| 215 |
from app.control.proxy import get_proxy_directory
|
| 216 |
from app.control.proxy.scheduler import ProxyClearanceScheduler
|
|
|
|
| 217 |
proxy_dir = await get_proxy_directory()
|
| 218 |
proxy_scheduler = ProxyClearanceScheduler(proxy_dir)
|
| 219 |
if is_leader:
|
| 220 |
proxy_scheduler.start()
|
| 221 |
|
| 222 |
-
# 6. Console 配额窗口重置
|
|
|
|
|
|
|
| 223 |
async def _console_reset_loop() -> None:
|
| 224 |
while True:
|
| 225 |
-
await asyncio.sleep(
|
| 226 |
try:
|
| 227 |
await refresh_svc.reset_expired_console_windows()
|
| 228 |
except asyncio.CancelledError:
|
|
@@ -230,61 +248,39 @@ async def lifespan(app: FastAPI):
|
|
| 230 |
except Exception:
|
| 231 |
pass
|
| 232 |
|
| 233 |
-
console_reset_task = asyncio.create_task(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
|
| 236 |
-
async def _smart_backup_monitor_loop():
|
| 237 |
-
last_logged_size = 0
|
| 238 |
while True:
|
| 239 |
-
await asyncio.sleep(
|
| 240 |
-
if not secret_key or not target_db.exists():
|
| 241 |
-
continue
|
| 242 |
try:
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
await asyncio.sleep(5)
|
| 248 |
-
size_2 = target_db.stat().st_size
|
| 249 |
-
if size_1 == size_2:
|
| 250 |
-
db_bytes = target_db.read_bytes()
|
| 251 |
-
enc_data = generic_cipher(db_bytes, secret_key)
|
| 252 |
-
b64_str = base64.b64encode(enc_data).decode("utf-8")
|
| 253 |
-
last_logged_size = size_1
|
| 254 |
-
|
| 255 |
-
print(f"\n\n==================== 🔒 [Grok2API 密文备份点已安全生成] ====================\n"
|
| 256 |
-
f"585 个账号池已成功接收并保存。为了让数据在重启后【永不归零】,请前往 Space 的 `Files` 页面:\n"
|
| 257 |
-
f"1. 编辑或创建新文件,文件名严格命名为: accounts.db.enc\n"
|
| 258 |
-
f"2. 完整复制并粘贴下方整串密文保存并 Commit 提交即可:\n\n"
|
| 259 |
-
f"{b64_str}\n"
|
| 260 |
-
f"====================================================================\n\n", flush=True)
|
| 261 |
except Exception:
|
| 262 |
pass
|
| 263 |
|
| 264 |
-
|
|
|
|
|
|
|
| 265 |
|
| 266 |
logger.info("application startup completed")
|
| 267 |
yield
|
| 268 |
|
|
|
|
| 269 |
# Shutdown
|
| 270 |
-
|
| 271 |
-
backup_monitor_task.cancel()
|
| 272 |
-
try:
|
| 273 |
-
await backup_monitor_task
|
| 274 |
-
except asyncio.CancelledError:
|
| 275 |
-
pass
|
| 276 |
if console_reset_task is not None:
|
| 277 |
console_reset_task.cancel()
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
except asyncio.CancelledError:
|
| 281 |
-
pass
|
| 282 |
sync_task.cancel()
|
| 283 |
-
|
| 284 |
-
await sync_task
|
| 285 |
-
except asyncio.CancelledError:
|
| 286 |
-
pass
|
| 287 |
-
|
| 288 |
if is_leader:
|
| 289 |
scheduler.stop()
|
| 290 |
proxy_scheduler.stop()
|
|
@@ -294,12 +290,26 @@ async def lifespan(app: FastAPI):
|
|
| 294 |
set_refresh_scheduler_leader(False)
|
| 295 |
set_refresh_service(None)
|
| 296 |
await repo.close()
|
| 297 |
-
logger.info("application shutdown completed")
|
| 298 |
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
def create_app() -> FastAPI:
|
| 301 |
-
app = FastAPI(
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
@app.middleware("http")
|
| 305 |
async def _ensure_config(request: Request, call_next):
|
|
@@ -323,6 +333,7 @@ def create_app() -> FastAPI:
|
|
| 323 |
from app.products.web import router as web_router
|
| 324 |
from app.products.openai.router import router as openai_router
|
| 325 |
from app.products.anthropic.router import router as anthropic_router
|
|
|
|
| 326 |
app.include_router(web_router)
|
| 327 |
app.include_router(openai_router)
|
| 328 |
app.include_router(anthropic_router)
|
|
@@ -337,5 +348,4 @@ def create_app() -> FastAPI:
|
|
| 337 |
|
| 338 |
return app
|
| 339 |
|
| 340 |
-
|
| 341 |
app = create_app()
|
|
|
|
| 8 |
import os
|
| 9 |
import platform
|
| 10 |
import sys
|
|
|
|
| 11 |
from contextlib import asynccontextmanager
|
| 12 |
from pathlib import Path
|
| 13 |
|
| 14 |
+
# ===========================================================================
|
| 15 |
+
# 🌟 终极云原生拦截流:动态重定向存储至 HF 永久网盘 + 内存级配置接管
|
| 16 |
+
# ===========================================================================
|
| 17 |
+
import app.platform.paths
|
| 18 |
+
_original_data_path = app.platform.paths.data_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
def patched_data_path(*args):
|
| 21 |
+
# 检测 Hugging Face 挂载的运行期不灭网盘 /data 是否存在且可写
|
| 22 |
+
hf_data = Path("/data")
|
| 23 |
+
if hf_data.exists():
|
| 24 |
+
try:
|
| 25 |
+
test_file = hf_data / ".hf_write_test"
|
| 26 |
+
test_file.touch()
|
| 27 |
+
test_file.unlink()
|
| 28 |
+
# 完美的运行时穿透:将所有数据直接写进不灭网盘,拒绝临时容器抹除
|
| 29 |
+
return hf_data.joinpath(*args)
|
| 30 |
+
except Exception:
|
| 31 |
+
pass
|
| 32 |
+
return _original_data_path(*args)
|
| 33 |
|
| 34 |
+
# 全局覆盖路径劫持
|
| 35 |
+
app.platform.paths.data_path = patched_data_path
|
| 36 |
+
data_path = patched_data_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
from app.platform.config.snapshot import config as _config
|
|
|
|
|
|
|
| 39 |
_orig_get_str = _config.get_str
|
| 40 |
def _patched_get_str(key: str, default: str = "") -> str:
|
| 41 |
+
# 强制在内存级让管理密码绝对对齐你在后台配的隐藏密码
|
| 42 |
if key in ("app.app_key", "app.api_key", "app.webui_key"):
|
| 43 |
return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
|
| 44 |
if key == "app.app_url":
|
|
|
|
| 48 |
|
| 49 |
_orig_get_bool = _config.get_bool
|
| 50 |
def _patched_get_bool(key: str, default: bool = False) -> bool:
|
| 51 |
+
# 强行焊死前端所有功能开关状态(完美对齐图3、图4)
|
| 52 |
if key == "app.webui_enabled":
|
| 53 |
return True
|
| 54 |
if key == "features.temporary":
|
|
|
|
| 57 |
return True
|
| 58 |
return _orig_get_bool(key, default)
|
| 59 |
_config.get_bool = _patched_get_bool
|
| 60 |
+
# ===========================================================================
|
| 61 |
+
|
| 62 |
+
from dotenv import load_dotenv
|
| 63 |
+
from fastapi import FastAPI, Request
|
| 64 |
+
from fastapi.exceptions import RequestValidationError
|
| 65 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 66 |
+
from fastapi.responses import JSONResponse
|
| 67 |
+
from fastapi.staticfiles import StaticFiles
|
| 68 |
+
|
| 69 |
+
from app.platform.logging.logger import logger, setup_logging, reload_logging
|
| 70 |
+
from app.platform.errors import AppError
|
| 71 |
+
from app.platform.meta import get_project_version
|
| 72 |
+
from app.platform.storage import reconcile_local_media_cache_async
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
load_dotenv()
|
| 76 |
|
| 77 |
|
| 78 |
# ---------------------------------------------------------------------------
|
|
|
|
| 87 |
global _lock_fd
|
| 88 |
try:
|
| 89 |
import fcntl
|
| 90 |
+
|
| 91 |
_LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 92 |
fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY)
|
| 93 |
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
|
|
| 105 |
return
|
| 106 |
try:
|
| 107 |
import fcntl
|
| 108 |
+
|
| 109 |
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
|
| 110 |
os.close(_lock_fd)
|
| 111 |
except (ImportError, OSError):
|
|
|
|
| 113 |
_lock_fd = None
|
| 114 |
|
| 115 |
|
| 116 |
+
# ---------------------------------------------------------------------------
|
| 117 |
+
# Early logging setup
|
| 118 |
+
# ---------------------------------------------------------------------------
|
| 119 |
+
|
| 120 |
setup_logging(
|
| 121 |
level=os.getenv("LOG_LEVEL", "INFO"),
|
| 122 |
+
file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower()
|
| 123 |
+
in {"1", "true", "yes", "on"},
|
| 124 |
)
|
| 125 |
|
| 126 |
|
|
|
|
| 128 |
# Lifespan
|
| 129 |
# ---------------------------------------------------------------------------
|
| 130 |
|
| 131 |
+
|
| 132 |
@asynccontextmanager
|
| 133 |
async def lifespan(app: FastAPI):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
# 1. Load configuration.
|
| 135 |
await _config.load()
|
| 136 |
reload_logging(
|
|
|
|
| 144 |
platform.system(),
|
| 145 |
)
|
| 146 |
|
| 147 |
+
# 2. Initialise account repository
|
| 148 |
+
from app.control.account.backends.factory import (
|
| 149 |
+
create_repository,
|
| 150 |
+
describe_repository_target,
|
| 151 |
+
)
|
| 152 |
+
from app.control.account.runtime import (
|
| 153 |
+
reconcile_refresh_runtime,
|
| 154 |
+
set_refresh_scheduler,
|
| 155 |
+
set_refresh_scheduler_leader,
|
| 156 |
+
set_refresh_service,
|
| 157 |
+
)
|
| 158 |
from app.control.account.scheduler import get_account_refresh_scheduler
|
| 159 |
from app.dataplane.account import get_account_directory
|
| 160 |
|
| 161 |
storage_backend, storage_target = describe_repository_target()
|
| 162 |
+
logger.info(
|
| 163 |
+
"account storage configured: backend={} target={}",
|
| 164 |
+
storage_backend,
|
| 165 |
+
storage_target,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
repo = create_repository()
|
| 169 |
await repo.initialize()
|
| 170 |
|
| 171 |
+
# 2a. First-boot migrations
|
| 172 |
from app.platform.startup import run_startup_migrations
|
| 173 |
+
|
| 174 |
+
await run_startup_migrations(
|
| 175 |
+
config_backend=_config._get_backend(),
|
| 176 |
+
account_repo=repo,
|
| 177 |
+
)
|
| 178 |
await _config.load()
|
| 179 |
await reconcile_local_media_cache_async()
|
| 180 |
|
| 181 |
directory = await get_account_directory(repo)
|
| 182 |
+
|
| 183 |
app.state.repository = repo
|
| 184 |
app.state.directory = directory
|
| 185 |
|
|
|
|
| 191 |
async def _sync_loop() -> None:
|
| 192 |
idle_streak = 0
|
| 193 |
while True:
|
| 194 |
+
interval = (
|
| 195 |
+
_SYNC_ACTIVE_INTERVAL
|
| 196 |
+
if idle_streak < _SYNC_IDLE_AFTER
|
| 197 |
+
else _SYNC_IDLE_INTERVAL
|
| 198 |
+
)
|
| 199 |
await asyncio.sleep(interval)
|
| 200 |
try:
|
| 201 |
changed = await directory.sync_if_changed()
|
|
|
|
| 210 |
|
| 211 |
# 4. Account refresh scheduler
|
| 212 |
from app.control.account.refresh import AccountRefreshService
|
| 213 |
+
|
| 214 |
refresh_enabled = _config.get_bool("account.refresh.enabled", False)
|
| 215 |
+
|
| 216 |
refresh_svc = AccountRefreshService(repo)
|
| 217 |
set_refresh_service(refresh_svc)
|
| 218 |
app.state.refresh_service = refresh_svc
|
|
|
|
| 221 |
scheduler = get_account_refresh_scheduler(refresh_svc)
|
| 222 |
set_refresh_scheduler(scheduler)
|
| 223 |
set_refresh_scheduler_leader(is_leader)
|
| 224 |
+
app.state.account_refresh_scheduler = scheduler
|
| 225 |
+
app.state.account_refresh_is_leader = is_leader
|
| 226 |
+
|
| 227 |
+
strategy_name = reconcile_refresh_runtime(refresh_enabled)
|
| 228 |
|
| 229 |
# 5. Initialise proxy directory
|
| 230 |
from app.control.proxy import get_proxy_directory
|
| 231 |
from app.control.proxy.scheduler import ProxyClearanceScheduler
|
| 232 |
+
|
| 233 |
proxy_dir = await get_proxy_directory()
|
| 234 |
proxy_scheduler = ProxyClearanceScheduler(proxy_dir)
|
| 235 |
if is_leader:
|
| 236 |
proxy_scheduler.start()
|
| 237 |
|
| 238 |
+
# 6. Console 配额窗口自动重置任务
|
| 239 |
+
_CONSOLE_RESET_INTERVAL = 30
|
| 240 |
+
|
| 241 |
async def _console_reset_loop() -> None:
|
| 242 |
while True:
|
| 243 |
+
await asyncio.sleep(_CONSOLE_RESET_INTERVAL)
|
| 244 |
try:
|
| 245 |
await refresh_svc.reset_expired_console_windows()
|
| 246 |
except asyncio.CancelledError:
|
|
|
|
| 248 |
except Exception:
|
| 249 |
pass
|
| 250 |
|
| 251 |
+
console_reset_task = asyncio.create_task(
|
| 252 |
+
_console_reset_loop(), name="console-quota-reset"
|
| 253 |
+
) if is_leader else None
|
| 254 |
+
|
| 255 |
+
# 7. Console 429 EXPIRED 账号自动恢复任务
|
| 256 |
+
_CONSOLE_RECOVERY_INTERVAL = 600
|
| 257 |
|
| 258 |
+
async def _console_recovery_loop() -> None:
|
|
|
|
|
|
|
| 259 |
while True:
|
| 260 |
+
await asyncio.sleep(_CONSOLE_RECOVERY_INTERVAL)
|
|
|
|
|
|
|
| 261 |
try:
|
| 262 |
+
await refresh_svc.recover_console_expired_accounts()
|
| 263 |
+
except asyncio.CancelledError:
|
| 264 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
except Exception:
|
| 266 |
pass
|
| 267 |
|
| 268 |
+
console_recovery_task = asyncio.create_task(
|
| 269 |
+
_console_recovery_loop(), name="console-expired-recovery"
|
| 270 |
+
) if is_leader else None
|
| 271 |
|
| 272 |
logger.info("application startup completed")
|
| 273 |
yield
|
| 274 |
|
| 275 |
+
# -----------
|
| 276 |
# Shutdown
|
| 277 |
+
# -----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
if console_reset_task is not None:
|
| 279 |
console_reset_task.cancel()
|
| 280 |
+
if console_recovery_task is not None:
|
| 281 |
+
console_recovery_task.cancel()
|
|
|
|
|
|
|
| 282 |
sync_task.cancel()
|
| 283 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
if is_leader:
|
| 285 |
scheduler.stop()
|
| 286 |
proxy_scheduler.stop()
|
|
|
|
| 290 |
set_refresh_scheduler_leader(False)
|
| 291 |
set_refresh_service(None)
|
| 292 |
await repo.close()
|
|
|
|
| 293 |
|
| 294 |
|
| 295 |
+
# ---------------------------------------------------------------------------
|
| 296 |
+
# Application factory
|
| 297 |
+
# ---------------------------------------------------------------------------
|
| 298 |
+
|
| 299 |
def create_app() -> FastAPI:
|
| 300 |
+
app = FastAPI(
|
| 301 |
+
title="Grok2API",
|
| 302 |
+
version=get_project_version(),
|
| 303 |
+
lifespan=lifespan,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
app.add_middleware(
|
| 307 |
+
CORSMiddleware,
|
| 308 |
+
allow_origins=["*"],
|
| 309 |
+
allow_credentials=True,
|
| 310 |
+
allow_methods=["*"],
|
| 311 |
+
allow_headers=["*"],
|
| 312 |
+
)
|
| 313 |
|
| 314 |
@app.middleware("http")
|
| 315 |
async def _ensure_config(request: Request, call_next):
|
|
|
|
| 333 |
from app.products.web import router as web_router
|
| 334 |
from app.products.openai.router import router as openai_router
|
| 335 |
from app.products.anthropic.router import router as anthropic_router
|
| 336 |
+
|
| 337 |
app.include_router(web_router)
|
| 338 |
app.include_router(openai_router)
|
| 339 |
app.include_router(anthropic_router)
|
|
|
|
| 348 |
|
| 349 |
return app
|
| 350 |
|
|
|
|
| 351 |
app = create_app()
|