refactor: refactor of backend

This commit is contained in:
sophie committed 2026-09-28 14:52:28 +08:00
1 parent d4cb8c5def
commit 14e5af0c9c
55 files changed
+2251 -1805

No files matched your search

+119 -20
View File
@@ -2,8 +2,9 @@
backend/app/core/config/env_persistence.py
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
依赖:app.extensions.db、app.models.AppSetting。
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
依赖:app.extensions.db、app.models.AppSetting、threading/time(进程内 TTL 缓存)。
逻辑:admin 经 persist_env_settings 写入;HTTP before_request 调用 apply_env_settings
按 APP_SETTINGS_REFRESH_SECONDS 做进程内 TTL,避免每个请求全表扫描;写入时刷新缓存。
Storage strategy:
1. Database (app_settings) - canonical
@@ -15,6 +16,8 @@ from __future__ import annotations
import logging
import os
import threading
import time
from pathlib import Path
from typing import Iterable
@@ -39,6 +42,12 @@ WECOM_BOOL_KEYS = {
'WECOM_FEEDBACK_NOTIFY_ENABLED',
}
_DEFAULT_REFRESH_SECONDS = 30.0
_cache_lock = threading.Lock()
_cache_prefixes: tuple[str, ...] | None = None
_cache_applied: dict[str, object] = {}
_cache_loaded_at: float = 0.0
# ---------------------------------------------------------------------------
# Helpers
@@ -87,6 +96,27 @@ def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
return any(key.startswith(prefix) for prefix in prefixes)
def _refresh_ttl_seconds() -> float:
"""
读取进程内配置热更新 TTL(秒)。
核心逻辑:优先 Flask app.config;否则环境变量;非法值回退默认 30。
设为 0 表示每次强制重载(兼容旧行为,便于排障)。
"""
raw: object = os.getenv('APP_SETTINGS_REFRESH_SECONDS', str(_DEFAULT_REFRESH_SECONDS))
try:
from flask import current_app, has_app_context
if has_app_context():
raw = current_app.config.get('APP_SETTINGS_REFRESH_SECONDS', raw)
except Exception: # pragma: no cover - 无 Flask 上下文时忽略
pass
try:
return max(0.0, float(raw if raw not in (None, '') else _DEFAULT_REFRESH_SECONDS))
except (TypeError, ValueError):
return _DEFAULT_REFRESH_SECONDS
# ---------------------------------------------------------------------------
# Database read/write (primary store)
# ---------------------------------------------------------------------------
@@ -127,7 +157,14 @@ def _persist_to_db(values: dict[str, str]) -> bool:
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
"""
从 app_settings 读取匹配前缀的配置行。
核心逻辑:用 LIKE 前缀过滤,避免每次 before_request 拉全表后再 Python 过滤。
"""
try:
from sqlalchemy import or_
from app.extensions import db
from app.models import AppSetting
except Exception as exc: # pragma: no cover
@@ -135,7 +172,11 @@ def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
return {}
try:
rows = db.session.query(AppSetting).all()
if not prefixes:
rows = db.session.query(AppSetting).all()
else:
clauses = [AppSetting.key.like(f'{prefix}%') for prefix in prefixes]
rows = db.session.query(AppSetting).filter(or_(*clauses)).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.
@@ -197,15 +238,36 @@ def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
# ---------------------------------------------------------------------------
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
"""Persist settings to the canonical store and mirror to ``os.environ``.
def invalidate_env_settings_cache() -> None:
"""
清空进程内配置缓存,使下次 apply_env_settings 强制读库。
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.
用途:测试或运维需要立刻看到外部写入的 app_settings 时调用。
"""
global _cache_loaded_at, _cache_applied, _cache_prefixes
with _cache_lock:
_cache_loaded_at = 0.0
_cache_applied = {}
_cache_prefixes = None
def _store_cache(prefixes: tuple[str, ...], applied: dict[str, object]) -> None:
"""写入进程内 TTL 缓存(调用方须已持有 _cache_lock)。"""
global _cache_loaded_at, _cache_applied, _cache_prefixes
_cache_prefixes = prefixes
_cache_applied = dict(applied)
_cache_loaded_at = time.monotonic()
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
"""
将设置写入权威存储,并镜像到 ``os.environ`` 与进程内缓存。
顺序:
1. 镜像到 ``os.environ``,当前进程立即可见;
2. 写入数据库(权威源,容器重建后仍在);
3. 仅在 dev 尽力写 ``.env.local``;
4. 合并进 TTL 缓存并刷新时间戳,避免本进程还要等 TTL 才看到新值。
"""
if not values:
return {}
@@ -226,24 +288,61 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
list(persisted.keys()),
)
# [STEP] 写入后失效缓存:下一请求全量重载,避免「只合并写入键」导致 TTL 内缺键。
# 当前进程通常已在 admin service 里同步写过 current_app.config。
invalidate_env_settings_cache()
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.
def apply_env_settings(
prefixes: tuple[str, ...] = ('WECOM_',),
*,
force: bool = False,
) -> dict[str, object]:
"""
从权威存储加载设置并应用到 ``os.environ``。
核心逻辑:DB 优先于 env 文件;进程内按 TTL 复用上次完整加载结果,减轻 before_request 查库压力。
force=True 或 TTL=0 时始终重载。
Args:
prefixes: 仅加载匹配此前缀的配置键,默认 WECOM_。
force: 为 True 时忽略 TTL 强制读库。
Returns:
解析后的配置字典(bool 键已转为 bool)。
"""
ttl = _refresh_ttl_seconds()
now = time.monotonic()
with _cache_lock:
if (
not force
and ttl > 0
and _cache_prefixes == prefixes
and _cache_applied
and (now - _cache_loaded_at) < ttl
):
applied = dict(_cache_applied)
else:
applied = None
if applied is not None:
for key, parsed in applied.items():
os.environ[key] = _to_env_string(parsed)
return applied
# [STEP] 锁外读库/读文件,缩短临界区
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] = {}
applied = {}
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
with _cache_lock:
_store_cache(prefixes, applied)
return dict(applied)
+2
View File
@@ -101,6 +101,8 @@ class Config:
ENV_NAME = ACTIVE_ENV_NAME
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
# 运行时可编辑配置(app_settings)进程内热更新间隔(秒);0=每请求强制读库
APP_SETTINGS_REFRESH_SECONDS = float(os.getenv('APP_SETTINGS_REFRESH_SECONDS', '30') or '30')
# 配置最大上传文件大小(200MB)
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')