new-api/model/channel_monitor_daily_rollup.go
zizi 959ee42bcb feat: add channel monitor rollups
Aggregate monitor history into daily rollups and add maintenance helpers for rollup refresh and history cleanup.
2026-05-20 13:51:22 +08:00

65 lines
2.3 KiB
Go

package model
import "gorm.io/gorm/clause"
type ChannelMonitorDailyRollup struct {
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
MonitorId int `json:"monitor_id" gorm:"not null;index;uniqueIndex:idx_channel_monitor_daily_rollup,priority:1"`
ChannelId int `json:"channel_id" gorm:"index;uniqueIndex:idx_channel_monitor_daily_rollup,priority:2"`
ModelName string `json:"model_name" gorm:"size:128;not null;uniqueIndex:idx_channel_monitor_daily_rollup,priority:3"`
Date string `json:"date" gorm:"size:10;not null;uniqueIndex:idx_channel_monitor_daily_rollup,priority:4"`
TotalChecks int `json:"total_checks" gorm:"not null;default:0"`
PassCount int `json:"pass_count" gorm:"not null;default:0"`
DegradedCount int `json:"degraded_count" gorm:"not null;default:0"`
FailedCount int `json:"failed_count" gorm:"not null;default:0"`
AvgLatencyMs int `json:"avg_latency_ms" gorm:"not null;default:0"`
}
func (ChannelMonitorDailyRollup) TableName() string {
return "channel_monitor_daily_rollups"
}
func GetChannelMonitorDailyRollups(monitorId int, modelName string, startDate string, endDate string) ([]ChannelMonitorDailyRollup, error) {
var rollups []ChannelMonitorDailyRollup
query := DB.Model(&ChannelMonitorDailyRollup{})
if monitorId > 0 {
query = query.Where("monitor_id = ?", monitorId)
}
if modelName != "" {
query = query.Where("model_name = ?", modelName)
}
if startDate != "" {
query = query.Where("date >= ?", startDate)
}
if endDate != "" {
query = query.Where("date <= ?", endDate)
}
err := query.Order("date DESC").Find(&rollups).Error
return rollups, err
}
func GetMonitorDailyRollups(monitorId int, modelName string, startDate string, endDate string) ([]ChannelMonitorDailyRollup, error) {
return GetChannelMonitorDailyRollups(monitorId, modelName, startDate, endDate)
}
func UpsertChannelMonitorDailyRollups(rollups []ChannelMonitorDailyRollup) error {
if len(rollups) == 0 {
return nil
}
return DB.Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "monitor_id"},
{Name: "channel_id"},
{Name: "model_name"},
{Name: "date"},
},
DoUpdates: clause.AssignmentColumns([]string{
"total_checks",
"pass_count",
"degraded_count",
"failed_count",
"avg_latency_ms",
}),
}).Create(&rollups).Error
}