All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m46s
invalidateGroups、invalidateRules 误写为调用自身,任何限流组或错误分类规则保存成功后 API 进程栈溢出退出;改为调用限流组与分类器的 Invalidate
659 lines
24 KiB
Go
659 lines
24 KiB
Go
package polling
|
|
|
|
import (
|
|
"context"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/bytedance/sonic"
|
|
"gorm.io/datatypes"
|
|
"gorm.io/gorm"
|
|
|
|
auditinfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
|
|
"github.com/break/junhong_cmp_fiber/internal/infrastructure/gatewaylimit"
|
|
"github.com/break/junhong_cmp_fiber/internal/model"
|
|
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
|
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
|
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
|
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
|
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
|
)
|
|
|
|
// GatewayRateLimitService 维护运营商账户网关限流组与上游错误分类规则(后台配置,简单写事务脚本)。
|
|
// 读取仅超级管理员与平台用户可用;修改仅超级管理员可用,并在同一事务写统一审计。
|
|
type GatewayRateLimitService struct {
|
|
db *gorm.DB
|
|
auditWriter *auditinfra.Writer
|
|
groups *postgres.CarrierRateLimitGroupStore
|
|
rules *postgres.GatewayErrorClassificationStore
|
|
runtime *gatewaylimit.Runtime
|
|
}
|
|
|
|
// NewGatewayRateLimitService 创建网关限流配置服务。
|
|
func NewGatewayRateLimitService(db *gorm.DB, auditWriter *auditinfra.Writer, runtime *gatewaylimit.Runtime) *GatewayRateLimitService {
|
|
return &GatewayRateLimitService{
|
|
db: db, auditWriter: auditWriter, runtime: runtime,
|
|
groups: postgres.NewCarrierRateLimitGroupStore(db), rules: postgres.NewGatewayErrorClassificationStore(db),
|
|
}
|
|
}
|
|
|
|
// requirePlatformReader 校验读取权限:超级管理员或平台用户。
|
|
func requirePlatformReader(ctx context.Context) error {
|
|
switch middleware.GetUserTypeFromContext(ctx) {
|
|
case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
|
|
return nil
|
|
default:
|
|
return errors.New(errors.CodeForbidden, "仅平台账号可查看网关限流配置")
|
|
}
|
|
}
|
|
|
|
// requireSuperAdminWriter 校验修改权限:仅超级管理员,返回操作者 ID。
|
|
func requireSuperAdminWriter(ctx context.Context) (uint, error) {
|
|
if middleware.GetUserTypeFromContext(ctx) != constants.UserTypeSuperAdmin {
|
|
return 0, errors.New(errors.CodeForbidden, "仅超级管理员可修改网关限流配置")
|
|
}
|
|
operatorID := middleware.GetUserIDFromContext(ctx)
|
|
if operatorID == 0 {
|
|
return 0, errors.New(errors.CodeUnauthorized, "未授权访问")
|
|
}
|
|
return operatorID, nil
|
|
}
|
|
|
|
func normalizePage(page, size int) (int, int) {
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if size < 1 {
|
|
size = 20
|
|
}
|
|
if size > 100 {
|
|
size = 100
|
|
}
|
|
return page, size
|
|
}
|
|
|
|
// ListGroups 分页查询限流组。
|
|
func (s *GatewayRateLimitService) ListGroups(ctx context.Context, req *dto.RateLimitGroupListRequest) (*dto.RateLimitGroupPageResult, error) {
|
|
if err := requirePlatformReader(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
page, size := normalizePage(req.Page, req.PageSize)
|
|
rows, total, err := s.groups.List(ctx, postgres.RateLimitGroupFilter{CarrierID: req.CarrierID, OnlyGlobal: req.OnlyGlobal, Status: req.Status, Page: page, PageSize: size})
|
|
if err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询网关限流组失败")
|
|
}
|
|
names, err := s.carrierNames(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
items := make([]dto.RateLimitGroupResponse, 0, len(rows))
|
|
for i := range rows {
|
|
items = append(items, toRateLimitGroupResponse(&rows[i], names))
|
|
}
|
|
return &dto.RateLimitGroupPageResult{List: items, Total: total, Page: page, PageSize: size}, nil
|
|
}
|
|
|
|
// GetGroup 查询限流组详情。
|
|
func (s *GatewayRateLimitService) GetGroup(ctx context.Context, id uint) (*dto.RateLimitGroupResponse, error) {
|
|
if err := requirePlatformReader(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
row, err := s.loadGroup(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
names, err := s.carrierNames(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resp := toRateLimitGroupResponse(row, names)
|
|
return &resp, nil
|
|
}
|
|
|
|
// CreateGroup 新建限流组。
|
|
func (s *GatewayRateLimitService) CreateGroup(ctx context.Context, req *dto.SaveRateLimitGroupRequest) (*dto.RateLimitGroupResponse, error) {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := s.validateGroup(ctx, req, 0); err != nil {
|
|
return nil, err
|
|
}
|
|
row := &model.CarrierRateLimitGroup{CarrierID: req.CarrierID, Status: constants.RateLimitGroupStatusEnabled}
|
|
applyGroupRequest(row, req)
|
|
row.Creator, row.Updater = operatorID, operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Create(row).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "新建网关限流组失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, groupAudit(constants.AuditActionRateLimitGroupCreated, "创建网关限流组", row, operatorID, nil))
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.invalidateGroups()
|
|
return s.GetGroup(ctx, row.ID)
|
|
}
|
|
|
|
// UpdateGroup 修改限流组。
|
|
func (s *GatewayRateLimitService) UpdateGroup(ctx context.Context, req *dto.SaveRateLimitGroupRequest) (*dto.RateLimitGroupResponse, error) {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
row, err := s.loadGroup(ctx, req.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !sameCarrier(row.CarrierID, req.CarrierID) {
|
|
return nil, errors.New(errors.CodeInvalidParam, "限流组所属运营商账户不可修改,请删除后重新创建")
|
|
}
|
|
if err := s.validateGroup(ctx, req, row.ID); err != nil {
|
|
return nil, err
|
|
}
|
|
before := groupState(row)
|
|
applyGroupRequest(row, req)
|
|
row.Updater = operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Save(row).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "修改网关限流组失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, groupAudit(constants.AuditActionRateLimitGroupUpdated, "更新网关限流组", row, operatorID, before))
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.invalidateGroups()
|
|
return s.GetGroup(ctx, row.ID)
|
|
}
|
|
|
|
// UpdateGroupStatus 启停限流组;停用后组内操作回落为默认每秒请求上限。
|
|
func (s *GatewayRateLimitService) UpdateGroupStatus(ctx context.Context, id uint, status int) error {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
row, err := s.loadGroup(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if status == constants.RateLimitGroupStatusEnabled {
|
|
ops, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
if err := s.checkOperationsFree(ctx, row.CarrierID, ops, row.ID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
before := groupState(row)
|
|
row.Status, row.Updater = status, operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Model(&model.CarrierRateLimitGroup{}).Where("id = ?", id).
|
|
Updates(map[string]any{"status": status, "updater": operatorID}).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "更新网关限流组状态失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, groupAudit(constants.AuditActionRateLimitGroupStatusUpdated, "更新网关限流组状态", row, operatorID, before))
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.invalidateGroups()
|
|
return nil
|
|
}
|
|
|
|
// DeleteGroup 删除限流组;组内操作回落为默认每秒请求上限。
|
|
func (s *GatewayRateLimitService) DeleteGroup(ctx context.Context, id uint) error {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
row, err := s.loadGroup(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Delete(&model.CarrierRateLimitGroup{}, id).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "删除网关限流组失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, groupAudit(constants.AuditActionRateLimitGroupDeleted, "删除网关限流组", row, operatorID, groupState(row)))
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.invalidateGroups()
|
|
return nil
|
|
}
|
|
|
|
func (s *GatewayRateLimitService) loadGroup(ctx context.Context, id uint) (*model.CarrierRateLimitGroup, error) {
|
|
row, err := s.groups.Get(ctx, id)
|
|
if err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询网关限流组失败")
|
|
}
|
|
if row == nil {
|
|
return nil, errors.New(errors.CodeNotFound, "网关限流组不存在")
|
|
}
|
|
return row, nil
|
|
}
|
|
|
|
// validateGroup 校验预留额度、高优先级操作归属、同账户同操作只属于一个启用组、组标识唯一。
|
|
func (s *GatewayRateLimitService) validateGroup(ctx context.Context, req *dto.SaveRateLimitGroupRequest, selfID uint) error {
|
|
if req.ReservedQPS >= req.MaxQPS {
|
|
return errors.New(errors.CodeInvalidParam, "预留额度必须小于每秒请求上限")
|
|
}
|
|
ops := uniqueStrings(operationStrings(req.Operations))
|
|
opSet := map[string]bool{}
|
|
for _, op := range ops {
|
|
opSet[op] = true
|
|
}
|
|
for _, op := range operationStrings(req.HighPriorityOperations) {
|
|
if !opSet[op] {
|
|
return errors.New(errors.CodeInvalidParam, "高优先级操作必须属于组内操作:"+constants.GatewayOperationName(op))
|
|
}
|
|
}
|
|
if req.ReservedQPS > 0 && len(req.HighPriorityOperations) == 0 {
|
|
return errors.New(errors.CodeInvalidParam, "设置预留额度时必须指定高优先级操作")
|
|
}
|
|
if req.CarrierID != nil {
|
|
var count int64
|
|
if err := s.db.WithContext(ctx).Model(&model.Carrier{}).Where("id = ?", *req.CarrierID).Count(&count).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "查询运营商账户失败")
|
|
}
|
|
if count == 0 {
|
|
return errors.New(errors.CodeInvalidParam, "运营商账户不存在")
|
|
}
|
|
}
|
|
existing, err := s.groups.ListByCarrier(ctx, req.CarrierID)
|
|
if err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "查询网关限流组失败")
|
|
}
|
|
for _, row := range existing {
|
|
if row.ID != selfID && row.GroupCode == req.GroupCode {
|
|
return errors.New(errors.CodeInvalidParam, "同一运营商账户内组标识已存在")
|
|
}
|
|
}
|
|
if req.Status == nil || *req.Status == constants.RateLimitGroupStatusEnabled {
|
|
return s.checkOperationsFree(ctx, req.CarrierID, ops, selfID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkOperationsFree 校验操作未被同账户其他启用组占用。
|
|
func (s *GatewayRateLimitService) checkOperationsFree(ctx context.Context, carrierID *uint, ops []string, selfID uint) error {
|
|
existing, err := s.groups.ListByCarrier(ctx, carrierID)
|
|
if err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "查询网关限流组失败")
|
|
}
|
|
for _, row := range existing {
|
|
if row.ID == selfID || row.Status != constants.RateLimitGroupStatusEnabled {
|
|
continue
|
|
}
|
|
used, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
for _, op := range used {
|
|
for _, want := range ops {
|
|
if op == want {
|
|
return errors.New(errors.CodeInvalidParam, "操作「"+constants.GatewayOperationName(op)+"」已属于限流组「"+row.GroupName+"」,同一账户下每个操作只能属于一个启用的组")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func applyGroupRequest(row *model.CarrierRateLimitGroup, req *dto.SaveRateLimitGroupRequest) {
|
|
row.GroupCode = strings.TrimSpace(req.GroupCode)
|
|
row.GroupName = strings.TrimSpace(req.GroupName)
|
|
row.MaxQPS = req.MaxQPS
|
|
row.ReservedQPS = req.ReservedQPS
|
|
row.Operations = encodeStrings(uniqueStrings(operationStrings(req.Operations)))
|
|
row.HighPriorityOperations = encodeStrings(uniqueStrings(operationStrings(req.HighPriorityOperations)))
|
|
if req.Status != nil {
|
|
row.Status = *req.Status
|
|
}
|
|
}
|
|
|
|
func groupState(row *model.CarrierRateLimitGroup) map[string]any {
|
|
ops, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
high, _ := gatewaylimit.DecodeOperations(row.HighPriorityOperations)
|
|
return map[string]any{"group_code": row.GroupCode, "group_name": row.GroupName, "max_qps": row.MaxQPS,
|
|
"reserved_qps": row.ReservedQPS, "operations": ops, "high_priority_operations": high, "status": row.Status}
|
|
}
|
|
|
|
func groupAudit(action, summary string, row *model.CarrierRateLimitGroup, operatorID uint, before map[string]any) auditinfra.PollingInput {
|
|
var carrierID any
|
|
if row.CarrierID != nil {
|
|
carrierID = *row.CarrierID
|
|
}
|
|
return auditinfra.PollingInput{
|
|
ActionCode: action, Summary: summary, ResourceType: constants.AuditResourceRateLimitGroup,
|
|
ResourceID: row.ID, ResourceKey: "rate_limit_group:" + uintString(row.ID), DisplayName: row.GroupName,
|
|
OperatorID: operatorID,
|
|
IdentitySnapshot: map[string]any{"id": row.ID, "carrier_id": carrierID, "group_code": row.GroupCode,
|
|
"group_name": row.GroupName, "max_qps": row.MaxQPS, "reserved_qps": row.ReservedQPS, "status": row.Status},
|
|
BeforeData: before, AfterData: groupState(row),
|
|
}
|
|
}
|
|
|
|
func toRateLimitGroupResponse(row *model.CarrierRateLimitGroup, names map[uint]string) dto.RateLimitGroupResponse {
|
|
ops, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
high, _ := gatewaylimit.DecodeOperations(row.HighPriorityOperations)
|
|
resp := dto.RateLimitGroupResponse{
|
|
ID: row.ID, CarrierID: row.CarrierID, GroupCode: row.GroupCode, GroupName: row.GroupName, MaxQPS: row.MaxQPS,
|
|
Operations: nonNil(ops), HighPriorityOperations: nonNil(high), ReservedQPS: row.ReservedQPS,
|
|
Status: row.Status, StatusName: enabledName(row.Status), CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
|
}
|
|
if row.CarrierID != nil {
|
|
resp.CarrierName = names[*row.CarrierID]
|
|
}
|
|
return resp
|
|
}
|
|
|
|
// ListRules 分页查询上游错误分类规则。
|
|
func (s *GatewayRateLimitService) ListRules(ctx context.Context, req *dto.GatewayErrorRuleListRequest) (*dto.GatewayErrorRulePageResult, error) {
|
|
if err := requirePlatformReader(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
page, size := normalizePage(req.Page, req.PageSize)
|
|
rows, total, err := s.rules.List(ctx, postgres.ErrorClassificationFilter{Category: req.Category, Status: req.Status, Keyword: strings.TrimSpace(req.Keyword), Page: page, PageSize: size})
|
|
if err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询上游错误分类规则失败")
|
|
}
|
|
items := make([]dto.GatewayErrorRuleResponse, 0, len(rows))
|
|
for i := range rows {
|
|
items = append(items, toRuleResponse(&rows[i]))
|
|
}
|
|
return &dto.GatewayErrorRulePageResult{List: items, Total: total, Page: page, PageSize: size}, nil
|
|
}
|
|
|
|
// CreateRule 新建上游错误分类规则。
|
|
func (s *GatewayRateLimitService) CreateRule(ctx context.Context, req *dto.SaveGatewayErrorRuleRequest) (*dto.GatewayErrorRuleResponse, error) {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateRule(req); err != nil {
|
|
return nil, err
|
|
}
|
|
row := &model.GatewayErrorClassification{Status: constants.RateLimitGroupStatusEnabled}
|
|
applyRuleRequest(row, req)
|
|
row.Creator, row.Updater = operatorID, operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Create(row).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "新建上游错误分类规则失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, ruleAudit(constants.AuditActionGatewayErrorRuleCreated, "创建上游错误分类规则", row, operatorID, nil))
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.invalidateRules()
|
|
resp := toRuleResponse(row)
|
|
return &resp, nil
|
|
}
|
|
|
|
// UpdateRule 修改上游错误分类规则。
|
|
func (s *GatewayRateLimitService) UpdateRule(ctx context.Context, req *dto.SaveGatewayErrorRuleRequest) (*dto.GatewayErrorRuleResponse, error) {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateRule(req); err != nil {
|
|
return nil, err
|
|
}
|
|
row, err := s.loadRule(ctx, req.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
before := ruleState(row)
|
|
applyRuleRequest(row, req)
|
|
row.Updater = operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Save(row).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "修改上游错误分类规则失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, ruleAudit(constants.AuditActionGatewayErrorRuleUpdated, "更新上游错误分类规则", row, operatorID, before))
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.invalidateRules()
|
|
resp := toRuleResponse(row)
|
|
return &resp, nil
|
|
}
|
|
|
|
// UpdateRuleStatus 启停上游错误分类规则。
|
|
func (s *GatewayRateLimitService) UpdateRuleStatus(ctx context.Context, id uint, status int) error {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
row, err := s.loadRule(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
before := ruleState(row)
|
|
row.Status, row.Updater = status, operatorID
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Model(&model.GatewayErrorClassification{}).Where("id = ?", id).
|
|
Updates(map[string]any{"status": status, "updater": operatorID}).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "更新上游错误分类规则状态失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, ruleAudit(constants.AuditActionGatewayErrorRuleStatusUpdated, "更新上游错误分类规则状态", row, operatorID, before))
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.invalidateRules()
|
|
return nil
|
|
}
|
|
|
|
// DeleteRule 删除上游错误分类规则。
|
|
func (s *GatewayRateLimitService) DeleteRule(ctx context.Context, id uint) error {
|
|
operatorID, err := requireSuperAdminWriter(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
row, err := s.loadRule(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
|
if err := tx.WithContext(ctx).Delete(&model.GatewayErrorClassification{}, id).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "删除上游错误分类规则失败")
|
|
}
|
|
return writePollingAudit(ctx, tx, s.auditWriter, ruleAudit(constants.AuditActionGatewayErrorRuleDeleted, "删除上游错误分类规则", row, operatorID, ruleState(row)))
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.invalidateRules()
|
|
return nil
|
|
}
|
|
|
|
// TestRule 用已启用规则(可附带一条未保存的草稿)对上游返回信息分类,不写任何数据。
|
|
func (s *GatewayRateLimitService) TestRule(ctx context.Context, req *dto.TestGatewayErrorRuleRequest) (*dto.TestGatewayErrorRuleResponse, error) {
|
|
if err := requirePlatformReader(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := s.rules.ListEnabled(ctx)
|
|
if err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询上游错误分类规则失败")
|
|
}
|
|
if req.Draft != nil {
|
|
if err := validateRule(req.Draft); err != nil {
|
|
return nil, err
|
|
}
|
|
draft := model.GatewayErrorClassification{}
|
|
applyRuleRequest(&draft, req.Draft)
|
|
rows = append(rows, draft)
|
|
sort.SliceStable(rows, func(i, j int) bool { return rows[i].Priority < rows[j].Priority })
|
|
}
|
|
result := gatewaylimit.ClassifyWith(rows, req.Operation, req.Message)
|
|
matched := result.Keyword != ""
|
|
return &dto.TestGatewayErrorRuleResponse{
|
|
Category: result.Category, CategoryName: constants.GatewayErrorClassName(result.Category),
|
|
RuleID: result.RuleID, Keyword: result.Keyword, MaybeAccepted: result.MaybeAccepted,
|
|
AutoDisablePolling: result.AutoDisablePolling, Matched: matched,
|
|
}, nil
|
|
}
|
|
|
|
func (s *GatewayRateLimitService) loadRule(ctx context.Context, id uint) (*model.GatewayErrorClassification, error) {
|
|
row, err := s.rules.Get(ctx, id)
|
|
if err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询上游错误分类规则失败")
|
|
}
|
|
if row == nil {
|
|
return nil, errors.New(errors.CodeNotFound, "上游错误分类规则不存在")
|
|
}
|
|
return row, nil
|
|
}
|
|
|
|
func validateRule(req *dto.SaveGatewayErrorRuleRequest) error {
|
|
if strings.TrimSpace(req.Keyword) == "" {
|
|
return errors.New(errors.CodeInvalidParam, "匹配关键字不能为空")
|
|
}
|
|
if req.AutoDisablePolling != nil && *req.AutoDisablePolling && req.Category != constants.GatewayClassTerminal {
|
|
return errors.New(errors.CodeInvalidParam, "只有终态不可操作类别的规则可以勾选自动关闭轮询")
|
|
}
|
|
if req.MatchType == constants.GatewayMatchRegex {
|
|
if _, err := regexp.Compile(req.Keyword); err != nil {
|
|
return errors.New(errors.CodeInvalidParam, "正则表达式不合法")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func applyRuleRequest(row *model.GatewayErrorClassification, req *dto.SaveGatewayErrorRuleRequest) {
|
|
row.Keyword = strings.TrimSpace(req.Keyword)
|
|
row.MatchType = req.MatchType
|
|
row.Category = req.Category
|
|
row.Operations = encodeStrings(uniqueStrings(operationStrings(req.Operations)))
|
|
row.Priority = req.Priority
|
|
if row.Priority == 0 {
|
|
row.Priority = 100
|
|
}
|
|
row.MaybeAccepted = req.MaybeAccepted
|
|
if req.AutoDisablePolling != nil {
|
|
row.AutoDisablePolling = *req.AutoDisablePolling
|
|
}
|
|
// 类别改为非终态时自动关闭轮询标记随之失效,避免违反"仅终态可置位"。
|
|
if row.Category != constants.GatewayClassTerminal {
|
|
row.AutoDisablePolling = false
|
|
}
|
|
row.Remark = strings.TrimSpace(req.Remark)
|
|
if req.Status != nil {
|
|
row.Status = *req.Status
|
|
}
|
|
}
|
|
|
|
func ruleState(row *model.GatewayErrorClassification) map[string]any {
|
|
ops, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
return map[string]any{"keyword": row.Keyword, "match_type": row.MatchType, "category": row.Category,
|
|
"operations": ops, "priority": row.Priority, "maybe_accepted": row.MaybeAccepted,
|
|
"auto_disable_polling": row.AutoDisablePolling, "status": row.Status}
|
|
}
|
|
|
|
func ruleAudit(action, summary string, row *model.GatewayErrorClassification, operatorID uint, before map[string]any) auditinfra.PollingInput {
|
|
return auditinfra.PollingInput{
|
|
ActionCode: action, Summary: summary, ResourceType: constants.AuditResourceGatewayErrorRule,
|
|
ResourceID: row.ID, ResourceKey: "gateway_error_rule:" + uintString(row.ID), DisplayName: row.Keyword,
|
|
OperatorID: operatorID,
|
|
IdentitySnapshot: map[string]any{"id": row.ID, "keyword": row.Keyword, "match_type": row.MatchType,
|
|
"category": row.Category, "priority": row.Priority, "status": row.Status},
|
|
BeforeData: before, AfterData: ruleState(row),
|
|
}
|
|
}
|
|
|
|
func toRuleResponse(row *model.GatewayErrorClassification) dto.GatewayErrorRuleResponse {
|
|
ops, _ := gatewaylimit.DecodeOperations(row.Operations)
|
|
return dto.GatewayErrorRuleResponse{
|
|
ID: row.ID, Keyword: row.Keyword, MatchType: row.MatchType, Category: row.Category,
|
|
CategoryName: constants.GatewayErrorClassName(row.Category), Operations: nonNil(ops), Priority: row.Priority,
|
|
MaybeAccepted: row.MaybeAccepted, AutoDisablePolling: row.AutoDisablePolling, Status: row.Status, Remark: row.Remark, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
// carrierNames 返回运营商账户 ID → 名称映射(含已删除账户,便于展示历史配置)。
|
|
func (s *GatewayRateLimitService) carrierNames(ctx context.Context) (map[uint]string, error) {
|
|
var carriers []model.Carrier
|
|
if err := s.db.WithContext(ctx).Unscoped().Select("id", "carrier_name").Find(&carriers).Error; err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询运营商账户失败")
|
|
}
|
|
names := make(map[uint]string, len(carriers))
|
|
for _, carrier := range carriers {
|
|
names[carrier.ID] = carrier.CarrierName
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
func sameCarrier(a, b *uint) bool {
|
|
if a == nil || b == nil {
|
|
return a == nil && b == nil
|
|
}
|
|
return *a == *b
|
|
}
|
|
|
|
func uniqueStrings(values []string) []string {
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" || seen[value] {
|
|
continue
|
|
}
|
|
seen[value] = true
|
|
out = append(out, value)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func operationStrings(values []dto.GatewayOperation) []string {
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
out = append(out, string(value))
|
|
}
|
|
return out
|
|
}
|
|
|
|
func encodeStrings(values []string) datatypes.JSON {
|
|
if values == nil {
|
|
values = []string{}
|
|
}
|
|
raw, err := sonic.Marshal(values)
|
|
if err != nil {
|
|
return datatypes.JSON("[]")
|
|
}
|
|
return datatypes.JSON(raw)
|
|
}
|
|
|
|
func nonNil(values []string) []string {
|
|
if values == nil {
|
|
return []string{}
|
|
}
|
|
return values
|
|
}
|
|
|
|
func enabledName(status int) string {
|
|
if status == constants.RateLimitGroupStatusEnabled {
|
|
return "启用"
|
|
}
|
|
return "停用"
|
|
}
|
|
|
|
func uintString(value uint) string {
|
|
return strconv.FormatUint(uint64(value), 10)
|
|
}
|
|
|
|
// invalidateGroups 让本进程限流组缓存立即失效;其他进程在缓存时长(数秒)内自动刷新。
|
|
func (s *GatewayRateLimitService) invalidateGroups() {
|
|
if s.runtime != nil && s.runtime.Groups != nil {
|
|
s.runtime.Groups.Invalidate()
|
|
}
|
|
}
|
|
|
|
// invalidateRules 让本进程错误分类规则缓存立即失效。
|
|
func (s *GatewayRateLimitService) invalidateRules() {
|
|
if s.runtime != nil && s.runtime.Classifier != nil {
|
|
s.runtime.Classifier.Invalidate()
|
|
}
|
|
}
|