Application lifespan manager
(app: FastAPI)
| 86 | |
| 87 | @asynccontextmanager |
| 88 | async def lifespan(app: FastAPI): |
| 89 | """Application lifespan manager""" |
| 90 | # Startup |
| 91 | print("=" * 60) |
| 92 | print("Flow2API Starting...") |
| 93 | print("=" * 60) |
| 94 | |
| 95 | # Get config from setting.toml |
| 96 | config_dict = config.get_raw_config() |
| 97 | |
| 98 | # Check if database exists (determine if first startup) |
| 99 | is_first_startup = not db.db_exists() |
| 100 | |
| 101 | # Initialize database tables structure |
| 102 | await db.init_db() |
| 103 | |
| 104 | # Handle database initialization based on startup type |
| 105 | if is_first_startup: |
| 106 | print("First startup detected. Initializing database and configuration from setting.toml...") |
| 107 | await db.init_config_from_toml(config_dict, is_first_startup=True) |
| 108 | print("Database and configuration initialized successfully.") |
| 109 | else: |
| 110 | print("Existing database detected. Checking for missing tables and columns...") |
| 111 | await db.check_and_migrate_db(config_dict) |
| 112 | print("Database migration check completed.") |
| 113 | |
| 114 | # 启动时统一把数据库配置同步到内存,避免 personal/brower 相关运行时配置遗漏。 |
| 115 | await db.reload_config_to_memory() |
| 116 | generation_handler.file_cache.set_timeout(config.cache_timeout) |
| 117 | cache_cleanup_enabled = await generation_handler.file_cache.refresh_cleanup_task() |
| 118 | captcha_config = await db.get_captcha_config() |
| 119 | |
| 120 | # 尽量在浏览器服务启动前就拿到 token 快照,后续并发管理和预热共用。 |
| 121 | tokens = await token_manager.get_all_tokens() |
| 122 | |
| 123 | # Initialize browser captcha service if needed |
| 124 | browser_service = None |
| 125 | if captcha_config.captcha_method == "personal": |
| 126 | from .services.browser_captcha_personal import ( |
| 127 | BrowserCaptchaService, |
| 128 | PERSONAL_POOL_MAX_TOTAL_RESIDENT_TABS, |
| 129 | resolve_effective_browser_count, |
| 130 | resolve_effective_personal_max_resident_tabs, |
| 131 | ) |
| 132 | browser_service = await BrowserCaptchaService.get_instance(db) |
| 133 | print("Browser captcha service initialized (nodriver mode)") |
| 134 | |
| 135 | warmup_limit = max(1, min( |
| 136 | PERSONAL_POOL_MAX_TOTAL_RESIDENT_TABS, |
| 137 | resolve_effective_browser_count(config.browser_count) |
| 138 | * resolve_effective_personal_max_resident_tabs(config.personal_max_resident_tabs), |
| 139 | )) |
| 140 | warmup_project_ids = await token_manager.get_personal_warmup_project_ids( |
| 141 | tokens=tokens, |
| 142 | limit=warmup_limit, |
| 143 | ) |
| 144 | |
| 145 | warmed_slots = [] |
nothing calls this directly
no test coverage detected