feat: 重建 Bell 规则与预警链路 (#132)
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package alert
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
|
||||
"go-admin/app/bell/evaluation"
|
||||
)
|
||||
|
||||
type Handler struct{ api.Api }
|
||||
|
||||
func (h Handler) List(c *gin.Context) {
|
||||
var query PageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&query, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusBadRequest, errors.New("查询条件不正确"), "查询条件不正确")
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm).List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
h.Logger.Errorf("list Bell alerts failed: %v", err)
|
||||
h.Error(http.StatusInternalServerError, errors.New("读取预警失败"), "读取预警失败")
|
||||
return
|
||||
}
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
h.PageOK(items, int(count), page, size, "查询成功")
|
||||
}
|
||||
|
||||
func (h Handler) Get(c *gin.Context) {
|
||||
h.MakeContext(c).MakeOrm()
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusInternalServerError, errors.New("数据库连接获取失败"), "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
detail, err := NewService(h.Orm).Get(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
h.Error(http.StatusNotFound, ErrNotFound, ErrNotFound.Error())
|
||||
return
|
||||
}
|
||||
h.Logger.Errorf("get Bell alert failed: %v", err)
|
||||
h.Error(http.StatusInternalServerError, errors.New("读取预警失败"), "读取预警失败")
|
||||
return
|
||||
}
|
||||
h.OK(detail, "查询成功")
|
||||
}
|
||||
|
||||
func (h Handler) ListEvents(c *gin.Context) {
|
||||
var query EventPageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&query, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusBadRequest, errors.New("查询条件不正确"), "查询条件不正确")
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm).ListEvents(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
h.Logger.Errorf("list Bell events failed: %v", err)
|
||||
h.Error(http.StatusInternalServerError, errors.New("读取事件失败"), "读取事件失败")
|
||||
return
|
||||
}
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
h.PageOK(items, int(count), page, size, "查询成功")
|
||||
}
|
||||
|
||||
func (h Handler) EventResults(c *gin.Context) {
|
||||
h.MakeContext(c).MakeOrm()
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusInternalServerError, errors.New("数据库连接获取失败"), "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
result, err := evaluation.NewService(h.Orm).ForEvent(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
if errors.Is(err, evaluation.ErrEventNotFound) {
|
||||
h.Error(http.StatusNotFound, evaluation.ErrEventNotFound, evaluation.ErrEventNotFound.Error())
|
||||
return
|
||||
}
|
||||
h.Logger.Errorf("get Bell event rule results failed: %v", err)
|
||||
h.Error(http.StatusInternalServerError, errors.New("读取规则评估失败"), "读取规则评估失败")
|
||||
return
|
||||
}
|
||||
h.OK(result, "查询成功")
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package alert
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Alert struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
PrimaryRuleID string `json:"primaryRuleId" gorm:"type:uuid;not null;index"`
|
||||
CorrelationKey string `json:"-" gorm:"size:384;not null"`
|
||||
Status string `json:"status" gorm:"size:24;not null;default:open;index"`
|
||||
Severity string `json:"severity" gorm:"size:16;not null;index"`
|
||||
Summary string `json:"summary" gorm:"size:256;not null"`
|
||||
Location string `json:"location" gorm:"size:256;not null;index"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null;index"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Alert) TableName() string { return "bell_alerts" }
|
||||
|
||||
type AlertEvent struct {
|
||||
AlertID string `json:"alertId" gorm:"type:uuid;primaryKey"`
|
||||
EventID string `json:"eventId" gorm:"type:uuid;primaryKey"`
|
||||
LinkedAt time.Time `json:"linkedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (AlertEvent) TableName() string { return "bell_alert_events" }
|
||||
|
||||
type RuleMatch struct {
|
||||
EventID string `json:"eventId" gorm:"type:uuid;primaryKey"`
|
||||
RuleID string `json:"ruleId" gorm:"type:uuid;primaryKey"`
|
||||
AlertID string `json:"alertId" gorm:"type:uuid;not null;index"`
|
||||
RuleVersion int `json:"ruleVersion" gorm:"not null"`
|
||||
RuleSnapshot json.RawMessage `json:"ruleSnapshot" gorm:"type:jsonb;not null"`
|
||||
Explanation string `json:"explanation" gorm:"size:512;not null"`
|
||||
MatchedAt time.Time `json:"matchedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (RuleMatch) TableName() string { return "bell_rule_matches" }
|
||||
@@ -0,0 +1,136 @@
|
||||
package alert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/bell/event"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("预警不存在")
|
||||
|
||||
type PageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
Status string `form:"status"`
|
||||
Severity string `form:"severity"`
|
||||
Location string `form:"location"`
|
||||
}
|
||||
|
||||
type Summary struct {
|
||||
Alert
|
||||
RuleName string `json:"ruleName"`
|
||||
EventCount int64 `json:"eventCount"`
|
||||
}
|
||||
|
||||
type LinkedEvent struct {
|
||||
event.Event
|
||||
LinkedAt time.Time `json:"linkedAt"`
|
||||
}
|
||||
|
||||
type Detail struct {
|
||||
Alert Summary `json:"alert"`
|
||||
Events []LinkedEvent `json:"events"`
|
||||
Matches []RuleMatch `json:"matches"`
|
||||
}
|
||||
|
||||
type Service struct{ DB *gorm.DB }
|
||||
|
||||
func NewService(db *gorm.DB) Service { return Service{DB: db} }
|
||||
|
||||
func (s Service) List(ctx context.Context, query PageQuery) ([]Summary, int64, error) {
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
base := s.DB.WithContext(ctx).Table("bell_alerts a")
|
||||
if query.Status = strings.TrimSpace(query.Status); query.Status != "" {
|
||||
base = base.Where("a.status = ?", query.Status)
|
||||
}
|
||||
if query.Severity = strings.TrimSpace(query.Severity); query.Severity != "" {
|
||||
base = base.Where("a.severity = ?", query.Severity)
|
||||
}
|
||||
if query.Location = strings.TrimSpace(query.Location); query.Location != "" {
|
||||
base = base.Where("a.location ILIKE ?", "%"+query.Location+"%")
|
||||
}
|
||||
var count int64
|
||||
if err := base.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
items := make([]Summary, 0)
|
||||
err := base.Select("a.*, r.name AS rule_name, (SELECT count(*) FROM bell_alert_events ae WHERE ae.alert_id = a.id) AS event_count").
|
||||
Joins("JOIN bell_rules r ON r.id = a.primary_rule_id").
|
||||
Order("a.created_at DESC, a.id DESC").Offset((page - 1) * size).Limit(size).Scan(&items).Error
|
||||
return items, count, err
|
||||
}
|
||||
|
||||
func (s Service) Get(ctx context.Context, id string) (Detail, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return Detail{}, ErrNotFound
|
||||
}
|
||||
detail := Detail{Events: make([]LinkedEvent, 0), Matches: make([]RuleMatch, 0)}
|
||||
db := s.DB.WithContext(ctx)
|
||||
err := db.Table("bell_alerts a").
|
||||
Select("a.*, r.name AS rule_name, (SELECT count(*) FROM bell_alert_events ae WHERE ae.alert_id = a.id) AS event_count").
|
||||
Joins("JOIN bell_rules r ON r.id = a.primary_rule_id").Where("a.id = ?", id).Take(&detail.Alert).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return Detail{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Detail{}, err
|
||||
}
|
||||
if err = db.Table("bell_events e").Select("e.*, ae.linked_at").
|
||||
Joins("JOIN bell_alert_events ae ON ae.event_id = e.id").
|
||||
Where("ae.alert_id = ?", id).Order("e.occurred_at, e.id").Scan(&detail.Events).Error; err != nil {
|
||||
return Detail{}, err
|
||||
}
|
||||
err = db.Where("alert_id = ?", id).Order("matched_at, event_id, rule_id").Find(&detail.Matches).Error
|
||||
return detail, err
|
||||
}
|
||||
|
||||
type EventPageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
EventType string `form:"eventType"`
|
||||
Severity string `form:"severity"`
|
||||
Location string `form:"location"`
|
||||
}
|
||||
|
||||
type EventSummary struct {
|
||||
event.Event
|
||||
AlertCount int64 `json:"alertCount"`
|
||||
}
|
||||
|
||||
func (s Service) ListEvents(ctx context.Context, query EventPageQuery) ([]EventSummary, int64, error) {
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
db := s.DB.WithContext(ctx).Model(&event.Event{})
|
||||
if value := strings.TrimSpace(query.EventType); value != "" {
|
||||
db = db.Where("event_type ILIKE ?", "%"+value+"%")
|
||||
}
|
||||
if value := strings.TrimSpace(query.Severity); value != "" {
|
||||
db = db.Where("severity = ?", value)
|
||||
}
|
||||
if value := strings.TrimSpace(query.Location); value != "" {
|
||||
db = db.Where("location ILIKE ?", "%"+value+"%")
|
||||
}
|
||||
var count int64
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
items := make([]EventSummary, 0)
|
||||
err := db.Select("bell_events.*, (SELECT count(*) FROM bell_alert_events ae WHERE ae.event_id = bell_events.id) AS alert_count").
|
||||
Order("occurred_at DESC, id DESC").Offset((page - 1) * size).Limit(size).Scan(&items).Error
|
||||
return items, count, err
|
||||
}
|
||||
|
||||
func pageValues(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package evaluation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Evaluation is an immutable explanation of one rule version evaluated
|
||||
// against one Event.
|
||||
type Evaluation struct {
|
||||
EventID string `json:"eventId" gorm:"type:uuid;primaryKey"`
|
||||
RuleID string `json:"ruleId" gorm:"type:uuid;primaryKey"`
|
||||
RuleVersion int `json:"ruleVersion" gorm:"not null"`
|
||||
RuleSnapshot json.RawMessage `json:"ruleSnapshot" gorm:"type:jsonb;not null"`
|
||||
Matched bool `json:"matched" gorm:"not null"`
|
||||
Explanation string `json:"explanation" gorm:"size:512;not null"`
|
||||
EvaluatedAt time.Time `json:"evaluatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Evaluation) TableName() string { return "bell_rule_evaluations" }
|
||||
@@ -0,0 +1,50 @@
|
||||
package evaluation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var ErrEventNotFound = errors.New("事件不存在")
|
||||
|
||||
type EventResults struct {
|
||||
Evaluations []Evaluation `json:"evaluations"`
|
||||
Alerts []AlertLink `json:"alerts"`
|
||||
}
|
||||
|
||||
type AlertLink struct {
|
||||
ID string `json:"id"`
|
||||
Summary string `json:"summary"`
|
||||
Status string `json:"status"`
|
||||
Severity string `json:"severity"`
|
||||
Location string `json:"location"`
|
||||
}
|
||||
|
||||
type Service struct{ DB *gorm.DB }
|
||||
|
||||
func NewService(db *gorm.DB) Service { return Service{DB: db} }
|
||||
|
||||
func (s Service) ForEvent(ctx context.Context, eventID string) (EventResults, error) {
|
||||
if _, err := uuid.Parse(eventID); err != nil {
|
||||
return EventResults{}, ErrEventNotFound
|
||||
}
|
||||
var count int64
|
||||
if err := s.DB.WithContext(ctx).Table("bell_events").Where("id = ?", eventID).Count(&count).Error; err != nil {
|
||||
return EventResults{}, err
|
||||
}
|
||||
if count == 0 {
|
||||
return EventResults{}, ErrEventNotFound
|
||||
}
|
||||
result := EventResults{Evaluations: make([]Evaluation, 0), Alerts: make([]AlertLink, 0)}
|
||||
if err := s.DB.WithContext(ctx).Where("event_id = ?", eventID).Order("evaluated_at, rule_id").Find(&result.Evaluations).Error; err != nil {
|
||||
return EventResults{}, err
|
||||
}
|
||||
err := s.DB.WithContext(ctx).Table("bell_alerts a").
|
||||
Select("a.id, a.summary, a.status, a.severity, a.location").
|
||||
Joins("JOIN bell_alert_events ae ON ae.alert_id = a.id").
|
||||
Where("ae.event_id = ?", eventID).Order("a.created_at, a.id").Scan(&result.Alerts).Error
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/bell/alert"
|
||||
"go-admin/app/bell/rule"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registrars = append(registrars, registerRuleAlertRouter)
|
||||
}
|
||||
|
||||
func registerRuleAlertRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
rules := rule.Handler{}
|
||||
alerts := alert.Handler{}
|
||||
secured := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
secured.GET("/rules", rules.List)
|
||||
secured.POST("/rules", rules.Create)
|
||||
secured.PUT("/rules/:id", rules.Update)
|
||||
secured.PUT("/rules/:id/enabled", rules.SetEnabled)
|
||||
|
||||
secured.GET("/alerts", alerts.List)
|
||||
secured.GET("/alerts/:id", alerts.Get)
|
||||
secured.GET("/events", alerts.ListEvents)
|
||||
secured.GET("/events/:id/rule-results", alerts.EventResults)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package rule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
)
|
||||
|
||||
type Handler struct{ api.Api }
|
||||
|
||||
type enabledInput struct {
|
||||
Enabled *bool `json:"enabled" binding:"required"`
|
||||
}
|
||||
|
||||
func (h Handler) List(c *gin.Context) {
|
||||
var query PageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&query, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusBadRequest, ErrInvalid, "查询条件不正确")
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm).List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
h.Logger.Errorf("list Bell rules failed: %v", err)
|
||||
h.Error(http.StatusInternalServerError, errors.New("读取规则失败"), "读取规则失败")
|
||||
return
|
||||
}
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
h.PageOK(items, int(count), page, size, "查询成功")
|
||||
}
|
||||
|
||||
func (h Handler) Create(c *gin.Context) {
|
||||
if !isAdmin(c) {
|
||||
h.MakeContext(c).Error(http.StatusForbidden, errors.New("仅管理员可修改规则"), "仅管理员可修改规则")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).Create(c.Request.Context(), input, user.GetUserId(c))
|
||||
h.writeResult(item, err)
|
||||
}
|
||||
|
||||
func (h Handler) Update(c *gin.Context) {
|
||||
if !isAdmin(c) {
|
||||
h.MakeContext(c).Error(http.StatusForbidden, errors.New("仅管理员可修改规则"), "仅管理员可修改规则")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).Update(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.writeResult(item, err)
|
||||
}
|
||||
|
||||
func (h Handler) SetEnabled(c *gin.Context) {
|
||||
if !isAdmin(c) {
|
||||
h.MakeContext(c).Error(http.StatusForbidden, errors.New("仅管理员可修改规则"), "仅管理员可修改规则")
|
||||
return
|
||||
}
|
||||
var input enabledInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil || input.Enabled == nil {
|
||||
h.Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).SetEnabled(c.Request.Context(), c.Param("id"), *input.Enabled, user.GetUserId(c))
|
||||
h.writeResult(item, err)
|
||||
}
|
||||
|
||||
func (h Handler) writeResult(item Rule, err error) {
|
||||
switch {
|
||||
case err == nil:
|
||||
h.OK(item, "保存成功")
|
||||
case errors.Is(err, ErrInvalid):
|
||||
h.Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
case errors.Is(err, ErrNotFound):
|
||||
h.Error(http.StatusNotFound, ErrNotFound, ErrNotFound.Error())
|
||||
default:
|
||||
h.Logger.Errorf("write Bell rule failed: %v", err)
|
||||
h.Error(http.StatusConflict, errors.New("规则编码已存在或保存失败"), "规则编码已存在或保存失败")
|
||||
}
|
||||
}
|
||||
|
||||
func isAdmin(c *gin.Context) bool {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
role, _ := claims[jwt.RoleKey].(string)
|
||||
return role == "admin"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package rule
|
||||
|
||||
import "time"
|
||||
|
||||
// Rule is the current editable rule definition. Historical evaluations keep a
|
||||
// complete versioned snapshot, so editing this row never rewrites history.
|
||||
type Rule struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Code string `json:"code" gorm:"size:128;not null;uniqueIndex"`
|
||||
Name string `json:"name" gorm:"size:128;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true;index"`
|
||||
EventType *string `json:"eventType,omitempty" gorm:"size:128"`
|
||||
MinimumSeverity string `json:"minimumSeverity" gorm:"size:16;not null"`
|
||||
LocationContains *string `json:"locationContains,omitempty" gorm:"size:128"`
|
||||
Version int `json:"version" gorm:"not null;default:1"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
UpdatedBy int `json:"updatedBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Rule) TableName() string { return "bell_rules" }
|
||||
@@ -0,0 +1,124 @@
|
||||
package rule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type PageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
Name string `form:"name"`
|
||||
Enabled *bool `form:"enabled"`
|
||||
}
|
||||
|
||||
type Service struct{ DB *gorm.DB }
|
||||
|
||||
func NewService(db *gorm.DB) Service { return Service{DB: db} }
|
||||
|
||||
func (s Service) List(ctx context.Context, query PageQuery) ([]Rule, int64, error) {
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
db := s.DB.WithContext(ctx).Model(&Rule{})
|
||||
if name := strings.TrimSpace(query.Name); name != "" {
|
||||
db = db.Where("name ILIKE ? OR code ILIKE ?", "%"+name+"%", "%"+name+"%")
|
||||
}
|
||||
if query.Enabled != nil {
|
||||
db = db.Where("enabled = ?", *query.Enabled)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
items := make([]Rule, 0)
|
||||
err := db.Order("created_at DESC, id DESC").Offset((page - 1) * size).Limit(size).Find(&items).Error
|
||||
return items, count, err
|
||||
}
|
||||
|
||||
func (s Service) Create(ctx context.Context, input WriteInput, actorID int) (Rule, error) {
|
||||
normalized, err := Normalize(input, true)
|
||||
if err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Rule{
|
||||
ID: uuid.NewString(), Code: normalized.Code, Name: normalized.Name, Enabled: true,
|
||||
EventType: normalized.EventType, MinimumSeverity: normalized.MinimumSeverity,
|
||||
LocationContains: normalized.LocationContains, Version: 1,
|
||||
CreatedBy: actorID, UpdatedBy: actorID, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err = s.DB.WithContext(ctx).Create(&item).Error; err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (s Service) Update(ctx context.Context, id string, input WriteInput, actorID int) (Rule, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return Rule{}, ErrNotFound
|
||||
}
|
||||
normalized, err := Normalize(input, false)
|
||||
if err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
var item Rule
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&item, "id = ?", id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
updates := map[string]any{
|
||||
"name": normalized.Name, "event_type": normalized.EventType,
|
||||
"minimum_severity": normalized.MinimumSeverity, "location_contains": normalized.LocationContains,
|
||||
"version": item.Version + 1, "updated_by": actorID, "updated_at": time.Now().UTC(),
|
||||
}
|
||||
if err := tx.Model(&item).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.First(&item, "id = ?", id).Error
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (s Service) SetEnabled(ctx context.Context, id string, enabled bool, actorID int) (Rule, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return Rule{}, ErrNotFound
|
||||
}
|
||||
var item Rule
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&item, "id = ?", id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if item.Enabled == enabled {
|
||||
return nil
|
||||
}
|
||||
if err := tx.Model(&item).Updates(map[string]any{
|
||||
"enabled": enabled, "version": item.Version + 1,
|
||||
"updated_by": actorID, "updated_at": time.Now().UTC(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.First(&item, "id = ?", id).Error
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
|
||||
func pageValues(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package rule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("规则内容不符合要求")
|
||||
ErrNotFound = errors.New("规则不存在")
|
||||
codePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{1,127}$`)
|
||||
)
|
||||
|
||||
type WriteInput struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
EventType *string `json:"eventType"`
|
||||
MinimumSeverity string `json:"minimumSeverity"`
|
||||
LocationContains *string `json:"locationContains"`
|
||||
}
|
||||
|
||||
func Normalize(input WriteInput, requireCode bool) (WriteInput, error) {
|
||||
input.Code = strings.ToLower(strings.TrimSpace(input.Code))
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
input.MinimumSeverity = strings.ToLower(strings.TrimSpace(input.MinimumSeverity))
|
||||
if requireCode && !codePattern.MatchString(input.Code) {
|
||||
return WriteInput{}, ErrInvalid
|
||||
}
|
||||
if !validText(input.Name, 128) || !validSeverity(input.MinimumSeverity) {
|
||||
return WriteInput{}, ErrInvalid
|
||||
}
|
||||
var err error
|
||||
if input.EventType, err = optionalText(input.EventType, 128); err != nil {
|
||||
return WriteInput{}, err
|
||||
}
|
||||
if input.LocationContains, err = optionalText(input.LocationContains, 128); err != nil {
|
||||
return WriteInput{}, err
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func validSeverity(value string) bool {
|
||||
switch value {
|
||||
case "low", "medium", "high", "critical":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func optionalText(value *string, max int) (*string, error) {
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
normalized := strings.TrimSpace(*value)
|
||||
if normalized == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if !validText(normalized, max) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
return &normalized, nil
|
||||
}
|
||||
|
||||
func validText(value string, max int) bool {
|
||||
return value != "" && utf8.ValidString(value) && utf8.RuneCountInString(value) <= max &&
|
||||
!strings.ContainsAny(value, "\x00\r\n")
|
||||
}
|
||||
Reference in New Issue
Block a user