(app: FastAPI)
| 35 | |
| 36 | @asynccontextmanager |
| 37 | async def lifespan(app: FastAPI): |
| 38 | # 初始化 Token 数据库 |
| 39 | from app.services.request_log_dao import init_request_log_dao |
| 40 | from app.services.token_automation import ( |
| 41 | run_directory_import, |
| 42 | start_token_automation_scheduler, |
| 43 | stop_token_automation_scheduler, |
| 44 | ) |
| 45 | from app.services.token_dao import init_token_database |
| 46 | |
| 47 | await init_token_database() |
| 48 | init_request_log_dao() |
| 49 | |
| 50 | if ( |
| 51 | settings.TOKEN_AUTO_IMPORT_ENABLED |
| 52 | and settings.TOKEN_AUTO_IMPORT_SOURCE_DIR.strip() |
| 53 | ): |
| 54 | try: |
| 55 | await run_directory_import( |
| 56 | settings.TOKEN_AUTO_IMPORT_SOURCE_DIR, |
| 57 | provider="zai", |
| 58 | ) |
| 59 | logger.info("✅ 启动阶段已完成一次目录自动导入") |
| 60 | except Exception as exc: |
| 61 | logger.warning(f"⚠️ 启动阶段目录自动导入失败: {exc}") |
| 62 | |
| 63 | # 从数据库初始化认证 token 池 |
| 64 | from app.utils.token_pool import initialize_token_pool_from_db |
| 65 | |
| 66 | token_pool = await initialize_token_pool_from_db( |
| 67 | provider="zai", |
| 68 | failure_threshold=settings.TOKEN_FAILURE_THRESHOLD, |
| 69 | recovery_timeout=settings.TOKEN_RECOVERY_TIMEOUT, |
| 70 | ) |
| 71 | |
| 72 | if not token_pool and not settings.ANONYMOUS_MODE: |
| 73 | logger.warning( |
| 74 | "⚠️ 未找到可用 Token 且未启用匿名模式,服务可能无法正常工作" |
| 75 | ) |
| 76 | |
| 77 | if settings.ANONYMOUS_MODE: |
| 78 | from app.utils.guest_session_pool import initialize_guest_session_pool |
| 79 | |
| 80 | guest_pool = await initialize_guest_session_pool( |
| 81 | pool_size=settings.GUEST_POOL_SIZE, |
| 82 | ) |
| 83 | guest_status = guest_pool.get_pool_status() |
| 84 | logger.info( |
| 85 | "🫥 匿名会话池已就绪: " |
| 86 | f"{guest_status.get('valid_sessions', 0)} 个可用会话" |
| 87 | ) |
| 88 | |
| 89 | await warmup_upstream_client() |
| 90 | await start_token_automation_scheduler() |
| 91 | |
| 92 | yield |
| 93 | |
| 94 | logger.info("🔄 应用正在关闭...") |
nothing calls this directly
no test coverage detected