feat(alerts): add MasterID to log records and improve traffic spike detection

- Add MasterID field with index to LogRecord model for efficient queries
- Fix threshold config loading to use fixed ID=1 with FirstOrCreate
- Allow traffic spike detection to work without Redis for log-based checks
- Add traffic_spike to API documentation for alert type filter
- Add comprehensive tests for RPM/RPD/TPM spike detection scenarios
This commit is contained in:
zenfun
2025-12-31 18:01:09 +08:00
parent f714a314a9
commit 4cda273f7b
4 changed files with 324 additions and 24 deletions

View File

@@ -89,7 +89,7 @@ type ListAlertsResponse struct {
// @Param offset query int false "offset"
// @Param status query string false "filter by status (active, acknowledged, resolved, dismissed)"
// @Param severity query string false "filter by severity (info, warning, critical)"
// @Param type query string false "filter by type (rate_limit, error_spike, quota_exceeded, key_disabled, key_expired, provider_down)"
// @Param type query string false "filter by type (rate_limit, error_spike, quota_exceeded, key_disabled, key_expired, provider_down, traffic_spike)"
// @Success 200 {object} ListAlertsResponse
// @Failure 500 {object} gin.H
// @Router /admin/alerts [get]
@@ -544,19 +544,12 @@ func (h *AlertHandler) UpdateAlertThresholds(c *gin.Context) {
c.JSON(http.StatusOK, toAlertThresholdView(cfg))
}
// loadThresholdConfig loads the threshold config from DB or returns defaults
// loadThresholdConfig loads the threshold config from DB or creates default with fixed ID=1
func (h *AlertHandler) loadThresholdConfig() (model.AlertThresholdConfig, error) {
var cfg model.AlertThresholdConfig
err := h.db.First(&cfg).Error
cfg := model.DefaultAlertThresholdConfig()
cfg.ID = 1 // Fixed ID to ensure single config row
err := h.db.Where("id = ?", 1).FirstOrCreate(&cfg).Error
if err != nil {
if err.Error() == "record not found" {
// Create default config
cfg = model.DefaultAlertThresholdConfig()
if createErr := h.db.Create(&cfg).Error; createErr != nil {
return cfg, createErr
}
return cfg, nil
}
return cfg, err
}
return cfg, nil