File size: 14,480 Bytes
2e8394f ddebc3e 0f0b612 2e8394f ddebc3e 0f0b612 27e8a43 ddebc3e 27e8a43 0f0b612 27e8a43 2e8394f 0f0b612 ddebc3e 27e8a43 05672d5 2e8394f 0f0b612 101dfac 2e8394f 101dfac 0f0b612 101dfac 27e8a43 0f0b612 2e8394f 0f0b612 27e8a43 101dfac 0f0b612 101dfac ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 101dfac ddebc3e 101dfac ddebc3e 27e8a43 ddebc3e 101dfac ddebc3e 101dfac ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 101dfac ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 101dfac ddebc3e 27e8a43 ddebc3e 27e8a43 a01eff8 27e8a43 a01eff8 27e8a43 a01eff8 27e8a43 a01eff8 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 27e8a43 ddebc3e 2e8394f 27e8a43 2e8394f 27e8a43 ddebc3e 101dfac 2e8394f ddebc3e 2e8394f ddebc3e 27e8a43 ddebc3e 2e8394f ddebc3e 101dfac | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | # ===========================================================================
# 🌟 终极云原生拦截流:必须放在文件最顶部(第1行),确保在所有原版组件加载前完成重定向
# ===========================================================================
import sys
import os
from pathlib import Path
# 1. 强行重定向数据路径到 Hugging Face 运行期不灭网盘 /data
import app.platform.paths
def patched_data_path(*args):
hf_data = Path("/data")
if hf_data.exists():
try:
hf_data.mkdir(parents=True, exist_ok=True)
return hf_data.joinpath(*args)
except Exception:
pass
# 本地开发环境降级兜底
local_path = Path(__file__).resolve().parent.parent / "data"
local_path.mkdir(parents=True, exist_ok=True)
return local_path.joinpath(*args)
app.platform.paths.data_path = patched_data_path
# 2. 强行在内存级接管 snapshot 配置管理器,防止数据库锁死老配置
import app.platform.config.snapshot
_config = app.platform.config.snapshot.config
_orig_get_str = _config.get_str
def _patched_get_str(key: str, default: str = "") -> str:
# 无论数据库或 TOML 里锁了什么,内存中强制让密码对齐你在 HF 后台配的专属隐藏密码
if key in ("app.app_key", "app.api_key", "app.webui_key"):
return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
if key == "app.app_url":
return "https://lifevta-grok2api.hf.space/"
return _orig_get_str(key, default)
_config.get_str = _patched_get_str
_orig_get_bool = _config.get_bool
def _patched_get_bool(key: str, default: bool = False) -> bool:
# 内存中强行焊死前端所有功能开关状态(完美对齐图3、图4)
if key == "app.webui_enabled":
return True
if key == "features.temporary":
return False
if key in ("features.memory", "features.thinking_summary", "features.dynamic_statsig", "features.enable_nsfw"):
return True
return _orig_get_bool(key, default)
_config.get_bool = _patched_get_bool
# ===========================================================================
"""Grok2API application entry point.
Start with:
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
"""
import asyncio
import platform # 🌟 完美修复:补齐核心平台依赖包,彻底告别 NameError
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from app.platform.logging.logger import logger, setup_logging, reload_logging
from app.platform.errors import AppError
from app.platform.meta import get_project_version
from app.platform.storage import reconcile_local_media_cache_async
load_dotenv()
from app.platform.paths import data_path
# ---------------------------------------------------------------------------
# Scheduler leader-election via advisory file lock
# ---------------------------------------------------------------------------
_LOCK_FILE = data_path(".scheduler.lock")
_lock_fd: int | None = None
def _try_acquire_scheduler_lock() -> bool:
global _lock_fd
try:
import fcntl
_LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY)
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
_lock_fd = fd
return True
except BlockingIOError:
return False
except (ImportError, OSError, AttributeError):
return True
def _release_scheduler_lock() -> None:
global _lock_fd
if _lock_fd is None:
return
try:
import fcntl
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
os.close(_lock_fd)
except (ImportError, OSError):
pass
_lock_fd = None
# ---------------------------------------------------------------------------
# Early logging setup
# ---------------------------------------------------------------------------
setup_logging(
level=os.getenv("LOG_LEVEL", "INFO"),
file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower()
in {"1", "true", "yes", "on"},
)
# ---------------------------------------------------------------------------
# Lifespan
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
# 1. Load configuration.
await _config.load()
reload_logging(
level=os.getenv("LOG_LEVEL", "INFO"),
file_level=_config.get_str("logging.file_level", "") or None,
max_files=_config.get_int("logging.max_files", 7),
)
logger.info(
"application startup: service=grok2api python={} platform={}",
sys.version.split()[0],
platform.system(),
)
# 2. Initialise account repository
from app.control.account.backends.factory import (
create_repository,
describe_repository_target,
)
from app.control.account.runtime import (
reconcile_refresh_runtime,
set_refresh_scheduler,
set_refresh_scheduler_leader,
set_refresh_service,
)
from app.control.account.scheduler import get_account_refresh_scheduler
from app.dataplane.account import get_account_directory
storage_backend, storage_target = describe_repository_target()
logger.info(
"account storage configured: backend={} target={}",
storage_backend,
storage_target,
)
repo = create_repository()
await repo.initialize()
# 2a. First-boot migrations
from app.platform.startup import run_startup_migrations
await run_startup_migrations(
config_backend=_config._get_backend(),
account_repo=repo,
)
await _config.load()
await reconcile_local_media_cache_async()
directory = await get_account_directory(repo)
app.state.repository = repo
app.state.directory = directory
# 3. Account directory sync loop
_SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30"))
_SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3"))
_SYNC_IDLE_AFTER = 5
async def _sync_loop() -> None:
idle_streak = 0
while True:
interval = (
_SYNC_ACTIVE_INTERVAL
if idle_streak < _SYNC_IDLE_AFTER
else _SYNC_IDLE_INTERVAL
)
await asyncio.sleep(interval)
try:
changed = await directory.sync_if_changed()
idle_streak = 0 if changed else min(idle_streak + 1, _SYNC_IDLE_AFTER)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.debug("account directory sync error: error={}", exc)
idle_streak = _SYNC_IDLE_AFTER
sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync")
# 4. Account refresh scheduler
from app.control.account.refresh import AccountRefreshService
refresh_enabled = _config.get_bool("account.refresh.enabled", False)
refresh_svc = AccountRefreshService(repo)
set_refresh_service(refresh_svc)
app.state.refresh_service = refresh_svc
is_leader = _try_acquire_scheduler_lock()
scheduler = get_account_refresh_scheduler(refresh_svc)
set_refresh_scheduler(scheduler)
set_refresh_scheduler_leader(is_leader)
app.state.account_refresh_scheduler = scheduler
app.state.account_refresh_is_leader = is_leader
strategy_name = reconcile_refresh_runtime(refresh_enabled)
# 5. Initialise proxy directory
from app.control.proxy import get_proxy_directory
from app.control.proxy.scheduler import ProxyClearanceScheduler
proxy_dir = await get_proxy_directory()
proxy_scheduler = ProxyClearanceScheduler(proxy_dir)
if is_leader:
proxy_scheduler.start()
# 6. Console 配额窗口自动重置任务
_CONSOLE_RESET_INTERVAL = 30
async def _console_reset_loop() -> None:
while True:
await asyncio.sleep(_CONSOLE_RESET_INTERVAL)
try:
await refresh_svc.reset_expired_console_windows()
except asyncio.CancelledError:
raise
except Exception:
pass
console_reset_task = asyncio.create_task(
_console_reset_loop(), name="console-quota-reset"
) if is_leader else None
# 7. Console 429 EXPIRED 账号自动恢复任务
_CONSOLE_RECOVERY_INTERVAL = 600
async def _console_recovery_loop() -> None:
while True:
await asyncio.sleep(_CONSOLE_RECOVERY_INTERVAL)
try:
await refresh_svc.recover_console_expired_accounts()
except asyncio.CancelledError:
raise
except Exception:
pass
console_recovery_task = asyncio.create_task(
_console_recovery_loop(), name="console-expired-recovery"
) if is_leader else None
logger.info("application startup completed")
yield
# -----------
# Shutdown
# -----------
if console_reset_task is not None:
console_reset_task.cancel()
if console_recovery_task is not None:
console_recovery_task.cancel()
sync_task.cancel()
if is_leader:
scheduler.stop()
proxy_scheduler.stop()
_release_scheduler_lock()
set_refresh_scheduler(None)
set_refresh_scheduler_leader(False)
set_refresh_service(None)
await repo.close()
# ---------------------------------------------------------------------------
# Application factory
# ---------------------------------------------------------------------------
def create_app() -> FastAPI:
openapi_tags = [
{"name": "OpenAI - Models", "description": "Model discovery endpoints."},
{"name": "OpenAI - Chat", "description": "Chat Completions compatible endpoints."},
{"name": "OpenAI - Responses", "description": "Responses API compatible endpoints."},
{"name": "OpenAI - Images", "description": "Image generation and image edit endpoints."},
{"name": "OpenAI - Videos", "description": "Video job creation and retrieval endpoints."},
{"name": "OpenAI - Files", "description": "Locally cached media file endpoints."},
{"name": "Anthropic - Messages", "description": "Anthropic Messages API compatible endpoints."},
{"name": "Admin - System", "description": "Admin system status and runtime configuration endpoints."},
{"name": "Admin - Tokens", "description": "Admin account token management endpoints."},
{"name": "Admin - Batch", "description": "Admin batch operation endpoints."},
{"name": "Admin - Assets", "description": "Admin online asset management endpoints."},
{"name": "Admin - Cache", "description": "Admin local cache management endpoints."},
{"name": "WebUI - System", "description": "WebUI authentication and system endpoints."},
{"name": "WebUI - Chat", "description": "WebUI chat API endpoints."},
{"name": "WebUI - Voice", "description": "WebUI voice API endpoints."},
]
app = FastAPI(
title="Grok2API",
version=get_project_version(),
description="OpenAI-compatible API gateway for Grok",
openapi_tags=openapi_tags,
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def _ensure_config(request: Request, call_next):
from app.control.account.runtime import reconcile_refresh_runtime
await _config.load()
reconcile_refresh_runtime()
return await call_next(request)
@app.exception_handler(AppError)
async def _app_error_handler(request: Request, exc: AppError):
return JSONResponse(exc.to_dict(), status_code=exc.status)
@app.exception_handler(RequestValidationError)
async def _request_validation_handler(request: Request, exc: RequestValidationError):
errors = exc.errors()
first = errors[0] if errors else {}
loc = tuple(first.get("loc") or ())
param_parts = [
str(part)
for part in loc
if str(part) not in {"body", "query", "path", "header", "cookie"}
]
param = ".".join(param_parts)
message = first.get("msg") or "Request validation failed"
logger.warning(
"request validation failed: method={} path={} param={} errors={}",
request.method,
request.url.path,
param or "-",
errors,
)
payload = {
"error": {
"message": message,
"type": "invalid_request_error",
"code": "invalid_value",
}
}
if param:
payload["error"]["param"] = param
return JSONResponse(payload, status_code=400)
@app.exception_handler(Exception)
async def _generic_error_handler(request: Request, exc: Exception):
logger.exception("unhandled application exception: error={}", exc)
return JSONResponse(
{"error": {"message": "Internal server error", "type": "server_error"}},
status_code=500,
)
from app.products.web import router as web_router
from app.products.openai.router import router as openai_router
from app.products.anthropic.router import router as anthropic_router
app.include_router(web_router)
app.include_router(openai_router)
app.include_router(anthropic_router)
_statics_dir = Path(__file__).resolve().parent / "statics"
if _statics_dir.is_dir():
app.mount("/static", StaticFiles(directory=_statics_dir), name="static")
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
from fastapi.responses import FileResponse as _FR
_ico = _statics_dir / "favicon.ico"
if _ico.exists():
return _FR(_ico)
return JSONResponse({"error": "not found"}, status_code=404)
@app.get("/health", include_in_schema=False)
def health():
return {"status": "ok"}
return app
app = create_app() |