| package middleware |
|
|
| import ( |
| "errors" |
| "net/http" |
| "strings" |
|
|
| "github.com/QuantumNous/new-api/common" |
| "github.com/QuantumNous/new-api/types" |
| "github.com/gin-gonic/gin" |
| ) |
|
|
| |
| func SystemPerformanceCheck() gin.HandlerFunc { |
| return func(c *gin.Context) { |
| |
| |
| path := c.Request.URL.Path |
| if strings.HasPrefix(path, "/v1/messages") { |
| if err := checkSystemPerformance(); err != nil { |
| c.JSON(err.StatusCode, gin.H{ |
| "error": err.ToClaudeError(), |
| }) |
| c.Abort() |
| return |
| } |
| } else { |
| if err := checkSystemPerformance(); err != nil { |
| c.JSON(err.StatusCode, gin.H{ |
| "error": err.ToOpenAIError(), |
| }) |
| c.Abort() |
| return |
| } |
| } |
| c.Next() |
| } |
| } |
|
|
| |
| func checkSystemPerformance() *types.NewAPIError { |
| config := common.GetPerformanceMonitorConfig() |
| if !config.Enabled { |
| return nil |
| } |
|
|
| status := common.GetSystemStatus() |
|
|
| |
| if config.CPUThreshold > 0 && int(status.CPUUsage) > config.CPUThreshold { |
| return types.NewErrorWithStatusCode(errors.New("system cpu overloaded"), "system_cpu_overloaded", http.StatusServiceUnavailable) |
| } |
|
|
| |
| if config.MemoryThreshold > 0 && int(status.MemoryUsage) > config.MemoryThreshold { |
| return types.NewErrorWithStatusCode(errors.New("system memory overloaded"), "system_memory_overloaded", http.StatusServiceUnavailable) |
| } |
|
|
| |
| if config.DiskThreshold > 0 && int(status.DiskUsage) > config.DiskThreshold { |
| return types.NewErrorWithStatusCode(errors.New("system disk overloaded"), "system_disk_overloaded", http.StatusServiceUnavailable) |
| } |
|
|
| return nil |
| } |
|
|