feat: disk request body cache (#2780)

* feat: 引入通用 HTTP BodyStorage/DiskCache 缓存配置与管理

- 新增 common/body_storage.go 提供 HTTP 请求体存储抽象和文件缓存能力
- 增加 common/disk_cache_config.go 支持全局磁盘缓存配置
- main.go 挂载缓存初始化流程
- 新增和补充 controller/performance.go (及 unix/windows) 用于缓存性能监控接口
- middleware/body_cleanup.go 自动清理缓存文件
- router 挂载相关接口
- 前端 settings 页面新增性能监控设置 PerformanceSetting
- 优化缓存开关状态和模块热插拔能力
- 其他相关文件同步适配缓存扩展

* fix: 修复 BodyStorage 并发安全和错误处理问题

- 修复 diskStorage.Close() 竞态条件,先获取锁再执行 CAS
- 为 memoryStorage 添加互斥锁和 closed 状态检查
- 修复 CreateBodyStorageFromReader 在磁盘存储失败时的回退逻辑
- 添加缓存命中统计调用 (IncrementDiskCacheHits/IncrementMemoryCacheHits)
- 修复 gin.go 中 Seek 错误被忽略的问题
- 在 api-router 添加 BodyStorageCleanup 中间件
- 修复前端 formatBytes 对异常值的处理

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Calcium-Ion
2026-01-30 01:00:49 +08:00
committed by GitHub
parent 1e9b567fc0
commit 1c983a04d3
18 changed files with 1472 additions and 14 deletions

View File

@@ -0,0 +1,64 @@
package performance_setting
import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/config"
)
// PerformanceSetting 性能设置配置
type PerformanceSetting struct {
// DiskCacheEnabled 是否启用磁盘缓存(磁盘换内存)
DiskCacheEnabled bool `json:"disk_cache_enabled"`
// DiskCacheThresholdMB 触发磁盘缓存的请求体大小阈值MB
DiskCacheThresholdMB int `json:"disk_cache_threshold_mb"`
// DiskCacheMaxSizeMB 磁盘缓存最大总大小MB
DiskCacheMaxSizeMB int `json:"disk_cache_max_size_mb"`
// DiskCachePath 磁盘缓存目录
DiskCachePath string `json:"disk_cache_path"`
}
// 默认配置
var performanceSetting = PerformanceSetting{
DiskCacheEnabled: false,
DiskCacheThresholdMB: 10, // 超过 10MB 使用磁盘缓存
DiskCacheMaxSizeMB: 1024, // 最大 1GB 磁盘缓存
DiskCachePath: "", // 空表示使用系统临时目录
}
func init() {
// 注册到全局配置管理器
config.GlobalConfig.Register("performance_setting", &performanceSetting)
// 同步初始配置到 common 包
syncToCommon()
}
// syncToCommon 将配置同步到 common 包
func syncToCommon() {
common.SetDiskCacheConfig(common.DiskCacheConfig{
Enabled: performanceSetting.DiskCacheEnabled,
ThresholdMB: performanceSetting.DiskCacheThresholdMB,
MaxSizeMB: performanceSetting.DiskCacheMaxSizeMB,
Path: performanceSetting.DiskCachePath,
})
}
// GetPerformanceSetting 获取性能设置
func GetPerformanceSetting() *PerformanceSetting {
return &performanceSetting
}
// UpdateAndSync 更新配置并同步到 common 包
// 当配置从数据库加载后,需要调用此函数同步
func UpdateAndSync() {
syncToCommon()
}
// GetCacheStats 获取缓存统计信息(代理到 common 包)
func GetCacheStats() common.DiskCacheStats {
return common.GetDiskCacheStats()
}
// ResetStats 重置统计信息
func ResetStats() {
common.ResetDiskCacheStats()
}