"""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. ``.env.local`` (dev only) - best-effort secondary write so local/dev workflows that 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 files (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_DIR = Path(__file__).resolve().parents[1] _ROOT_DIR = _BACKEND_DIR.parent ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local' LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env' # Backward-compatible alias for tests and older callers that still patch/read # the historical backend/.env location directly. BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH WECOM_BOOL_KEYS = { 'WECOM_ENABLED', 'WECOM_AUTO_CREATE_USER', 'WECOM_MOBILE_NORMALIZE', 'WECOM_NOTIFY_ENABLED', 'WECOM_FEEDBACK_NOTIFY_ENABLED', } # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _ensure_env_file_exists() -> bool: try: ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True) if not ROOT_ENV_LOCAL_PATH.exists(): ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8') return True except OSError as exc: logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc) return False def _normalize_env_name(raw: str | None) -> str: value = (raw or '').strip().lower() if value in ('dev', 'development', ''): return 'dev' if value in ('test', 'testing'): return 'test' if value in ('prod', 'production'): return 'prod' return 'dev' 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: env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV')) if env_name != 'dev': return True 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(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto') except OSError as exc: logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc) ok = False return ok def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]: merged: dict[str, str] = {} for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH): if not env_path.exists(): continue try: loaded = dotenv_values(env_path) except OSError as exc: logger.warning('Cannot read %s: %s', env_path, exc) continue for key, value in loaded.items(): if key and _matches_prefixes(key, prefixes): merged[key] = value if value is not None else '' return merged # --------------------------------------------------------------------------- # 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. In dev only, best-effort write to ``.env.local`` so local restarts 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.local mirror. ' '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 env-file values; both are merged so keys that only live in env files (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