diff --git a/apps/admin/services.py b/apps/admin/services.py index 664c832..f6965a2 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -1609,7 +1609,7 @@ class ConfigService: next_config["jwt_secret"] = generate_jwt_secret() await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) - await refresh_settings() + await refresh_settings(force=True) class LocalFileService: diff --git a/apps/base/config.py b/apps/base/config.py index 433d896..2d1734e 100644 --- a/apps/base/config.py +++ b/apps/base/config.py @@ -60,7 +60,7 @@ async def ensure_security_settings() -> None: logger.info("已将管理员密码迁移为哈希存储") if security_config.jwt_secret_rotated: logger.info("已生成独立 JWT 签名密钥") - await refresh_settings() + await refresh_settings(force=True) def _sync_ip_limits() -> None: @@ -74,14 +74,31 @@ def _sync_ip_limits() -> None: ip_limit["login"].count = settings.login_count -async def refresh_settings() -> None: - """从数据库读取最新配置并应用到运行时。""" +# Per-process config cache: the middleware refreshes settings on every request, +# which otherwise means one DB read per request. Writes call refresh_settings(force=True) +# so same-process visibility is immediate; other processes converge within the TTL +# (documented deployment is a single worker). +CONFIG_CACHE_TTL_SECONDS = 2.0 +_config_cached_until = 0.0 + + +async def refresh_settings(force: bool = False) -> None: + """从数据库读取最新配置并应用到运行时。 + + 默认带短 TTL 缓存(避免每请求查库);写配置的代码路径必须传 force=True。 + """ + global _config_cached_until + import time as _time + + if not force and _time.monotonic() < _config_cached_until: + return config_record = await KeyValue.filter(key="settings").first() settings.user_config = config_record.value if config_record and config_record.value else {} unknown = settings.unknown_keys(settings.user_config) if unknown: logger.warning("配置中存在未登记的键(将被忽略其类型语义,仅透传): %s", unknown) _sync_ip_limits() + _config_cached_until = _time.monotonic() + CONFIG_CACHE_TTL_SECONDS def is_runtime_initialized() -> bool: @@ -120,4 +137,4 @@ async def initialize_system( next_config["jwt_secret"] = generate_jwt_secret() await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) - await refresh_settings() + await refresh_settings(force=True) diff --git a/main.py b/main.py index b79faec..0127b27 100644 --- a/main.py +++ b/main.py @@ -74,7 +74,7 @@ async def load_config(): # refresh_settings already syncs every rate limiter (error/metadata/upload/login) # via _sync_ip_limits; do not hand-sync a subset here — that once drifted by # missing the metadata limiter. - await refresh_settings() + await refresh_settings(force=True) await ensure_security_settings() # Rate limiters keep per-process state (apps.base.dependencies.IPRateLimit). diff --git a/tests/helpers.py b/tests/helpers.py index 8b679b8..6722cd1 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -39,6 +39,11 @@ class SettingsOverrideMixin: async def init_memory_db(): """Init Tortoise against an in-memory DB and create all schemas.""" + # 每个测试都是全新 DB,必须同步失效进程级配置 TTL 缓存, + # 否则上一个测试的缓存会让 middleware 误判初始化状态。 + import apps.base.config as config_module + + config_module._config_cached_until = 0.0 await Tortoise.init(config=MEMORY_DB_CONFIG) await Tortoise.generate_schemas() diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py index 597ea1c..53cf54c 100644 --- a/tests/test_admin_security.py +++ b/tests/test_admin_security.py @@ -152,7 +152,7 @@ class FakeKeyValue: return None, True -async def fake_refresh_settings(): +async def fake_refresh_settings(force=False): return None diff --git a/tests/test_password_hashing.py b/tests/test_password_hashing.py index 88e8cc7..0744927 100644 --- a/tests/test_password_hashing.py +++ b/tests/test_password_hashing.py @@ -108,3 +108,40 @@ class CheapInitProbeTests(unittest.TestCase): self.assertFalse(is_config_initialized({"admin_token": ""})) self.assertFalse(is_config_initialized({"admin_token": LEGACY_DEFAULT_ADMIN_TOKEN})) + + +class ConfigCacheTests(unittest.TestCase): + """D6 回归:TTL 内的 refresh_settings 不再读库,写路径 force=True 必须穿透。 + + 验证手法(无 mock):直接改 DB 里的值—— + - TTL 内普通 refresh 不读库 → settings 仍是旧值; + - force=True 读库 → 新值生效。 + """ + + def test_ttl_cache_skips_db_and_force_bypasses(self): + import apps.base.config as config_module + from apps.base.models import KeyValue + from tests.helpers import close_db, init_memory_db + + async def scenario(): + await init_memory_db() + try: + row = await KeyValue.create( + key="settings", value={"name": "旧值", "admin_token": "x" * 64} + ) + await config_module.refresh_settings(force=True) + self.assertEqual(settings.name, "旧值") + + # 直接改 DB(绕过应用层),TTL 内普通 refresh 不应看到 + row.value = {"name": "新值", "admin_token": "x" * 64} + await row.save() + await config_module.refresh_settings() + self.assertEqual(settings.name, "旧值", "TTL 内不应读库") + + await config_module.refresh_settings(force=True) + self.assertEqual(settings.name, "新值", "force 必须穿透缓存") + finally: + config_module._config_cached_until = 0.0 + await close_db() + + asyncio.run(scenario())