# Aether API V3 Core Architecture (Refactor 2026-01-15) This document describes the modular architecture of the Aether API backend, finalized in January 2026. The goal of this refactor was to resolve boot-time circular dependencies, eliminate naming collisions, and isolate global state from business logic. ## 1. Application Entry Point (`app/main.py`) The `app/main.py` file is now a lightweight orchestrator. Its primary roles are: - Defining the FastAPI application instance. - Managing the **lifespan** context manager for startup/shutdown tasks. - Calling the centralized registries for routers and middleware. ### The Lifespan Sequence: 1. **Logging Setup**: `setup_logging(settings)` is called first but safely. 2. **Configuration Bootstrap**: `bootstrap_db_config(settings)` queries the `cfg` table. 3. **Database Refresh**: `reconnect_db()` refreshes the SQLAlchemy engine with production credentials. 4. **Validation**: `validate_critical_config(settings)` ensures the environment is production-ready. ## 2. Centralized Registries To keep `main.py` clean, registrations are moved to dedicated modules: - **`app/routers/registry.py`**: Exports `setup_routers(app)`. Handles the import and inclusion of 50+ application routers. - **`app/middleware.py`**: A dedicated home for utility middlewares (e.g., `add_process_time_header`). ## 3. Modular Database Logic The monolithic `db_sql.py` has been split into three distinct layers: - **`app/lib_sql_core.py` (Foundational)**: Manages the global SQLAlchemy `engine`, the `db` connection, and the thread-local error state. It is the "Source of Truth" for the connection. - **`app/lib_sql_crud.py` (Logic)**: Contains high-level CRUD helpers (`sql_insert`, `sql_select`, etc.) that import the connection from the core. - **`app/db_sql.py` (Facade)**: Maintains backward compatibility by importing and re-exporting all functions. Existing code should still import from `app.db_sql`. ## 4. Modernized Logging (`app/lib_log_v3.py`) Logging configuration is no longer executed at the module level. - **`setup_logging(settings)`**: Must be explicitly called during application startup. - **`logger_reset`**: A decorator used throughout the app to ensure consistent log state. - **`app/log.py`**: Acts as a facade for backward compatibility. ## 5. Configuration Sync (`app/lib_config_v3.py`) Handles the multi-layered configuration strategy: 1. **Initial**: Values are loaded from Docker `.env` via `app/config.py`. 2. **Bootstrap**: `bootstrap_db_config` pulls production values from the MariaDB `cfg` table. 3. **Safety**: Implements a non-fatal fallback; if the DB sync fails, the app continues using `.env` settings.