feat: implement V2 alert center and scoped alert governance

This commit is contained in:
Yvan
2026-11-05 20:08:29 +08:00
parent f8e26c5baf
commit 999c9a6315
57 changed files with 2711 additions and 216 deletions
+118 -18
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"log/slog"
"math/big"
"strconv"
"sort"
"strings"
"time"
)
@@ -18,10 +18,22 @@ type AlertTriggerChannel struct {
}
type AlertTriggerInput struct {
Rules []*AlertRule
Accounts []*Account
Bindings []*Binding
Channels []*AlertTriggerChannel
Exemptions map[AlertExemptionKey]bool
Gaps map[uint]*AlertGap
Dedup map[uint]bool
Rules []*AlertRule
Accounts []*Account
Bindings []*Binding
Channels []*AlertTriggerChannel
}
type AlertExemptionKey struct {
ChannelKey
OwnerID uint
}
type AlertSnapshot struct {
Players int64
Pay string
}
type AlertComparison struct {
@@ -30,6 +42,8 @@ type AlertComparison struct {
}
type AlertTriggerRepo interface {
FilterWritable(context.Context, []*AlertRecord, []int, func(*AlertRecord) bool) ([]*AlertRecord, error)
Snapshots(context.Context, []ChannelKey, time.Time, bool) (map[ChannelKey]AlertSnapshot, error)
Input(context.Context) (*AlertTriggerInput, error)
Comparison(context.Context, int, []ChannelKey, time.Time, int) (map[ChannelKey]AlertComparison, error)
// 仓储在渠道/分类键锁及事务内读取未关闭记录,由领域决定是否刷新。
@@ -38,10 +52,13 @@ type AlertTriggerRepo interface {
type AlertTriggerResult struct{ Rules, Written, Skipped int }
type AlertTriggerUsecase struct{ repo AlertTriggerRepo }
type AlertTriggerUsecase struct {
repo AlertTriggerRepo
governance *AlertGovernanceUsecase
}
func NewAlertTriggerUsecase(repo AlertTriggerRepo) *AlertTriggerUsecase {
return &AlertTriggerUsecase{repo: repo}
func NewAlertTriggerUsecase(repo AlertTriggerRepo, governance *AlertGovernanceUsecase) *AlertTriggerUsecase {
return &AlertTriggerUsecase{repo: repo, governance: governance}
}
func (uc *AlertTriggerUsecase) Run(ctx context.Context) error {
@@ -53,6 +70,10 @@ func validTriggerRule(rule *AlertRule) bool {
if rule == nil || rule.CreatorID == 0 || strings.TrimSpace(rule.Type) == "" {
return false
}
if rule.Metric == 2 && rule.ConditionMode == 2 {
copy := *rule
return validateAlertRule(&copy) == nil
}
if rule.Metric == 3 {
return rule.UnloginDays != nil && *rule.UnloginDays > 0
}
@@ -102,18 +123,15 @@ func triggerOwners(input *AlertTriggerInput) (map[ChannelKey]*Account, map[uint]
channel.SourceDB = source
key := PlatformKey{SourceDB: source, BusierID: channel.BusierID}
account := accounts[bindings[key]]
if conflicts[key] || account == nil || account.Level != 3 {
if conflicts[key] || account == nil || account.Level < 1 || account.Level > 3 {
continue
}
path := strings.Split(account.IDPath, ",")
if len(path) < 2 {
continue
}
id, err := strconv.ParseUint(path[1], 10, 64)
owner := accounts[uint(id)]
if err != nil || owner == nil || owner.Level != 1 {
scope := LevelOneOwnerForAccount(account)
owner := accounts[scope.UserID]
if scope.Empty || owner == nil || owner.Level != 1 {
continue
}
owners[channel.ChannelKey] = owner
}
return owners, accounts
@@ -122,6 +140,11 @@ func triggerOwners(input *AlertTriggerInput) (map[ChannelKey]*Account, map[uint]
// 一次执行固定上海自然日,避免跨午夜时同一任务的各规则使用不同的比较窗口。
func (uc *AlertTriggerUsecase) Detect(ctx context.Context, now time.Time) (*AlertTriggerResult, error) {
result := &AlertTriggerResult{}
if uc.governance != nil {
if err := uc.governance.Reconcile(ctx, now); err != nil {
return result, err
}
}
input, err := uc.repo.Input(ctx)
if err != nil {
return result, err
@@ -139,6 +162,7 @@ func (uc *AlertTriggerUsecase) Detect(ctx context.Context, now time.Time) (*Aler
}
snapshots := map[snapshotKey]map[ChannelKey]AlertComparison{}
var failures []string
pending := map[uint][]*AlertRecord{}
for _, rule := range input.Rules {
if err := ctx.Err(); err != nil {
return result, err
@@ -160,6 +184,9 @@ func (uc *AlertTriggerUsecase) Detect(ctx context.Context, now time.Time) (*Aler
}
owner := owners[channel.ChannelKey]
if owner != nil && (creator.AuthorityID == 888 || owner.ID == creator.ID) {
if input.Exemptions[AlertExemptionKey{ChannelKey: channel.ChannelKey, OwnerID: owner.ID}] {
continue
}
channels = append(channels, channel)
keys = append(keys, channel.ChannelKey)
}
@@ -198,9 +225,62 @@ func (uc *AlertTriggerUsecase) Detect(ctx context.Context, now time.Time) (*Aler
record := &AlertRecord{RuleID: rule.ID, RuleName: rule.Name, RuleType: strings.TrimSpace(rule.Type), MonitorMetric: &rule.Metric,
PlatformCode: channel.SourceDB, PlatformName: PlatformName(channel.SourceDB), TargetPromoteID: channel.ID, TargetPromoteName: channel.Account,
BusinessID: owner.ID, BusinessName: owner.Username, AlertContent: content, Status: AlertUnprocessed, CreatedAt: now, UpdatedAt: now}
written, err := uc.repo.StoreHit(ctx, record, []int{AlertUnprocessed, AlertProcessing, AlertPendingAudit, AlertAuditRejected}, func(current *AlertRecord) bool { return current == nil || current.Status == AlertUnprocessed })
record.WarningColor = &rule.WarningColor
record.IndependentRule = rule.Metric == 2 && rule.ConditionMode == 2
ownerScope := alertUserScope(owner)
record.OwnerScope = &ownerScope
if gap := input.Gaps[creator.ID]; gap != nil && gap.Enabled {
record.GapDays = gap.Days
}
pending[creator.ID] = append(pending[creator.ID], record)
}
}
creators := make([]uint, 0, len(pending))
for creator := range pending {
creators = append(creators, creator)
}
sort.Slice(creators, func(i, j int) bool { return creators[i] < creators[j] })
for _, creator := range creators {
hits := pending[creator]
openStatuses := []int{AlertUnprocessed, AlertProcessing, AlertPendingAudit, AlertAuditRejected}
canWrite := func(current *AlertRecord) bool { return current == nil || current.Status == AlertUnprocessed }
hits, err = uc.repo.FilterWritable(ctx, hits, openStatuses, canWrite)
if err != nil {
failures = append(failures, fmt.Sprintf("商务 %d 读取在途预警失败: %v", creator, err))
continue
}
if len(hits) == 0 {
continue
}
keys := []ChannelKey{}
seen := map[ChannelKey]bool{}
for _, hit := range hits {
key := ChannelKey{SourceDB: hit.PlatformCode, ID: hit.TargetPromoteID}
if !seen[key] {
keys = append(keys, key)
seen[key] = true
}
}
dedup, ok := input.Dedup[creator]
if !ok {
dedup = true
}
totals, err := uc.repo.Snapshots(ctx, keys, now, dedup)
if err != nil {
failures = append(failures, fmt.Sprintf("商务 %d 读取预警快照失败: %v", creator, err))
continue
}
for _, record := range hits {
total, ok := totals[ChannelKey{SourceDB: record.PlatformCode, ID: record.TargetPromoteID}]
if !ok {
failures = append(failures, "预警快照缺失")
continue
}
record.TotalPlayers = &total.Players
record.TotalPay = &total.Pay
written, err := uc.repo.StoreHit(ctx, record, openStatuses, canWrite)
if err != nil {
failures = append(failures, fmt.Sprintf("规则 %d 渠道 %s/%d 写入失败: %v", rule.ID, channel.SourceDB, channel.ID, err))
failures = append(failures, fmt.Sprintf("规则 %d 渠道 %s/%d 写入失败: %v", record.RuleID, record.PlatformCode, record.TargetPromoteID, err))
continue
}
if written {
@@ -208,6 +288,7 @@ func (uc *AlertTriggerUsecase) Detect(ctx context.Context, now time.Time) (*Aler
}
}
}
if len(failures) > 0 {
for _, failure := range failures {
slog.ErrorContext(ctx, "预警检测失败", "detail", failure)
@@ -234,6 +315,25 @@ func triggerContent(rule *AlertRule, channel *AlertTriggerChannel, sample AlertC
}
return fmt.Sprintf("连续%d天未登录", days), true, nil
}
if rule.Metric == 2 && rule.ConditionMode == 2 {
amount, err := portraitNumber(sample.Current)
if err != nil {
return "", false, err
}
threshold, ok := new(big.Rat).SetString(*rule.AmountThreshold)
if !ok {
return "", false, ErrAlertRuleInput
}
reached := amount.Cmp(threshold) >= 0
if (rule.AmountDirection == 1 && !reached) || (rule.AmountDirection == 2 && reached) {
return "", false, nil
}
direction := "满"
if rule.AmountDirection == 2 {
direction = "未满"
}
return fmt.Sprintf("截至昨日%d个完整自然日充值¥%s,%s¥%s(汇总子渠道)", *rule.StatPeriodDays, portraitDecimal(amount, 2), direction, *rule.AmountThreshold), true, nil
}
days := *rule.StatPeriodDays
if sample.FirstUnix <= 0 || time.Unix(sample.FirstUnix, 0).In(today.Location()).Format("2006-01-02") > today.AddDate(0, 0, -2*days).Format("2006-01-02") {
return "", false, nil