From 5ece1d34e3c960eaabfbd06b28d5327cd620ffb4 Mon Sep 17 00:00:00 2001 From: Scott Idem Date: Thu, 15 Jan 2026 17:10:42 -0500 Subject: [PATCH] Refactor: Relocate bootstrap and validation logic into lifespan context manager --- app/main.py | 62 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/app/main.py b/app/main.py index a0ed11f..c9afa6b 100644 --- a/app/main.py +++ b/app/main.py @@ -1,4 +1,4 @@ -import datetime, json, os, pytz, random, secrets # , uvicorn +import datetime, json, os, pytz, random, secrets, contextlib # , uvicorn from enum import Enum #from datetime import datetime, time, timedelta @@ -34,6 +34,40 @@ log = logging.getLogger(__name__) #format='[%(asctime)s] %(levelname)s @ %(module)s.%(funcName)s()#%(lineno)d: %(message)s' #) +@contextlib.asynccontextmanager +async def lifespan(app: FastAPI): + """ + Handles application startup and shutdown lifecycle. + """ + log.setLevel(logging.INFO) + log.info('### **** *** ** * Aether API v4 using FastAPI - Startup Lifespan Initiated * ** *** **** ###') + + # 1. Bootstrapping Configuration from DB with robust error handling + log.info("Bootstrapping Configuration...") + try: + if bootstrap_db_config(config.settings): + log.info("Successfully bootstrapped configuration from database.") + # Re-initialize the database engine with new credentials/URI + if reconnect_db(): + log.info("Database connection re-established with production configuration.") + else: + log.warning("FAILED to re-establish database connection after bootstrap. Falling back to .env settings.") + else: + log.warning("System bootstrap from DB returned no results. Using environment defaults.") + except Exception as e: + log.error(f"Unexpected error during configuration bootstrap: {e}. Falling back to .env settings.") + + # 2. Final validation of critical infrastructure + validate_critical_config(config.settings) + + log.info('### **** *** ** * Aether API v4 using FastAPI - Startup Sequence Complete * ** *** **** ###') + + yield + + # Shutdown logic + log.info('### **** *** ** * Aether API v4 using FastAPI - Shutdown Lifespan Initiated * ** *** **** ###') + log.info('The Aether FastAPI API is shutting down...') + print('### **** *** ** * Aether API v4 using FastAPI - About to try FastAPI() while loading... * ** *** **** ###') app = FastAPI( @@ -42,34 +76,10 @@ app = FastAPI( description = 'One Sky IT\'s Aether API v4 using FastAPI.', version = '4.9.0', operationsSorter = 'method', + lifespan = lifespan, ) -log.setLevel(logging.INFO) -# log.debug(config.settings) - -print('### **** *** ** * Aether API v4 using FastAPI - Bootstrapping Configuration... * ** *** **** ###') - -# Sync settings from DB with robust error handling -try: - if bootstrap_db_config(config.settings): - log.info("Successfully bootstrapped configuration from database.") - # Re-initialize the database engine with new credentials/URI - if reconnect_db(): - log.info("Database connection re-established with production configuration.") - else: - log.warning("FAILED to re-establish database connection after bootstrap. Falling back to .env settings.") - else: - log.warning("System bootstrap from DB returned no results. Using environment defaults.") -except Exception as e: - log.error(f"Unexpected error during configuration bootstrap: {e}. Falling back to .env settings.") - -# Perform final validation of critical infrastructure -validate_critical_config(config.settings) - -print('### **** *** ** * Aether API v4 using FastAPI - Finished Configuration Phase * ** *** **** ###' ) -log.debug(config.settings) - # @lru_cache() # def get_settings(): # return config.Settings()