refactor: optimize structure, stability and runtime performance
This commit is contained in:
55
database.py
55
database.py
@@ -120,7 +120,7 @@ config = get_config()
|
||||
DB_FILE = config.DB_FILE
|
||||
|
||||
# 数据库版本 (用于迁移管理)
|
||||
DB_VERSION = 17
|
||||
DB_VERSION = 18
|
||||
|
||||
|
||||
# ==================== 系统配置缓存(P1 / O-03) ====================
|
||||
@@ -142,6 +142,37 @@ def invalidate_system_config_cache() -> None:
|
||||
_system_config_cache_loaded_at = 0.0
|
||||
|
||||
|
||||
def _normalize_system_config_value(value) -> dict:
|
||||
try:
|
||||
return dict(value or {})
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _is_system_config_cache_valid(now_ts: float) -> bool:
|
||||
if _system_config_cache_value is None:
|
||||
return False
|
||||
if _SYSTEM_CONFIG_CACHE_TTL_SECONDS <= 0:
|
||||
return True
|
||||
return (now_ts - _system_config_cache_loaded_at) < _SYSTEM_CONFIG_CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
def _read_system_config_cache(now_ts: float, *, ignore_ttl: bool = False) -> Optional[dict]:
|
||||
with _system_config_cache_lock:
|
||||
if _system_config_cache_value is None:
|
||||
return None
|
||||
if (not ignore_ttl) and (not _is_system_config_cache_valid(now_ts)):
|
||||
return None
|
||||
return dict(_system_config_cache_value)
|
||||
|
||||
|
||||
def _write_system_config_cache(value: dict, now_ts: float) -> None:
|
||||
global _system_config_cache_value, _system_config_cache_loaded_at
|
||||
with _system_config_cache_lock:
|
||||
_system_config_cache_value = dict(value)
|
||||
_system_config_cache_loaded_at = now_ts
|
||||
|
||||
|
||||
def init_database():
|
||||
"""初始化数据库表结构 + 迁移(入口统一)。"""
|
||||
db_pool.init_pool(DB_FILE, pool_size=config.DB_POOL_SIZE)
|
||||
@@ -165,19 +196,21 @@ def migrate_database():
|
||||
|
||||
def get_system_config():
|
||||
"""获取系统配置(带进程内缓存)。"""
|
||||
global _system_config_cache_value, _system_config_cache_loaded_at
|
||||
|
||||
now_ts = time.time()
|
||||
with _system_config_cache_lock:
|
||||
if _system_config_cache_value is not None:
|
||||
if _SYSTEM_CONFIG_CACHE_TTL_SECONDS <= 0 or (now_ts - _system_config_cache_loaded_at) < _SYSTEM_CONFIG_CACHE_TTL_SECONDS:
|
||||
return dict(_system_config_cache_value)
|
||||
|
||||
value = _get_system_config_raw()
|
||||
cached_value = _read_system_config_cache(now_ts)
|
||||
if cached_value is not None:
|
||||
return cached_value
|
||||
|
||||
with _system_config_cache_lock:
|
||||
_system_config_cache_value = dict(value)
|
||||
_system_config_cache_loaded_at = now_ts
|
||||
try:
|
||||
value = _normalize_system_config_value(_get_system_config_raw())
|
||||
except Exception:
|
||||
fallback_value = _read_system_config_cache(now_ts, ignore_ttl=True)
|
||||
if fallback_value is not None:
|
||||
return fallback_value
|
||||
raise
|
||||
|
||||
_write_system_config_cache(value, now_ts)
|
||||
return dict(value)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user