diff --git a/airflow-core/src/airflow/api_fastapi/app.py b/airflow-core/src/airflow/api_fastapi/app.py index 337d09b2ce36b..3261f073f194b 100644 --- a/airflow-core/src/airflow/api_fastapi/app.py +++ b/airflow-core/src/airflow/api_fastapi/app.py @@ -18,6 +18,7 @@ import logging from contextlib import AsyncExitStack, asynccontextmanager +from functools import cache from typing import TYPE_CHECKING, cast from urllib.parse import urlsplit @@ -54,8 +55,9 @@ log = logging.getLogger(__name__) -app: FastAPI | None = None -auth_manager: BaseAuthManager | None = None + +class _AuthManagerState: + instance: BaseAuthManager | None = None @asynccontextmanager @@ -107,19 +109,16 @@ def create_app(apps: str = "all") -> FastAPI: return app +@cache def cached_app(config=None, testing=False, apps="all") -> FastAPI: """Return cached instance of Airflow API app.""" - global app - if not app: - app = create_app(apps=apps) - return app + return create_app(apps=apps) def purge_cached_app() -> None: """Remove the cached version of the app and auth_manager in global state.""" - global app, auth_manager - app = None - auth_manager = None + cached_app.cache_clear() + _AuthManagerState.instance = None def get_auth_manager_cls() -> type[BaseAuthManager]: @@ -140,10 +139,9 @@ def get_auth_manager_cls() -> type[BaseAuthManager]: def create_auth_manager() -> BaseAuthManager: """Create the auth manager.""" - global auth_manager auth_manager_cls = get_auth_manager_cls() - auth_manager = auth_manager_cls() - return auth_manager + _AuthManagerState.instance = auth_manager_cls() + return _AuthManagerState.instance def init_auth_manager(app: FastAPI | None = None) -> BaseAuthManager: @@ -161,12 +159,12 @@ def init_auth_manager(app: FastAPI | None = None) -> BaseAuthManager: def get_auth_manager() -> BaseAuthManager: """Return the auth manager, provided it's been initialized before.""" - if auth_manager is None: + if _AuthManagerState.instance is None: raise RuntimeError( "Auth Manager has not been initialized yet. " "The `init_auth_manager` method needs to be called first." ) - return auth_manager + return _AuthManagerState.instance def init_plugins(app: FastAPI) -> None: