Files
go-sms-V2/internal/service/router/steer.go
T

208 lines
7.5 KiB
Go

// steer.go Day 38:导流策略——按账号维度/内容关键字指定通道(如"张三"走 A 通道),
// 命中即直连指定通道(优先于四步路由);规则 CRUD + 引擎消费同包。
// rule_type 当前支持 keyword(内容包含)/account(账号全部消息);region/content 预留(实体允许,引擎后续接入)。
package router
import (
"context"
"errors"
"strings"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// 合法导流规则类型(引擎消费范围;其余类型仅存储不消费)。
var validRuleTypes = map[string]bool{"keyword": true, "account": true}
// CreateRuleReq 导流规则创建请求。
type CreateRuleReq struct {
AccountID int64 `json:"account_id"` // 账号维度;0=全局(keyword 规则允许 0)
ChannelID int64 `json:"channel_id"`
RuleType string `json:"rule_type"` // keyword/account
RuleConfig string `json:"rule_config"` // keyword 类型的匹配字(≤512)
Priority int `json:"priority"` // 大者优先;同优先级按创建倒序
}
// CreateRule 创建导流规则(类型白名单/参数完备/通道存在)。
func (r *Router) CreateRule(ctx context.Context, req *CreateRuleReq) (*entity.RouteRule, error) {
req.RuleType = strings.ToLower(strings.TrimSpace(req.RuleType))
req.RuleConfig = strings.TrimSpace(req.RuleConfig)
if !validRuleTypes[req.RuleType] {
return nil, errs.InvalidParam.WithMsg("规则类型仅支持 keyword/account")
}
if req.RuleType == "account" && req.AccountID <= 0 {
return nil, errs.InvalidParam.WithMsg("账号维度规则须指定 account_id")
}
if req.RuleType == "keyword" && req.RuleConfig == "" {
return nil, errs.InvalidParam.WithMsg("关键字规则须配置 rule_config")
}
var n int64
if err := r.db.WithContext(ctx).Model(&entity.ChannelChannel{}).Where("id = ?", req.ChannelID).Count(&n).Error; err != nil {
return nil, err
}
if n == 0 {
return nil, errs.NotFound.WithMsg("通道不存在")
}
rule := &entity.RouteRule{
AccountID: req.AccountID, ChannelID: req.ChannelID,
RuleType: req.RuleType, RuleConfig: req.RuleConfig,
Priority: req.Priority, Status: 1,
}
if err := r.db.WithContext(ctx).Create(rule).Error; err != nil {
return nil, err
}
return rule, nil
}
// ListRules 导流规则列表(优先级倒序)。
func (r *Router) ListRules(ctx context.Context) ([]entity.RouteRule, error) {
var out []entity.RouteRule
if err := r.db.WithContext(ctx).Order("priority DESC").Order("id DESC").Find(&out).Error; err != nil {
return nil, err
}
return out, nil
}
// UpdateRule 更新导流规则(白名单:priority/status/rule_config)。
func (r *Router) UpdateRule(ctx context.Context, id int64, fields map[string]any) error {
for k := range fields {
if k != "priority" && k != "status" && k != "rule_config" {
return errs.InvalidParam.WithMsg("不允许更新字段 " + k)
}
}
if v, ok := fields["status"].(int); ok && v != 0 && v != 1 {
return errs.InvalidParam.WithMsg("状态仅 0/1")
}
res := r.db.WithContext(ctx).Model(&entity.RouteRule{}).Where("id = ?", id).Updates(fields)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg("导流规则不存在")
}
return nil
}
// DeleteRule 删除导流规则(软删)。
func (r *Router) DeleteRule(ctx context.Context, id int64) error {
res := r.db.WithContext(ctx).Delete(&entity.RouteRule{}, id)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg("导流规则不存在")
}
return nil
}
// AccountSteerResp 账号当前通道绑定快照(rule_id=0=未绑定,走四步智能路由)。
type AccountSteerResp struct {
AccountID int64 `json:"account_id"`
RuleID int64 `json:"rule_id"`
ChannelID int64 `json:"channel_id"`
ChannelName string `json:"channel_name"`
ChannelCode string `json:"channel_code"`
ChannelStatus int8 `json:"channel_status"`
}
// GetAccountSteer 查账号当前 account 型导流规则+通道快照(多条历史停用规则
// 不影响——仅取启用中优先级最高一条;通道已删/停用时快照字段标注)。
func (r *Router) GetAccountSteer(ctx context.Context, accountID int64) (*AccountSteerResp, error) {
resp := &AccountSteerResp{AccountID: accountID}
var rule entity.RouteRule
err := r.db.WithContext(ctx).
Where("account_id = ? AND rule_type = ? AND status = 1", accountID, "account").
Order("priority DESC").Order("id DESC").First(&rule).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return resp, nil // 未绑定=正常态,非错误
}
return nil, err
}
resp.RuleID = rule.ID
resp.ChannelID = rule.ChannelID
var ch entity.ChannelChannel
if err := r.db.WithContext(ctx).Select("id", "name", "code", "status").
Where("id = ?", rule.ChannelID).First(&ch).Error; err == nil {
resp.ChannelName, resp.ChannelCode, resp.ChannelStatus = ch.Name, ch.Code, ch.Status
} else {
resp.ChannelName, resp.ChannelStatus = "通道不存在/已删除", 0
}
return resp, nil
}
// SetAccountSteer 绑定/切换/解绑账号级通道(channelID=0=解绑回退智能路由)。
// 事务内软删该账号全部 account 型旧规则再建新规则——原子切换,消除
// 「删旧→建新」间隙新消息走四步路由的窗口(切换语义=整账号定向,与
// UpdateRule 字段白名单不冲突;priority 沿用既有 account 规则惯例 100)。
func (r *Router) SetAccountSteer(ctx context.Context, accountID, channelID int64) (*entity.RouteRule, error) {
if accountID <= 0 {
return nil, errs.InvalidParam.WithMsg("账号 ID 无效")
}
if channelID > 0 {
var ch entity.ChannelChannel
if err := r.db.WithContext(ctx).Select("id", "status").
Where("id = ?", channelID).First(&ch).Error; err != nil {
return nil, errs.NotFound.WithMsg("通道不存在")
}
if ch.Status != 1 {
return nil, errs.InvalidParam.WithMsg("通道已停用")
}
}
var created *entity.RouteRule
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Where("account_id = ? AND rule_type = ?", accountID, "account").
Delete(&entity.RouteRule{}).Error; err != nil {
return err
}
if channelID == 0 {
return nil // 解绑:仅清规则
}
created = &entity.RouteRule{
AccountID: accountID, ChannelID: channelID,
RuleType: "account", Priority: 100, Status: 1,
}
return tx.Create(created).Error
})
if err != nil {
return nil, err
}
return created, nil
}
// steer Step0 导流:启用规则按优先级降序匹配(账号维度/关键字),命中且通道可用即直连。
// 返回 (nil, "", nil) 表示未命中,继续四步路由。
func (r *Router) steer(ctx context.Context, req *PickReq) (*entity.ChannelChannel, string, error) {
var rules []entity.RouteRule
if err := r.db.WithContext(ctx).Where("status = 1").Order("priority DESC").Order("id ASC").Find(&rules).Error; err != nil {
return nil, "", err
}
for _, rule := range rules {
var hit bool
switch rule.RuleType {
case "account":
hit = rule.AccountID != 0 && req.AccountID == rule.AccountID
case "keyword":
kw := strings.TrimSpace(rule.RuleConfig)
hit = kw != "" && strings.Contains(req.Content, kw)
}
if !hit {
continue
}
var ch entity.ChannelChannel
err := r.db.WithContext(ctx).Where("id = ? AND status = 1", rule.ChannelID).First(&ch).Error
if err != nil {
continue // 规则指向的通道不存在/停用 → 跳过继续匹配
}
why := "steer(" + rule.RuleType
if rule.RuleConfig != "" {
why += ":" + rule.RuleConfig
}
return &ch, why + ")", nil
}
return nil, "", nil
}