diff --git a/config/setting_example.toml b/config/setting_example.toml index dfe9291..a02ad50 100644 --- a/config/setting_example.toml +++ b/config/setting_example.toml @@ -47,7 +47,7 @@ error_ban_threshold = 3 [cache] enabled = false -timeout = 7200 # 缓存超时时间(秒), 默认2小时 +timeout = 7200 # 缓存超时时间(秒), 默认2小时; 设置为0表示不自动删除缓存 base_url = "" # 缓存文件访问的基础URL, 留空则使用服务器地址 [captcha] diff --git a/src/api/admin.py b/src/api/admin.py index 0082c52..a61fda3 100644 --- a/src/api/admin.py +++ b/src/api/admin.py @@ -1218,6 +1218,11 @@ async def update_token_refresh_enabled( } +def _sync_runtime_cache_config(): + from . import routes + if routes.generation_handler and routes.generation_handler.file_cache: + routes.generation_handler.file_cache.set_timeout(config.cache_timeout) + # ========== Cache Configuration Endpoints ========== @router.get("/api/cache/config") @@ -1250,6 +1255,7 @@ async def update_cache_enabled( # 🔥 Hot reload: sync database config to memory await db.reload_config_to_memory() + _sync_runtime_cache_config() return {"success": True, "message": f"缓存已{'启用' if enabled else '禁用'}"} @@ -1264,10 +1270,19 @@ async def update_cache_config_full( timeout = request.get("timeout") base_url = request.get("base_url") + if timeout is not None: + try: + timeout = int(timeout) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="缓存超时时间必须为整数") + if timeout < 0: + raise HTTPException(status_code=400, detail="缓存超时时间不能小于 0") + await db.update_cache_config(enabled=enabled, timeout=timeout, base_url=base_url) # 🔥 Hot reload: sync database config to memory await db.reload_config_to_memory() + _sync_runtime_cache_config() return {"success": True, "message": "缓存配置更新成功"} @@ -1283,6 +1298,7 @@ async def update_cache_base_url( # 🔥 Hot reload: sync database config to memory await db.reload_config_to_memory() + _sync_runtime_cache_config() return {"success": True, "message": "缓存Base URL更新成功"} diff --git a/src/core/models.py b/src/core/models.py index a66f881..a368e40 100644 --- a/src/core/models.py +++ b/src/core/models.py @@ -132,7 +132,7 @@ class CacheConfig(BaseModel): """Cache configuration""" id: int = 1 cache_enabled: bool = False - cache_timeout: int = 7200 # seconds (2 hours) + cache_timeout: int = 7200 # seconds (2 hours), 0 means never expire cache_base_url: Optional[str] = None created_at: Optional[datetime] = None updated_at: Optional[datetime] = None diff --git a/src/services/file_cache.py b/src/services/file_cache.py index 85eae64..878fd31 100644 --- a/src/services/file_cache.py +++ b/src/services/file_cache.py @@ -25,10 +25,13 @@ class FileCache: """ self.cache_dir = Path(cache_dir) self.cache_dir.mkdir(exist_ok=True) - self.default_timeout = default_timeout + self.default_timeout = max(0, int(default_timeout)) self.proxy_manager = proxy_manager self._cleanup_task = None + def _is_cleanup_disabled(self) -> bool: + return self.default_timeout <= 0 + async def _resolve_download_proxy(self, media_type: str) -> Optional[str]: """根据媒体类型解析下载代理地址。""" if not self.proxy_manager: @@ -84,6 +87,8 @@ class FileCache: async def _cleanup_expired_files(self): """Remove expired cache files""" try: + if self._is_cleanup_disabled(): + return current_time = time.time() removed_count = 0 @@ -139,6 +144,8 @@ class FileCache: # Check if already cached and not expired if file_path.exists(): + if self._is_cleanup_disabled(): + return filename file_age = time.time() - file_path.stat().st_mtime if file_age < self.default_timeout: debug_logger.log_info(f"Cache hit: {filename}") @@ -323,7 +330,7 @@ class FileCache: def set_timeout(self, timeout: int): """Set cache timeout in seconds""" - self.default_timeout = timeout + self.default_timeout = max(0, int(timeout)) debug_logger.log_info(f"Cache timeout updated to {timeout} seconds") def get_timeout(self) -> int: diff --git a/static/manage.html b/static/manage.html index 244cdf8..49b983d 100644 --- a/static/manage.html +++ b/static/manage.html @@ -276,8 +276,8 @@