"""Persistent storage for runtime-editable application settings. Settings managed from the admin console (e.g. WeCom configuration) need to survive process restarts AND container/image rebuilds in production. Writing only to ``backend/.env`` is not enough on Docker deployments because the container's writable layer is discarded on every ``docker compose up --build``. Storage strategy: 1. Database (``app_settings`` table) - canonical, always authoritative. 2. ``backend/.env`` - best-effort secondary write so local/dev workflows that read the env file directly (or restart without DB access) still see updates. 3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay in sync within the running process. On read we merge .env (lowest priority) over DB (highest priority); the DB value wins whenever it exists. """ from __future__ import annotations import logging import os from pathlib import Path from typing import Iterable from dotenv import dotenv_values, set_key logger = logging.getLogger(__name__) BACKEND_ENV_PATH = Path(__file__).resolve().parents[1] / '.env' WECOM_BOOL_KEYS = { 'WECOM_ENABLED', 'WECOM_AUTO_CREATE_USER', 'WECOM_MOBILE_NORMALIZE', 'WECOM_NOTIFY_ENABLED', } # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _ensure_env_file_exists() -> bool: try: BACKEND_ENV_PATH.parent.mkdir(parents=True, exist_ok=True) if not BACKEND_ENV_PATH.exists(): BACKEND_ENV_PATH.write_text('', encoding='utf-8') return True except OSError as exc: logger.warning('Cannot create %s: %s', BACKEND_ENV_PATH, exc) return False def _to_env_string(value: object) -> str: if isinstance(value, bool): return 'true' if value else 'false' if value is None: return '' return str(value) def _parse_env_value(key: str, value: object) -> object: if value is None: return None if key in WECOM_BOOL_KEYS: return str(value).strip().lower() == 'true' return str(value) def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool: return any(key.startswith(prefix) for prefix in prefixes) # --------------------------------------------------------------------------- # Database read/write (primary store) # --------------------------------------------------------------------------- def _persist_to_db(values: dict[str, str]) -> bool: """Write key/value pairs into the ``app_settings`` table. Returns True if every value was committed, False otherwise. The function is defensive: it must not raise, because settings persistence is also written to ``.env`` and we don't want to fail the API request. """ if not values: return True try: from app import db from app.models import AppSetting except Exception as exc: # pragma: no cover - import safety net logger.warning('AppSetting model unavailable: %s', exc) return False try: for key, value in values.items(): existing = db.session.get(AppSetting, key) if existing is None: db.session.add(AppSetting(key=key, value=value)) else: existing.value = value db.session.commit() return True except Exception as exc: logger.warning('Failed to persist settings to DB: %s', exc) try: db.session.rollback() except Exception: # pragma: no cover pass return False def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]: try: from app import db from app.models import AppSetting except Exception as exc: # pragma: no cover logger.debug('AppSetting model unavailable for read: %s', exc) return {} try: rows = db.session.query(AppSetting).all() except Exception as exc: # Most common case: the migration has not been applied yet on a # freshly-built container. Degrade gracefully to .env-only mode. logger.debug('app_settings table not readable yet: %s', exc) try: db.session.rollback() except Exception: # pragma: no cover pass return {} result: dict[str, str] = {} for row in rows: if row.key and _matches_prefixes(row.key, prefixes): result[row.key] = row.value if row.value is not None else '' return result # --------------------------------------------------------------------------- # .env read/write (secondary store, best-effort) # --------------------------------------------------------------------------- def _persist_to_env_file(values: dict[str, str]) -> bool: if not values: return True if not _ensure_env_file_exists(): return False ok = True for key, value in values.items(): try: set_key(str(BACKEND_ENV_PATH), key, value, quote_mode='auto') except OSError as exc: logger.warning('Cannot write %s to %s: %s', key, BACKEND_ENV_PATH, exc) ok = False return ok def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]: if not BACKEND_ENV_PATH.exists(): return {} try: loaded = dotenv_values(BACKEND_ENV_PATH) except OSError as exc: logger.warning('Cannot read %s: %s', BACKEND_ENV_PATH, exc) return {} return { key: (value if value is not None else '') for key, value in loaded.items() if key and _matches_prefixes(key, prefixes) } # --------------------------------------------------------------------------- # Public API # --------------------------------------------------------------------------- def persist_env_settings(values: dict[str, object]) -> dict[str, str]: """Persist settings to the canonical store and mirror to ``os.environ``. Order: 1. Mirror to ``os.environ`` so the current process picks them up immediately. 2. Persist to the database (canonical, survives container rebuilds). 3. Best-effort write to ``backend/.env`` so dev workflows that grep the file or restart without DB access keep working. """ if not values: return {} persisted: dict[str, str] = {} for key, value in values.items(): env_value = _to_env_string(value) os.environ[key] = env_value persisted[key] = env_value db_ok = _persist_to_db(persisted) file_ok = _persist_to_env_file(persisted) if not db_ok and not file_ok: logger.error( 'Failed to persist settings %s to BOTH database and .env file. ' 'Settings will be lost when the process restarts.', list(persisted.keys()), ) return persisted def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]: """Load settings from the canonical store and apply to ``os.environ``. DB values take priority over ``backend/.env`` values; both are merged so keys that only live in the env file (e.g. fresh deploy before any admin edit) are still honored. """ file_values = _load_from_env_file(prefixes) db_values = _load_from_db(prefixes) merged: dict[str, str] = {**file_values, **db_values} applied: dict[str, object] = {} for key, raw_value in merged.items(): parsed = _parse_env_value(key, raw_value) os.environ[key] = _to_env_string(parsed) applied[key] = parsed return applied