MCPcopy Create free account
hub / github.com/CJackHwang/AIstudioProxyAPI / lifespan

Function lifespan

api_utils/app.py:266–355  ·  view source on GitHub ↗

FastAPI application lifecycle management

(app: FastAPI)

Source from the content-addressed store, hash-verified

264
265@asynccontextmanager
266async 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

Calls 15

load_excluded_modelsFunction · 0.90
get_environment_variableFunction · 0.90
queue_workerFunction · 0.90
start_periodic_refreshFunction · 0.90
stop_periodic_refreshFunction · 0.90
save_cookies_on_shutdownFunction · 0.90
restore_original_streamsFunction · 0.90
_setup_loggingFunction · 0.85
_initialize_globalsFunction · 0.85
_start_stream_proxyFunction · 0.85