Update app/main.py
Browse files- app/main.py +75 -241
app/main.py
CHANGED
|
@@ -2,13 +2,6 @@
|
|
| 2 |
|
| 3 |
Start with:
|
| 4 |
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
|
| 5 |
-
|
| 6 |
-
Multi-worker notes:
|
| 7 |
-
- All workers run a lightweight account-directory sync loop (ACCOUNT_SYNC_INTERVAL env, default 30 s).
|
| 8 |
-
- Only the worker that wins the advisory file lock runs the heavy AccountRefreshScheduler.
|
| 9 |
-
On Linux/macOS this uses fcntl.flock; on Windows it falls back to "always be leader"
|
| 10 |
-
(i.e. every worker runs the scheduler — acceptable because Windows deployments are
|
| 11 |
-
almost always single-worker anyway).
|
| 12 |
"""
|
| 13 |
|
| 14 |
import asyncio
|
|
@@ -38,7 +31,7 @@ load_dotenv()
|
|
| 38 |
|
| 39 |
|
| 40 |
# ---------------------------------------------------------------------------
|
| 41 |
-
# 🌟 纯正 Python 串行流加密/解密算法
|
| 42 |
# ---------------------------------------------------------------------------
|
| 43 |
def generic_cipher(data: bytes, key: str) -> bytes:
|
| 44 |
import hashlib
|
|
@@ -51,6 +44,32 @@ def generic_cipher(data: bytes, key: str) -> bytes:
|
|
| 51 |
return bytes(result)
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# ---------------------------------------------------------------------------
|
| 55 |
# Scheduler leader-election via advisory file lock
|
| 56 |
# ---------------------------------------------------------------------------
|
|
@@ -60,25 +79,17 @@ _lock_fd: int | None = None
|
|
| 60 |
|
| 61 |
|
| 62 |
def _try_acquire_scheduler_lock() -> bool:
|
| 63 |
-
"""Non-blocking attempt to become the scheduler leader.
|
| 64 |
-
|
| 65 |
-
Returns True if this worker acquired the lock (i.e. is the leader).
|
| 66 |
-
Falls back to True on Windows where fcntl is unavailable.
|
| 67 |
-
"""
|
| 68 |
global _lock_fd
|
| 69 |
try:
|
| 70 |
import fcntl
|
| 71 |
-
|
| 72 |
_LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 73 |
fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY)
|
| 74 |
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 75 |
_lock_fd = fd
|
| 76 |
return True
|
| 77 |
except BlockingIOError:
|
| 78 |
-
# Another worker already holds the lock.
|
| 79 |
return False
|
| 80 |
except (ImportError, OSError, AttributeError):
|
| 81 |
-
# fcntl unavailable (Windows) or unexpected FS error — treat as leader.
|
| 82 |
return True
|
| 83 |
|
| 84 |
|
|
@@ -88,7 +99,6 @@ def _release_scheduler_lock() -> None:
|
|
| 88 |
return
|
| 89 |
try:
|
| 90 |
import fcntl
|
| 91 |
-
|
| 92 |
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
|
| 93 |
os.close(_lock_fd)
|
| 94 |
except (ImportError, OSError):
|
|
@@ -96,14 +106,9 @@ def _release_scheduler_lock() -> None:
|
|
| 96 |
_lock_fd = None
|
| 97 |
|
| 98 |
|
| 99 |
-
# ---------------------------------------------------------------------------
|
| 100 |
-
# Early logging setup (before config is loaded)
|
| 101 |
-
# ---------------------------------------------------------------------------
|
| 102 |
-
|
| 103 |
setup_logging(
|
| 104 |
level=os.getenv("LOG_LEVEL", "INFO"),
|
| 105 |
-
file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower()
|
| 106 |
-
in {"1", "true", "yes", "on"},
|
| 107 |
)
|
| 108 |
|
| 109 |
|
|
@@ -111,25 +116,33 @@ setup_logging(
|
|
| 111 |
# Lifespan
|
| 112 |
# ---------------------------------------------------------------------------
|
| 113 |
|
| 114 |
-
|
| 115 |
@asynccontextmanager
|
| 116 |
async def lifespan(app: FastAPI):
|
| 117 |
target_db = data_path("accounts.db")
|
| 118 |
-
# 加密存储的目标文件,位于根目录下
|
| 119 |
enc_file = Path(__file__).resolve().parent.parent / "accounts.db.enc"
|
| 120 |
-
secret_key = os.getenv("APP_ACCESS_PASSWORD", "")
|
| 121 |
|
| 122 |
-
# 🌟 核心
|
| 123 |
if secret_key and enc_file.exists() and (not target_db.exists() or target_db.stat().st_size == 0):
|
| 124 |
try:
|
| 125 |
-
logger.info("[🔒 自动化自愈] 检测到加密备份卷,正在
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
-
logger.error("[❌ 自动化自愈失败]
|
| 133 |
|
| 134 |
# 1. Load configuration.
|
| 135 |
await _config.load()
|
|
@@ -144,60 +157,34 @@ async def lifespan(app: FastAPI):
|
|
| 144 |
platform.system(),
|
| 145 |
)
|
| 146 |
|
| 147 |
-
# 2. Initialise account repository
|
| 148 |
-
from app.control.account.backends.factory import
|
| 149 |
-
|
| 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 (config seed / account migration from SQLite).
|
| 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 |
-
# Reload config in case it was just seeded/migrated into the backend.
|
| 179 |
await _config.load()
|
| 180 |
await reconcile_local_media_cache_async()
|
| 181 |
|
| 182 |
directory = await get_account_directory(repo)
|
| 183 |
-
|
| 184 |
-
# Expose repository on app.state for admin handlers.
|
| 185 |
app.state.repository = repo
|
| 186 |
app.state.directory = directory
|
| 187 |
|
| 188 |
-
# 3. Account directory sync loop
|
| 189 |
_SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30"))
|
| 190 |
_SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3"))
|
| 191 |
-
_SYNC_IDLE_AFTER = 5
|
| 192 |
|
| 193 |
async def _sync_loop() -> None:
|
| 194 |
idle_streak = 0
|
| 195 |
while True:
|
| 196 |
-
interval =
|
| 197 |
-
_SYNC_ACTIVE_INTERVAL
|
| 198 |
-
if idle_streak < _SYNC_IDLE_AFTER
|
| 199 |
-
else _SYNC_IDLE_INTERVAL
|
| 200 |
-
)
|
| 201 |
await asyncio.sleep(interval)
|
| 202 |
try:
|
| 203 |
changed = await directory.sync_if_changed()
|
|
@@ -206,15 +193,13 @@ async def lifespan(app: FastAPI):
|
|
| 206 |
raise
|
| 207 |
except Exception as exc:
|
| 208 |
logger.debug("account directory sync error: error={}", exc)
|
| 209 |
-
idle_streak = _SYNC_IDLE_AFTER
|
| 210 |
|
| 211 |
sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync")
|
| 212 |
|
| 213 |
-
# 4. Account refresh scheduler
|
| 214 |
from app.control.account.refresh import AccountRefreshService
|
| 215 |
-
|
| 216 |
refresh_enabled = _config.get_bool("account.refresh.enabled", False)
|
| 217 |
-
|
| 218 |
refresh_svc = AccountRefreshService(repo)
|
| 219 |
set_refresh_service(refresh_svc)
|
| 220 |
app.state.refresh_service = refresh_svc
|
|
@@ -223,78 +208,31 @@ async def lifespan(app: FastAPI):
|
|
| 223 |
scheduler = get_account_refresh_scheduler(refresh_svc)
|
| 224 |
set_refresh_scheduler(scheduler)
|
| 225 |
set_refresh_scheduler_leader(is_leader)
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
if is_leader and strategy_name == "quota":
|
| 231 |
-
logger.info(
|
| 232 |
-
"scheduler leader: pid={} strategy=quota active_sync_s={} idle_sync_s={}",
|
| 233 |
-
os.getpid(),
|
| 234 |
-
_SYNC_ACTIVE_INTERVAL,
|
| 235 |
-
_SYNC_IDLE_INTERVAL,
|
| 236 |
-
)
|
| 237 |
-
elif is_leader:
|
| 238 |
-
logger.info(
|
| 239 |
-
"scheduler leader: pid={} strategy=random (scheduler idle) "
|
| 240 |
-
"active_sync_s={} idle_sync_s={}",
|
| 241 |
-
os.getpid(),
|
| 242 |
-
_SYNC_ACTIVE_INTERVAL,
|
| 243 |
-
_SYNC_IDLE_INTERVAL,
|
| 244 |
-
)
|
| 245 |
-
else:
|
| 246 |
-
logger.info(
|
| 247 |
-
"scheduler follower: pid={} strategy={} active_sync_s={} idle_sync_s={}",
|
| 248 |
-
os.getpid(),
|
| 249 |
-
strategy_name,
|
| 250 |
-
_SYNC_ACTIVE_INTERVAL,
|
| 251 |
-
_SYNC_IDLE_INTERVAL,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
# 5. Initialise proxy directory and start clearance refresh scheduler.
|
| 255 |
from app.control.proxy import get_proxy_directory
|
| 256 |
from app.control.proxy.scheduler import ProxyClearanceScheduler
|
| 257 |
-
|
| 258 |
proxy_dir = await get_proxy_directory()
|
| 259 |
proxy_scheduler = ProxyClearanceScheduler(proxy_dir)
|
| 260 |
if is_leader:
|
| 261 |
proxy_scheduler.start()
|
| 262 |
|
| 263 |
-
# 6. Console 配额窗口
|
| 264 |
-
_CONSOLE_RESET_INTERVAL = 30 # 秒
|
| 265 |
-
|
| 266 |
async def _console_reset_loop() -> None:
|
| 267 |
while True:
|
| 268 |
-
await asyncio.sleep(
|
| 269 |
try:
|
| 270 |
await refresh_svc.reset_expired_console_windows()
|
| 271 |
except asyncio.CancelledError:
|
| 272 |
raise
|
| 273 |
-
except Exception
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
console_reset_task = asyncio.create_task(
|
| 277 |
-
_console_reset_loop(), name="console-quota-reset"
|
| 278 |
-
) if is_leader else None
|
| 279 |
-
|
| 280 |
-
# 7. Console 429 EXPIRED 账号自动恢复任务
|
| 281 |
-
_CONSOLE_RECOVERY_INTERVAL = 600 # 10 分钟
|
| 282 |
-
|
| 283 |
-
async def _console_recovery_loop() -> None:
|
| 284 |
-
while True:
|
| 285 |
-
await asyncio.sleep(_CONSOLE_RECOVERY_INTERVAL)
|
| 286 |
-
try:
|
| 287 |
-
await refresh_svc.recover_console_expired_accounts()
|
| 288 |
-
except asyncio.CancelledError:
|
| 289 |
-
raise
|
| 290 |
-
except Exception as exc:
|
| 291 |
-
logger.debug("console expired recovery loop error: error={}", exc)
|
| 292 |
|
| 293 |
-
|
| 294 |
-
_console_recovery_loop(), name="console-expired-recovery"
|
| 295 |
-
) if is_leader else None
|
| 296 |
|
| 297 |
-
#
|
| 298 |
async def _smart_backup_monitor_loop():
|
| 299 |
last_logged_size = 0
|
| 300 |
while True:
|
|
@@ -306,10 +244,9 @@ async def lifespan(app: FastAPI):
|
|
| 306 |
if size_1 == 0 or size_1 == last_logged_size:
|
| 307 |
continue
|
| 308 |
|
| 309 |
-
# 关键防死锁设计:发现大小变化后静静等待 5 秒,确保大批量导入事务已彻底关闭
|
| 310 |
await asyncio.sleep(5)
|
| 311 |
size_2 = target_db.stat().st_size
|
| 312 |
-
if size_1 == size_2:
|
| 313 |
db_bytes = target_db.read_bytes()
|
| 314 |
enc_data = generic_cipher(db_bytes, secret_key)
|
| 315 |
b64_str = base64.b64encode(enc_data).decode("utf-8")
|
|
@@ -317,9 +254,8 @@ async def lifespan(app: FastAPI):
|
|
| 317 |
|
| 318 |
print(f"\n\n==================== 🔒 [Grok2API 密文备份点已安全生成] ====================\n"
|
| 319 |
f"585 个账号池已成功接收并保存。为了让数据在重启后【永不归零】,请前往 Space 的 `Files` 页面:\n"
|
| 320 |
-
f"1.
|
| 321 |
-
f"2. 文
|
| 322 |
-
f"3. 完整复制并粘贴下方整串密文保存并 Commit 提交即可(由于已使用你的隐藏密码加密,公开项目绝对安全):\n\n"
|
| 323 |
f"{b64_str}\n"
|
| 324 |
f"====================================================================\n\n", flush=True)
|
| 325 |
except Exception:
|
|
@@ -330,30 +266,19 @@ async def lifespan(app: FastAPI):
|
|
| 330 |
logger.info("application startup completed")
|
| 331 |
yield
|
| 332 |
|
| 333 |
-
# -----------
|
| 334 |
# Shutdown
|
| 335 |
-
# -----------
|
| 336 |
logger.info("application shutdown started")
|
| 337 |
-
|
| 338 |
-
# 🌟 核心自愈逻辑 [3/3]:释放监控器
|
| 339 |
backup_monitor_task.cancel()
|
| 340 |
try:
|
| 341 |
await backup_monitor_task
|
| 342 |
except asyncio.CancelledError:
|
| 343 |
pass
|
| 344 |
-
|
| 345 |
if console_reset_task is not None:
|
| 346 |
console_reset_task.cancel()
|
| 347 |
try:
|
| 348 |
await console_reset_task
|
| 349 |
except asyncio.CancelledError:
|
| 350 |
pass
|
| 351 |
-
if console_recovery_task is not None:
|
| 352 |
-
console_recovery_task.cancel()
|
| 353 |
-
try:
|
| 354 |
-
await console_recovery_task
|
| 355 |
-
except asyncio.CancelledError:
|
| 356 |
-
pass
|
| 357 |
sync_task.cancel()
|
| 358 |
try:
|
| 359 |
await sync_task
|
|
@@ -372,123 +297,40 @@ async def lifespan(app: FastAPI):
|
|
| 372 |
logger.info("application shutdown completed")
|
| 373 |
|
| 374 |
|
| 375 |
-
# ---------------------------------------------------------------------------
|
| 376 |
-
# Application factory
|
| 377 |
-
# ---------------------------------------------------------------------------
|
| 378 |
-
|
| 379 |
-
|
| 380 |
def create_app() -> FastAPI:
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
{"name": "OpenAI - Chat", "description": "Chat Completions compatible endpoints."},
|
| 384 |
-
{"name": "OpenAI - Responses", "description": "Responses API compatible endpoints."},
|
| 385 |
-
{"name": "OpenAI - Images", "description": "Image generation and image edit endpoints."},
|
| 386 |
-
{"name": "OpenAI - Videos", "description": "Video job creation and retrieval endpoints."},
|
| 387 |
-
{"name": "OpenAI - Files", "description": "Locally cached media file endpoints."},
|
| 388 |
-
{"name": "Anthropic - Messages", "description": "Anthropic Messages API compatible endpoints."},
|
| 389 |
-
{"name": "Admin - System", "description": "Admin system status and runtime configuration endpoints."},
|
| 390 |
-
{"name": "Admin - Tokens", "description": "Admin account token management endpoints."},
|
| 391 |
-
{"name": "Admin - Batch", "description": "Admin batch operation endpoints."},
|
| 392 |
-
{"name": "Admin - Assets", "description": "Admin online asset management endpoints."},
|
| 393 |
-
{"name": "Admin - Cache", "description": "Admin local cache management endpoints."},
|
| 394 |
-
{"name": "WebUI - System", "description": "WebUI authentication and system endpoints."},
|
| 395 |
-
{"name": "WebUI - Chat", "description": "WebUI chat API endpoints."},
|
| 396 |
-
{"name": "WebUI - Voice", "description": "WebUI voice API endpoints."},
|
| 397 |
-
]
|
| 398 |
-
app = FastAPI(
|
| 399 |
-
title="Grok2API",
|
| 400 |
-
version=get_project_version(),
|
| 401 |
-
description="OpenAI-compatible API gateway for Grok",
|
| 402 |
-
openapi_tags=openapi_tags,
|
| 403 |
-
lifespan=lifespan,
|
| 404 |
-
)
|
| 405 |
-
|
| 406 |
-
app.add_middleware(
|
| 407 |
-
CORSMiddleware,
|
| 408 |
-
allow_origins=["*"],
|
| 409 |
-
allow_credentials=True,
|
| 410 |
-
allow_methods=["*"],
|
| 411 |
-
allow_headers=["*"],
|
| 412 |
-
)
|
| 413 |
|
| 414 |
-
# Ensure config is loaded on every request.
|
| 415 |
@app.middleware("http")
|
| 416 |
async def _ensure_config(request: Request, call_next):
|
| 417 |
from app.control.account.runtime import reconcile_refresh_runtime
|
| 418 |
-
|
| 419 |
await _config.load()
|
| 420 |
reconcile_refresh_runtime()
|
| 421 |
return await call_next(request)
|
| 422 |
|
| 423 |
-
# Global exception handler — converts AppError to JSON.
|
| 424 |
@app.exception_handler(AppError)
|
| 425 |
async def _app_error_handler(request: Request, exc: AppError):
|
| 426 |
return JSONResponse(exc.to_dict(), status_code=exc.status)
|
| 427 |
|
| 428 |
@app.exception_handler(RequestValidationError)
|
| 429 |
-
async def _request_validation_handler(
|
| 430 |
-
|
| 431 |
-
exc: RequestValidationError,
|
| 432 |
-
):
|
| 433 |
-
errors = exc.errors()
|
| 434 |
-
first = errors[0] if errors else {}
|
| 435 |
-
loc = tuple(first.get("loc") or ())
|
| 436 |
-
param_parts = [
|
| 437 |
-
str(part)
|
| 438 |
-
for part in loc
|
| 439 |
-
if str(part) not in {"body", "query", "path", "header", "cookie"}
|
| 440 |
-
]
|
| 441 |
-
param = ".".join(param_parts)
|
| 442 |
-
message = first.get("msg") or "Request validation failed"
|
| 443 |
-
logger.warning(
|
| 444 |
-
"request validation failed: method={} path={} param={} errors={}",
|
| 445 |
-
request.method,
|
| 446 |
-
request.url.path,
|
| 447 |
-
param or "-",
|
| 448 |
-
errors,
|
| 449 |
-
)
|
| 450 |
-
payload = {
|
| 451 |
-
"error": {
|
| 452 |
-
"message": message,
|
| 453 |
-
"type": "invalid_request_error",
|
| 454 |
-
"code": "invalid_value",
|
| 455 |
-
}
|
| 456 |
-
}
|
| 457 |
-
if param:
|
| 458 |
-
payload["error"]["param"] = param
|
| 459 |
-
return JSONResponse(payload, status_code=400)
|
| 460 |
|
| 461 |
@app.exception_handler(Exception)
|
| 462 |
async def _generic_error_handler(request: Request, exc: Exception):
|
| 463 |
-
|
| 464 |
-
return JSONResponse(
|
| 465 |
-
{"error": {"message": "Internal server error", "type": "server_error"}},
|
| 466 |
-
status_code=500,
|
| 467 |
-
)
|
| 468 |
|
| 469 |
-
# Routers.
|
| 470 |
from app.products.web import router as web_router
|
| 471 |
from app.products.openai.router import router as openai_router
|
| 472 |
from app.products.anthropic.router import router as anthropic_router
|
| 473 |
-
|
| 474 |
app.include_router(web_router)
|
| 475 |
app.include_router(openai_router)
|
| 476 |
app.include_router(anthropic_router)
|
| 477 |
|
| 478 |
-
# Static assets — new statics only.
|
| 479 |
_statics_dir = Path(__file__).resolve().parent / "statics"
|
| 480 |
if _statics_dir.is_dir():
|
| 481 |
app.mount("/static", StaticFiles(directory=_statics_dir), name="static")
|
| 482 |
|
| 483 |
-
@app.get("/favicon.ico", include_in_schema=False)
|
| 484 |
-
def favicon():
|
| 485 |
-
from fastapi.responses import FileResponse as _FR
|
| 486 |
-
|
| 487 |
-
_ico = _statics_dir / "favicon.ico"
|
| 488 |
-
if _ico.exists():
|
| 489 |
-
return _FR(_ico)
|
| 490 |
-
return JSONResponse({"error": "not found"}, status_code=404)
|
| 491 |
-
|
| 492 |
@app.get("/health", include_in_schema=False)
|
| 493 |
def health():
|
| 494 |
return {"status": "ok"}
|
|
@@ -496,12 +338,4 @@ def create_app() -> FastAPI:
|
|
| 496 |
return app
|
| 497 |
|
| 498 |
|
| 499 |
-
app = create_app()
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
if __name__ == "__main__":
|
| 503 |
-
logger.error(
|
| 504 |
-
"direct startup is disabled: use "
|
| 505 |
-
"uv run granian --interface asgi --host 0.0.0.0 --port 8000 app.main:app"
|
| 506 |
-
)
|
| 507 |
-
raise SystemExit(1)
|
|
|
|
| 2 |
|
| 3 |
Start with:
|
| 4 |
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import asyncio
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
# ---------------------------------------------------------------------------
|
| 34 |
+
# 🌟 纯正 Python 串行流加密/解密算法
|
| 35 |
# ---------------------------------------------------------------------------
|
| 36 |
def generic_cipher(data: bytes, key: str) -> bytes:
|
| 37 |
import hashlib
|
|
|
|
| 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 |
+
# 强制将所有密码接口直接对齐你在 HF 后台设置的专属隐藏密码
|
| 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":
|
| 56 |
+
return "https://lifevta-grok2api.hf.space/"
|
| 57 |
+
return _orig_get_str(key, default)
|
| 58 |
+
_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 |
+
# 强制劫持前端所有功能开关状态(完美对齐图3、图4)
|
| 63 |
+
if key == "app.webui_enabled":
|
| 64 |
+
return True
|
| 65 |
+
if key == "features.temporary":
|
| 66 |
+
return False
|
| 67 |
+
if key in ("features.memory", "features.thinking_summary", "features.dynamic_statsig", "features.enable_nsfw"):
|
| 68 |
+
return True
|
| 69 |
+
return _orig_get_bool(key, default)
|
| 70 |
+
_config.get_bool = _patched_get_bool
|
| 71 |
+
|
| 72 |
+
|
| 73 |
# ---------------------------------------------------------------------------
|
| 74 |
# Scheduler leader-election via advisory file lock
|
| 75 |
# ---------------------------------------------------------------------------
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
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)
|
| 88 |
_lock_fd = fd
|
| 89 |
return True
|
| 90 |
except BlockingIOError:
|
|
|
|
| 91 |
return False
|
| 92 |
except (ImportError, OSError, AttributeError):
|
|
|
|
| 93 |
return True
|
| 94 |
|
| 95 |
|
|
|
|
| 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 |
_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() in {"1", "true", "yes", "on"},
|
|
|
|
| 112 |
)
|
| 113 |
|
| 114 |
|
|
|
|
| 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()
|
|
|
|
| 157 |
platform.system(),
|
| 158 |
)
|
| 159 |
|
| 160 |
+
# 2. Initialise account repository.
|
| 161 |
+
from app.control.account.backends.factory import create_repository, describe_repository_target
|
| 162 |
+
from app.control.account.runtime import reconcile_refresh_runtime, set_refresh_scheduler, set_refresh_scheduler_leader, set_refresh_service
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
await run_startup_migrations(config_backend=_config._get_backend(), account_repo=repo)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|
| 179 |
+
# 3. Account directory sync loop
|
| 180 |
_SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30"))
|
| 181 |
_SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3"))
|
| 182 |
+
_SYNC_IDLE_AFTER = 5
|
| 183 |
|
| 184 |
async def _sync_loop() -> None:
|
| 185 |
idle_streak = 0
|
| 186 |
while True:
|
| 187 |
+
interval = _SYNC_ACTIVE_INTERVAL if idle_streak < _SYNC_IDLE_AFTER else _SYNC_IDLE_INTERVAL
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
await asyncio.sleep(interval)
|
| 189 |
try:
|
| 190 |
changed = await directory.sync_if_changed()
|
|
|
|
| 193 |
raise
|
| 194 |
except Exception as exc:
|
| 195 |
logger.debug("account directory sync error: error={}", exc)
|
| 196 |
+
idle_streak = _SYNC_IDLE_AFTER
|
| 197 |
|
| 198 |
sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync")
|
| 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 |
scheduler = get_account_refresh_scheduler(refresh_svc)
|
| 209 |
set_refresh_scheduler(scheduler)
|
| 210 |
set_refresh_scheduler_leader(is_leader)
|
| 211 |
+
|
| 212 |
+
reconcile_refresh_runtime(refresh_enabled)
|
| 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(30)
|
| 226 |
try:
|
| 227 |
await refresh_svc.reset_expired_console_windows()
|
| 228 |
except asyncio.CancelledError:
|
| 229 |
raise
|
| 230 |
+
except Exception:
|
| 231 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
console_reset_task = asyncio.create_task(_console_reset_loop(), name="console-quota-reset") if is_leader else None
|
|
|
|
|
|
|
| 234 |
|
| 235 |
+
# 7. 智能防死锁监控器(静止检测,生成最新的加密文本包)
|
| 236 |
async def _smart_backup_monitor_loop():
|
| 237 |
last_logged_size = 0
|
| 238 |
while True:
|
|
|
|
| 244 |
if size_1 == 0 or size_1 == last_logged_size:
|
| 245 |
continue
|
| 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")
|
|
|
|
| 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:
|
|
|
|
| 266 |
logger.info("application startup completed")
|
| 267 |
yield
|
| 268 |
|
|
|
|
| 269 |
# Shutdown
|
|
|
|
| 270 |
logger.info("application shutdown started")
|
|
|
|
|
|
|
| 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 |
try:
|
| 279 |
await console_reset_task
|
| 280 |
except asyncio.CancelledError:
|
| 281 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
sync_task.cancel()
|
| 283 |
try:
|
| 284 |
await sync_task
|
|
|
|
| 297 |
logger.info("application shutdown completed")
|
| 298 |
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
def create_app() -> FastAPI:
|
| 301 |
+
app = FastAPI(title="Grok2API", version=get_project_version(), lifespan=lifespan)
|
| 302 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
|
|
|
| 304 |
@app.middleware("http")
|
| 305 |
async def _ensure_config(request: Request, call_next):
|
| 306 |
from app.control.account.runtime import reconcile_refresh_runtime
|
|
|
|
| 307 |
await _config.load()
|
| 308 |
reconcile_refresh_runtime()
|
| 309 |
return await call_next(request)
|
| 310 |
|
|
|
|
| 311 |
@app.exception_handler(AppError)
|
| 312 |
async def _app_error_handler(request: Request, exc: AppError):
|
| 313 |
return JSONResponse(exc.to_dict(), status_code=exc.status)
|
| 314 |
|
| 315 |
@app.exception_handler(RequestValidationError)
|
| 316 |
+
async def _request_validation_handler(request: Request, exc: RequestValidationError):
|
| 317 |
+
return JSONResponse({"error": {"message": "Validation failed"}}, status_code=400)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
@app.exception_handler(Exception)
|
| 320 |
async def _generic_error_handler(request: Request, exc: Exception):
|
| 321 |
+
return JSONResponse({"error": {"message": "Internal server error"}}, status_code=500)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
|
|
|
| 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)
|
| 329 |
|
|
|
|
| 330 |
_statics_dir = Path(__file__).resolve().parent / "statics"
|
| 331 |
if _statics_dir.is_dir():
|
| 332 |
app.mount("/static", StaticFiles(directory=_statics_dir), name="static")
|
| 333 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
@app.get("/health", include_in_schema=False)
|
| 335 |
def health():
|
| 336 |
return {"status": "ok"}
|
|
|
|
| 338 |
return app
|
| 339 |
|
| 340 |
|
| 341 |
+
app = create_app()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|