FastAPI application lifecycle management
(app: FastAPI)
| 264 | |
| 265 | @asynccontextmanager |
| 266 | async def lifespan(app: FastAPI): |
| 267 | """FastAPI application lifecycle management""" |
| 268 | from .queue_worker import queue_worker |
| 269 | |
| 270 | original_streams = sys.stdout, sys.stderr |
| 271 | initial_stdout, initial_stderr = _setup_logging() |
| 272 | logger = state.logger |
| 273 | |
| 274 | _initialize_globals() |
| 275 | _initialize_proxy_settings() |
| 276 | load_excluded_models(EXCLUDED_MODELS_FILENAME) |
| 277 | |
| 278 | state.is_initializing = True |
| 279 | startup_start_time = time.time() |
| 280 | logger.info("Starting AI Studio Proxy Server...") |
| 281 | |
| 282 | try: |
| 283 | await _start_stream_proxy() |
| 284 | await _initialize_browser_and_page() |
| 285 | |
| 286 | launch_mode = get_environment_variable("LAUNCH_MODE", "unknown") |
| 287 | if state.is_page_ready or launch_mode == "direct_debug_no_browser": |
| 288 | state.worker_task = asyncio.create_task(queue_worker()) |
| 289 | logger.info("Request processing worker started.") |
| 290 | else: |
| 291 | raise RuntimeError("Failed to initialize browser/page, worker not started.") |
| 292 | |
| 293 | logger.info("[WATCHDOG] Starting Quota Watchdog Task...") |
| 294 | watchdog_func = state.quota_watchdog |
| 295 | if watchdog_func: |
| 296 | app.state.watchdog_task = asyncio.create_task(watchdog_func()) |
| 297 | else: |
| 298 | logger.warning( |
| 299 | "[WATCHDOG] Quota Watchdog function not found, task not started." |
| 300 | ) |
| 301 | |
| 302 | # Start periodic cookie refresh task |
| 303 | try: |
| 304 | from browser_utils.cookie_refresh import start_periodic_refresh |
| 305 | |
| 306 | cookie_refresh_task = start_periodic_refresh() |
| 307 | if cookie_refresh_task: |
| 308 | app.state.cookie_refresh_task = cookie_refresh_task |
| 309 | except Exception as e: |
| 310 | logger.warning(f"[COOKIE-REFRESH] Failed to start periodic refresh: {e}") |
| 311 | |
| 312 | startup_duration = time.time() - startup_start_time |
| 313 | logger.info(f"Server startup complete. (Took: {startup_duration:.2f}s)") |
| 314 | state.is_initializing = False |
| 315 | yield |
| 316 | except Exception as e: |
| 317 | logger.critical(f"Application startup failed: {e}", exc_info=True) |
| 318 | await _shutdown_resources() |
| 319 | raise RuntimeError(f"Application startup failed: {e}") from e |
| 320 | finally: |
| 321 | logger.info("Shutting down server...") |
| 322 | |
| 323 | # Stop periodic cookie refresh and save cookies before shutdown |