S1-B D3-P1: B 层搬运 send 主链 26 文件(P1 等价;唯一适配=channel.BatchAck→pool.BatchAck 因 D2.5-P2 拆包移位,3 文件+import;79.8% 覆盖 -race 绿;P2 拆 submit/consume/dispatch 三子包随后)
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
// aggregator.go Day 47:合包聚合器(技术方案 6.3 CMPPSubmitAggregator)。
|
||||
// 通道+内容 相同的明细聚合为批:满 maxBatch(1000)立即 flush,或窗口(5s)到期统一
|
||||
// flush——同批一次批量提交(CMPP 单包 ≤100 号码,由通道层切包),显著降低
|
||||
// 提交调用次数(验收口径:较逐号提交减少 ≥80%)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/pkg/logger"
|
||||
"go-sms/internal/service/channel/pool"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AggregatorDefaults 默认参数(与开发计划 Day47 对齐:5s/1000 条)。
|
||||
const (
|
||||
DefaultAggrWindow = 5 * time.Second
|
||||
DefaultAggrMaxBatch = 1000
|
||||
)
|
||||
|
||||
// aggrGroup 聚合组(同通道+同内容)。
|
||||
type aggrGroup struct {
|
||||
channelID int64
|
||||
content string
|
||||
items []aggrItem
|
||||
}
|
||||
|
||||
// aggrItem 单条待发明细。
|
||||
type aggrItem struct {
|
||||
detailID int64
|
||||
mobile string
|
||||
}
|
||||
|
||||
// BatchLinkSubmitter 批量链路提交(channel.linkManager 实现;聚合器出口)。
|
||||
// 未实现时聚合器退化为逐号提交(行为兼容,聚合收益归零)。
|
||||
// Day 56:返回「包×片」级 acks(每片独立 msg_id+包内号码+段序/总段数),
|
||||
// flushGroup 据此逐段登记 message_report_seg 供回执段级配对。
|
||||
type BatchLinkSubmitter interface {
|
||||
SubmitBatchViaLink(ctx context.Context, channelID int64, mobiles []string, content string) ([]pool.BatchAck, error)
|
||||
}
|
||||
|
||||
// SubmitAggregator 合包聚合器。
|
||||
type SubmitAggregator struct {
|
||||
lk LinkSubmitter
|
||||
db *gorm.DB // Day 56:seg 配对登记落库(nil=跳过,纯内存测试场景)
|
||||
window time.Duration
|
||||
maxBatch int
|
||||
mark func(ctx context.Context, ids []int64, status int8, channelID int64, errCode string)
|
||||
|
||||
mu sync.Mutex
|
||||
groups map[string]*aggrGroup
|
||||
|
||||
// 计数器走 atomic:flushGroup 在锁外执行(Run/FlushAll 换出组后提交),
|
||||
// 与 Stats() 并发读写必须无竞争(-race 门禁;2026-09-29 补修,原 int64 裸写遗留)。
|
||||
addTotal atomic.Int64 // 累计入聚合条数
|
||||
batchTotal atomic.Int64 // 累计批量提交次数(调用次数口径)
|
||||
singleTotal atomic.Int64 // 累计回退逐号次数
|
||||
}
|
||||
|
||||
// NewSubmitAggregator 构造(window/maxBatch 零值取默认;mark 可后期 bindMark 绑定)。
|
||||
func NewSubmitAggregator(lk LinkSubmitter, window time.Duration, maxBatch int) *SubmitAggregator {
|
||||
if window <= 0 {
|
||||
window = DefaultAggrWindow
|
||||
}
|
||||
if maxBatch <= 0 {
|
||||
maxBatch = DefaultAggrMaxBatch
|
||||
}
|
||||
return &SubmitAggregator{
|
||||
lk: lk, window: window, maxBatch: maxBatch,
|
||||
groups: map[string]*aggrGroup{},
|
||||
}
|
||||
}
|
||||
|
||||
// bindMark 终态回写绑定(ChannelDispatcher 构造时注入,避免循环依赖)。
|
||||
func (a *SubmitAggregator) bindMark(fn func(ctx context.Context, ids []int64, status int8, channelID int64, errCode string)) {
|
||||
a.mark = fn
|
||||
}
|
||||
|
||||
// WithDB 注入 DB(Day 56:seg 配对登记;nil 保持跳过)。
|
||||
func (a *SubmitAggregator) WithDB(db *gorm.DB) *SubmitAggregator {
|
||||
a.db = db
|
||||
return a
|
||||
}
|
||||
|
||||
// Add 入聚合(组满 maxBatch 同步 flush 该组,保证阈值触发实时性)。
|
||||
func (a *SubmitAggregator) Add(channelID int64, content, mobile string, detailID int64) {
|
||||
key := aggrKey(channelID, content)
|
||||
var full *aggrGroup
|
||||
a.mu.Lock()
|
||||
g := a.groups[key]
|
||||
if g == nil {
|
||||
g = &aggrGroup{channelID: channelID, content: content}
|
||||
a.groups[key] = g
|
||||
}
|
||||
g.items = append(g.items, aggrItem{detailID: detailID, mobile: mobile})
|
||||
a.addTotal.Add(1)
|
||||
if len(g.items) >= a.maxBatch {
|
||||
delete(a.groups, key)
|
||||
full = g
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if full != nil {
|
||||
a.flushGroup(full)
|
||||
}
|
||||
}
|
||||
|
||||
// Run 常驻窗口 flush(随 ctx 退出;退出前清空缓冲)。
|
||||
func (a *SubmitAggregator) Run(ctx context.Context) {
|
||||
t := time.NewTicker(a.window)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
a.FlushAll()
|
||||
return
|
||||
case <-t.C:
|
||||
a.FlushAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FlushAll 冲洗全部缓冲组。
|
||||
func (a *SubmitAggregator) FlushAll() {
|
||||
a.mu.Lock()
|
||||
pending := a.groups
|
||||
a.groups = map[string]*aggrGroup{}
|
||||
a.mu.Unlock()
|
||||
for _, g := range pending {
|
||||
a.flushGroup(g)
|
||||
}
|
||||
}
|
||||
|
||||
// flushGroup 单组提交:批量优先,失败逐号回退;终态按结果回写。
|
||||
func (a *SubmitAggregator) flushGroup(g *aggrGroup) {
|
||||
if len(g.items) == 0 {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
mobiles := make([]string, 0, len(g.items))
|
||||
ids := make([]int64, 0, len(g.items))
|
||||
for _, it := range g.items {
|
||||
mobiles = append(mobiles, it.mobile)
|
||||
ids = append(ids, it.detailID)
|
||||
}
|
||||
|
||||
if bl, ok := a.lk.(BatchLinkSubmitter); ok {
|
||||
a.batchTotal.Add(1)
|
||||
acks, err := bl.SubmitBatchViaLink(ctx, g.channelID, mobiles, g.content)
|
||||
// Day 56:成功包先行登记段级配对(哪怕整批报错,已确认包不丢 seg)。
|
||||
writeSegRows(ctx, a.db, segRowsForBatch(g.channelID, g.items, acks))
|
||||
acked := make(map[string]bool, len(mobiles))
|
||||
for _, ack := range acks {
|
||||
for _, mo := range ack.Mobiles {
|
||||
acked[mo] = true
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
logger.L().Warn("aggr_batch_submit_failed_fallback_single",
|
||||
zap.Int64("channel_id", g.channelID), zap.Error(err))
|
||||
// 批量失败回退逐号,尽量保送达(逐号独立成败)。
|
||||
// Day 56 增强:已确认包(在 acks 内)不重复发送——重复提交=重复计费风险。
|
||||
var okIDs, failIDs []int64
|
||||
for _, it := range g.items {
|
||||
if acked[it.mobile] {
|
||||
okIDs = append(okIDs, it.detailID)
|
||||
continue
|
||||
}
|
||||
mids, serr := a.lk.SubmitViaLink(ctx, g.channelID, it.mobile, g.content)
|
||||
if serr != nil {
|
||||
failIDs = append(failIDs, it.detailID)
|
||||
} else {
|
||||
writeSegRows(ctx, a.db, segRowsFor(g.channelID, it.detailID, it.mobile, mids))
|
||||
okIDs = append(okIDs, it.detailID)
|
||||
}
|
||||
a.singleTotal.Add(1)
|
||||
}
|
||||
a.markIDs(ctx, okIDs, detailStSubmitted, g.channelID, "")
|
||||
a.markIDs(ctx, failIDs, detailStFailed, g.channelID, errText(err))
|
||||
return
|
||||
}
|
||||
a.markIDs(ctx, ids, detailStSubmitted, g.channelID, "")
|
||||
return
|
||||
}
|
||||
|
||||
// 链路无批量能力:逐号提交(兼容路径;Day52 修复:终态保留最后错误,原空串丢排障信息)。
|
||||
var okIDs, failIDs []int64
|
||||
lastErr := ""
|
||||
for _, it := range g.items {
|
||||
mids, serr := a.lk.SubmitViaLink(ctx, g.channelID, it.mobile, g.content)
|
||||
if serr != nil {
|
||||
failIDs = append(failIDs, it.detailID)
|
||||
lastErr = errText(serr)
|
||||
} else {
|
||||
writeSegRows(ctx, a.db, segRowsFor(g.channelID, it.detailID, it.mobile, mids))
|
||||
okIDs = append(okIDs, it.detailID)
|
||||
}
|
||||
a.singleTotal.Add(1)
|
||||
}
|
||||
a.markIDs(ctx, okIDs, detailStSubmitted, g.channelID, "")
|
||||
a.markIDs(ctx, failIDs, detailStFailed, g.channelID, lastErr)
|
||||
}
|
||||
|
||||
// markIDs 批量终态回写(mark 未绑定时忽略——纯内存测试场景)。
|
||||
func (a *SubmitAggregator) markIDs(ctx context.Context, ids []int64, status int8, channelID int64, errCode string) {
|
||||
if len(ids) == 0 || a.mark == nil {
|
||||
return
|
||||
}
|
||||
a.mark(ctx, ids, status, channelID, errCode)
|
||||
}
|
||||
|
||||
// Stats 聚合统计(观测/验收:调用次数口径)。计数器为 atomic,无需持锁。
|
||||
func (a *SubmitAggregator) Stats() (added, batchCalls, singleCalls int64) {
|
||||
return a.addTotal.Load(), a.batchTotal.Load(), a.singleTotal.Load()
|
||||
}
|
||||
|
||||
// aggrKey 组键(通道+内容;内容即签名+正文一体,同内容才可合包)。
|
||||
func aggrKey(channelID int64, content string) string {
|
||||
return strconv.FormatInt(channelID, 10) + "\x00" + content
|
||||
}
|
||||
|
||||
func errText(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// aggregator_test.go Day 47:合包聚合器单测——双阈值触发(1000 条即时/窗口到期)、
|
||||
// 调用次数削减(验收口径 ≥80%)、批量失败逐号回退、分发器聚合接线。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/service/channel/pool"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// fakeBatchLink 批量链路桩:统计批量/逐号调用次数。
|
||||
type fakeBatchLink struct {
|
||||
batchCalls atomic.Int64
|
||||
singleCalls atomic.Int64
|
||||
failBatch atomic.Bool
|
||||
mu sync.Mutex
|
||||
lastMobiles []string
|
||||
}
|
||||
|
||||
func (f *fakeBatchLink) SubmitViaLink(ctx context.Context, channelID int64, mobile, content string) ([]string, error) {
|
||||
f.singleCalls.Add(1)
|
||||
return []string{"1"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeBatchLink) SubmitBatchViaLink(ctx context.Context, channelID int64, mobiles []string, content string) ([]pool.BatchAck, error) {
|
||||
f.batchCalls.Add(1)
|
||||
f.mu.Lock()
|
||||
f.lastMobiles = append([]string{}, mobiles...)
|
||||
f.mu.Unlock()
|
||||
if f.failBatch.Load() {
|
||||
return nil, errors.New("batch failed")
|
||||
}
|
||||
// 单片合包回执:每号一段,msg_id=号序(可配对)。
|
||||
acks := make([]pool.BatchAck, 0, 1)
|
||||
acks = append(acks, pool.BatchAck{
|
||||
MsgID: fmt.Sprintf("b%d", f.batchCalls.Load()), Mobiles: mobiles,
|
||||
PkNumber: 1, PkTotal: 1,
|
||||
})
|
||||
return acks, nil
|
||||
}
|
||||
|
||||
// TestAggregator_ThresholdFlush 满 maxBatch 立即冲洗(阈值触发实时性)。
|
||||
func TestAggregator_ThresholdFlush(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(lk, time.Hour, 100) // 窗口拉长:只验证阈值路径
|
||||
for i := 0; i < 99; i++ {
|
||||
agg.Add(7, "hi", fmt.Sprintf("1380013%05d", i), int64(i))
|
||||
}
|
||||
if _, b, _ := agg.Stats(); b != 0 {
|
||||
t.Fatalf("99 条不应触发: batch=%d", b)
|
||||
}
|
||||
agg.Add(7, "hi", "13800138099", 99) // 第 100 条:满阈值即时 flush
|
||||
if _, b, s := agg.Stats(); b != 1 || s != 0 {
|
||||
t.Fatalf("阈值未即时触发: batch=%d single=%d", b, s)
|
||||
}
|
||||
if n := lk.batchCalls.Load(); n != 1 {
|
||||
t.Fatalf("批量调用=%d", n)
|
||||
}
|
||||
if len(lk.lastMobiles) != 100 {
|
||||
t.Fatalf("批量号码数=%d", len(lk.lastMobiles))
|
||||
}
|
||||
}
|
||||
|
||||
// TestAggregator_CallReduction 验收口径:1000 条聚合后批量调用 1 次
|
||||
// (逐号 1000 次 → 1 次,调用次数降 99.9% ≥ 80%)。
|
||||
func TestAggregator_CallReduction(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(lk, time.Hour, 1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
agg.Add(7, "【签名】内容", fmt.Sprintf("1380013%05d", i), int64(i))
|
||||
}
|
||||
added, batch, single := agg.Stats()
|
||||
if added != 1000 || batch != 1 || single != 0 {
|
||||
t.Fatalf("added=%d batch=%d single=%d", added, batch, single)
|
||||
}
|
||||
reduction := 1 - float64(lk.batchCalls.Load())/float64(1000)
|
||||
if reduction < 0.8 {
|
||||
t.Fatalf("调用次数削减 %.1f%% 低于 80%%", reduction*100)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAggregator_WindowFlush 窗口到期统一冲洗(未满阈值)。
|
||||
func TestAggregator_WindowFlush(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(lk, 40*time.Millisecond, 1000)
|
||||
agg.Add(7, "hi", "13800138000", 1)
|
||||
agg.Add(8, "hi", "13800138001", 2) // 不同通道:独立分组
|
||||
if _, b, _ := agg.Stats(); b != 0 {
|
||||
t.Fatalf("不应提前触发: batch=%d", b)
|
||||
}
|
||||
time.Sleep(90 * time.Millisecond)
|
||||
agg.FlushAll()
|
||||
if _, b, s := agg.Stats(); b != 2 || s != 0 {
|
||||
t.Fatalf("窗口冲洗错误: batch=%d single=%d", b, s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAggregator_RunTicker 常驻窗口自动冲洗(Run 路径)。
|
||||
func TestAggregator_RunTicker(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(lk, 30*time.Millisecond, 1000)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go agg.Run(ctx)
|
||||
agg.Add(9, "x", "13800138000", 1)
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, b, _ := agg.Stats(); b >= 1 {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("Run 窗口未触发冲洗")
|
||||
}
|
||||
|
||||
// TestAggregator_BatchFailFallback 批量失败→逐号回退保送达。
|
||||
func TestAggregator_BatchFailFallback(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
lk.failBatch.Store(true)
|
||||
agg := NewSubmitAggregator(lk, time.Hour, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
agg.Add(7, "hi", fmt.Sprintf("1380013%05d", i), int64(i))
|
||||
}
|
||||
if lk.batchCalls.Load() != 1 {
|
||||
t.Fatalf("批量调用=%d", lk.batchCalls.Load())
|
||||
}
|
||||
if n := lk.singleCalls.Load(); n != 10 {
|
||||
t.Fatalf("回退逐号=%d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAggregator_NoBatchLinkFallback 链路无批量能力:逐号兼容路径。
|
||||
func TestAggregator_NoBatchLinkFallback(t *testing.T) {
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(singleOnly{lk}, time.Hour, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
agg.Add(7, "hi", fmt.Sprintf("1380013%05d", i), int64(i))
|
||||
}
|
||||
if n := lk.singleCalls.Load(); n != 5 {
|
||||
t.Fatalf("逐号调用=%d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// singleOnly 只暴露单号接口(包装去批量)。
|
||||
type singleOnly struct{ inner *fakeBatchLink }
|
||||
|
||||
func (s singleOnly) SubmitViaLink(ctx context.Context, channelID int64, mobile, content string) ([]string, error) {
|
||||
return s.inner.SubmitViaLink(ctx, channelID, mobile, content)
|
||||
}
|
||||
|
||||
// TestDispatcher_WithAggregator 分发器聚合接线:任务分发→聚合→批量冲洗→明细终态落库。
|
||||
func TestDispatcher_WithAggregator(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrator().CreateTable(&entity.MessageTask{}, &entity.MessageDetail{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sf, _ := util.NewSnowflake(1)
|
||||
task := entity.MessageTask{TaskNo: "T47", AccountID: 1, ChannelID: 7, SendType: 1}
|
||||
if err := db.Create(&task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
details := make([]entity.MessageDetail, 0, 20)
|
||||
for i := 0; i < 20; i++ {
|
||||
d := entity.MessageDetail{TaskID: task.ID, AccountID: 1,
|
||||
Mobile: fmt.Sprintf("1380013%05d", i), Content: "hi", Status: 0}
|
||||
d.ID = sf.NextID()
|
||||
details = append(details, d)
|
||||
}
|
||||
if err := db.CreateInBatches(details, 100).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lk := &fakeBatchLink{}
|
||||
agg := NewSubmitAggregator(lk, time.Hour, 1000)
|
||||
d := NewChannelDispatcher(db, nil, lk, agg) // rt=nil:task 已置 ChannelID,不走 Pick
|
||||
sent, failed, derr := d.Dispatch(context.Background(), &task)
|
||||
if derr != nil || failed != 0 || sent != 20 {
|
||||
t.Fatalf("dispatch: sent=%d failed=%d err=%v", sent, failed, derr)
|
||||
}
|
||||
if n := lk.batchCalls.Load(); n != 1 {
|
||||
t.Fatalf("批量调用=%d(任务级即时冲洗)", n)
|
||||
}
|
||||
var cnt int64
|
||||
db.Model(&entity.MessageDetail{}).Where("channel_id = ? AND status = ?", 7, detailStSubmitted).Count(&cnt)
|
||||
if cnt != 20 {
|
||||
t.Fatalf("明细终态落库=%d/20", cnt)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// backpressure.go Day 48(技术方案 10.4.4):背压三级水位。
|
||||
//
|
||||
// L1 lag>10 万 → 告警(日志+metrics);
|
||||
// L2 lag>100 万 → 入口限流收紧(写 Redis 水位键,网关侧账号桶容量收至 Σ通道speed);
|
||||
// L3 lag>500 万 → 暂停低优先级投放(消费组 Pause;恢复即 Resume)。
|
||||
//
|
||||
// 水位键由消费者进程写入(30s TTL,采样周期 10s),网关进程只读——跨进程解耦。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/pkg/cache"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// BPLevel 背压水位(0 正常)。
|
||||
type BPLevel int32
|
||||
|
||||
// 三级水位(阈值与开发计划 Day48 对齐)。
|
||||
const (
|
||||
BPNormal BPLevel = iota
|
||||
BPAlert
|
||||
BPTighten
|
||||
BPPause
|
||||
)
|
||||
|
||||
// 背压阈值(lag 条)与采样/键 TTL。
|
||||
const (
|
||||
BPThresholdL1 = 100_000
|
||||
BPThresholdL2 = 1_000_000
|
||||
BPThresholdL3 = 5_000_000
|
||||
BPKeyTTL = 30 * time.Second
|
||||
)
|
||||
|
||||
// BPLevelOf 水位判定(纯函数,单测口径)。
|
||||
func BPLevelOf(lag int64) BPLevel {
|
||||
switch {
|
||||
case lag > BPThresholdL3:
|
||||
return BPPause
|
||||
case lag > BPThresholdL2:
|
||||
return BPTighten
|
||||
case lag > BPThresholdL1:
|
||||
return BPAlert
|
||||
default:
|
||||
return BPNormal
|
||||
}
|
||||
}
|
||||
|
||||
// BPStore 水位存储(Redis 实现;测试可替身)。
|
||||
type BPStore interface {
|
||||
SetLevel(ctx context.Context, level BPLevel, capPerSec int64) error
|
||||
}
|
||||
|
||||
// RedisBPStore 水位键实现:level 与 cap(收紧后的入口预算=Σ通道speed)。
|
||||
type RedisBPStore struct {
|
||||
rc *cache.Client
|
||||
}
|
||||
|
||||
// NewRedisBPStore 构造(rc 可 nil:降级为不动作)。
|
||||
func NewRedisBPStore(rc *cache.Client) *RedisBPStore { return &RedisBPStore{rc: rc} }
|
||||
|
||||
// BPLevelKey/BPCapKey 键名(网关侧 middleware 读取同款)。
|
||||
const (
|
||||
BPLevelKey = "go-sms:bp:level"
|
||||
BPCapKey = "go-sms:bp:cap"
|
||||
)
|
||||
|
||||
// SetLevel 写入水位与入口预算(30s TTL;cap<=0 不写)。
|
||||
func (s *RedisBPStore) SetLevel(ctx context.Context, level BPLevel, capPerSec int64) error {
|
||||
if s.rc == nil {
|
||||
return nil
|
||||
}
|
||||
pipe := s.rc.TxPipeline()
|
||||
pipe.Set(ctx, BPLevelKey, int32(level), BPKeyTTL)
|
||||
if capPerSec > 0 {
|
||||
pipe.Set(ctx, BPCapKey, capPerSec, BPKeyTTL)
|
||||
}
|
||||
_, err := pipe.Exec(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadBPLevel 读当前水位(网关侧收紧判定共用;键缺失/Redis 错=正常)。
|
||||
func ReadBPLevel(ctx context.Context, rc *cache.Client) BPLevel {
|
||||
if rc == nil {
|
||||
return BPNormal
|
||||
}
|
||||
v, err := rc.Get(ctx, BPLevelKey).Result()
|
||||
if err != nil {
|
||||
return BPNormal // 键缺失(redis.Nil)/故障:可用性优先按正常
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return BPNormal
|
||||
}
|
||||
return BPLevel(n)
|
||||
}
|
||||
|
||||
// Backpressure 背压控制器:采样 lag → 水位判定 → 动作。
|
||||
// 恢复语义:水位回落时反向解除(L3→Resume;L2→写回正常水位键)。
|
||||
type Backpressure struct {
|
||||
store BPStore
|
||||
log *zap.Logger
|
||||
pause func() // L3:暂停投放(消费组 Pause;可 nil)
|
||||
resume func() // 恢复
|
||||
capFn func() int64 // Σ通道speed(入口收紧预算;可 nil=不收紧只告警)
|
||||
|
||||
last BPLevel // 上次水位(边缘触发动作,避免每拍重复)
|
||||
}
|
||||
|
||||
// NewBackpressure 构造(pause/resume/capFn 可 nil 降级)。
|
||||
func NewBackpressure(store BPStore, log *zap.Logger,
|
||||
pause, resume func(), capFn func() int64) *Backpressure {
|
||||
return &Backpressure{store: store, log: log, pause: pause, resume: resume, capFn: capFn}
|
||||
}
|
||||
|
||||
// Check 单次采样处理:返回本次水位(边缘动作+持续状态键写入)。
|
||||
func (b *Backpressure) Check(ctx context.Context, lag int64) BPLevel {
|
||||
lv := BPLevelOf(lag)
|
||||
if lv != b.last { // 边缘触发:升降沿各一次
|
||||
b.log.Warn("backpressure_level_changed",
|
||||
zap.Int64("lag", lag), zap.Int32("from", int32(b.last)), zap.Int32("to", int32(lv)))
|
||||
switch {
|
||||
case lv >= BPPause && b.last < BPPause:
|
||||
if b.pause != nil {
|
||||
b.pause()
|
||||
}
|
||||
case lv < BPPause && b.last >= BPPause:
|
||||
if b.resume != nil {
|
||||
b.resume()
|
||||
}
|
||||
}
|
||||
b.last = lv
|
||||
}
|
||||
if b.store != nil { // 持续写入水位键(30s TTL;网关侧据此收紧)
|
||||
var cap int64
|
||||
if lv >= BPTighten && b.capFn != nil {
|
||||
cap = b.capFn()
|
||||
}
|
||||
_ = b.store.SetLevel(ctx, lv, cap)
|
||||
}
|
||||
return lv
|
||||
}
|
||||
|
||||
// Run 周期采样(sample 返回总 lag;err 时按 0 处理一拍)。
|
||||
func (b *Backpressure) Run(ctx context.Context, interval time.Duration, sample func(context.Context) (int64, error)) {
|
||||
tk := time.NewTicker(interval)
|
||||
defer tk.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tk.C:
|
||||
lag, err := sample(ctx)
|
||||
if err != nil {
|
||||
b.log.Warn("backpressure_sample_failed", zap.Error(err))
|
||||
continue
|
||||
}
|
||||
b.Check(ctx, lag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// backpressure_test.go Day 48:三级水位单测——阈值判定/边缘动作(暂停恢复)/
|
||||
// 水位键写入(miniredis)/ReadBPLevel 网关侧读取。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"go-sms/internal/pkg/cache"
|
||||
)
|
||||
|
||||
// TestBPLevelOf 三级阈值(10万/100万/500万,含边界)。
|
||||
func TestBPLevelOf(t *testing.T) {
|
||||
cases := []struct {
|
||||
lag int64
|
||||
want BPLevel
|
||||
}{
|
||||
{0, BPNormal}, {100_000, BPNormal}, {100_001, BPAlert},
|
||||
{1_000_000, BPAlert}, {1_000_001, BPTighten},
|
||||
{5_000_000, BPTighten}, {5_000_001, BPPause},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := BPLevelOf(c.lag); got != c.want {
|
||||
t.Fatalf("BPLevelOf(%d)=%d 期望 %d", c.lag, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeBPStore 捕获写入。
|
||||
type fakeBPStore struct {
|
||||
levels []BPLevel
|
||||
caps []int64
|
||||
}
|
||||
|
||||
func (f *fakeBPStore) SetLevel(_ context.Context, l BPLevel, cap int64) error {
|
||||
f.levels = append(f.levels, l)
|
||||
f.caps = append(f.caps, cap)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestBPCheckEdgeActions 边缘动作:L3 升沿 pause 一次;回落 resume 一次;
|
||||
// L2 持续写水位键(每拍)但动作不重复。
|
||||
func TestBPCheckEdgeActions(t *testing.T) {
|
||||
store := &fakeBPStore{}
|
||||
paused, resumed := 0, 0
|
||||
bp := NewBackpressure(store, zap.NewNop(),
|
||||
func() { paused++ }, func() { resumed++ }, func() int64 { return 3000 })
|
||||
ctx := context.Background()
|
||||
|
||||
bp.Check(ctx, 50_000) // 正常
|
||||
bp.Check(ctx, 100_001) // →L1
|
||||
bp.Check(ctx, 1_000_001) // →L2(收紧键带 cap)
|
||||
bp.Check(ctx, 1_500_000) // L2 持续
|
||||
bp.Check(ctx, 5_000_001) // →L3 pause
|
||||
bp.Check(ctx, 6_000_000) // L3 持续
|
||||
bp.Check(ctx, 90_000) // →正常 resume
|
||||
|
||||
if paused != 1 || resumed != 1 {
|
||||
t.Fatalf("pause=%d resume=%d 期望各 1", paused, resumed)
|
||||
}
|
||||
if len(store.levels) != 7 {
|
||||
t.Fatalf("水位键每拍写入: %d", len(store.levels))
|
||||
}
|
||||
// L2/L3 期间(第 3~6 拍)携带入口收紧预算;末拍回落不带。
|
||||
for i := 2; i < len(store.caps)-1; i++ {
|
||||
if store.caps[i] != 3000 {
|
||||
t.Fatalf("第 %d 拍 cap=%d 期望 3000", i, store.caps[i])
|
||||
}
|
||||
}
|
||||
if last := store.caps[len(store.caps)-1]; last != 0 {
|
||||
t.Fatalf("回落拍 cap=%d 期望 0", last)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRedisBPStoreRoundTrip miniredis 写读 + ReadBPLevel 缺失键=正常。
|
||||
func TestRedisBPStoreRoundTrip(t *testing.T) {
|
||||
mr := miniredis.RunT(t)
|
||||
rc, err := cache.New(cache.Options{Addrs: []string{mr.Addr()}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewRedisBPStore(rc)
|
||||
ctx := context.Background()
|
||||
|
||||
if got := ReadBPLevel(ctx, rc); got != BPNormal {
|
||||
t.Fatalf("缺键应正常: %d", got)
|
||||
}
|
||||
if err := store.SetLevel(ctx, BPTighten, 3000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := ReadBPLevel(ctx, rc); got != BPTighten {
|
||||
t.Fatalf("读水位 = %d 期望 L2", got)
|
||||
}
|
||||
if v, err := rc.Get(ctx, BPCapKey).Int64(); err != nil || v != 3000 {
|
||||
t.Fatalf("cap 键 = %d err=%v", v, err)
|
||||
}
|
||||
// nil store 降级不动作。
|
||||
if err := NewRedisBPStore(nil).SetLevel(ctx, BPPause, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// batchwriter.go Day 48(技术方案 10.4.3,开发计划④):明细终态批量落库 writer。
|
||||
// 攒批(默认 500 条/批)× N 并发 worker 异步 UPDATE ... WHERE id IN(...),
|
||||
// 保证 MySQL 批量写入不阻塞 Kafka 消费(lag 不因落库增长)。
|
||||
// Add 非阻塞:通道满/已关闭返回 false,调用方直写兜底(可用性优先)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// BatchWriterDefaults 攒批参数(与开发计划对齐:500 条/批×10 writer)。
|
||||
const (
|
||||
DefaultWriterBatch = 500
|
||||
DefaultWriterWorker = 10
|
||||
WriterFlushEvery = 200 * time.Millisecond // 攒批等待上限(低流量不迟滞)
|
||||
WriterQueue = 4096 // 入队缓冲(批元素数)
|
||||
)
|
||||
|
||||
// DetailUpdate 一批同终态明细(id 列表可能 >batchN,写时分片)。
|
||||
type DetailUpdate struct {
|
||||
IDs []int64
|
||||
Status int8
|
||||
ChannelID int64
|
||||
ErrorCode string
|
||||
SendAt time.Time
|
||||
}
|
||||
|
||||
// DetailWriter 异步批量明细终态回写。
|
||||
type DetailWriter struct {
|
||||
db *gorm.DB
|
||||
batch int
|
||||
ch chan DetailUpdate
|
||||
wg sync.WaitGroup
|
||||
once sync.Once
|
||||
closed atomic.Bool // 先置位再关 chan:Add 据此拒收(防 send on closed channel)
|
||||
}
|
||||
|
||||
// NewDetailWriter 构造(batch/workers 零值取默认)。
|
||||
func NewDetailWriter(db *gorm.DB, batch, workers int) *DetailWriter {
|
||||
if batch <= 0 {
|
||||
batch = DefaultWriterBatch
|
||||
}
|
||||
if workers <= 0 {
|
||||
workers = DefaultWriterWorker
|
||||
}
|
||||
w := &DetailWriter{db: db, batch: batch, ch: make(chan DetailUpdate, WriterQueue)}
|
||||
w.wg.Add(workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
go w.worker()
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// Add 入队(非阻塞;false=已关闭或缓冲满→调用方直写)。
|
||||
func (w *DetailWriter) Add(u DetailUpdate) bool {
|
||||
if len(u.IDs) == 0 {
|
||||
return true
|
||||
}
|
||||
if w.closed.Load() {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case w.ch <- u:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// worker 单消费者:收到即按 batch 分片落库(元素内 IDs 已是同终态批)。
|
||||
func (w *DetailWriter) worker() {
|
||||
defer w.wg.Done()
|
||||
for u := range w.ch {
|
||||
w.apply(u)
|
||||
}
|
||||
}
|
||||
|
||||
// apply 分片落库(每片 ≤batch 个 id 的 UPDATE IN;失败静默——终态可由
|
||||
// 对账/重扫补偿,与 markDetails 同容错口径)。
|
||||
func (w *DetailWriter) apply(u DetailUpdate) {
|
||||
if ec := []rune(u.ErrorCode); len(ec) > 16 { // 与 markDetails 同截断
|
||||
u.ErrorCode = string(ec[:16])
|
||||
}
|
||||
if u.SendAt.IsZero() {
|
||||
u.SendAt = time.Now()
|
||||
}
|
||||
for start := 0; start < len(u.IDs); start += w.batch {
|
||||
end := start + w.batch
|
||||
if end > len(u.IDs) {
|
||||
end = len(u.IDs)
|
||||
}
|
||||
_ = w.db.Model(&entity.MessageDetail{}).Where("id IN ?", u.IDs[start:end]).
|
||||
Updates(map[string]any{
|
||||
"status": u.Status, "channel_id": u.ChannelID,
|
||||
"error_code": u.ErrorCode, "send_at": u.SendAt,
|
||||
}).Error
|
||||
}
|
||||
}
|
||||
|
||||
// Close 排空落库并退出 worker(优雅停机调用)。
|
||||
func (w *DetailWriter) Close() {
|
||||
w.once.Do(func() {
|
||||
w.closed.Store(true)
|
||||
close(w.ch)
|
||||
w.wg.Wait()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// batchwriter_test.go Day 48:明细终态批量落库 writer 单测——分片落库/截断/
|
||||
// Close 冲刷/空批。
|
||||
package send
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
)
|
||||
|
||||
func newWriterDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrator().CreateTable(&entity.MessageDetail{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func mkDetails(t *testing.T, db *gorm.DB, n int) []int64 {
|
||||
t.Helper()
|
||||
ids := make([]int64, n)
|
||||
batch := make([]entity.MessageDetail, n)
|
||||
for i := 0; i < n; i++ {
|
||||
ids[i] = int64(100 + i)
|
||||
batch[i] = entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: ids[i]},
|
||||
TaskID: 1, Mobile: "13800138000", Status: 0}
|
||||
}
|
||||
if err := db.CreateInBatches(batch, 500).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestDetailWriterBatchAndSlice 1200 条→500/500/200 三片全落;错误码 16 字符截断。
|
||||
func TestDetailWriterBatchAndSlice(t *testing.T) {
|
||||
db := newWriterDB(t)
|
||||
ids := mkDetails(t, db, 1200)
|
||||
w := NewDetailWriter(db, 500, 2)
|
||||
|
||||
long := "UT:0001-" + string(make([]byte, 64))
|
||||
if !w.Add(DetailUpdate{IDs: ids, Status: 1, ChannelID: 7, ErrorCode: long, SendAt: time.Now()}) {
|
||||
t.Fatal("入队失败")
|
||||
}
|
||||
w.Close() // 冲刷+退出
|
||||
|
||||
var done int64
|
||||
db.Model(&entity.MessageDetail{}).Where("status = ? AND channel_id = ?", 1, 7).Count(&done)
|
||||
if done != 1200 {
|
||||
t.Fatalf("终态落库 = %d, 期望 1200", done)
|
||||
}
|
||||
var d entity.MessageDetail
|
||||
db.First(&d, ids[0])
|
||||
if ec := []rune(d.ErrorCode); len(ec) != 16 {
|
||||
t.Fatalf("错误码截断 = %d 字符", len(ec))
|
||||
}
|
||||
if d.SendAt == nil {
|
||||
t.Fatal("send_at 未落")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDetailWriterEmptyAndClosed 空 IDs 直成功;关闭后拒绝入队。
|
||||
func TestDetailWriterEmptyAndClosed(t *testing.T) {
|
||||
db := newWriterDB(t)
|
||||
w := NewDetailWriter(db, 0, 0) // 零值取默认
|
||||
if !w.Add(DetailUpdate{}) {
|
||||
t.Fatal("空批应成功")
|
||||
}
|
||||
w.Close()
|
||||
if w.Add(DetailUpdate{IDs: []int64{1}, Status: 1}) {
|
||||
t.Fatal("关闭后应拒绝")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
// consumer.go Day 48:submit 消费者——sms-submit 事件驱动立即任务下发。
|
||||
// 设计与 timer 同构(Kafka 事件=加速器,MySQL 原子认领=事实源):
|
||||
// - HandlePayload:解析事件 → claim(UPDATE status 0→1 WHERE 审核可发+send_type∈{1,2})
|
||||
// →RowsAffected=0 直接成功(已处理/待审/定时域,天然幂等去重);
|
||||
// - ReclaimScanner:5s 补偿扫描同域任务(事件丢失/审核通过后无人认领的兜底,
|
||||
// 顺带修复"手动审核通过后任务停滞"缺陷);
|
||||
// - 分发复用 ChannelDispatcher(router 选路→聚合/直发链路→明细终态);
|
||||
// 系统性错误回滚 status 1→0 留待重扫(claim 原子性保证重试幂等)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/service/balance"
|
||||
"go-sms/internal/service/interceptor"
|
||||
"go-sms/internal/util"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// SubmitEvent sms-submit 事件载荷(Day46 openapi 五字段向后兼容+Day48 扩展+Day52 R2 明细全量)。
|
||||
type SubmitEvent struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
TaskNo string `json:"task_no"`
|
||||
AccountID int64 `json:"account_id"`
|
||||
SendType int8 `json:"send_type"`
|
||||
PassCount int `json:"pass_count"` // 过拦截条数(0=全拦,消费者跳过;Day52 起由 details 推导)
|
||||
Source string `json:"source"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Business string `json:"business,omitempty"` // Day 49:sms/video(biz_type 路由;空=sms 兼容 Day48 旧载荷)
|
||||
// Day52 R2:明细全量(入口预生成雪花 ID+拦截终态;消费侧批量落库,入口事务零明细写)。
|
||||
// 空=Day48 旧格式/兜底扫描场景,消费侧不落(明细已由降级路径或旧版本落库)。
|
||||
Details []EventDetail `json:"details,omitempty"`
|
||||
// P0-1(Day 63)接入异步化:Deferred=true 表示受理侧走 SubmitFast 快路径
|
||||
// (Validate+预扣+DetailID 预生成+投递,零 DB 写),task 落库/拦截判定/退费/
|
||||
// 审核分流全部由消费侧补全(handleDeferred);TaskID=0(自增主键消费侧生成)。
|
||||
Deferred bool `json:"deferred,omitempty"`
|
||||
// TaskMeta Deferred 专用:任务行补建字段(与 entity.MessageTask 对齐;
|
||||
// 旧事件零携带,消费侧按非 Deferred 老路径处理)。
|
||||
TaskMeta *SubmitTaskMeta `json:"task_meta,omitempty"`
|
||||
}
|
||||
|
||||
// SubmitTaskMeta 快路径任务补建载荷(受理侧未落库,消费侧 INSERT 重建)。
|
||||
type SubmitTaskMeta struct {
|
||||
Content string `json:"content"`
|
||||
Sign string `json:"sign"`
|
||||
MobileCount int `json:"mobile_count"`
|
||||
FeeTotal float64 `json:"fee_total"`
|
||||
SubmitIP string `json:"submit_ip"`
|
||||
CallData string `json:"call_data"`
|
||||
Source int8 `json:"source"` // 任务来源 int8(WEB=4/CMPP=2/SMPP=3/API=1)
|
||||
ScheduleAt string `json:"schedule_at,omitempty"` // RFC3339,空=非定时
|
||||
}
|
||||
|
||||
// EventDetail 明细行载荷(task_id/account_id 公共字段在事件级;字段与 entity.MessageDetail 对齐)。
|
||||
type EventDetail struct {
|
||||
ID int64 `json:"id"` // 雪花主键(入口预生成,回执配对键)
|
||||
Mobile string `json:"mobile"`
|
||||
Content string `json:"content"`
|
||||
Status int8 `json:"status"` // 0=存活 5=拦截终态(受理期已退费)
|
||||
Fee float64 `json:"fee"` // 计费条数
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
ExtCode string `json:"ext_code,omitempty"`
|
||||
CallData string `json:"call_data,omitempty"`
|
||||
// Day66:明细单表化冗余(空=旧载荷,persistDetailsDB 兜底 ev.Business/'sms')。
|
||||
Business string `json:"business,omitempty"`
|
||||
Source int8 `json:"source,omitempty"` // 0=旧载荷→兜底 API
|
||||
}
|
||||
|
||||
// SubmitConsumer 事件消费者。
|
||||
type SubmitConsumer struct {
|
||||
db *gorm.DB
|
||||
dp TaskDispatcher
|
||||
log *zap.Logger
|
||||
blocked BlockedDeliverSink // Day62c:拦截终态 CMPP 下发出口(nil=静默)
|
||||
// P0-1(Day 63)Deferred 补全依赖(受理快路径的同步链后移;nil=对应环节降级)。
|
||||
chain *interceptor.Chain // 拦截器链(nil=全放行,兼容最小装配)
|
||||
rt TaskRouter // 审核分流(nil=停留待审,48h Scanner 兜底)
|
||||
bal balance.Store // 拦截/审核拒退费(nil=不退,对账 Reconciler 兜底)
|
||||
}
|
||||
|
||||
// BlockedDeliverSink Day62c:受理期拦截终态(status=5)下发出口。
|
||||
// 背景:拦截明细不经 finishDetail(上游回执路径),CMPP 客户收不到任何状态
|
||||
// (真机报障:8 条 ISC:004 全拦,客户端一直等回执)。接口在 send 域定义、
|
||||
// 装配层适配 report.DeliverEvent,避免 send↔report 循环依赖。
|
||||
type BlockedDeliverSink interface {
|
||||
// PushBlocked errCode 透传(ISC:004 等);submitAt=MMDDHHMMSS;尽力而为不返回错误。
|
||||
PushBlocked(ctx context.Context, accountID, detailID int64, mobile, errCode, submitAt string)
|
||||
}
|
||||
|
||||
// WithBlockedDeliverSink 注入拦截终态下发出口(Day62c;链式)。
|
||||
func (c *SubmitConsumer) WithBlockedDeliverSink(s BlockedDeliverSink) *SubmitConsumer {
|
||||
c.blocked = s
|
||||
return c
|
||||
}
|
||||
|
||||
// WithConsumerChain 注入拦截器链(P0-1 Deferred 补全;链式)。
|
||||
func (c *SubmitConsumer) WithConsumerChain(ch *interceptor.Chain) *SubmitConsumer {
|
||||
c.chain = ch
|
||||
return c
|
||||
}
|
||||
|
||||
// WithConsumerRouter 注入审核分流(P0-1 Deferred 补全;链式)。
|
||||
func (c *SubmitConsumer) WithConsumerRouter(rt TaskRouter) *SubmitConsumer {
|
||||
c.rt = rt
|
||||
return c
|
||||
}
|
||||
|
||||
// WithConsumerBalance 注入资金 Store(P0-1 Deferred 退费;链式)。
|
||||
func (c *SubmitConsumer) WithConsumerBalance(b balance.Store) *SubmitConsumer {
|
||||
c.bal = b
|
||||
return c
|
||||
}
|
||||
|
||||
// NewSubmitConsumer 构造。
|
||||
func NewSubmitConsumer(db *gorm.DB, dp TaskDispatcher, log *zap.Logger) *SubmitConsumer {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &SubmitConsumer{db: db, dp: dp, log: log}
|
||||
}
|
||||
|
||||
// HandlePayload 处理单条事件(装配层适配 sarama 消息取 Value)。
|
||||
// 解析失败返回错误(进重试→死信,毒丸不阻塞分区);业务态跳过返回 nil。
|
||||
// Day52 R2:明细批量落库先于认领/下发(回执配对键先于 submit 存在;
|
||||
// 雪花主键冲突 DoNothing=重投幂等;失败返回错误进重试——明细为对账事实源不能丢)。
|
||||
func (c *SubmitConsumer) HandlePayload(ctx context.Context, payload []byte) error {
|
||||
var ev SubmitEvent
|
||||
if err := json.Unmarshal(payload, &ev); err != nil {
|
||||
return err
|
||||
}
|
||||
// P0-1(Day 63)快路径补全分支:受理侧零 DB 写,消费侧补建任务/拦截/退费/审核。
|
||||
if ev.Deferred {
|
||||
return c.handleDeferred(ctx, &ev)
|
||||
}
|
||||
if ev.TaskID == 0 {
|
||||
return nil // 无任务标识:忽略(防御旧格式)
|
||||
}
|
||||
if err := c.persistDetails(ctx, &ev); err != nil {
|
||||
return fmt.Errorf("明细落库(task %d): %w", ev.TaskID, err)
|
||||
}
|
||||
if ev.PassCount == 0 { // 零值兼容 Day46 事件(未带 pass_count):按任务现状认领
|
||||
ev.PassCount = 1
|
||||
}
|
||||
if !c.claim(ctx, ev.TaskID) {
|
||||
return nil // 已处理/待审/定时域/全拦终态:幂等成功(明细已落)
|
||||
}
|
||||
return c.dispatch(ctx, ev.TaskID)
|
||||
}
|
||||
|
||||
// handleDeferred P0-1(Day 63)快路径事件补全:受理侧 SubmitFast 零 DB 写,
|
||||
// 本函数在消费侧重建完整受理语义(与 SubmitService.Submit 同口径):
|
||||
// ①拦截器链判定(命中→明细终态 5+拦截费退)②task INSERT 补建(uk_task_no
|
||||
// 冲突=重投幂等:查回既有 ID,退费仅首次执行)③明细落库+拦截回执桥(Day62c)
|
||||
// ④全拦→任务终态 ⑤审核分流(拒绝→存活费退)⑥claim/dispatch(待审/定时自然跳过)。
|
||||
func (c *SubmitConsumer) handleDeferred(ctx context.Context, ev *SubmitEvent) error {
|
||||
if len(ev.Details) == 0 || ev.TaskMeta == nil {
|
||||
return nil // 防御:Deferred 事件必带明细与任务载荷(缺失静默,防毒丸循环重试)
|
||||
}
|
||||
// ①拦截判定(nil=全放行,兼容最小装配;请求级快照单事件构造一次)。
|
||||
var blockedFee float64
|
||||
if c.chain != nil {
|
||||
mobiles := make([]string, 0, len(ev.Details))
|
||||
for i := range ev.Details {
|
||||
mobiles = append(mobiles, ev.Details[i].Mobile)
|
||||
}
|
||||
sc := c.chain.NewScope(ctx, ev.AccountID, mobiles)
|
||||
for i := range ev.Details {
|
||||
d := &ev.Details[i]
|
||||
if b := c.chain.Check(ctx, &interceptor.Req{
|
||||
TaskNo: ev.TaskNo, AccountID: ev.AccountID, Mobile: d.Mobile,
|
||||
Content: d.Content, SendType: ev.SendType, Scope: sc,
|
||||
}); b != nil {
|
||||
d.Status = 5
|
||||
d.ErrorCode = util.Truncate(b.Code, 16)
|
||||
blockedFee += d.Fee
|
||||
}
|
||||
}
|
||||
}
|
||||
// ②任务补建(自增主键消费侧生成;uk_task_no 冲突=事件重投:取回既有 ID)。
|
||||
var scheduleAt *time.Time
|
||||
if ev.TaskMeta.ScheduleAt != "" {
|
||||
if at, perr := time.Parse(time.RFC3339, ev.TaskMeta.ScheduleAt); perr == nil {
|
||||
scheduleAt = &at
|
||||
}
|
||||
}
|
||||
task := entity.MessageTask{
|
||||
TaskNo: ev.TaskNo, AccountID: ev.AccountID, SendType: ev.SendType,
|
||||
Content: ev.TaskMeta.Content, Sign: ev.TaskMeta.Sign,
|
||||
MobileCount: ev.TaskMeta.MobileCount, FeeTotal: ev.TaskMeta.FeeTotal,
|
||||
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt,
|
||||
SubmitIP: ev.TaskMeta.SubmitIP, CallData: util.Truncate(ev.TaskMeta.CallData, 64),
|
||||
Source: ev.TaskMeta.Source,
|
||||
}
|
||||
// ②④任务补建+明细落库(Day65 合一事务:单号事件原先两写事务→一,省一次
|
||||
// commit fsync 往返;失败整体回滚重试,幂等锚=uk_task_no+明细雪花主键)。
|
||||
firstInsert := false
|
||||
skipRoute := false // 重投幂等:任务已分流(audit≠0)则跳过 Route(ISC:037 防死信)
|
||||
var inserted int64
|
||||
txErr := c.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Create(&task)
|
||||
if res.Error == nil {
|
||||
firstInsert = true
|
||||
} else if isDupTaskNo(res.Error) {
|
||||
// 重投幂等:查回既有任务续跑(明细 OnConflict/claim 原子幂等;退费不重复执行)。
|
||||
var exist entity.MessageTask
|
||||
if err := tx.Select("id", "audit_status").
|
||||
Where("task_no = ?", ev.TaskNo).Take(&exist).Error; err != nil {
|
||||
return fmt.Errorf("deferred 重投查任务: %w", err)
|
||||
}
|
||||
task.ID = exist.ID
|
||||
if exist.AuditStatus != 0 {
|
||||
skipRoute = true
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("deferred 建任务: %w", res.Error)
|
||||
}
|
||||
ev.TaskID = task.ID
|
||||
var perr error
|
||||
inserted, perr = persistDetailsDB(tx, ctx, ev)
|
||||
return perr
|
||||
})
|
||||
if txErr != nil {
|
||||
return fmt.Errorf("明细落库(task %s): %w", ev.TaskNo, txErr)
|
||||
}
|
||||
// ③拦截号退费(仅首次建任务执行;预扣在受理侧,此处对冲被拦号——事务提交后
|
||||
// 执行,Redis 侧对冲不参与 DB 回滚)。拦截回执桥同置事务外(RowsAffected 防重)。
|
||||
if firstInsert && blockedFee > 0 && c.bal != nil {
|
||||
_ = c.bal.Refund(ctx, ev.AccountID, int64(blockedFee), ev.TaskNo, "拦截号码退费")
|
||||
}
|
||||
c.pushBlocked(ctx, ev, inserted)
|
||||
// ⑤全拦:任务直接终态(与 Submit 同口径;拦截回执已由桥推送)。
|
||||
pass := 0
|
||||
for i := range ev.Details {
|
||||
if ev.Details[i].Status == 0 {
|
||||
pass++
|
||||
}
|
||||
}
|
||||
if pass == 0 {
|
||||
_ = c.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", task.ID, 0).
|
||||
Updates(map[string]any{
|
||||
"status": taskStDone, "fail_count": len(ev.Details), "finished_at": time.Now(),
|
||||
}).Error
|
||||
return nil
|
||||
}
|
||||
// ⑥审核分流(nil=停留待审,48h Scanner 兜底;拒绝→存活费退;重投已分流跳过)。
|
||||
if c.rt != nil && !skipRoute {
|
||||
t2, _, rerr := c.rt.Route(ctx, task.ID)
|
||||
if rerr != nil {
|
||||
return fmt.Errorf("deferred 审核分流(task %d): %w", task.ID, rerr)
|
||||
}
|
||||
if t2 != nil && t2.AuditStatus == 2 && c.bal != nil {
|
||||
_ = c.bal.Refund(ctx, ev.AccountID,
|
||||
int64(ev.TaskMeta.FeeTotal)-int64(blockedFee), ev.TaskNo, "审核拒绝退费")
|
||||
}
|
||||
}
|
||||
// ⑦认领+分发(待审/定时域 claim 自然跳过;已处理幂等成功)。
|
||||
if !c.claim(ctx, task.ID) {
|
||||
return nil
|
||||
}
|
||||
return c.dispatch(ctx, task.ID)
|
||||
}
|
||||
|
||||
// isDupTaskNo 唯一键冲突判定(MySQL 1062/DUPLICATE 与 SQLite 兼容,同 Submit 口径)。
|
||||
func isDupTaskNo(err error) bool {
|
||||
msg := strings.ToUpper(err.Error())
|
||||
return strings.Contains(msg, "DUPLICATE") || strings.Contains(msg, "1062") ||
|
||||
strings.Contains(msg, "UNIQUE CONSTRAINT")
|
||||
}
|
||||
|
||||
// 定时/全拦事件同样落明细后由 claim 语义自然跳过下发;旧格式无 details 直通。
|
||||
// Day62c:落库成功且本轮实际插入(RowsAffected>0,重投幂等防重)时,对拦截终态行
|
||||
// (status=5)且 task.source=CMPP 逐条推送下发事件——拦截明细无上游回执可等,
|
||||
// 不推则 CMPP 客户永远收不到状态(真机报障实证)。
|
||||
// Day65:内核拆出 persistDetailsDB(exec)——deferred 路径与任务补建同事务执行。
|
||||
func (c *SubmitConsumer) persistDetails(ctx context.Context, ev *SubmitEvent) error {
|
||||
inserted, err := persistDetailsDB(c.db.WithContext(ctx), ctx, ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.pushBlocked(ctx, ev, inserted)
|
||||
return nil
|
||||
}
|
||||
|
||||
// persistDetailsDB 明细批量落库(exec=连接或事务;返回本轮实际插入行数——
|
||||
// 重投幂等锚=雪花主键 OnConflict DoNothing)。
|
||||
func persistDetailsDB(exec *gorm.DB, ctx context.Context, ev *SubmitEvent) (int64, error) {
|
||||
if len(ev.Details) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
rows := make([]entity.MessageDetail, 0, len(ev.Details))
|
||||
for i := range ev.Details {
|
||||
d := &ev.Details[i]
|
||||
// Day66:business/source 冗余透传;旧载荷兜底(ev.Business 空=sms 兼容 Day48;
|
||||
// source 0=API 缺省——与 task 侧 Normalize 口径一致)。
|
||||
biz, src := d.Business, d.Source
|
||||
if biz == "" {
|
||||
biz = ev.Business
|
||||
if biz == "" {
|
||||
biz = "sms"
|
||||
}
|
||||
}
|
||||
if src == 0 {
|
||||
src = TaskSourceAPI
|
||||
}
|
||||
rows = append(rows, entity.MessageDetail{
|
||||
SnowflakeModel: entity.SnowflakeModel{ID: d.ID},
|
||||
TaskID: ev.TaskID,
|
||||
AccountID: ev.AccountID,
|
||||
Mobile: d.Mobile,
|
||||
Content: d.Content,
|
||||
Status: d.Status,
|
||||
Fee: d.Fee,
|
||||
ErrorCode: d.ErrorCode,
|
||||
ExtCode: d.ExtCode,
|
||||
CallData: d.CallData,
|
||||
Business: biz,
|
||||
Source: src,
|
||||
})
|
||||
}
|
||||
res := exec.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
CreateInBatches(rows, 500)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
// pushBlocked 拦截终态下发(Day62c):本轮新插入才推(RowsAffected=0=纯重投跳过;
|
||||
// 批内混合插入的极端重投重复可容忍,客户端按 Stat 幂等处理)。
|
||||
func (c *SubmitConsumer) pushBlocked(ctx context.Context, ev *SubmitEvent, inserted int64) {
|
||||
if c.blocked == nil || inserted == 0 {
|
||||
return
|
||||
}
|
||||
hasBlocked := false
|
||||
for i := range ev.Details {
|
||||
if ev.Details[i].Status == 5 {
|
||||
hasBlocked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasBlocked {
|
||||
return
|
||||
}
|
||||
// 事件不含 task.source 数值(入口字符串标识),查一次任务来源;非 CMPP 短路零开销。
|
||||
var source int8
|
||||
if err := c.db.WithContext(ctx).
|
||||
Table("message_task").Select("source").Where("id = ?", ev.TaskID).
|
||||
Take(&source).Error; err != nil {
|
||||
c.log.Warn("blocked_deliver_source_lookup_failed",
|
||||
zap.Int64("task_id", ev.TaskID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
if source != TaskSourceCMPP {
|
||||
return // HTTP/控制台/SMPP 来源无 CMPP 会话诉求(SMPP 下发另立项)
|
||||
}
|
||||
submitAt := time.Now().Format("0102150405") // CMPP MMDDHHMMSS
|
||||
for i := range ev.Details {
|
||||
d := &ev.Details[i]
|
||||
if d.Status != 5 {
|
||||
continue
|
||||
}
|
||||
c.blocked.PushBlocked(ctx, ev.AccountID, d.ID, d.Mobile, d.ErrorCode, submitAt)
|
||||
}
|
||||
}
|
||||
|
||||
// claim 原子认领(与 timer.claim 同构;send_type∈{1,2} 立即/个性域)。
|
||||
func (c *SubmitConsumer) claim(ctx context.Context, id int64) bool {
|
||||
res := c.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = 0 AND audit_status IN (1, 3) AND send_type IN (1, 2)", id).
|
||||
Update("status", taskStSending)
|
||||
return res.RowsAffected == 1
|
||||
}
|
||||
|
||||
// dispatch 分发并落终态(系统性错误回滚 1→0 留待重扫)。
|
||||
func (c *SubmitConsumer) dispatch(ctx context.Context, id int64) error {
|
||||
var task entity.MessageTask
|
||||
if err := c.db.WithContext(ctx).First(&task, id).Error; err != nil {
|
||||
return c.rollback(ctx, id)
|
||||
}
|
||||
sent, failed, derr := c.dp.Dispatch(ctx, &task)
|
||||
if derr != nil {
|
||||
// Day62d:陈年孤儿任务(旧格式无明细,事件永不再来)一次性终态结案——
|
||||
// 否则 ReclaimScanner 5s/轮死循环重试(dev 实证 task 343 刷 warn 两日)。
|
||||
// 1h 宽限覆盖 Day52 事件在途窗口;正常任务明细早已落库。
|
||||
if errors.Is(derr, ErrDetailsNotReady) && time.Since(task.CreatedAt) > time.Hour {
|
||||
c.log.Warn("orphan_task_finalized",
|
||||
zap.Int64("task_id", id), zap.Time("created_at", task.CreatedAt))
|
||||
res := c.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", id, taskStSending).
|
||||
Updates(map[string]any{"status": taskStDone, "finished_at": time.Now()})
|
||||
if res.Error == nil && res.RowsAffected > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
c.log.Warn("submit_dispatch_rollback", zap.Int64("task_id", id), zap.Error(derr))
|
||||
return c.rollback(ctx, id)
|
||||
}
|
||||
res := c.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", id, taskStSending).
|
||||
Updates(map[string]any{
|
||||
"status": taskStDone, "success_count": sent, "fail_count": failed,
|
||||
"finished_at": time.Now(),
|
||||
})
|
||||
if res.Error != nil || res.RowsAffected == 0 {
|
||||
return nil // 并发终态:以先写者为准
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rollback 认领回退(status 1→0,下轮重扫;幂等由 claim 保证)。
|
||||
func (c *SubmitConsumer) rollback(ctx context.Context, id int64) error {
|
||||
return c.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", id, taskStSending).
|
||||
Update("status", 0).Error
|
||||
}
|
||||
|
||||
// ReclaimScanner 补偿扫描(5s/轮,单轮 batch 条;48h 内同域任务)。
|
||||
type ReclaimScanner struct {
|
||||
db *gorm.DB
|
||||
sc *SubmitConsumer
|
||||
batch int
|
||||
}
|
||||
|
||||
// NewReclaimScanner 构造。
|
||||
func NewReclaimScanner(db *gorm.DB, dp TaskDispatcher, log *zap.Logger) *ReclaimScanner {
|
||||
return &ReclaimScanner{db: db, sc: NewSubmitConsumer(db, dp, log), batch: 100}
|
||||
}
|
||||
|
||||
// WithBatch 覆写单轮上限(测试)。
|
||||
func (s *ReclaimScanner) WithBatch(n int) *ReclaimScanner { s.batch = n; return s }
|
||||
|
||||
// ScanOnce 单轮:捞同域待发任务逐个认领分发(claim 失败即跳过)。
|
||||
func (s *ReclaimScanner) ScanOnce(ctx context.Context) (claimed, done int, err error) {
|
||||
var ids []int64
|
||||
if err = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("status = 0 AND audit_status IN (1, 3) AND send_type IN (1, 2)"+
|
||||
" AND created_at > ?", time.Now().Add(-48*time.Hour)).
|
||||
Limit(s.batch).Pluck("id", &ids).Error; err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
for _, id := range ids {
|
||||
if !s.sc.claim(ctx, id) {
|
||||
continue
|
||||
}
|
||||
claimed++
|
||||
if derr := s.sc.dispatch(ctx, id); derr == nil {
|
||||
done++
|
||||
}
|
||||
}
|
||||
return claimed, done, nil
|
||||
}
|
||||
|
||||
// Run 周期扫描(默认 5s;随 ctx 退出)。
|
||||
func (s *ReclaimScanner) Run(ctx context.Context, interval time.Duration) {
|
||||
tk := time.NewTicker(interval)
|
||||
defer tk.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tk.C:
|
||||
if _, _, err := s.ScanOnce(ctx); err != nil {
|
||||
continue // 单轮失败不退出(下轮重试)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// consumer_test.go Day 48:submit 消费者单测——事件认领分发终态/幂等重投/
|
||||
// 定时域不认领/补偿扫描(审核通过即发)/毒丸载荷回死信口径。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// mkImmediateTask 直插立即任务(audit 默认免审 3;sendType 默认群发 1)。
|
||||
func mkImmediateTask(t *testing.T, db *gorm.DB, audit int8, sendType int8) *entity.MessageTask {
|
||||
t.Helper()
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "CS" + time.Now().Format("150405.000000000"), AccountID: 1001,
|
||||
SendType: sendType, Content: "【店】测试", Sign: "店",
|
||||
MobileCount: 2, AuditStatus: audit, Status: 0,
|
||||
}
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
d := entity.MessageDetail{TaskID: task.ID, AccountID: 1001,
|
||||
Mobile: "1380013800", Content: task.Content, Status: 0}
|
||||
d.ID = int64(9100000000 + task.ID*10 + int64(i))
|
||||
if err := db.Create(&d).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
func evPayload(t *testing.T, task *entity.MessageTask, pass int) []byte {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(SubmitEvent{TaskID: task.ID, TaskNo: task.TaskNo,
|
||||
AccountID: task.AccountID, SendType: task.SendType, PassCount: pass})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// TestConsumerHandleClaimDispatch 事件→认领→分发→终态 2+计数回填。
|
||||
func TestConsumerHandleClaimDispatch(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := mkImmediateTask(t, db, 3, 1)
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
|
||||
if err := sc.HandlePayload(context.Background(), evPayload(t, task, 2)); err != nil {
|
||||
t.Fatalf("HandlePayload err=%v", err)
|
||||
}
|
||||
if len(dp.calls) != 1 || dp.calls[0] != task.ID {
|
||||
t.Fatalf("分发调用缺失: %v", dp.calls)
|
||||
}
|
||||
got := getTask(t, db, task.ID)
|
||||
if got.Status != 2 || got.SuccessCount != 2 || got.FinishedAt == nil {
|
||||
t.Fatalf("终态错: status=%d sent=%d fin=%v", got.Status, got.SuccessCount, got.FinishedAt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerIdempotentReplay 重投幂等:已终态任务再消费→零动作成功。
|
||||
func TestConsumerIdempotentReplay(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := mkImmediateTask(t, db, 3, 1)
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
for i := 0; i < 3; i++ { // 事件重投 3 次
|
||||
if err := sc.HandlePayload(context.Background(), evPayload(t, task, 2)); err != nil {
|
||||
t.Fatalf("第 %d 次重投 err=%v", i+1, err)
|
||||
}
|
||||
}
|
||||
if len(dp.calls) != 1 {
|
||||
t.Fatalf("重投应只分发 1 次, 实际 %d", len(dp.calls))
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerSkipDomains 域过滤:定时(3)/待审(audit=0)不认领。
|
||||
func TestConsumerSkipDomains(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
timerTask := mkImmediateTask(t, db, 3, SendTypeTimer)
|
||||
pending := mkImmediateTask(t, db, 0, 1)
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
|
||||
for _, tk := range []*entity.MessageTask{timerTask, pending} {
|
||||
if err := sc.HandlePayload(context.Background(), evPayload(t, tk, 2)); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
}
|
||||
if len(dp.calls) != 0 {
|
||||
t.Fatalf("非本域任务不应分发: %v", dp.calls)
|
||||
}
|
||||
if getTask(t, db, timerTask.ID).Status != 0 {
|
||||
t.Fatal("定时任务被误认领")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerDispatchErrorRollback 系统性错误:回滚 1→0 留待重扫。
|
||||
func TestConsumerDispatchErrorRollback(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := mkImmediateTask(t, db, 3, 1)
|
||||
dp := &fakeDispatcher{err: context.DeadlineExceeded}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
|
||||
if err := sc.HandlePayload(context.Background(), evPayload(t, task, 2)); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := getTask(t, db, task.ID)
|
||||
if got.Status != 0 {
|
||||
t.Fatalf("系统性错误应回滚 0, 实际 %d", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReclaimScannerApproveThenSend 补偿扫描:手动审核通过(audit=1)后无人发→
|
||||
// ScanOnce 认领下发(Day48 修复"审核通过即发"缺陷)。
|
||||
func TestReclaimScannerApproveThenSend(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := mkImmediateTask(t, db, 1, 1) // 手动档已过审
|
||||
dp := &fakeDispatcher{}
|
||||
rs := NewReclaimScanner(db, dp, zap.NewNop())
|
||||
|
||||
claimed, done, err := rs.ScanOnce(context.Background())
|
||||
if err != nil || claimed != 1 || done != 1 {
|
||||
t.Fatalf("ScanOnce claimed=%d done=%d err=%v", claimed, done, err)
|
||||
}
|
||||
got := getTask(t, db, task.ID)
|
||||
if got.Status != 2 || got.SuccessCount != 2 {
|
||||
t.Fatalf("审核通过任务应下发终态: status=%d sent=%d", got.Status, got.SuccessCount)
|
||||
}
|
||||
// 二轮幂等:无待发任务。
|
||||
claimed2, _, _ := rs.ScanOnce(context.Background())
|
||||
if claimed2 != 0 {
|
||||
t.Fatalf("二轮应无认领, 实际 %d", claimed2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerBadPayload 毒丸载荷:解析失败返回错误(进重试→死信)。
|
||||
func TestConsumerBadPayload(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
sc := NewSubmitConsumer(db, &fakeDispatcher{}, zap.NewNop())
|
||||
if err := sc.HandlePayload(context.Background(), []byte("{not-json")); err == nil {
|
||||
t.Fatal("坏载荷应报错")
|
||||
}
|
||||
// 旧格式兼容:无 task_id 忽略成功。
|
||||
if err := sc.HandlePayload(context.Background(), []byte(`{"task_no":"X"}`)); err != nil {
|
||||
t.Fatalf("旧格式应忽略, err=%v", err)
|
||||
}
|
||||
// Day46 事件(无 pass_count)按任务现状认领。
|
||||
task := mkImmediateTask(t, db, 3, 1)
|
||||
dp := &fakeDispatcher{}
|
||||
sc2 := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
raw := `{"task_id":` + taskNoDigits(task.ID) + `,"task_no":"` + task.TaskNo + `"}`
|
||||
if err := sc2.HandlePayload(context.Background(), []byte(raw)); err != nil {
|
||||
t.Fatalf("旧事件 err=%v", err)
|
||||
}
|
||||
if len(dp.calls) != 1 {
|
||||
t.Fatalf("旧事件应正常认领: %v", dp.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerPersistDetailsIdempotent Day52 R2:事件载明细→批量落库+认领下发;
|
||||
// 重投 3 次明细不重复(雪花主键 DoNothing)且只分发 1 次。
|
||||
func TestConsumerPersistDetailsIdempotent(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "CS" + time.Now().Format("150405.000000000"), AccountID: 1001,
|
||||
SendType: 1, Content: "【店】测试", Sign: "店", MobileCount: 2, AuditStatus: 3, Status: 0,
|
||||
}
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dets := []EventDetail{
|
||||
{ID: 9200000001, Mobile: "13800138000", Content: "【店】测试", Fee: 1},
|
||||
{ID: 9200000002, Mobile: "13800138001", Content: "【店】测试", Fee: 1},
|
||||
}
|
||||
b, err := json.Marshal(SubmitEvent{TaskID: task.ID, TaskNo: task.TaskNo,
|
||||
AccountID: task.AccountID, SendType: 1, PassCount: 2, Details: dets})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
for i := 0; i < 3; i++ { // 重投 3 次
|
||||
if err := sc.HandlePayload(context.Background(), b); err != nil {
|
||||
t.Fatalf("第 %d 次消费 err=%v", i+1, err)
|
||||
}
|
||||
}
|
||||
if len(dp.calls) != 1 {
|
||||
t.Fatalf("重投应只分发 1 次, 实际 %d", len(dp.calls))
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", task.ID).Count(&n)
|
||||
if n != 2 {
|
||||
t.Fatalf("明细应恰 2 行(重投幂等): %d", n)
|
||||
}
|
||||
var d entity.MessageDetail
|
||||
if err := db.Where("task_id = ? AND mobile = ?", task.ID, "13800138000").First(&d).Error; err != nil {
|
||||
t.Fatal("明细行缺失")
|
||||
}
|
||||
if d.AccountID != 1001 || d.ID != 9200000001 || d.Fee != 1 {
|
||||
t.Fatalf("明细字段口径错: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeBlockedSink Day62c:拦截终态出口桩(记录调用)。
|
||||
type fakeBlockedSink struct{ calls []string }
|
||||
|
||||
func (f *fakeBlockedSink) PushBlocked(_ context.Context, accountID, detailID int64,
|
||||
mobile, errCode, submitAt string) {
|
||||
f.calls = append(f.calls, fmt.Sprintf("%d/%d/%s/%s/%s",
|
||||
accountID, detailID, mobile, errCode, submitAt))
|
||||
}
|
||||
|
||||
// TestConsumerBlockedDeliver Day62c:拦截终态下发——source=CMPP 且 status=5 的行
|
||||
// 逐条推送;存活行不推;纯重投(RowsAffected=0)不重推;非 CMPP 来源零调用。
|
||||
func TestConsumerBlockedDeliver(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
source int8
|
||||
want int
|
||||
}{
|
||||
{TaskSourceCMPP, 2}, // CMPP:2 条拦截行各 1 次
|
||||
{TaskSourceAPI, 0}, // API 来源:不下发
|
||||
{TaskSourceWeb, 0}, // 控制台来源:不下发
|
||||
} {
|
||||
db := newTimerDB(t)
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "CS" + time.Now().Format("150405.000000000"), AccountID: 1001,
|
||||
SendType: 1, Content: "[半角签名]测试", MobileCount: 3, AuditStatus: 3,
|
||||
Status: 0, Source: tc.source,
|
||||
}
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dets := []EventDetail{
|
||||
{ID: 9300000001, Mobile: "13800138000", Content: task.Content, Fee: 1}, // 存活
|
||||
{ID: 9300000002, Mobile: "13800138001", Content: task.Content, Status: 5,
|
||||
ErrorCode: "ISC:004"}, // 拦截(签名)
|
||||
{ID: 9300000003, Mobile: "13800138002", Content: task.Content, Status: 5,
|
||||
ErrorCode: "ISC:009"}, // 拦截(其他码)
|
||||
}
|
||||
b, err := json.Marshal(SubmitEvent{TaskID: task.ID, TaskNo: task.TaskNo,
|
||||
AccountID: task.AccountID, SendType: 1, PassCount: 1, Details: dets})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fb := &fakeBlockedSink{}
|
||||
sc := NewSubmitConsumer(db, &fakeDispatcher{}, zap.NewNop()).WithBlockedDeliverSink(fb)
|
||||
for i := 0; i < 2; i++ { // 重投一次验证幂等
|
||||
if err := sc.HandlePayload(context.Background(), b); err != nil {
|
||||
t.Fatalf("source=%d 第 %d 次消费 err=%v", tc.source, i+1, err)
|
||||
}
|
||||
}
|
||||
if len(fb.calls) != tc.want {
|
||||
t.Fatalf("source=%d 调用 %d 次, 期望 %d: %v", tc.source, len(fb.calls), tc.want, fb.calls)
|
||||
}
|
||||
if tc.want > 0 {
|
||||
if !strings.Contains(fb.calls[0], "1001/9300000002/13800138001/ISC:004/") {
|
||||
t.Fatalf("首条载荷口径错: %s", fb.calls[0])
|
||||
}
|
||||
if !strings.Contains(fb.calls[1], "9300000003") || strings.Contains(fb.calls[1], "9300000001") {
|
||||
t.Fatalf("次条应仅含拦截行: %v", fb.calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrphanTaskFinalized Day62d:陈年孤儿任务(无明细+超 1h)dispatch 一次性终态
|
||||
// 结案,不再 5s/轮死循环重试(dev 实证 task 343 刷 warn 两日);新任务同错误仍回滚重试。
|
||||
func TestOrphanTaskFinalized(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
mk := func(back time.Duration) *entity.MessageTask {
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "CS" + time.Now().Format("150405.000000000"), AccountID: 1001,
|
||||
SendType: 1, Content: "【店】测试", MobileCount: 2, AuditStatus: 3, Status: 0,
|
||||
}
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Model(&entity.MessageTask{}).Where("id = ?", task.ID).
|
||||
Update("created_at", time.Now().Add(back)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
old, fresh := mk(-2*time.Hour), mk(-time.Minute)
|
||||
dp := &fakeDispatcher{err: ErrDetailsNotReady} // 明细缺失(事件在途/孤儿)
|
||||
rs := NewReclaimScanner(db, dp, zap.NewNop()).WithBatch(10)
|
||||
for i := 0; i < 2; i++ { // 两轮扫描:孤儿首轮结案;新任务始终回滚
|
||||
if _, _, err := rs.ScanOnce(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var got entity.MessageTask
|
||||
if err := db.First(&got, old.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status != taskStDone || got.FinishedAt.IsZero() {
|
||||
t.Fatalf("孤儿任务应终态结案: status=%d finished_at=%v", got.Status, got.FinishedAt)
|
||||
}
|
||||
var freshGot entity.MessageTask
|
||||
if err := db.First(&freshGot, fresh.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if freshGot.Status != 0 {
|
||||
t.Fatalf("新任务(事件在途)应回滚待重扫而非结案: status=%d", freshGot.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsumerTimerEventPersistOnly Day52 R2:定时域事件(载明细)→落明细不认领不下发
|
||||
// (claim 的 send_type∈{1,2} 保证;到点由 TimerScheduler 认领)。
|
||||
func TestConsumerTimerEventPersistOnly(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "CS" + time.Now().Format("150405.000000001"), AccountID: 1001,
|
||||
SendType: SendTypeTimer, Content: "【店】定时", Sign: "店",
|
||||
MobileCount: 1, AuditStatus: 3, Status: 0,
|
||||
}
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := json.Marshal(SubmitEvent{TaskID: task.ID, TaskNo: task.TaskNo,
|
||||
AccountID: task.AccountID, SendType: SendTypeTimer, PassCount: 1,
|
||||
Details: []EventDetail{{ID: 9200000003, Mobile: "13800138000", Content: "【店】定时", Fee: 1}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop())
|
||||
if err := sc.HandlePayload(context.Background(), b); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(dp.calls) != 0 {
|
||||
t.Fatalf("定时域事件不应分发: %v", dp.calls)
|
||||
}
|
||||
if getTask(t, db, task.ID).Status != 0 {
|
||||
t.Fatal("定时任务被误认领")
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", task.ID).Count(&n)
|
||||
if n != 1 {
|
||||
t.Fatalf("定时事件明细应落库: %d 行", n)
|
||||
}
|
||||
}
|
||||
func taskNoDigits(id int64) string {
|
||||
d, _ := json.Marshal(id)
|
||||
return string(d)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// deferred_test.go P0-1(Day 63)接入异步化——SubmitFast 快路径(零 DB 写+
|
||||
// MsgID=DetailID 口径)+handleDeferred 消费侧补全(建任务/拦截终态/退费/
|
||||
// 全拦终态/claim 幂等)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/service/interceptor"
|
||||
"go-sms/internal/util"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// fakeBal P0-1 资金桩(记 Hold/Refund 调用序)。
|
||||
type fakeBal struct {
|
||||
holds []string
|
||||
refunds []string
|
||||
failHold bool
|
||||
}
|
||||
|
||||
func (f *fakeBal) Hold(_ context.Context, _, _ int64, taskNo string) error {
|
||||
if f.failHold {
|
||||
return errors.Arrears.WithMsg("余额不足")
|
||||
}
|
||||
f.holds = append(f.holds, taskNo)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeBal) Refund(_ context.Context, _ int64, _ int64, taskNo, _ string) error {
|
||||
f.refunds = append(f.refunds, taskNo)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeBal) Mode() string { return "fake" }
|
||||
|
||||
// failSink 投递失败桩。
|
||||
type failSink struct{}
|
||||
|
||||
func (failSink) EmitSubmit(context.Context, *entity.MessageTask, []entity.MessageDetail) error {
|
||||
return errors.QueueError
|
||||
}
|
||||
|
||||
// TestSubmitFastEmit 快路径受理:预扣 1 次+Deferred 事件(task.ID=0)+
|
||||
// MsgID=DetailID+DB 零任务写(与 Deliver msg_id 同口径)。
|
||||
func TestSubmitFastEmit(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
sf, _ := util.NewSnowflake(9)
|
||||
fb, sink := &fakeBal{}, &captureSink{}
|
||||
svc := NewSubmitService(db, sf, nil, WithBalanceStore(fb), WithEventSink(sink))
|
||||
|
||||
req := &SubmitReq{AccountID: 1001, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000"}, Content: "【梦网】验证码", Source: TaskSourceCMPP}
|
||||
res, err := svc.SubmitFast(context.Background(), req, req.Content, "1.2.3.4")
|
||||
if err != nil {
|
||||
t.Fatalf("SubmitFast err=%v", err)
|
||||
}
|
||||
if len(fb.holds) != 1 {
|
||||
t.Fatalf("Hold 调用 %d 次,期望 1", len(fb.holds))
|
||||
}
|
||||
if len(sink.events) != 1 || sink.events[0].ID != 0 {
|
||||
t.Fatalf("Deferred 事件 task.ID 应为 0(消费侧补建),got=%+v", sink.events[0])
|
||||
}
|
||||
if len(sink.details) != 1 || sink.details[0][0].ID != res.MsgID || res.MsgID == 0 {
|
||||
t.Fatalf("MsgID 应=DetailID 雪花,got MsgID=%d detail=%d",
|
||||
res.MsgID, sink.details[0][0].ID)
|
||||
}
|
||||
if sink.details[0][0].Status != 0 {
|
||||
t.Fatalf("快路径明细不判拦截(status=0),got=%d", sink.details[0][0].Status)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageTask{}).Count(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("快路径零 DB 任务写,实际落库 %d 行", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitFastFail 欠费同步拒绝(唯一同步拒绝语义)+投递失败全额退回。
|
||||
func TestSubmitFastFail(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
sf, _ := util.NewSnowflake(9)
|
||||
req := &SubmitReq{AccountID: 1001, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000"}, Content: "【梦网】x"}
|
||||
|
||||
fb := &fakeBal{failHold: true}
|
||||
svc := NewSubmitService(db, sf, nil, WithBalanceStore(fb), WithEventSink(&captureSink{}))
|
||||
if _, err := svc.SubmitFast(context.Background(), req, req.Content, ""); err == nil {
|
||||
t.Fatal("欠费应同步拒绝")
|
||||
}
|
||||
|
||||
fb2 := &fakeBal{}
|
||||
svc2 := NewSubmitService(db, sf, nil, WithBalanceStore(fb2), WithEventSink(failSink{}))
|
||||
if _, err := svc2.SubmitFast(context.Background(), req, req.Content, ""); err == nil {
|
||||
t.Fatal("投递失败应拒绝")
|
||||
}
|
||||
if len(fb2.refunds) != 1 {
|
||||
t.Fatalf("投递失败应全额退回,Refund %d 次", len(fb2.refunds))
|
||||
}
|
||||
}
|
||||
|
||||
// mkDeferredEv 构造快路径事件载荷。
|
||||
func mkDeferredEv(t *testing.T, taskNo, content string, detailID int64, mobile string) []byte {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(SubmitEvent{
|
||||
TaskNo: taskNo, AccountID: 1001, SendType: SendTypeBatch, Deferred: true,
|
||||
TaskMeta: &SubmitTaskMeta{Content: content, Sign: "梦网", MobileCount: 1,
|
||||
FeeTotal: 1, SubmitIP: "protocol", Source: TaskSourceCMPP},
|
||||
Details: []EventDetail{{ID: detailID, Mobile: mobile, Content: content,
|
||||
Status: 0, Fee: 1}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// fakeRouter 审核分流桩(免审 audit 0→3,供 claim 通过)。
|
||||
type fakeRouter struct{ db *gorm.DB }
|
||||
|
||||
func (f *fakeRouter) Route(ctx context.Context, taskID int64) (*entity.MessageTask, *entity.AuditRecord, error) {
|
||||
if err := f.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ?", taskID).Update("audit_status", int8(3)).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var t entity.MessageTask
|
||||
if err := f.db.First(&t, taskID).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &t, nil, nil
|
||||
}
|
||||
|
||||
// TestHandleDeferredPass 全放行:补建任务(source=2)+明细落库+claim/dispatch;
|
||||
// 重投幂等(任务不重建/dispatch 不重发/退费不重复)。
|
||||
func TestHandleDeferredPass(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
dp := &fakeDispatcher{}
|
||||
fb := &fakeBal{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop()).
|
||||
WithConsumerRouter(&fakeRouter{db: db}).WithConsumerBalance(fb)
|
||||
|
||||
payload := mkDeferredEv(t, "DF-PASS-1", "【梦网】验证码", int64(9200000001), "13800138000")
|
||||
if err := sc.HandlePayload(context.Background(), payload); err != nil {
|
||||
t.Fatalf("HandlePayload err=%v", err)
|
||||
}
|
||||
var task entity.MessageTask
|
||||
if err := db.Where("task_no = ?", "DF-PASS-1").First(&task).Error; err != nil {
|
||||
t.Fatalf("任务应补建: %v", err)
|
||||
}
|
||||
if task.Source != TaskSourceCMPP || task.MobileCount != 1 || task.Status != taskStDone {
|
||||
t.Fatalf("补建任务字段异常: source=%d mobile=%d status=%d",
|
||||
task.Source, task.MobileCount, task.Status)
|
||||
}
|
||||
var d entity.MessageDetail
|
||||
if err := db.First(&d, "id = ?", int64(9200000001)).Error; err != nil {
|
||||
t.Fatalf("明细应落库: %v", err)
|
||||
}
|
||||
if d.TaskID != task.ID || d.Status != 0 {
|
||||
t.Fatalf("明细 task_id/status 异常: %+v", d)
|
||||
}
|
||||
if len(dp.calls) != 1 || dp.calls[0] != task.ID {
|
||||
t.Fatalf("dispatch 应执行一次 task=%v", dp.calls)
|
||||
}
|
||||
|
||||
// 重投幂等:任务不重建(uk 冲突查回)+claim 失败跳过+退费零调用。
|
||||
if err := sc.HandlePayload(context.Background(), payload); err != nil {
|
||||
t.Fatalf("重投 err=%v", err)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageTask{}).Where("task_no = ?", "DF-PASS-1").Count(&n)
|
||||
if n != 1 || len(dp.calls) != 1 || len(fb.refunds) != 0 {
|
||||
t.Fatalf("重投应幂等: 任务 %d 行 dispatch %d 次 退费 %d 次", n, len(dp.calls), len(fb.refunds))
|
||||
}
|
||||
|
||||
// 已分流重投(audit=3+status 回滚 0,模拟超时重投/Reclaim 后事件迟到):
|
||||
// Route 不得重入(ISC:037 死信缺陷),claim 兜底认领。
|
||||
db.Model(&entity.MessageTask{}).Where("task_no = ?", "DF-PASS-1").
|
||||
Update("status", 0)
|
||||
if err := sc.HandlePayload(context.Background(), payload); err != nil {
|
||||
t.Fatalf("已分流重投 err=%v(ISC:037 死信缺陷回归)", err)
|
||||
}
|
||||
if len(dp.calls) != 2 {
|
||||
t.Fatalf("回滚 status 后重投应重新认领下发,got %d 次", len(dp.calls))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDeferredBlocked 拦截(消费侧判定):明细终态 5+拦截费退+全拦任务终态+不下发。
|
||||
func TestHandleDeferredBlocked(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
dp := &fakeDispatcher{}
|
||||
fb := &fakeBal{}
|
||||
chain := interceptor.NewChain(nil, interceptor.NewSign(nil)) // 无【】→ISC:004
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop()).
|
||||
WithConsumerChain(chain).WithConsumerBalance(fb)
|
||||
|
||||
payload := mkDeferredEv(t, "DF-BLK-1", "noverify66", int64(9200000002), "13800138000")
|
||||
if err := sc.HandlePayload(context.Background(), payload); err != nil {
|
||||
t.Fatalf("HandlePayload err=%v", err)
|
||||
}
|
||||
var d entity.MessageDetail
|
||||
if err := db.First(&d, "id = ?", int64(9200000002)).Error; err != nil {
|
||||
t.Fatalf("明细应落库: %v", err)
|
||||
}
|
||||
if d.Status != 5 || d.ErrorCode != "ISC:004" {
|
||||
t.Fatalf("拦截明细应终态 5/ISC:004,got status=%d code=%s", d.Status, d.ErrorCode)
|
||||
}
|
||||
if len(fb.refunds) != 1 {
|
||||
t.Fatalf("拦截号应退费 1 次,got %d", len(fb.refunds))
|
||||
}
|
||||
var task entity.MessageTask
|
||||
if err := db.Where("task_no = ?", "DF-BLK-1").First(&task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Status != taskStDone {
|
||||
t.Fatalf("全拦任务应终态,got status=%d", task.Status)
|
||||
}
|
||||
if len(dp.calls) != 0 {
|
||||
t.Fatalf("全拦不应下发,got %v", dp.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDeferredPendingAudit rt 未注入(停留待审 audit=0):明细落库、claim 跳过。
|
||||
func TestHandleDeferredPendingAudit(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
dp := &fakeDispatcher{}
|
||||
sc := NewSubmitConsumer(db, dp, zap.NewNop()) // 无 rt/chain/bal:最小装配降级
|
||||
payload := mkDeferredEv(t, "DF-AUD-1", "【梦网】hi", int64(9200000003), "13800138000")
|
||||
if err := sc.HandlePayload(context.Background(), payload); err != nil {
|
||||
t.Fatalf("HandlePayload err=%v", err)
|
||||
}
|
||||
var task entity.MessageTask
|
||||
if err := db.Where("task_no = ?", "DF-AUD-1").First(&task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.AuditStatus != 0 || len(dp.calls) != 0 {
|
||||
t.Fatalf("无 rt 应停留待审不认领: audit=%d dispatch=%v", task.AuditStatus, dp.calls)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("id = ?", int64(9200000003)).Count(&n)
|
||||
if n != 1 {
|
||||
t.Fatalf("明细应落库 %d 行", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// P0-1 诊断(临时,Day63 复压定位):快路径分段耗时打点。
|
||||
package send
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-sms/internal/pkg/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// WarnSubmitFastSlow emit/hold 超阈值打点(emit 含 Kafka Send 背压)。
|
||||
func WarnSubmitFastSlow(emit, hold time.Duration) {
|
||||
logger.L().Warn("submit_fast_slow_seg",
|
||||
zap.Duration("emit", emit), zap.Duration("hold", hold))
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// fileimport.go Day 44:号码文件导入服务(文件入口)——multipart 上传→解析(TXT/CSV/XLSX)
|
||||
// →归一校验去重→原始文件落 MinIO→返回计数/预览/对象键。
|
||||
// 与 SubmitService 解耦:导入只做「号码准备」,提交仍走 POST /send/submit(文件类型 send_type=4)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/pkg/storage"
|
||||
"go-sms/internal/util"
|
||||
"go-sms/internal/util/fileparse"
|
||||
)
|
||||
|
||||
// PreviewLimit 预览行数(前端回显;与 D17 前端本地预览 50 行一致)。
|
||||
const PreviewLimit = 50
|
||||
|
||||
// FileImportService 号码文件导入。
|
||||
type FileImportService struct {
|
||||
store storage.ObjectStore
|
||||
sf *util.Snowflake
|
||||
}
|
||||
|
||||
// NewFileImportService 构造(sf 生成对象键;store 为 nil 时拒绝装配——文件入口不可降级)。
|
||||
func NewFileImportService(store storage.ObjectStore, sf *util.Snowflake) *FileImportService {
|
||||
return &FileImportService{store: store, sf: sf}
|
||||
}
|
||||
|
||||
// ImportResult 导入结果。
|
||||
type ImportResult struct {
|
||||
Total int `json:"total"` // 文件数据行数(含表头/非法)
|
||||
Valid int `json:"valid"` // 合格去重后号码数
|
||||
Duplicated int `json:"duplicated"` // 重复行数
|
||||
Invalid int `json:"invalid"` // 非法行数(不含表头)
|
||||
HeaderSkip bool `json:"header_skipped"` // 表头启发命中(首行非号码且后续有合法)
|
||||
Mobiles []string `json:"mobiles"` // 合格号码全量(≤MaxMobiles;供直接进入 estimate/submit)
|
||||
Preview []string `json:"preview"` // 合格号码预览(前 50)
|
||||
ObjectKey string `json:"object_key"` // MinIO 对象键(numbers/{account}/{snowID}{ext})
|
||||
}
|
||||
|
||||
// Import 导入:r 原始内容(调用方负责 multipart 打开);filename 决定解析器分发;size 上限校验。
|
||||
func (s *FileImportService) Import(ctx context.Context, r io.Reader, filename string, size int64, accountID int64) (*ImportResult, error) {
|
||||
if size <= 0 && size != -1 {
|
||||
return nil, errors.InvalidParam.WithMsg("缺少文件内容")
|
||||
}
|
||||
if size > 10<<20 { // 10MB(万行号码文件量级,防滥用)
|
||||
return nil, errors.InvalidParam.WithMsg("文件超 10MB 上限")
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
if _, err := buf.ReadFrom(r); err != nil {
|
||||
return nil, errors.InvalidParam.WithMsg("文件读取失败: " + err.Error())
|
||||
}
|
||||
raw, err := fileparse.Parse(bytes.NewReader(buf.Bytes()), filename)
|
||||
if err != nil {
|
||||
return nil, errors.InvalidParam.WithMsg(err.Error())
|
||||
}
|
||||
if len(raw.Mobiles) == 0 {
|
||||
return nil, errors.InvalidParam.WithMsg("文件为空或无数据行")
|
||||
}
|
||||
|
||||
res := &ImportResult{Total: raw.Rows, Preview: make([]string, 0, PreviewLimit)}
|
||||
seen := make(map[string]struct{}, len(raw.Mobiles))
|
||||
valid := 0
|
||||
mobiles := make([]string, 0, 32)
|
||||
headerChecked := false
|
||||
for i, m := range raw.Mobiles {
|
||||
n := util.NormalizeMobile(m)
|
||||
if !util.IsValidMainlandMobile(n) {
|
||||
// 表头启发:首行非法且后续存在合法 → 视为表头跳过(不计 invalid)
|
||||
if i == 0 && !headerChecked && len(raw.Mobiles) > 1 {
|
||||
headerChecked = true
|
||||
if hasAnyValid(raw.Mobiles[1:]) {
|
||||
res.HeaderSkip = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
res.Invalid++
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[n]; dup {
|
||||
res.Duplicated++
|
||||
continue
|
||||
}
|
||||
seen[n] = struct{}{}
|
||||
valid++
|
||||
mobiles = append(mobiles, n)
|
||||
if valid <= PreviewLimit {
|
||||
res.Preview = append(res.Preview, n)
|
||||
}
|
||||
}
|
||||
if valid == 0 {
|
||||
return nil, errors.InvalidParam.WithMsg("文件中未解析到合法手机号")
|
||||
}
|
||||
if valid > MaxMobiles {
|
||||
return nil, errors.InvalidParam.WithMsg(numberLimitMsg(valid))
|
||||
}
|
||||
|
||||
// 原始文件落 MinIO(键含账号+雪花;内容原样,可审计可重放)
|
||||
ext := extOf(filename)
|
||||
res.ObjectKey = "numbers/" + int64ToString(accountID) + "/" + int64ToString(s.sf.NextID()) + ext
|
||||
if err := s.store.Put(ctx, res.ObjectKey, bytes.NewReader(buf.Bytes()), int64(buf.Len()), contentTypeOf(ext)); err != nil {
|
||||
return nil, errors.InternalError.WithMsg("对象存储写入失败: " + err.Error())
|
||||
}
|
||||
res.Valid = valid
|
||||
res.Mobiles = mobiles
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// hasAnyValid 任一候选为合法手机号(表头启发辅助)。
|
||||
func hasAnyValid(ms []string) bool {
|
||||
for _, m := range ms {
|
||||
if util.IsValidMainlandMobile(util.NormalizeMobile(m)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func numberLimitMsg(n int) string {
|
||||
return "号码 " + strconv.Itoa(n) + " 超单次上限 " + strconv.Itoa(MaxMobiles)
|
||||
}
|
||||
|
||||
func int64ToString(n int64) string { return strconv.FormatInt(n, 10) }
|
||||
|
||||
func extOf(name string) string {
|
||||
if i := strings.LastIndexByte(name, '.'); i >= 0 {
|
||||
return strings.ToLower(name[i:])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func contentTypeOf(ext string) string {
|
||||
switch ext {
|
||||
case ".csv":
|
||||
return "text/csv"
|
||||
case ".txt":
|
||||
return "text/plain"
|
||||
case ".xlsx":
|
||||
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
}
|
||||
return "application/octet-stream"
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// fileimport_test.go Day 44:导入服务——去重/非法/表头启发/超限/对象键(依赖倒置 memStore)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/pkg/storage"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// memStore 内存对象存储(测试替身)。
|
||||
type memStore struct {
|
||||
objects map[string]int64
|
||||
}
|
||||
|
||||
var _ storage.ObjectStore = (*memStore)(nil)
|
||||
|
||||
func (m *memStore) Put(_ context.Context, key string, _ io.Reader, size int64, _ string) error {
|
||||
if m.objects == nil {
|
||||
m.objects = map[string]int64{}
|
||||
}
|
||||
m.objects[key] = size
|
||||
return nil
|
||||
}
|
||||
|
||||
func newImporter() (*FileImportService, *memStore) {
|
||||
sf, _ := util.NewSnowflake(1)
|
||||
st := &memStore{}
|
||||
return NewFileImportService(st, sf), st
|
||||
}
|
||||
|
||||
func TestFileImportTxt(t *testing.T) {
|
||||
svc, st := newImporter()
|
||||
in := "13800138000\n13800138000\n13800138001\nbad123\n"
|
||||
res, err := svc.Import(context.Background(), strings.NewReader(in), "n.txt", int64(len(in)), 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Valid != 2 || res.Duplicated != 1 || res.Invalid != 1 {
|
||||
t.Fatalf("计数: %+v", res)
|
||||
}
|
||||
if !strings.HasPrefix(res.ObjectKey, "numbers/7/") || !strings.HasSuffix(res.ObjectKey, ".txt") {
|
||||
t.Fatalf("对象键: %q", res.ObjectKey)
|
||||
}
|
||||
if _, ok := st.objects[res.ObjectKey]; !ok {
|
||||
t.Fatal("对象未落存储")
|
||||
}
|
||||
if len(res.Preview) != 2 || res.Preview[0] != "13800138000" {
|
||||
t.Fatalf("预览: %v", res.Preview)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileImportHeaderHeuristic(t *testing.T) {
|
||||
svc, _ := newImporter()
|
||||
in := "手机号,姓名\n13800138000,张三\n13800138001,李四\n"
|
||||
res, err := svc.Import(context.Background(), strings.NewReader(in), "h.csv", int64(len(in)), 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !res.HeaderSkip || res.Valid != 2 || res.Invalid != 0 {
|
||||
t.Fatalf("表头启发: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileImportAllInvalid(t *testing.T) {
|
||||
svc, _ := newImporter()
|
||||
in := "abc\ndef\n"
|
||||
_, err := svc.Import(context.Background(), strings.NewReader(in), "bad.txt", int64(len(in)), 1)
|
||||
if err == nil || err.(*errors.Error).Code != "ISC:400" {
|
||||
t.Fatalf("全非法应 400: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileImportOverLimit(t *testing.T) {
|
||||
svc, _ := newImporter()
|
||||
var b strings.Builder
|
||||
for i := 0; i <= MaxMobiles; i++ {
|
||||
b.WriteString(strconv.FormatInt(13900000000+int64(i), 10))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
_, err := svc.Import(context.Background(), strings.NewReader(b.String()), "big.txt", int64(b.Len()), 1)
|
||||
if err == nil || !strings.Contains(err.Error(), "超单次上限") {
|
||||
t.Fatalf("超限应拒绝: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileImportRejectExt(t *testing.T) {
|
||||
svc, _ := newImporter()
|
||||
_, err := svc.Import(context.Background(), strings.NewReader("x"), "a.doc", 1, 1)
|
||||
if err == nil {
|
||||
t.Fatal("不支持的扩展名应拒绝")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// pacer.go Day 48(开发计划 Day47④⑤ 挪入):下发侧限速三件套——
|
||||
// - TokenBucket:单通道纯内存令牌桶(rate=channel.speed,默认 3000);
|
||||
// - ChannelPacer:per-channel 令牌桶 + 在途窗口(256=16 连接×16,Day39 实测背书)
|
||||
// - p50>50ms 持续 30s 自动降速 10%(单向,Reset 手动恢复);
|
||||
// - PaceBudget:群发匀速投放预算——每轮 min(剩余, Σ通道speed − 在途余量),
|
||||
// 防瞬时打满下游队列(技术方案 10.4.1)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PacerDefaults 与技术方案/开发计划对齐。
|
||||
const (
|
||||
DefaultChannelSpeed = 3000
|
||||
PacerWindow = 256 // 在途窗口:16 连接 × 16
|
||||
PacerSlowMs = 50.0 // p50 慢阈值(ms)
|
||||
PacerSlowHold = 30 * time.Second
|
||||
PacerSamples = 128 // p50 观测样本环
|
||||
)
|
||||
|
||||
// TokenBucket 纯内存令牌桶(时间补充,无需 ticker)。
|
||||
type TokenBucket struct {
|
||||
mu sync.Mutex
|
||||
tokens float64
|
||||
rate float64 // 个/秒
|
||||
cap float64
|
||||
last time.Time
|
||||
}
|
||||
|
||||
// NewTokenBucket 构造(cap=rate 起步满桶;rate<=0 用默认)。
|
||||
func NewTokenBucket(rate float64) *TokenBucket {
|
||||
if rate <= 0 {
|
||||
rate = DefaultChannelSpeed
|
||||
}
|
||||
return &TokenBucket{tokens: rate, rate: rate, cap: rate, last: time.Now()}
|
||||
}
|
||||
|
||||
// refill 时间补充(elapsed × rate,上限 cap;调用方持锁)。
|
||||
func (b *TokenBucket) refill(now time.Time) {
|
||||
if now.After(b.last) {
|
||||
b.tokens += now.Sub(b.last).Seconds() * b.rate
|
||||
if b.tokens > b.cap {
|
||||
b.tokens = b.cap
|
||||
}
|
||||
b.last = now
|
||||
}
|
||||
}
|
||||
|
||||
// Acquire 阻塞取 n 个令牌(ctx 取消即失败)。
|
||||
func (b *TokenBucket) Acquire(ctx context.Context, n int) error {
|
||||
if n <= 0 {
|
||||
return nil
|
||||
}
|
||||
for {
|
||||
b.mu.Lock()
|
||||
b.refill(time.Now())
|
||||
if b.tokens >= float64(n) {
|
||||
b.tokens -= float64(n)
|
||||
b.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
need := (float64(n) - b.tokens) / b.rate
|
||||
b.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(time.Duration(need * float64(time.Second))):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetRate 调整速率(降速用;同步收缩容量)。
|
||||
func (b *TokenBucket) SetRate(rate float64) {
|
||||
if rate <= 0 {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.rate = rate
|
||||
if b.cap > rate {
|
||||
b.cap = rate
|
||||
if b.tokens > b.cap {
|
||||
b.tokens = b.cap
|
||||
}
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
// Rate 当前速率。
|
||||
func (b *TokenBucket) Rate() float64 {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.rate
|
||||
}
|
||||
|
||||
// chanPace 单通道状态。
|
||||
type chanPace struct {
|
||||
bucket *TokenBucket
|
||||
window chan struct{} // 在途窗口(容量 PacerWindow)
|
||||
samples []float64 // 延迟样本环
|
||||
slowAt time.Time // p50 首次超阈值时刻(持续 30s 判定起点;零值=未超)
|
||||
}
|
||||
|
||||
// ChannelPacer per-channel 下发调度器(令牌桶+在途窗口+自动降速)。
|
||||
type ChannelPacer struct {
|
||||
mu sync.Mutex
|
||||
ch map[int64]*chanPace
|
||||
open bool // true=启用(测试/装配开关;关闭时 Acquire 直通,兼容旧链路)
|
||||
}
|
||||
|
||||
// NewChannelPacer 构造(open=false 直通——既有 timer 链路行为不变)。
|
||||
func NewChannelPacer(open bool) *ChannelPacer {
|
||||
return &ChannelPacer{ch: map[int64]*chanPace{}, open: open}
|
||||
}
|
||||
|
||||
// Open 是否启用。
|
||||
func (p *ChannelPacer) Open() bool { return p.open }
|
||||
|
||||
// SetSpeed 通道速率装载(<=0 用默认;首次调用建窗口)。
|
||||
func (p *ChannelPacer) SetSpeed(channelID int64, rate float64) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
st, ok := p.ch[channelID]
|
||||
if !ok {
|
||||
st = &chanPace{bucket: NewTokenBucket(rate), window: make(chan struct{}, PacerWindow)}
|
||||
p.ch[channelID] = st
|
||||
return
|
||||
}
|
||||
st.bucket.SetRate(rate)
|
||||
}
|
||||
|
||||
// state 取通道状态(懒建,默认速率)。
|
||||
func (p *ChannelPacer) state(channelID int64) *chanPace {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if st, ok := p.ch[channelID]; ok {
|
||||
return st
|
||||
}
|
||||
st := &chanPace{bucket: NewTokenBucket(0), window: make(chan struct{}, PacerWindow)}
|
||||
p.ch[channelID] = st
|
||||
return st
|
||||
}
|
||||
|
||||
// Acquire 预占 n 条额度(令牌+在途窗口;批量提交前调用)。
|
||||
// 未启用时直通 nil(默认装配在消费链路启用,timer 旧链路不启用)。
|
||||
func (p *ChannelPacer) Acquire(ctx context.Context, channelID int64, n int) error {
|
||||
if !p.open || n <= 0 {
|
||||
return nil
|
||||
}
|
||||
st := p.state(channelID)
|
||||
if err := st.bucket.Acquire(ctx, n); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < n; i++ { // 在途窗口逐槽占位
|
||||
select {
|
||||
case st.window <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
for j := 0; j < i; j++ { // 回退已占槽
|
||||
<-st.window
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release 释放在途占用(提交返回后调用,含失败路径)。
|
||||
func (p *ChannelPacer) Release(channelID int64, n int) {
|
||||
if !p.open || n <= 0 {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
st, ok := p.ch[channelID]
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-st.window:
|
||||
default: // 防御:超释放直接忽略
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Observe 提交延迟采样(ms):p50>50ms 持续 30s → 速率×0.9(下限默认 10%)。
|
||||
func (p *ChannelPacer) Observe(channelID int64, ms float64) {
|
||||
if !p.open {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
st, ok := p.ch[channelID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st.samples = append(st.samples, ms)
|
||||
if len(st.samples) > PacerSamples {
|
||||
st.samples = st.samples[len(st.samples)-PacerSamples:]
|
||||
}
|
||||
if p50(st.samples) <= PacerSlowMs {
|
||||
st.slowAt = time.Time{}
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if st.slowAt.IsZero() {
|
||||
st.slowAt = now
|
||||
return
|
||||
}
|
||||
if now.Sub(st.slowAt) >= PacerSlowHold {
|
||||
newRate := st.bucket.Rate() * 0.9
|
||||
if minRate := float64(DefaultChannelSpeed) * 0.1; newRate < minRate {
|
||||
newRate = minRate
|
||||
}
|
||||
st.bucket.SetRate(newRate)
|
||||
st.slowAt = now // 滚动继续判定(可再降)
|
||||
}
|
||||
}
|
||||
|
||||
// Rate 当前生效速率(测试/观测)。
|
||||
func (p *ChannelPacer) Rate(channelID int64) float64 {
|
||||
p.mu.Lock()
|
||||
st, ok := p.ch[channelID]
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return st.bucket.Rate()
|
||||
}
|
||||
|
||||
// p50 中位数(拷贝排序,不改原片)。
|
||||
func p50(xs []float64) float64 {
|
||||
if len(xs) == 0 {
|
||||
return 0
|
||||
}
|
||||
cp := append([]float64(nil), xs...)
|
||||
sort.Float64s(cp)
|
||||
return cp[len(cp)/2]
|
||||
}
|
||||
|
||||
// PaceBudget 匀速投放预算(⑤):本轮可投 = min(pending, Σspeed − inflight),下限 0。
|
||||
func PaceBudget(pending, sumSpeed, inflight int) int {
|
||||
b := sumSpeed - inflight
|
||||
if b < 0 {
|
||||
b = 0
|
||||
}
|
||||
if pending < b {
|
||||
return pending
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// pacer_test.go Day 48:下发调度三件套单测——令牌桶限速/在途窗口/自动降速/匀速预算。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestTokenBucketRate 令牌桶:满桶直取;补令牌按 rate 时间等待。
|
||||
func TestTokenBucketRate(t *testing.T) {
|
||||
b := NewTokenBucket(2) // 2 个/秒
|
||||
ctx := context.Background()
|
||||
start := time.Now()
|
||||
if err := b.Acquire(ctx, 2); err != nil { // 起步满桶
|
||||
t.Fatal(err)
|
||||
}
|
||||
if el := time.Since(start); el > 50*time.Millisecond {
|
||||
t.Fatalf("满桶不应等待: %v", el)
|
||||
}
|
||||
if err := b.Acquire(ctx, 1); err != nil { // 需补 1 个 ≈500ms
|
||||
t.Fatal(err)
|
||||
}
|
||||
if el := time.Since(start); el < 300*time.Millisecond {
|
||||
t.Fatalf("补令牌应等待 ≥300ms: %v", el)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTokenBucketCtxCancel 等令牌期间 ctx 取消即失败。
|
||||
func TestTokenBucketCtxCancel(t *testing.T) {
|
||||
b := NewTokenBucket(1)
|
||||
if err := b.Acquire(context.Background(), 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := b.Acquire(ctx, 1); err == nil {
|
||||
t.Fatal("ctx 超时应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPacerWindowBlocks 在途窗口:占满后阻塞,Release 后可再取。
|
||||
func TestPacerWindowBlocks(t *testing.T) {
|
||||
p := NewChannelPacer(true)
|
||||
p.SetSpeed(7, 0) // 0=默认速率(桶大,不构成约束)
|
||||
ctx := context.Background()
|
||||
if err := p.Acquire(ctx, 7, PacerWindow); err != nil { // 占满窗口
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx2, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := p.Acquire(ctx2, 7, 1); err == nil {
|
||||
t.Fatal("窗口满应阻塞至超时")
|
||||
}
|
||||
p.Release(7, PacerWindow)
|
||||
if err := p.Acquire(context.Background(), 7, 1); err != nil {
|
||||
t.Fatalf("释放后应可取: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPacerDegradeOnSlowP50 p50>50ms 持续 30s→速率×0.9(下限 10%)。
|
||||
func TestPacerDegradeOnSlowP50(t *testing.T) {
|
||||
p := NewChannelPacer(true)
|
||||
p.SetSpeed(7, 1000)
|
||||
rate0 := p.Rate(7)
|
||||
p.mu.Lock()
|
||||
st := p.ch[7]
|
||||
// 预置 128 个慢样本(p50=100ms>50)+首超时刻回拨 31s(免真等 30s)。
|
||||
st.samples = make([]float64, PacerSamples)
|
||||
for i := range st.samples {
|
||||
st.samples[i] = 100.0
|
||||
}
|
||||
st.slowAt = time.Now().Add(-PacerSlowHold - time.Second)
|
||||
p.mu.Unlock()
|
||||
|
||||
p.Observe(7, 100.0) // 触发降速判定
|
||||
rate1 := p.Rate(7)
|
||||
if math.Abs(rate1-rate0*0.9) > 0.01 {
|
||||
t.Fatalf("降速后速率 = %v, 期望 %v", rate1, rate0*0.9)
|
||||
}
|
||||
// 快样本复位(p50 回落→计时清零)。
|
||||
for i := 0; i < PacerSamples; i++ {
|
||||
p.Observe(7, 1.0)
|
||||
}
|
||||
p.mu.Lock()
|
||||
slowAt := p.ch[7].slowAt
|
||||
p.mu.Unlock()
|
||||
if !slowAt.IsZero() {
|
||||
t.Fatal("p50 回落后 slowAt 应清零")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPacerClosed 直通模式(timer 旧链路行为不变)。
|
||||
func TestPacerClosed(t *testing.T) {
|
||||
p := NewChannelPacer(false)
|
||||
if err := p.Acquire(context.Background(), 1, 1_000_000); err != nil {
|
||||
t.Fatal("关闭态应直通")
|
||||
}
|
||||
p.Release(1, 1_000_000) // 无状态不 panic
|
||||
}
|
||||
|
||||
// TestPaceBudget 匀速投放:本轮=min(pending,Σspeed−inflight),下限 0。
|
||||
func TestPaceBudget(t *testing.T) {
|
||||
cases := []struct {
|
||||
pending, sum, inflight, want int
|
||||
}{
|
||||
{5000, 3000, 0, 3000}, // 预算封顶
|
||||
{1000, 3000, 0, 1000}, // 剩余封顶
|
||||
{5000, 3000, 2500, 500}, // 在途挤压
|
||||
{100, 3000, 3000, 0}, // 在途打满→0(防瞬时打满队列)
|
||||
{10, 0, 0, 0}, // 无通道预算
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := PaceBudget(c.pending, c.sum, c.inflight); got != c.want {
|
||||
t.Fatalf("PaceBudget(%d,%d,%d)=%d 期望 %d", c.pending, c.sum, c.inflight, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// pipeline.go Day 48:发送全流程串联(API→预扣→审核→拦截→路由→Kafka)。
|
||||
// SubmitService 经 SubmitOption 注入拦截器链与事件出口,受理主链升级为显式状态机:
|
||||
//
|
||||
// ①Validate → ②余额只读快检(UX 快速失败) → ③holdFee 原子预扣(WHERE balance>=fee)
|
||||
// → ④事务落库(失败→RefundTask 对冲) → ⑤逐号拦截(命中→明细终态 5+该号即时退费)
|
||||
// → ⑥审核分流 Route(拒绝→退剩余全款) → ⑦EmitSubmit 入队 sms-submit(消费侧路由下发)。
|
||||
//
|
||||
// 路由/下发不在受理期(同步链路 ≤5ms 禁令,技术方案 10.4):由 submit 消费者
|
||||
// (consumer.go)认领后经 ChannelDispatcher 路由→pacer 限速→聚合/直发链路完成。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/queue"
|
||||
"go-sms/internal/service/balance"
|
||||
"go-sms/internal/service/interceptor"
|
||||
)
|
||||
|
||||
// EventSink 受理完成事件出口(装配层注入;nil=不投,发送由 ReclaimScanner 兜底)。
|
||||
// Day52 R2:details=入口预生成明细(含拦截终态行)随事件投递,消费侧批量落库;
|
||||
// 返回 error——投递失败由 SubmitService 降级同步落明细(零丢失红线)。
|
||||
type EventSink interface {
|
||||
EmitSubmit(ctx context.Context, task *entity.MessageTask, details []entity.MessageDetail) error
|
||||
}
|
||||
|
||||
// ProducerSink queue.Producer 适配器(sms-submit 统一投递口,Day48 起 openapi
|
||||
// 不再自行 emit,避免双投)。
|
||||
type ProducerSink struct {
|
||||
P interface {
|
||||
Send(topic string, key, value []byte) error
|
||||
}
|
||||
Source string // 来源标识(openapi/console/access)
|
||||
}
|
||||
|
||||
// EmitSubmit 投递 sms-submit(key=task_no;失败返回错误——Day52 起明细在事件里,
|
||||
// 丢失=对账事实源丢失,入口须降级同步落库对冲;任务认领仍由 ReclaimScanner 兜底)。
|
||||
func (s ProducerSink) EmitSubmit(ctx context.Context, task *entity.MessageTask, details []entity.MessageDetail) error {
|
||||
if s.P == nil || task == nil {
|
||||
return nil
|
||||
}
|
||||
eds := make([]EventDetail, 0, len(details))
|
||||
pass := 0
|
||||
for i := range details {
|
||||
d := &details[i]
|
||||
if d.Status == 0 {
|
||||
pass++
|
||||
}
|
||||
eds = append(eds, EventDetail{
|
||||
ID: d.ID, Mobile: d.Mobile, Content: d.Content, Status: d.Status,
|
||||
Fee: d.Fee, ErrorCode: d.ErrorCode, ExtCode: d.ExtCode, CallData: d.CallData,
|
||||
Business: d.Business, Source: d.Source, // Day66:明细单表化冗余透传
|
||||
})
|
||||
}
|
||||
// P0-1(Day 63)快路径:task.ID==0=受理侧零 DB 写(SubmitFast),消费侧
|
||||
// handleDeferred 补建任务/拦截/退费/审核;TaskMeta 携带任务行补建字段。
|
||||
ev := SubmitEvent{
|
||||
TaskID: task.ID, TaskNo: task.TaskNo, AccountID: task.AccountID,
|
||||
SendType: task.SendType, PassCount: pass, Source: s.Source,
|
||||
CreatedAt: task.CreatedAt.Format(time.RFC3339),
|
||||
Business: task.Business, // Day 49:biz_type 路由(video 记录隔离)
|
||||
Details: eds, // Day52 R2:明细全量(消费侧批量落库)
|
||||
}
|
||||
if task.ID == 0 {
|
||||
ev.Deferred = true
|
||||
meta := &SubmitTaskMeta{
|
||||
Content: task.Content, Sign: task.Sign, MobileCount: task.MobileCount,
|
||||
FeeTotal: task.FeeTotal, SubmitIP: task.SubmitIP, CallData: task.CallData,
|
||||
Source: task.Source,
|
||||
}
|
||||
if task.ScheduleAt != nil {
|
||||
meta.ScheduleAt = task.ScheduleAt.Format(time.RFC3339)
|
||||
}
|
||||
ev.TaskMeta = meta
|
||||
}
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.P.Send(queue.TopicSubmit, []byte(task.TaskNo), payload)
|
||||
}
|
||||
|
||||
// SubmitOption SubmitService 可选依赖(零破坏:既有三参构造不变)。
|
||||
type SubmitOption func(*SubmitService)
|
||||
|
||||
// WithInterceptorChain 注入拦截器链(Day42 五类;受理期逐号硬拦截)。
|
||||
func WithInterceptorChain(c *interceptor.Chain) SubmitOption {
|
||||
return func(s *SubmitService) { s.chain = c }
|
||||
}
|
||||
|
||||
// WithEventSink 注入事件出口(sms-submit 统一投递)。
|
||||
func WithEventSink(sink EventSink) SubmitOption {
|
||||
return func(s *SubmitService) { s.sink = sink }
|
||||
}
|
||||
|
||||
// WithBalanceStore 注入资金预扣 Store(Day54 R1;nil=MySQL 行锁原路径)。
|
||||
func WithBalanceStore(b balance.Store) SubmitOption {
|
||||
return func(s *SubmitService) { s.bal = b }
|
||||
}
|
||||
|
||||
// intercept 逐号拦截(非 DryRun:频次计数/落库副作用保留)。
|
||||
// 返回命中码列表(nil=该号放行);taskNo 用于 send_block_log 关联。
|
||||
// Day51 R3:sc 请求级快照(批量提交入口构造一次,拦截器批量 IN+跨号复用)。
|
||||
func (s *SubmitService) intercept(ctx context.Context, taskNo string,
|
||||
accountID int64, sendType int8, mobile, content string, sc *interceptor.Scope) *interceptor.Block {
|
||||
if s.chain == nil {
|
||||
return nil
|
||||
}
|
||||
return s.chain.Check(ctx, &interceptor.Req{
|
||||
TaskNo: taskNo, AccountID: accountID, Mobile: mobile,
|
||||
Content: content, SendType: sendType, Scope: sc,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// pipeline_test.go Day 48:全流程状态机单测——预扣/拦截退费/全拦终态/审核拒绝退费/
|
||||
// 落库失败对冲/事件投递口径(验收:失败各环节回退余额)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/service/interceptor"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// fakeBlocker 测试拦截器(命中指定号码)。
|
||||
type fakeBlocker struct{ hit map[string]bool }
|
||||
|
||||
func (f *fakeBlocker) Name() string { return "fake-black" }
|
||||
func (f *fakeBlocker) Check(_ context.Context, r *interceptor.Req) *interceptor.Block {
|
||||
if f.hit[r.Mobile] {
|
||||
return &interceptor.Block{Interceptor: "fake-black", Code: "ISC:021", Msg: "黑名单"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// captureSink 事件捕获(Day52 R2:捕获明细载荷)。
|
||||
type captureSink struct {
|
||||
events []*entity.MessageTask
|
||||
details [][]entity.MessageDetail
|
||||
}
|
||||
|
||||
func (c *captureSink) EmitSubmit(_ context.Context, t *entity.MessageTask,
|
||||
d []entity.MessageDetail) error {
|
||||
c.events = append(c.events, t)
|
||||
c.details = append(c.details, d)
|
||||
return nil
|
||||
}
|
||||
|
||||
// getBal 查余额(整型条数)。
|
||||
func getBal(t *testing.T, db *gorm.DB, id int64) int64 {
|
||||
t.Helper()
|
||||
var v int64
|
||||
if err := db.Model(&entity.AccountUser{}).Where("id = ?", id).
|
||||
Pluck("balance", &v).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// TestPipelineHoldFeeAndLog 预扣:受理 2 号→余额-2+submit 流水;事件投递 pass=2。
|
||||
func TestPipelineHoldFeeAndLog(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
sink := &captureSink{}
|
||||
s := newSubmitSvc(t, db)
|
||||
s.sink = sink
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】预扣", Sign: "【测】"}
|
||||
if _, err := s.Submit(context.Background(), req, nil, req.Content, ""); err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
if bal := getBal(t, db, 1); bal != 9998 {
|
||||
t.Fatalf("预扣后余额 = %d, 期望 9998", bal)
|
||||
}
|
||||
var logN int64
|
||||
db.Table("account_balance_log").
|
||||
Where("account_id = ? AND biz_type = ? AND amount = ?", 1, "submit", -2).Count(&logN)
|
||||
if logN != 1 {
|
||||
t.Fatalf("预扣流水缺失(%d 条)", logN)
|
||||
}
|
||||
if len(sink.events) != 1 || len(sink.details[0]) != 2 {
|
||||
t.Fatalf("事件投递缺失: %d 次 details=%v", len(sink.events), sink.details)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineInterceptBlockedRefund 拦截:命中号明细终态 5+ISC 码;该号费用即时退。
|
||||
func TestPipelineInterceptBlockedRefund(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
s.chain = interceptor.NewChain(nil, &fakeBlocker{hit: map[string]bool{"13800138001": true}})
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】拦一号", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
if res.Task.Status != 0 || res.Task.AuditStatus != 3 {
|
||||
t.Fatalf("存活 1 号应正常受理 audit=%d status=%d", res.Task.AuditStatus, res.Task.Status)
|
||||
}
|
||||
var blocked entity.MessageDetail
|
||||
if err := db.Where("task_id = ? AND mobile = ?", res.Task.ID, "13800138001").
|
||||
First(&blocked).Error; err != nil {
|
||||
t.Fatal("拦截明细缺失")
|
||||
}
|
||||
if blocked.Status != 5 || blocked.ErrorCode == "" {
|
||||
t.Fatalf("拦截明细终态错: status=%d code=%q", blocked.Status, blocked.ErrorCode)
|
||||
}
|
||||
if bal := getBal(t, db, 1); bal != 9999 { // 10000-2 预扣 +1 退
|
||||
t.Fatalf("拦截退费后余额 = %d, 期望 9999", bal)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineAllBlockedTerminal 全拦:任务直接终态 2+余额全额退;
|
||||
// Day52 R2 语义反转:仍投事件载拦截终态明细(拦截记录=对账事实源,消费侧落库)。
|
||||
func TestPipelineAllBlockedTerminal(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
s.chain = interceptor.NewChain(nil, &fakeBlocker{hit: map[string]bool{
|
||||
"13800138000": true, "13800138001": true}})
|
||||
sink := &captureSink{}
|
||||
s.sink = sink
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】全拦", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
if res.Task.Status != 2 {
|
||||
t.Fatalf("全拦任务应终态 2, 实际 %d", res.Task.Status)
|
||||
}
|
||||
if bal := getBal(t, db, 1); bal != 10000 {
|
||||
t.Fatalf("全拦应全额退, 余额 = %d", bal)
|
||||
}
|
||||
if len(sink.events) != 1 || len(sink.details[0]) != 2 {
|
||||
t.Fatalf("全拦应投事件载 2 行拦截明细(明细事实源): %d 次", len(sink.events))
|
||||
}
|
||||
for _, d := range sink.details[0] {
|
||||
if d.Status != 5 || d.ErrorCode == "" {
|
||||
t.Fatalf("全拦明细应终态 5+ISC 码: status=%d code=%q", d.Status, d.ErrorCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineAuditRejectRefund 审核拒绝(自动黑词):存活号费用全退,余额回起点。
|
||||
func TestPipelineAuditRejectRefund(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 3, 10000, 2) // 自动
|
||||
if err := db.Create(&entity.PolicyKeyword{Word: "发票", Level: 1, Status: 1}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := &SubmitReq{AccountID: 3, SendType: 1, Mobiles: []string{"13800138000"},
|
||||
Content: "【测】代开发票", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
if res.Task.AuditStatus != 2 {
|
||||
t.Fatalf("自动命中应 audit=2, 实际 %d", res.Task.AuditStatus)
|
||||
}
|
||||
if bal := getBal(t, db, 3); bal != 10000 {
|
||||
t.Fatalf("审核拒绝应退全款, 余额 = %d", bal)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineDupTaskNoRefund 落库失败对冲:同任务号二次提交→预扣退回余额零损。
|
||||
func TestPipelineDupTaskNoRefund(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
base := func() *SubmitReq {
|
||||
return &SubmitReq{TaskNo: "D48-DUP", AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】幂等", Sign: "【测】"}
|
||||
}
|
||||
if _, err := s.Submit(context.Background(), base(), nil, base().Content, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Submit(context.Background(), base(), nil, base().Content, ""); err == nil {
|
||||
t.Fatal("重复任务号应失败")
|
||||
}
|
||||
if bal := getBal(t, db, 1); bal != 9998 {
|
||||
t.Fatalf("二次提交失败应对冲退回, 余额 = %d 期望 9998", bal)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineTimerNoEmit→Day52 R2 更名语义:定时任务亦投事件(载明细,消费侧落明细后
|
||||
// 由 timer 域到点认领;claim 的 send_type 域保证不被消费侧误下发)。
|
||||
func TestPipelineTimerNoEmit(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
sink := &captureSink{}
|
||||
s.sink = sink
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
future := time.Now().Add(2 * time.Hour).Format("2006-01-02 15:04")
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeTimer, SendAt: future,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】定时", Sign: "【测】"}
|
||||
if _, err := s.Submit(context.Background(), req, nil, req.Content, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sink.events) != 1 || len(sink.details[0]) != 1 {
|
||||
t.Fatalf("Day52 R2:定时任务应投事件载明细(消费侧落库): %d 次", len(sink.events))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitPersonalPipeline 个性短信同构:预扣+拦截退费。
|
||||
func TestSubmitPersonalPipeline(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
s.chain = interceptor.NewChain(nil, &fakeBlocker{hit: map[string]bool{"13800138002": true}})
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
items := []PersonalItem{
|
||||
{Mobile: "13800138001", Content: "【测】个性A"},
|
||||
{Mobile: "13800138002", Content: "【测】个性B"},
|
||||
}
|
||||
if _, err := s.SubmitPersonal(context.Background(), 1, items, nil, "", "", "", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bal := getBal(t, db, 1); bal != 9999 { // 扣 2 退 1
|
||||
t.Fatalf("个性拦截退费后余额 = %d, 期望 9999", bal)
|
||||
}
|
||||
var blocked int64
|
||||
db.Model(&entity.MessageDetail{}).
|
||||
Where("mobile = ? AND status = ?", "13800138002", 5).Count(&blocked)
|
||||
if blocked != 1 {
|
||||
t.Fatalf("个性拦截明细终态缺失(%d)", blocked)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineDetailsViaEvent Day52 R2 核心口径:事件投递成功时入口零明细写
|
||||
// (DB 明细 0 行),明细全量在事件里(雪花 ID 预生成+拦截终态行)。
|
||||
func TestPipelineDetailsViaEvent(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
s.chain = interceptor.NewChain(nil, &fakeBlocker{hit: map[string]bool{"13800138001": true}})
|
||||
prod := &fakeQueueProd{}
|
||||
s.sink = ProducerSink{P: prod, Source: "test"}
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】事件明细", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", res.Task.ID).Count(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("入口事务零明细写红线被破: %d 行", n)
|
||||
}
|
||||
if len(prod.vals) != 1 {
|
||||
t.Fatalf("应投 1 条事件: %d", len(prod.vals))
|
||||
}
|
||||
var ev SubmitEvent
|
||||
if err := json.Unmarshal(prod.vals[0], &ev); err != nil {
|
||||
t.Fatalf("事件解析: %v", err)
|
||||
}
|
||||
if len(ev.Details) != 2 || ev.PassCount != 1 {
|
||||
t.Fatalf("事件应载 2 行明细/pass=1: len=%d pass=%d", len(ev.Details), ev.PassCount)
|
||||
}
|
||||
for _, d := range ev.Details {
|
||||
if d.ID == 0 {
|
||||
t.Fatal("明细雪花 ID 应入口预生成")
|
||||
}
|
||||
}
|
||||
var blockedRow, aliveRow *EventDetail
|
||||
for i := range ev.Details {
|
||||
if ev.Details[i].Mobile == "13800138001" {
|
||||
blockedRow = &ev.Details[i]
|
||||
} else {
|
||||
aliveRow = &ev.Details[i]
|
||||
}
|
||||
}
|
||||
if aliveRow == nil || aliveRow.Status != 0 || aliveRow.Mobile != "13800138000" {
|
||||
t.Fatalf("存活行口径错: %+v", aliveRow)
|
||||
}
|
||||
if blockedRow == nil || blockedRow.Status != 5 || blockedRow.ErrorCode != "ISC:021" {
|
||||
t.Fatalf("拦截行终态错: %+v", blockedRow)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipelineEmitFallback Kafka 故障降级:投递失败同步落明细(零丢失红线,旧行为兜底)。
|
||||
func TestPipelineEmitFallback(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
s.sink = ProducerSink{P: &fakeQueueProd{err: fmt.Errorf("kafka down")}, Source: "test"}
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】降级", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("受理 err=%v", err)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", res.Task.ID).Count(&n)
|
||||
if n != 1 {
|
||||
t.Fatalf("降级应同步落明细: %d 行", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// refund.go Day 48:全流程失败回款——各环节(落库失败/拦截退费/审核拒绝/消费失败)
|
||||
// 统一经 RefundTask 原子加回余额并记流水,口径与 Day43 审核超时回退一致
|
||||
// (balance 整型条数;Amount 负=扣款 正=退款)。
|
||||
// Day 54 R1:预扣/退款统一走 balance.Store(mysql 行锁|redis Lua+异步流水,
|
||||
// 评审 docs/review/r1-balance.md);本文件保留 MySQL 原路径实现,
|
||||
// 由 balance.MySQLStore 与回退路径复用。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go-sms/internal/service/balance"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RefundTask 退款兼容壳(Day54 起资金操作归口 balance.Store;外部历史调用零破坏)。
|
||||
func RefundTask(ctx context.Context, db *gorm.DB, accountID, amount int64,
|
||||
taskNo, reason string) error {
|
||||
return balance.NewMySQLStore(db).Refund(ctx, accountID, amount, taskNo, reason)
|
||||
}
|
||||
|
||||
// holdFee 预扣壳:经 s.bal(R1:flag=redis 时 Lua 原子扣,基础设施错自动回退 MySQL)。
|
||||
func (s *SubmitService) holdFee(ctx context.Context, accountID, fee int64, taskNo string) error {
|
||||
return s.bal.Hold(ctx, accountID, fee, taskNo)
|
||||
}
|
||||
|
||||
// refund 退款壳:经 s.bal(R1:redis 模式 Lua 加回+异步流水)。
|
||||
func (s *SubmitService) refund(ctx context.Context, accountID, amount int64,
|
||||
taskNo, reason string) error {
|
||||
return s.bal.Refund(ctx, accountID, amount, taskNo, reason)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// seg.go Day 56:段级回执配对登记——提交成功路径逐段写 message_report_seg
|
||||
// (msg_id+mobile 唯一),回执消费者按段置态聚合判 detail 终态(A-5.2)。
|
||||
// 写入失败仅日志不上抛:seg 缺失=该段回执到达时无配对(挂起日志),
|
||||
// 资损安全方向与 UNKNOWN 一致(宁可挂起不可错判)。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/logger"
|
||||
"go-sms/internal/service/channel/pool"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SegWriteBatch seg 批量落库分片(单条短信 1~9 段×100 号/包,500 与
|
||||
// DetailWriter 同口径;批内行数上限)。
|
||||
const SegWriteBatch = 500
|
||||
|
||||
// segRowsFor 单号 N 段行构造(PkNumber=1..N)。
|
||||
func segRowsFor(channelID, detailID int64, mobile string, msgIDs []string) []entity.MessageReportSeg {
|
||||
rows := make([]entity.MessageReportSeg, 0, len(msgIDs))
|
||||
for i, mid := range msgIDs {
|
||||
if mid == "" {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, entity.MessageReportSeg{
|
||||
DetailID: detailID, ChannelID: channelID,
|
||||
MsgID: mid, Mobile: mobile,
|
||||
PkNumber: int8(i + 1), PkTotal: int8(len(msgIDs)),
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// segRowsForBatch 合包路径:每 ack=「包×片」,包内逐号登记
|
||||
// (mobile→detailID 由 items 提供;同号跨片各一行,段数=该号出现次数)。
|
||||
func segRowsForBatch(channelID int64, items []aggrItem, acks []pool.BatchAck) []entity.MessageReportSeg {
|
||||
byMobile := make(map[string]int64, len(items))
|
||||
for _, it := range items {
|
||||
byMobile[it.mobile] = it.detailID
|
||||
}
|
||||
var rows []entity.MessageReportSeg
|
||||
for _, a := range acks {
|
||||
for _, mo := range a.Mobiles {
|
||||
detailID, ok := byMobile[mo]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, entity.MessageReportSeg{
|
||||
DetailID: detailID, ChannelID: channelID,
|
||||
MsgID: a.MsgID, Mobile: mo,
|
||||
PkNumber: int8(a.PkNumber), PkTotal: int8(a.PkTotal),
|
||||
})
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// writeSegRows 批量落库(失败仅 Warn;调用方在消费链路,不因 seg 失败
|
||||
// 阻断明细终态回写——配对缺失的回执按挂起口径兜底)。
|
||||
func writeSegRows(ctx context.Context, db *gorm.DB, rows []entity.MessageReportSeg) {
|
||||
if len(rows) == 0 || db == nil {
|
||||
return
|
||||
}
|
||||
if err := db.WithContext(ctx).CreateInBatches(rows, SegWriteBatch).Error; err != nil {
|
||||
logger.L().Warn("report_seg_write_failed", zap.Int("rows", len(rows)), zap.Error(err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// seg_test.go Day 56:段级配对登记构造单测——单号 N 段/合包包×片展开。
|
||||
package send
|
||||
|
||||
import (
|
||||
"go-sms/internal/service/channel/pool"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSegRowsFor_Single 单号:1~9 段逐段构造,PkNumber 连续、PkTotal=段数。
|
||||
func TestSegRowsFor_Single(t *testing.T) {
|
||||
rows := segRowsFor(7, 42, "13800001111", []string{"m1", "m2", "m3", "", "m5"})
|
||||
if len(rows) != 4 { // 空 msg_id 跳过
|
||||
t.Fatalf("行数=%d 期望 4(空段跳过)", len(rows))
|
||||
}
|
||||
if rows[0].MsgID != "m1" || rows[0].PkNumber != 1 || rows[0].PkTotal != 5 {
|
||||
t.Fatalf("首段错误: %+v", rows[0])
|
||||
}
|
||||
if rows[3].MsgID != "m5" || rows[3].PkNumber != 5 {
|
||||
t.Fatalf("末段序号错误: %+v", rows[3])
|
||||
}
|
||||
}
|
||||
|
||||
// TestSegRowsForBatch 合包:每片 ack×包内每号一行(长短信=号×片)。
|
||||
func TestSegRowsForBatch(t *testing.T) {
|
||||
items := []aggrItem{
|
||||
{detailID: 1, mobile: "13111110001"},
|
||||
{detailID: 2, mobile: "13111110002"},
|
||||
}
|
||||
acks := []pool.BatchAck{
|
||||
{MsgID: "f1", Mobiles: []string{"13111110001", "13111110002"}, PkNumber: 1, PkTotal: 2},
|
||||
{MsgID: "f2", Mobiles: []string{"13111110001", "13111110002"}, PkNumber: 2, PkTotal: 2},
|
||||
}
|
||||
rows := segRowsForBatch(7, items, acks)
|
||||
if len(rows) != 4 { // 2 号 × 2 片
|
||||
t.Fatalf("行数=%d 期望 4", len(rows))
|
||||
}
|
||||
seen := map[string][2]int8{}
|
||||
for _, r := range rows {
|
||||
seen[r.Mobile+"|"+r.MsgID] = [2]int8{r.PkNumber, r.PkTotal}
|
||||
}
|
||||
if got := seen["13111110001|f2"]; got != [2]int8{2, 2} {
|
||||
t.Fatalf("号1/片2 段序错误: %v", got)
|
||||
}
|
||||
if got := seen["13111110002|f1"]; got != [2]int8{1, 2} {
|
||||
t.Fatalf("号2/片1 段序错误: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/service/balance"
|
||||
"go-sms/internal/service/interceptor"
|
||||
"go-sms/internal/util"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TaskRouter 审核分流接口(audit.ReviewService 实现;依赖倒置避免 send→audit 包依赖)。
|
||||
// nil 时不分流,任务停留待审(由 48h 超时扫描兜底)。
|
||||
type TaskRouter interface {
|
||||
Route(ctx context.Context, taskID int64) (*entity.MessageTask, *entity.AuditRecord, error)
|
||||
}
|
||||
|
||||
// SubmitService 发送提交服务(Day 43 修复循环起步,Day 48 升级全流程状态机)。
|
||||
// 链路:校验→预扣→落库→拦截(退费)→审核分流(拒绝退费)→Kafka 事件;
|
||||
// 路由与下发移交 submit 消费者(同步链路 MySQL 禁令,技术方案 10.4.3)。
|
||||
type SubmitService struct {
|
||||
db *gorm.DB
|
||||
sf *util.Snowflake
|
||||
rt TaskRouter
|
||||
chain *interceptor.Chain // Day 48:受理期拦截(nil=跳过,兼容测试)
|
||||
sink EventSink // Day 48:sms-submit 统一出口(nil=不投)
|
||||
bal balance.Store // Day 54 R1:资金预扣/退款(mysql 行锁|redis Lua)
|
||||
}
|
||||
|
||||
// NewSubmitService 构造(rt 可 nil:single-test/未装配审核时分流跳过;
|
||||
// opts 按 Day48 链路注入拦截链/事件出口,Day54 R1 注入资金 Store)。
|
||||
func NewSubmitService(db *gorm.DB, sf *util.Snowflake, rt TaskRouter, opts ...SubmitOption) *SubmitService {
|
||||
s := &SubmitService{db: db, sf: sf, rt: rt}
|
||||
for _, opt := range opts {
|
||||
opt(s)
|
||||
}
|
||||
if s.bal == nil { // 未注入退化为 MySQL 原路径(既有测试/降级装配零破坏)
|
||||
s.bal = balance.NewMySQLStore(db)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// SubmitResult 提交结果(任务+分流后审核态+预估)。
|
||||
type SubmitResult struct {
|
||||
Task *entity.MessageTask
|
||||
Record *entity.AuditRecord // 自动档留痕(其余 nil)
|
||||
Estimate *Estimate
|
||||
}
|
||||
|
||||
// Submit 受理发送任务(Day 48 全流程状态机):
|
||||
// ①Validate ②余额快检 ③holdFee 原子预扣(不足→ISC:007;扣后失败环节全对冲)
|
||||
// ④事务{task+明细(拦截号直接终态 5)}(失败→Refund 全额)
|
||||
// ⑤拦截费即时退(RefundTask blockedFee) ⑥Route 审核(拒绝→退剩余)
|
||||
// ⑦EmitSubmit(有存活号才投;0 号存活=全拦终态)。
|
||||
// taskNo 幂等:请求带则用(uk 冲突→ISC:400),缺省生成 T+时间戳+随机。
|
||||
func (s *SubmitService) Submit(ctx context.Context, req *SubmitReq, tpl *entity.TemplateSMS,
|
||||
content string, clientIP string) (*SubmitResult, error) {
|
||||
est, err := req.Validate(tpl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 定时时刻(Validate 已保证 type3 非空;格式与 reschedule 同口径)。
|
||||
var scheduleAt *time.Time
|
||||
if req.SendType == SendTypeTimer {
|
||||
at, perr := time.ParseInLocation("2006-01-02 15:04", req.SendAt, time.Local)
|
||||
if perr != nil {
|
||||
return nil, errors.InvalidParam.WithMsg("send_at 格式须为 YYYY-MM-DD HH:mm")
|
||||
}
|
||||
if !at.After(time.Now()) {
|
||||
return nil, errors.InvalidParam.WithMsg("定时时刻须在未来")
|
||||
}
|
||||
scheduleAt = &at
|
||||
}
|
||||
// ②余额只读快检(快速失败体验;并发竞态由 ③原子预扣兜底精确拒绝)。
|
||||
var acct entity.AccountUser
|
||||
if err := s.db.WithContext(ctx).Select("id", "balance").
|
||||
First(&acct, req.AccountID).Error; err != nil {
|
||||
return nil, errors.NotFound.WithMsg("账号不存在")
|
||||
}
|
||||
if acct.Balance < int64(est.TotalFee) {
|
||||
return nil, errors.Arrears.WithMsg(
|
||||
fmt.Sprintf("余额不足:当前 %d 条,本次需 %d 条", acct.Balance, est.TotalFee))
|
||||
}
|
||||
// Day 49:video 须账号已开通(AccountConfig 业务行,openapi 鉴权同口径);
|
||||
// 未开通拒绝发生在预扣前,无需退款对冲。
|
||||
if req.Business == BusinessVideo {
|
||||
var n int64
|
||||
if err := s.db.WithContext(ctx).Model(&entity.AccountConfig{}).
|
||||
Where("account_id = ? AND business = ?", req.AccountID, BusinessVideo).
|
||||
Count(&n).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, errors.Forbidden.WithMsg("账号未开通视频短信业务")
|
||||
}
|
||||
}
|
||||
// 幂等任务号。
|
||||
taskNo := strings.TrimSpace(req.TaskNo)
|
||||
if taskNo == "" {
|
||||
taskNo = genTaskNo()
|
||||
}
|
||||
// ③原子预扣(WHERE balance>=fee;Day48 状态机起点——此后失败环节必有退款)。
|
||||
if err := s.holdFee(ctx, req.AccountID, int64(est.TotalFee), taskNo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
task := entity.MessageTask{
|
||||
TaskNo: taskNo, AccountID: req.AccountID,
|
||||
SendType: req.SendType, Content: content, Sign: req.Sign,
|
||||
MobileCount: est.ValidCount, FeeTotal: float64(est.TotalFee),
|
||||
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
||||
CallData: util.Truncate(req.CallData, 64), // Day 46:回执回传数据(截断防溢出)
|
||||
Business: req.Business, // Day 49:sms/video(Validate 已规范化)
|
||||
Source: NormalizeTaskSource(req.Source), // Day 60:受理来源(WEB=4/CMPP=2/SMPP=3/API=1)
|
||||
}
|
||||
// ⑤拦截预判定(内存;落库时拦截号直接终态 5,存活号才进下发域)。
|
||||
mobiles := validMobiles(req)
|
||||
blocks := make([]*interceptor.Block, len(mobiles))
|
||||
blockedFee, passCount := 0, 0
|
||||
// Day51 R3:请求级快照——白名单/黑名单批量 IN+策略/签名跨号复用(100 号 400 查→≤3 查)。
|
||||
sc := s.chain.NewScope(ctx, req.AccountID, mobiles)
|
||||
for i, m := range mobiles {
|
||||
if b := s.intercept(ctx, taskNo, req.AccountID, req.SendType, m, content, sc); b != nil {
|
||||
blocks[i] = b
|
||||
blockedFee += est.Segments
|
||||
continue
|
||||
}
|
||||
passCount++
|
||||
}
|
||||
details := make([]entity.MessageDetail, 0, est.ValidCount)
|
||||
for i, m := range mobiles {
|
||||
d := entity.MessageDetail{
|
||||
TaskID: 0, AccountID: req.AccountID,
|
||||
Mobile: m, Content: content, Status: 0, Fee: float64(est.Segments),
|
||||
ExtCode: util.Truncate(req.Extend, 32), // Day 46:扩展码透传
|
||||
CallData: util.Truncate(req.CallData, 64),
|
||||
Business: req.Business, Source: NormalizeTaskSource(req.Source), // Day66:明细单表化冗余
|
||||
}
|
||||
if blocks[i] != nil { // 拦截号:受理期即终态(ISC 码 16 字符截断)
|
||||
d.Status = 5
|
||||
d.ErrorCode = util.Truncate(blocks[i].Code, 16)
|
||||
}
|
||||
d.ID = s.sf.NextID() // 雪花主键(嵌入结构体,赋值式填入)
|
||||
details = append(details, d)
|
||||
}
|
||||
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&task).Error; err != nil {
|
||||
msg := strings.ToUpper(err.Error())
|
||||
if strings.Contains(msg, "DUPLICATE") || strings.Contains(msg, "1062") || // MySQL
|
||||
strings.Contains(msg, "UNIQUE CONSTRAINT") { // SQLite
|
||||
return errors.InvalidParam.WithMsg("任务号已存在: " + taskNo)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil // Day52 R2:入口事务仅落 task(同步链路零明细写,方案 10.4.3)
|
||||
})
|
||||
if err != nil {
|
||||
// ④落库失败:预扣全额对冲(状态机不变量——受理失败余额零损)。
|
||||
_ = s.refund(ctx, req.AccountID, int64(est.TotalFee), taskNo, "落库失败退回")
|
||||
return nil, err
|
||||
}
|
||||
for i := range details { // 事件/降级路径共用:TaskID 事务后回填(消费侧落库亦用)
|
||||
details[i].TaskID = task.ID
|
||||
}
|
||||
// ⑤拦截号费用即时退(预扣按全额,被拦号未消费;RefundTask 幂等由一次性调用保证)。
|
||||
if blockedFee > 0 {
|
||||
_ = s.refund(ctx, req.AccountID, int64(blockedFee), taskNo, "拦截号码退费")
|
||||
}
|
||||
// Day52 R2:明细随 sms-submit 投递(全拦/定时亦投——拦截记录与定时明细同为对账事实源;
|
||||
// 消费侧 claim 不认领全拦终态 2/待审 audit=0/定时域 send_type=3,仅落明细即返回)。
|
||||
s.emitOrFallback(ctx, &task, details)
|
||||
// 全拦:任务直接终态(事件已投,拦截明细由消费侧落库;计数=fail)。
|
||||
if passCount == 0 {
|
||||
_ = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", task.ID, 0).
|
||||
Updates(map[string]any{
|
||||
"status": taskStDone, "fail_count": len(mobiles), "finished_at": time.Now(),
|
||||
}).Error
|
||||
task.Status = taskStDone
|
||||
task.FailCount = len(mobiles)
|
||||
return &SubmitResult{Task: &task, Estimate: est}, nil
|
||||
}
|
||||
// 审核分流(事务外;三模式落定。失败不回滚受理——任务停留待审,48h Scanner 兜底)。
|
||||
var rec *entity.AuditRecord
|
||||
if s.rt != nil {
|
||||
t2, r2, rerr := s.rt.Route(ctx, task.ID)
|
||||
if rerr != nil {
|
||||
return nil, fmt.Errorf("任务已受理(任务号 %s)但审核分流失败: %w", taskNo, rerr)
|
||||
}
|
||||
task, rec = *t2, r2
|
||||
// ⑥审核拒绝:存活号费用全退(拦截费 ⑤ 已退;幂等由 Route 原子翻转保证只进一次)。
|
||||
if task.AuditStatus == 2 {
|
||||
_ = s.refund(ctx, req.AccountID,
|
||||
int64(est.TotalFee)-int64(blockedFee), taskNo, "审核拒绝退费")
|
||||
}
|
||||
}
|
||||
return &SubmitResult{Task: &task, Record: rec, Estimate: est}, nil
|
||||
}
|
||||
|
||||
// NextMsgID 预生成雪花 MsgID(入向长短信聚合组ID;与 DetailID 同源空间,
|
||||
// 供接入层首片分配、N 片 Resp 复用、合并受理时注入为首条 DetailID)。
|
||||
func (s *SubmitService) NextMsgID() int64 { return s.sf.NextID() }
|
||||
|
||||
// FastResult 快路径受理结果(P0-1)。
|
||||
type FastResult struct {
|
||||
MsgID int64 // =首条 DetailID 雪花(CMPP Submit_Resp 与 Deliver msg_id 同口径)
|
||||
TaskNo string // 幂等任务号(对账/退费键)
|
||||
}
|
||||
|
||||
// SubmitFast P0-1(Day 63)接入快路径:CMPP 高并发压测 80 并发封顶 ~45/s
|
||||
// (fsync 调优后),根因=同步链 5-8 次 DB 往返。快路径只做四件事:
|
||||
// ①Validate(内存) ②holdFee 原子预扣(Redis Lua ~1ms;欠费快速失败+防透支)
|
||||
// ③DetailID 雪花预生成 ④EmitSubmit(Deferred 事件,task.ID=0);
|
||||
// 拦截判定/任务落库/退费/审核分流全部移消费侧 handleDeferred 补全——
|
||||
// 平台=中间削峰缓存,受理速率与下发速率解耦(上下游流速不对齐是常态)。
|
||||
// 零 DB 读写;sink 未装配或投递失败→全额退费+返回错误(客户端重试,不丢)。
|
||||
func (s *SubmitService) SubmitFast(ctx context.Context, req *SubmitReq,
|
||||
content string, clientIP string) (*FastResult, error) {
|
||||
est, err := req.Validate(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 定时校验(与 Submit 同口径;CMPP 无定时,HTTP 走老路径,防御性保留)。
|
||||
var scheduleAt *time.Time
|
||||
if req.SendType == SendTypeTimer {
|
||||
at, perr := time.ParseInLocation("2006-01-02 15:04", req.SendAt, time.Local)
|
||||
if perr != nil {
|
||||
return nil, errors.InvalidParam.WithMsg("send_at 格式须为 YYYY-MM-DD HH:mm")
|
||||
}
|
||||
if !at.After(time.Now()) {
|
||||
return nil, errors.InvalidParam.WithMsg("定时时刻须在未来")
|
||||
}
|
||||
scheduleAt = &at
|
||||
}
|
||||
taskNo := strings.TrimSpace(req.TaskNo)
|
||||
if taskNo == "" {
|
||||
taskNo = genTaskNo()
|
||||
}
|
||||
// 原子预扣(Redis 优先;不足→ISC:007 同步拒绝——欠费是受理侧唯一同步拒绝语义)。
|
||||
tHold := time.Now()
|
||||
holdErr := s.holdFee(ctx, req.AccountID, int64(est.TotalFee), taskNo)
|
||||
holdCost := time.Since(tHold)
|
||||
if holdErr != nil {
|
||||
return nil, holdErr
|
||||
}
|
||||
task := entity.MessageTask{ // ID=0:自增主键由消费侧 handleDeferred 生成。
|
||||
TaskNo: taskNo, AccountID: req.AccountID,
|
||||
SendType: req.SendType, Content: content, Sign: req.Sign,
|
||||
MobileCount: est.ValidCount, FeeTotal: float64(est.TotalFee),
|
||||
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
||||
CallData: util.Truncate(req.CallData, 64),
|
||||
Business: req.Business, Source: NormalizeTaskSource(req.Source),
|
||||
}
|
||||
mobiles := validMobiles(req)
|
||||
details := make([]entity.MessageDetail, 0, len(mobiles))
|
||||
for i, m := range mobiles {
|
||||
d := entity.MessageDetail{
|
||||
AccountID: req.AccountID, Mobile: m, Content: content,
|
||||
Status: 0, Fee: float64(est.Segments), // 未拦截判定:消费侧 Check 后终态化
|
||||
ExtCode: util.Truncate(req.Extend, 32), CallData: util.Truncate(req.CallData, 64),
|
||||
Business: req.Business, Source: NormalizeTaskSource(req.Source), // Day66:明细单表化冗余
|
||||
}
|
||||
d.ID = s.sf.NextID()
|
||||
if i == 0 && req.PresetMsgID != 0 { // 长短信聚合组ID 注入:Resp/Deliver/明细三口径同 ID
|
||||
d.ID = req.PresetMsgID
|
||||
}
|
||||
details = append(details, d)
|
||||
}
|
||||
if len(details) == 0 { // 合格号为 0:预扣按 0 条(Validate 已拒空号列表,防御)。
|
||||
return &FastResult{MsgID: 0, TaskNo: taskNo}, nil
|
||||
}
|
||||
// 投递(Deferred 事件);快路径无 DB 降级路径——失败退全款+拒绝(客户端重试)。
|
||||
tEmit := time.Now()
|
||||
var emitErr error
|
||||
if s.sink == nil {
|
||||
emitErr = errors.InternalError.WithMsg("事件出口未装配")
|
||||
} else {
|
||||
emitErr = s.sink.EmitSubmit(ctx, &task, details)
|
||||
}
|
||||
if emitCost := time.Since(tEmit); emitCost > 80*time.Millisecond {
|
||||
WarnSubmitFastSlow(emitCost, holdCost) // P0-1 诊断(临时)
|
||||
}
|
||||
if emitErr != nil {
|
||||
_ = s.refund(ctx, req.AccountID, int64(est.TotalFee), taskNo, "快路径投递失败退回")
|
||||
return nil, emitErr
|
||||
}
|
||||
return &FastResult{MsgID: details[0].ID, TaskNo: taskNo}, nil
|
||||
}
|
||||
|
||||
// emitOrFallback 投递明细事件(Day52 R2);sink 未装配或投递失败降级同步落明细
|
||||
// (明细=对账事实源,零丢失红线;任务下发由 ReclaimScanner/Timer 扫描兜底认领)。
|
||||
func (s *SubmitService) emitOrFallback(ctx context.Context, task *entity.MessageTask,
|
||||
details []entity.MessageDetail) {
|
||||
if len(details) == 0 {
|
||||
return
|
||||
}
|
||||
if s.sink != nil {
|
||||
if err := s.sink.EmitSubmit(ctx, task, details); err == nil {
|
||||
return
|
||||
}
|
||||
// Kafka 故障窗口:降级回同步落库旧路径(性能让位于正确性)。
|
||||
}
|
||||
_ = s.db.WithContext(ctx).CreateInBatches(details, 500).Error
|
||||
}
|
||||
|
||||
// validMobiles 归一去重后的合格号码(与 Validate 同规则,供明细落库)。
|
||||
func validMobiles(r *SubmitReq) []string {
|
||||
seen := make(map[string]struct{}, len(r.Mobiles))
|
||||
out := make([]string, 0, len(r.Mobiles))
|
||||
for _, m := range r.Mobiles {
|
||||
n := util.NormalizeMobile(m)
|
||||
if !util.IsValidMainlandMobile(n) {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[n]; !dup {
|
||||
seen[n] = struct{}{}
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// genTaskNo 生成任务号 T+yyyyMMddHHmmss+6 位随机(≤32 字符)。
|
||||
// Day50 压测修复:4 位随机在 ~17 req/s 下 5min 即碰撞 3 次(实测);
|
||||
// 50 req/s(5000TPS 批量)时扩至 6 位,碰撞由任务号唯一索引+code:5 幂等兜底。
|
||||
func genTaskNo() string {
|
||||
n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
|
||||
return fmt.Sprintf("T%s%06d", time.Now().Format("20060102150405"), n.Int64())
|
||||
}
|
||||
|
||||
// PersonalItem 个性短信条目(逐号独立内容;Day 46 sendMessageOne)。
|
||||
type PersonalItem struct {
|
||||
Mobile string
|
||||
Content string
|
||||
}
|
||||
|
||||
// MaxPersonalItems 单次个性短信条目上限(协议文档 sendMessageOne 上限 1000)。
|
||||
const MaxPersonalItems = 1000
|
||||
|
||||
// SubmitPersonal 个性短信受理(Day 46 外部 API sendMessageOne):
|
||||
// 单 task(SendType=2)+逐 detail 独立内容;费用=逐条 segments 累计;
|
||||
// 余额校验/事务落库/审核分流与 Submit 同口径。号码去重取首条内容。
|
||||
// source Day 60:受理来源打标(0→API 归一)。
|
||||
func (s *SubmitService) SubmitPersonal(ctx context.Context, accountID int64,
|
||||
items []PersonalItem, scheduleAt *time.Time, extend, callData, clientIP string,
|
||||
source int8) (*SubmitResult, error) {
|
||||
if len(items) == 0 {
|
||||
return nil, errors.InvalidParam.WithMsg("个性短信条目为空")
|
||||
}
|
||||
if len(items) > MaxPersonalItems {
|
||||
return nil, errors.InvalidParam.WithMsg(fmt.Sprintf("条目 %d 超单次上限 %d", len(items), MaxPersonalItems))
|
||||
}
|
||||
seen := make(map[string]struct{}, len(items))
|
||||
merged := make([]PersonalItem, 0, len(items))
|
||||
totalFee := 0
|
||||
for _, it := range items {
|
||||
n := util.NormalizeMobile(it.Mobile)
|
||||
if !util.IsValidMainlandMobile(n) {
|
||||
return nil, errors.InvalidParam.WithMsg("非法手机号: " + it.Mobile)
|
||||
}
|
||||
if it.Content == "" {
|
||||
return nil, errors.InvalidParam.WithMsg("内容为空: " + n)
|
||||
}
|
||||
if rc := len([]rune(it.Content)); rc > MaxTextLen {
|
||||
return nil, errors.InvalidParam.WithMsg(fmt.Sprintf("内容 %d 字超上限 %d: %s", rc, MaxTextLen, n))
|
||||
}
|
||||
if _, dup := seen[n]; dup {
|
||||
continue
|
||||
}
|
||||
seen[n] = struct{}{}
|
||||
_, seg := util.SmsLength(it.Content)
|
||||
if seg == 0 {
|
||||
seg = 1
|
||||
}
|
||||
totalFee += seg
|
||||
merged = append(merged, PersonalItem{Mobile: n, Content: it.Content})
|
||||
}
|
||||
if len(merged) == 0 {
|
||||
return nil, errors.InvalidParam.WithMsg("无有效条目")
|
||||
}
|
||||
// 余额只读快检 + 原子预扣(Day48 与 Submit 同口径)。
|
||||
var acct entity.AccountUser
|
||||
if err := s.db.WithContext(ctx).Select("id", "balance").
|
||||
First(&acct, accountID).Error; err != nil {
|
||||
return nil, errors.NotFound.WithMsg("账号不存在")
|
||||
}
|
||||
if acct.Balance < int64(totalFee) {
|
||||
return nil, errors.Arrears.WithMsg(
|
||||
fmt.Sprintf("余额不足:当前 %d 条,本次需 %d 条", acct.Balance, totalFee))
|
||||
}
|
||||
taskNo := genTaskNo()
|
||||
if err := s.holdFee(ctx, accountID, int64(totalFee), taskNo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
task := entity.MessageTask{
|
||||
TaskNo: taskNo, AccountID: accountID,
|
||||
SendType: SendTypePersonal, Content: merged[0].Content,
|
||||
MobileCount: len(merged), FeeTotal: float64(totalFee),
|
||||
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
||||
CallData: util.Truncate(callData, 64),
|
||||
Source: NormalizeTaskSource(source), // Day 60:受理来源
|
||||
}
|
||||
// 逐号拦截(独立内容;命中号受理期终态 5+计费退)。
|
||||
// Day51 R3:请求级快照同 Submit(个性批量同受益)。
|
||||
blocks := make([]*interceptor.Block, len(merged))
|
||||
blockedFee, passCount := 0, 0
|
||||
pm := make([]string, len(merged))
|
||||
for i, it := range merged {
|
||||
pm[i] = it.Mobile
|
||||
}
|
||||
sc := s.chain.NewScope(ctx, accountID, pm)
|
||||
for i, it := range merged {
|
||||
if b := s.intercept(ctx, taskNo, accountID, SendTypePersonal, it.Mobile, it.Content, sc); b != nil {
|
||||
blocks[i] = b
|
||||
if _, seg := util.SmsLength(it.Content); seg > 0 {
|
||||
blockedFee += seg
|
||||
} else {
|
||||
blockedFee++
|
||||
}
|
||||
continue
|
||||
}
|
||||
passCount++
|
||||
}
|
||||
details := make([]entity.MessageDetail, 0, len(merged))
|
||||
for i, it := range merged {
|
||||
_, seg := util.SmsLength(it.Content)
|
||||
if seg == 0 {
|
||||
seg = 1
|
||||
}
|
||||
d := entity.MessageDetail{
|
||||
AccountID: accountID, Mobile: it.Mobile, Content: it.Content,
|
||||
Status: 0, Fee: float64(seg),
|
||||
ExtCode: util.Truncate(extend, 32),
|
||||
CallData: util.Truncate(callData, 64),
|
||||
Business: task.Business, Source: task.Source, // Day66:明细单表化冗余(个性发 task 已 Normalize)
|
||||
}
|
||||
if blocks[i] != nil {
|
||||
d.Status = 5
|
||||
d.ErrorCode = util.Truncate(blocks[i].Code, 16)
|
||||
}
|
||||
d.ID = s.sf.NextID()
|
||||
details = append(details, d)
|
||||
}
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&task).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil // Day52 R2:入口事务仅落 task(明细移消费侧批量落库)
|
||||
})
|
||||
if err != nil {
|
||||
_ = s.refund(ctx, accountID, int64(totalFee), taskNo, "落库失败退回")
|
||||
return nil, err
|
||||
}
|
||||
for i := range details { // Day52 R2:事件/降级路径共用 TaskID 回填
|
||||
details[i].TaskID = task.ID
|
||||
}
|
||||
if blockedFee > 0 {
|
||||
_ = s.refund(ctx, accountID, int64(blockedFee), taskNo, "拦截号码退费")
|
||||
}
|
||||
// Day52 R2:明细随事件投递(全拦/定时亦投;消费侧 claim 域外仅落明细)。
|
||||
s.emitOrFallback(ctx, &task, details)
|
||||
if passCount == 0 {
|
||||
_ = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", task.ID, 0).
|
||||
Updates(map[string]any{
|
||||
"status": taskStDone, "fail_count": len(merged), "finished_at": time.Now(),
|
||||
}).Error
|
||||
task.Status = taskStDone
|
||||
task.FailCount = len(merged)
|
||||
return &SubmitResult{Task: &task}, nil
|
||||
}
|
||||
var rec *entity.AuditRecord
|
||||
if s.rt != nil {
|
||||
t2, r2, rerr := s.rt.Route(ctx, task.ID)
|
||||
if rerr != nil {
|
||||
return nil, fmt.Errorf("任务已受理(任务号 %s)但审核分流失败: %w", taskNo, rerr)
|
||||
}
|
||||
task, rec = *t2, r2
|
||||
if task.AuditStatus == 2 { // 审核拒绝:存活号费用退(拦截费已退)
|
||||
_ = s.refund(ctx, accountID,
|
||||
int64(totalFee)-int64(blockedFee), taskNo, "审核拒绝退费")
|
||||
}
|
||||
}
|
||||
est := &Estimate{ValidCount: len(merged), TotalFee: totalFee}
|
||||
return &SubmitResult{Task: &task, Record: rec, Estimate: est}, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// submit_source_test.go Day 60(D24-25):受理来源打标——SubmitReq.Source/
|
||||
// SubmitPersonal source 归一(0/非法→API=1;入口显式 2 CMPP/3 SMPP/4 WEB),
|
||||
// message_task.source 落库供下行明细 v2 筛选。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
)
|
||||
|
||||
func TestNormalizeTaskSource(t *testing.T) {
|
||||
cases := []struct {
|
||||
in, want int8
|
||||
}{{-1, 1}, {0, 1}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 1}, {99, 1}}
|
||||
for _, c := range cases {
|
||||
if got := NormalizeTaskSource(c.in); got != c.want {
|
||||
t.Fatalf("NormalizeTaskSource(%d) = %d, 期望 %d", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitSourceTagging(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
// WEB 控制台入口显式打标 4。
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】来源打标", Sign: "【测】",
|
||||
Source: TaskSourceWeb}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("submit err=%v", err)
|
||||
}
|
||||
if res.Task.Source != TaskSourceWeb {
|
||||
t.Fatalf("WEB 提交 source = %d, 期望 %d", res.Task.Source, TaskSourceWeb)
|
||||
}
|
||||
// 未打标(0)缺省归一 API=1(历史调用方/openapi HTTP 直入)。
|
||||
req2 := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138001"}, Content: "【测】缺省来源", Sign: "【测】"}
|
||||
res2, err := s.Submit(context.Background(), req2, nil, req2.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("submit2 err=%v", err)
|
||||
}
|
||||
if res2.Task.Source != TaskSourceAPI {
|
||||
t.Fatalf("缺省 source = %d, 期望 %d(API)", res2.Task.Source, TaskSourceAPI)
|
||||
}
|
||||
// 落库复核(响应内存对象与库行一致)。
|
||||
var rows []entity.MessageTask
|
||||
if err := db.Select("id", "source").Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 2 || rows[0].Source != TaskSourceWeb || rows[1].Source != TaskSourceAPI {
|
||||
t.Fatalf("落库 source = %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitPersonalSourceTagging(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
items := []PersonalItem{{Mobile: "13800138003", Content: "【测】个性来源"}}
|
||||
|
||||
// CMPP 经 access→openapi SendOne 链传入 2。
|
||||
res, err := s.SubmitPersonal(context.Background(), 1, items, nil, "", "", "", TaskSourceCMPP)
|
||||
if err != nil {
|
||||
t.Fatalf("personal err=%v", err)
|
||||
}
|
||||
if res.Task.Source != TaskSourceCMPP {
|
||||
t.Fatalf("个性 source = %d, 期望 %d(CMPP)", res.Task.Source, TaskSourceCMPP)
|
||||
}
|
||||
// 缺省 0 → API。
|
||||
items2 := []PersonalItem{{Mobile: "13800138004", Content: "【测】个性缺省"}}
|
||||
res2, err := s.SubmitPersonal(context.Background(), 1, items2, nil, "", "", "", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("personal2 err=%v", err)
|
||||
}
|
||||
if res2.Task.Source != TaskSourceAPI {
|
||||
t.Fatalf("个性缺省 source = %d, 期望 %d(API)", res2.Task.Source, TaskSourceAPI)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
// submit_test.go Day 43 修复循环:最小提交链单测——立即/定时受理+明细雪花落库/
|
||||
// 三模式分流接线/余额只读校验/任务号幂等。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
errs "go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/service/audit"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// errCode 业务错误码(非业务错返回空串)。
|
||||
func errCode(err error) string {
|
||||
if e, ok := err.(*errs.Error); ok {
|
||||
return e.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// newSubmitDB 测试库(提交域全量表;索引撞名坑见 review_test.go 同款注记)。
|
||||
func newSubmitDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range []any{
|
||||
&entity.MessageTask{}, &entity.MessageDetail{},
|
||||
&entity.PolicyKeyword{}, &entity.AccountConfig{}, &entity.AccountUser{},
|
||||
} {
|
||||
if err := db.Migrator().CreateTable(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// account_balance_log 原生建表:其 idx_account_time 与 message_task 撞名
|
||||
// (SQLite 索引全局唯一;流水表无索引查询需求,测试内不建)。
|
||||
db.Exec(`CREATE TABLE account_balance_log (
|
||||
id integer primary key autoincrement, created_at datetime,
|
||||
account_id integer, biz_type text, amount integer,
|
||||
balance_after integer, ref_id text, operator text, remark text)`)
|
||||
// audit_record 原生建表:其 idx_status_time 与 message_detail 撞名(SQLite 索引全局唯一)。
|
||||
db.Exec(`CREATE TABLE audit_record (
|
||||
id integer primary key autoincrement, created_at datetime,
|
||||
biz_type text, biz_id integer, account_id integer, content text,
|
||||
status integer, auditor text, audit_at datetime, reason text)`)
|
||||
return db
|
||||
}
|
||||
|
||||
func newSubmitSvc(t *testing.T, db *gorm.DB) *SubmitService {
|
||||
t.Helper()
|
||||
sf, err := util.NewSnowflake(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return NewSubmitService(db, sf, audit.NewReviewService(db)) // 真 ReviewService:分流链路全真
|
||||
}
|
||||
|
||||
func mkAcct(t *testing.T, db *gorm.DB, id int64, balance int64, mode int8) {
|
||||
t.Helper()
|
||||
if err := db.Create(&entity.AccountUser{Model: entity.Model{ID: id},
|
||||
Username: "acct" + time.Now().Format("150405.000000000"), Role: "customer",
|
||||
Status: 1, Balance: balance,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&entity.AccountConfig{AccountID: id, Business: "sms",
|
||||
Protocol: "http", AuditMode: mode}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitBatchExempt 立即发送+免审:受理落任务(audit=3/status=0)+明细逐号雪花ID 唯一。
|
||||
func TestSubmitBatchExempt(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0) // 免审
|
||||
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000", "13800138001", "13800138000"}, // 含重复
|
||||
Content: "【测】促销通知", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("submit err=%v", err)
|
||||
}
|
||||
if res.Task.AuditStatus != 3 || res.Task.Status != 0 {
|
||||
t.Fatalf("免审受理 audit=%d status=%d", res.Task.AuditStatus, res.Task.Status)
|
||||
}
|
||||
if res.Estimate.ValidCount != 2 || res.Task.MobileCount != 2 || res.Task.FeeTotal != 2 {
|
||||
t.Fatalf("去重计费 valid=%d count=%d fee=%v", res.Estimate.ValidCount, res.Task.MobileCount, res.Task.FeeTotal)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", res.Task.ID).Count(&n)
|
||||
if n != 2 {
|
||||
t.Fatalf("明细行数 = %d, 期望 2(去重)", n)
|
||||
}
|
||||
var ids []int64
|
||||
db.Model(&entity.MessageDetail{}).Where("task_id = ?", res.Task.ID).Pluck("id", &ids)
|
||||
if len(ids) == 2 && ids[0] == ids[1] {
|
||||
t.Fatalf("雪花 ID 重复: %v", ids)
|
||||
}
|
||||
if res.Task.TaskNo == "" {
|
||||
t.Fatal("缺省任务号未生成")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitTimer 定时受理:ScheduleAt 落库;过去时刻拒绝。
|
||||
func TestSubmitTimer(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
|
||||
future := time.Now().Add(2 * time.Hour).Format("2006-01-02 15:04")
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeTimer, SendAt: future,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】定时", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("定时受理 err=%v", err)
|
||||
}
|
||||
if res.Task.ScheduleAt == nil || !res.Task.ScheduleAt.After(time.Now().Add(time.Hour)) {
|
||||
t.Fatalf("ScheduleAt 落库错误: %v", res.Task.ScheduleAt)
|
||||
}
|
||||
// 过去时刻 → 400
|
||||
past := time.Now().Add(-time.Hour).Format("2006-01-02 15:04")
|
||||
req2 := &SubmitReq{AccountID: 1, SendType: SendTypeTimer, SendAt: past,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】定时", Sign: "【测】"}
|
||||
if _, err := s.Submit(context.Background(), req2, nil, req2.Content, ""); err == nil {
|
||||
t.Fatal("过去时刻应拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitAuditModes 手动→0 待审/自动命中黑词→2+留痕(真 ReviewService 接线)。
|
||||
func TestSubmitAuditModes(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 2, 10000, 1) // 手动
|
||||
mkAcct(t, db, 3, 10000, 2) // 自动
|
||||
db.Create(&entity.PolicyKeyword{Word: "发票", Level: 1, Status: 1})
|
||||
|
||||
// 手动 → 保持待审 0
|
||||
req := &SubmitReq{AccountID: 2, SendType: 1, Mobiles: []string{"13800138000"},
|
||||
Content: "【测】代开发票", Sign: "【测】"}
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil || res.Task.AuditStatus != 0 {
|
||||
t.Fatalf("手动模式 audit=%d err=%v(期望 0 待审)", res.Task.AuditStatus, err)
|
||||
}
|
||||
// 自动+命中 → 2 + AuditRecord(auditor=system)
|
||||
req2 := &SubmitReq{AccountID: 3, SendType: 1, Mobiles: []string{"13800138000"},
|
||||
Content: "【测】代开发票", Sign: "【测】"}
|
||||
res2, err := s.Submit(context.Background(), req2, nil, req2.Content, "")
|
||||
if err != nil || res2.Task.AuditStatus != 2 {
|
||||
t.Fatalf("自动命中 audit=%d err=%v(期望 2 拒)", res2.Task.AuditStatus, err)
|
||||
}
|
||||
if res2.Record == nil || res2.Record.Auditor != "system" {
|
||||
t.Fatalf("自动档留痕缺失: %+v", res2.Record)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitArrears 余额只读校验:不足 → ISC:007。
|
||||
func TestSubmitArrears(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 1, 0) // 余额 1 条
|
||||
req := &SubmitReq{AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000", "13800138001"}, Content: "【测】两号", Sign: "【测】"}
|
||||
_, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err == nil {
|
||||
t.Fatal("余额不足应拒绝")
|
||||
}
|
||||
if got := errCode(err); got != "ISC:007" {
|
||||
t.Fatalf("余额不足码 = %s, 期望 ISC:007", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitDupTaskNo 任务号幂等:同号二次 → ISC:400。
|
||||
func TestSubmitDupTaskNo(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0)
|
||||
base := func() *SubmitReq {
|
||||
return &SubmitReq{TaskNo: "DUP-001", AccountID: 1, SendType: 1,
|
||||
Mobiles: []string{"13800138000"}, Content: "【测】幂等", Sign: "【测】"}
|
||||
}
|
||||
if _, err := s.Submit(context.Background(), base(), nil, base().Content, ""); err != nil {
|
||||
t.Fatalf("首次提交 err=%v", err)
|
||||
}
|
||||
if _, err := s.Submit(context.Background(), base(), nil, base().Content, ""); errCode(err) != "ISC:400" {
|
||||
t.Fatalf("重复任务号应 ISC:400,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmitVideoBizType Day 49:video 须账号已开通(AccountConfig 业务行);
|
||||
// 开通后 task.business=video 落库+事件载荷带 business;sms 默认不回归。
|
||||
func TestSubmitVideoBizType(t *testing.T) {
|
||||
db := newSubmitDB(t)
|
||||
s := newSubmitSvc(t, db)
|
||||
mkAcct(t, db, 1, 10000, 0) // 仅开通 sms 业务行
|
||||
|
||||
// ① 未开通 video:ISC:403 拒绝(发生在预扣前,无余额变动)。
|
||||
req := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138000"},
|
||||
Content: "【测】视频 https://v.example.com/a.mp4", Sign: "【测】", Business: BusinessVideo}
|
||||
if _, err := s.Submit(context.Background(), req, nil, req.Content, ""); errCode(err) != "ISC:403" {
|
||||
t.Fatalf("未开通 video 应 ISC:403,got %v", err)
|
||||
}
|
||||
var bal int64
|
||||
var acct entity.AccountUser
|
||||
if err := db.First(&acct, 1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bal = acct.Balance
|
||||
if bal != 10000 {
|
||||
t.Fatalf("拒绝不应动余额: %d", bal)
|
||||
}
|
||||
|
||||
// ② 开通后受理成功:task.business=video。
|
||||
db.Create(&entity.AccountConfig{AccountID: 1, Business: BusinessVideo, Protocol: "http", AuditMode: 0})
|
||||
res, err := s.Submit(context.Background(), req, nil, req.Content, "")
|
||||
if err != nil {
|
||||
t.Fatalf("开通后 video 受理: %v", err)
|
||||
}
|
||||
if res.Task.Business != BusinessVideo {
|
||||
t.Fatalf("task.business: %q", res.Task.Business)
|
||||
}
|
||||
var cnt int64
|
||||
db.Model(&entity.MessageTask{}).Where("business = ?", BusinessVideo).Count(&cnt)
|
||||
if cnt != 1 {
|
||||
t.Fatalf("video 任务落库: %d", cnt)
|
||||
}
|
||||
|
||||
// ③ 事件载荷带 business(走真实 ProducerSink 序列化)。
|
||||
prod := &fakeQueueProd{}
|
||||
s2 := newSubmitSvc(t, db)
|
||||
s2.sink = ProducerSink{P: prod, Source: "test"}
|
||||
req2 := &SubmitReq{AccountID: 1, SendType: SendTypeBatch,
|
||||
Mobiles: []string{"13800138001"},
|
||||
Content: "【测】视频 https://v.example.com/b.mp4", Sign: "【测】", Business: BusinessVideo}
|
||||
if _, err := s2.Submit(context.Background(), req2, nil, req2.Content, ""); err != nil {
|
||||
t.Fatalf("video 二次受理: %v", err)
|
||||
}
|
||||
if len(prod.vals) == 0 {
|
||||
t.Fatal("应投递 sms-submit 事件")
|
||||
}
|
||||
var ev SubmitEvent
|
||||
if err := json.Unmarshal(prod.vals[0], &ev); err != nil {
|
||||
t.Fatalf("事件解析: %v", err)
|
||||
}
|
||||
if ev.Business != BusinessVideo {
|
||||
t.Fatalf("事件载荷 business: %q (raw: %s)", ev.Business, prod.vals[0])
|
||||
}
|
||||
}
|
||||
|
||||
// fakeQueueProd sms-submit 投递捕获(Day52 R2:err 注入模拟 Kafka 故障降级)。
|
||||
type fakeQueueProd struct {
|
||||
topics []string
|
||||
vals [][]byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *fakeQueueProd) Send(topic string, key, value []byte) error {
|
||||
if p.err != nil {
|
||||
return p.err
|
||||
}
|
||||
p.topics = append(p.topics, topic)
|
||||
p.vals = append(p.vals, value)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
// timer.go Day 45:定时短信调度——Redis ZSet 唤醒索引 + 5s 扫描 + MySQL 原子认领。
|
||||
// 设计要点:
|
||||
//
|
||||
// ① ZSet 只是"唤醒索引",真值始终在 MySQL——认领用
|
||||
// UPDATE ... WHERE status=0 AND audit_status IN(1,3) AND schedule_at<=now 原子翻转,
|
||||
// 重复扫描/多实例并发天然幂等(RowsAffected=0 即丢弃并清理索引);
|
||||
// ② 每轮先"补偿入队"(DB 全量待发定时任务→ZADD,score 覆盖幂等):
|
||||
// 手动待审任务审核通过、改期(Reschedule)均无需跨包事件通知,
|
||||
// 下一轮补偿自动纠正 score——"重置批量生效";
|
||||
// ③ Redis 不可用时 q=nil,纯 DB 扫描降级(行为等价,ZSet 仅省全表轮询);
|
||||
// ④ 到点分发经 TaskDispatcher(router 选路→CMPP 链路提交);
|
||||
// 逐号独立成败,任务终态置 2 完成并回填计数;系统性错误回滚 status=1→0 下轮重试。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/cache"
|
||||
"go-sms/internal/service/router"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ErrDetailsNotReady 明细尚未落库(Day52 R2:事件明细在途,回滚认领留待重扫)。
|
||||
var ErrDetailsNotReady = errors.New("明细尚未落库")
|
||||
|
||||
// 审核态/任务态稳定契约值(与 audit 包常量一致;避免 send→audit 本体依赖)。
|
||||
const (
|
||||
auditReadyExempt = 3 // 免审(可发)
|
||||
taskStSending = 1
|
||||
taskStDone = 2
|
||||
detailStSubmitted = 1 // 明细:已提交
|
||||
detailStFailed = 3 // 明细:失败
|
||||
)
|
||||
|
||||
// TaskQueue 定时任务唤醒索引(Redis ZSet 实现;测试可替身)。
|
||||
type TaskQueue interface {
|
||||
Enqueue(ctx context.Context, taskID int64, at time.Time) error
|
||||
Due(ctx context.Context, now time.Time, limit int) ([]int64, error)
|
||||
All(ctx context.Context) ([]int64, error) // 全量成员(差集清理用)
|
||||
Remove(ctx context.Context, taskID int64) error
|
||||
}
|
||||
|
||||
// RedisZSetQueue ZSet 实现:member=taskID,score=unix(schedule_at)。
|
||||
type RedisZSetQueue struct {
|
||||
rc *cache.Client
|
||||
key string
|
||||
}
|
||||
|
||||
// NewRedisZSetQueue 构造(key 建议带业务前缀,如 go-sms:timer:tasks)。
|
||||
func NewRedisZSetQueue(rc *cache.Client, key string) *RedisZSetQueue {
|
||||
return &RedisZSetQueue{rc: rc, key: key}
|
||||
}
|
||||
|
||||
// Enqueue 入队/重排(ZADD 同 member 覆盖 score——改期幂等)。
|
||||
func (q *RedisZSetQueue) Enqueue(ctx context.Context, taskID int64, at time.Time) error {
|
||||
return q.rc.ZAdd(ctx, q.key, redis.Z{
|
||||
Score: float64(at.Unix()),
|
||||
Member: strconv.FormatInt(taskID, 10),
|
||||
}).Err()
|
||||
}
|
||||
|
||||
// Due 取到点任务(score<=now,升序)。
|
||||
func (q *RedisZSetQueue) Due(ctx context.Context, now time.Time, limit int) ([]int64, error) {
|
||||
ids, err := q.rc.ZRangeByScore(ctx, q.key, &redis.ZRangeBy{
|
||||
Min: "-inf", Max: strconv.FormatInt(now.Unix(), 10),
|
||||
Offset: 0, Count: int64(limit),
|
||||
}).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]int64, 0, len(ids))
|
||||
for _, s := range ids {
|
||||
if v, e := strconv.ParseInt(s, 10, 64); e == nil {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Remove 出队(终态/取消/拒绝清理)。
|
||||
func (q *RedisZSetQueue) Remove(ctx context.Context, taskID int64) error {
|
||||
return q.rc.ZRem(ctx, q.key, strconv.FormatInt(taskID, 10)).Err()
|
||||
}
|
||||
|
||||
// All 全量成员(差集清理:取消/拒绝/超时后不必等到点即出队)。
|
||||
func (q *RedisZSetQueue) All(ctx context.Context) ([]int64, error) {
|
||||
ids, err := q.rc.ZRange(ctx, q.key, 0, -1).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]int64, 0, len(ids))
|
||||
for _, s := range ids {
|
||||
if v, e := strconv.ParseInt(s, 10, 64); e == nil {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TaskDispatcher 到点任务分发(Day45:router 选路+CMPP 链路;Day47 升级 per-channel 令牌桶)。
|
||||
// 返回逐号(成功,失败)计数;err 非 nil 表示系统性错误(触发 status 回滚重试)。
|
||||
type TaskDispatcher interface {
|
||||
Dispatch(ctx context.Context, task *entity.MessageTask) (sent, failed int64, err error)
|
||||
}
|
||||
|
||||
// LinkSubmitter 通道链路提交(channel.Service 实现;依赖倒置)。
|
||||
// Day 56:返回各段 msg_id(顺序=PkNumber 1..N)——提交侧逐段登记
|
||||
// message_report_seg 供回执段级配对(单条=1 个元素)。
|
||||
type LinkSubmitter interface {
|
||||
SubmitViaLink(ctx context.Context, channelID int64, mobile, content string) ([]string, error)
|
||||
}
|
||||
|
||||
// ChannelDispatcher 默认分发器:明细逐号 router 选路→链路提交→明细落终态。
|
||||
// Day47:注入 SubmitAggregator(可选)时,链路提交段改走合包聚合(5s/1000 批),
|
||||
// 明细终态由聚合器 flush 时批量回写(markDetails)。
|
||||
// Day48:可选注入 ChannelPacer(per-channel 令牌桶+在途窗口+自动降速,直发路径
|
||||
// Acquire/Release/Observe)与 DetailWriter(终态批量落库,防消费阻塞)。
|
||||
type ChannelDispatcher struct {
|
||||
db *gorm.DB
|
||||
rt *router.Router
|
||||
lk LinkSubmitter
|
||||
agg *SubmitAggregator // nil=直发(兼容既有链路/测试)
|
||||
pacer *ChannelPacer // nil=不限速(timer 旧链路保持行为)
|
||||
writer *DetailWriter // nil=直写(默认;消费链路注入批量 writer)
|
||||
}
|
||||
|
||||
// NewChannelDispatcher 构造(agg 可选:第 4 参注入即启用聚合)。
|
||||
func NewChannelDispatcher(db *gorm.DB, rt *router.Router, lk LinkSubmitter, agg ...*SubmitAggregator) *ChannelDispatcher {
|
||||
d := &ChannelDispatcher{db: db, rt: rt, lk: lk}
|
||||
if len(agg) > 0 && agg[0] != nil {
|
||||
d.agg = agg[0]
|
||||
d.agg.bindMark(d.markDetails)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// WithPacer 注入限速器(Day48④;nil 或未 Open 时直通)。
|
||||
func (d *ChannelDispatcher) WithPacer(p *ChannelPacer) *ChannelDispatcher {
|
||||
d.pacer = p
|
||||
return d
|
||||
}
|
||||
|
||||
// WithDetailWriter 注入批量终态 writer(Day48④;nil 保持直写)。
|
||||
func (d *ChannelDispatcher) WithDetailWriter(w *DetailWriter) *ChannelDispatcher {
|
||||
d.writer = w
|
||||
return d
|
||||
}
|
||||
|
||||
// Dispatch 逐号分发:任务已置 channel_id 则直用;否则 router.Pick
|
||||
// (Step0 账号导流命中即直连→组四步→全局默认兜底)。明细独立成败;
|
||||
// 聚合模式下"入聚合"即计 sent(批量失败时聚合器回写 failed 终态)。
|
||||
func (d *ChannelDispatcher) Dispatch(ctx context.Context, task *entity.MessageTask) (int64, int64, error) {
|
||||
var details []entity.MessageDetail
|
||||
if err := d.db.WithContext(ctx).
|
||||
Where("task_id = ? AND status = 0", task.ID).Find(&details).Error; err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
// Day52 顺带修复:只下发存活号(status=0)——拦截终态 5 行受理期已退费,
|
||||
// 原全量读会重复下发并覆盖终态(部分拦截任务的存量缺陷)。
|
||||
// Day52 R2 防御:任务有号但明细 0 行=事件明细尚未落库(ReclaimScanner 抢跑窗口),
|
||||
// 返回错误触发认领回滚,留待明细落库后重扫(避免空跑终态 0/0 造成明细悬置)。
|
||||
if len(details) == 0 && task.MobileCount > 0 {
|
||||
return 0, 0, ErrDetailsNotReady
|
||||
}
|
||||
now := time.Now()
|
||||
var sent, failed int64
|
||||
for _, det := range details {
|
||||
chID := task.ChannelID
|
||||
if chID == 0 {
|
||||
ch, _, perr := d.rt.Pick(ctx, 0, &router.PickReq{
|
||||
AccountID: task.AccountID, Content: det.Content, Signature: task.Sign,
|
||||
})
|
||||
if perr != nil {
|
||||
d.markDetail(ctx, det.ID, detailStFailed, chID, "NO_ROUTE:"+perr.Error(), now)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
chID = ch.ID
|
||||
}
|
||||
if d.agg != nil {
|
||||
d.agg.Add(chID, det.Content, det.Mobile, det.ID)
|
||||
sent++
|
||||
continue
|
||||
}
|
||||
// Day48④:直发路径限速(令牌桶+在途窗口;未启用直通)+延迟采样降速判定。
|
||||
if d.pacer != nil {
|
||||
if aerr := d.pacer.Acquire(ctx, chID, 1); aerr != nil {
|
||||
d.markDetail(ctx, det.ID, detailStFailed, chID, aerr.Error(), now)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
msgIDs, serr := d.lk.SubmitViaLink(ctx, chID, det.Mobile, det.Content)
|
||||
if d.pacer != nil {
|
||||
d.pacer.Observe(chID, float64(time.Since(start).Milliseconds()))
|
||||
d.pacer.Release(chID, 1)
|
||||
}
|
||||
if serr != nil {
|
||||
d.markDetail(ctx, det.ID, detailStFailed, chID, serr.Error(), now)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
// Day 56:段级配对登记(单号 1~9 段,每段独立 msg_id)。
|
||||
writeSegRows(ctx, d.db, segRowsFor(chID, det.ID, det.Mobile, msgIDs))
|
||||
d.markDetail(ctx, det.ID, detailStSubmitted, chID, "", now)
|
||||
sent++
|
||||
}
|
||||
if d.agg != nil {
|
||||
d.agg.FlushAll() // 任务级即时冲洗(定时到点批次不等待窗口;跨任务凑批由消费链路负责)
|
||||
}
|
||||
return sent, failed, nil
|
||||
}
|
||||
|
||||
// TimerScheduler 定时扫描器(5s/轮,启动即扫)。
|
||||
type TimerScheduler struct {
|
||||
db *gorm.DB
|
||||
q TaskQueue // nil → 纯 DB 扫描降级
|
||||
dp TaskDispatcher
|
||||
interval time.Duration
|
||||
batch int // 单轮认领上限
|
||||
}
|
||||
|
||||
// NewTimerScheduler 构造(零值默认 5s/轮、单轮 100)。
|
||||
func NewTimerScheduler(db *gorm.DB, q TaskQueue, dp TaskDispatcher) *TimerScheduler {
|
||||
return &TimerScheduler{db: db, q: q, dp: dp, interval: 5 * time.Second, batch: 100}
|
||||
}
|
||||
|
||||
// WithInterval/WithBatch 覆写(测试注入)。
|
||||
func (s *TimerScheduler) WithInterval(d time.Duration) *TimerScheduler {
|
||||
s.interval = d
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *TimerScheduler) WithBatch(n int) *TimerScheduler {
|
||||
s.batch = n
|
||||
return s
|
||||
}
|
||||
|
||||
// Run 常驻扫描(随 ctx 退出;启动先扫一次)。
|
||||
func (s *TimerScheduler) Run(ctx context.Context) {
|
||||
t := time.NewTicker(s.interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
_, _, _, _ = s.ScanOnce(ctx) // 单轮失败不阻断调度(错误可由调用方经日志观测)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ScanOnce 单轮:①补偿入队 ②取 Due ③原子认领 ④分发终态。
|
||||
// 返回(补偿入队数, 认领数, 分发完成数, 错误)。
|
||||
func (s *TimerScheduler) ScanOnce(ctx context.Context) (enq, claimed, done int, err error) {
|
||||
now := time.Now()
|
||||
// ① 补偿入队:DB 全部"定时+待发+审核可发"任务 → ZADD(score 覆盖幂等;
|
||||
// 手动审核通过/改期由此自动纠正,无需跨包事件通知)。q=nil 跳过。
|
||||
if s.q != nil {
|
||||
var pend []entity.MessageTask
|
||||
if err = s.db.WithContext(ctx).
|
||||
Where("send_type = ? AND status = 0 AND audit_status IN (1, 3)", SendTypeTimer).
|
||||
Order("schedule_at ASC").Limit(200).Find(&pend).Error; err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
for _, t := range pend {
|
||||
if t.ScheduleAt == nil {
|
||||
continue
|
||||
}
|
||||
if qerr := s.q.Enqueue(ctx, t.ID, *t.ScheduleAt); qerr == nil {
|
||||
enq++
|
||||
}
|
||||
}
|
||||
}
|
||||
// ①' 差集清理:ZSet 全量对照 DB——取消/拒绝/超时/非定时成员即时出队
|
||||
// (不依赖到点 reconcile;Redis 故障跳过,残留到点仍会被 reconcile 兜底)。
|
||||
if s.q != nil {
|
||||
if all, aerr := s.q.All(ctx); aerr == nil && len(all) > 0 {
|
||||
var invalid []entity.MessageTask
|
||||
if err = s.db.WithContext(ctx).
|
||||
Where("id IN ? AND NOT (send_type = ? AND status = 0 AND audit_status IN (1, 3))",
|
||||
all, SendTypeTimer).Find(&invalid).Error; err == nil {
|
||||
for _, t := range invalid {
|
||||
_ = s.q.Remove(ctx, t.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ② 取 Due 候选(ZSet 优先;nil/不可达→DB 直查兜底)。
|
||||
var ids []int64
|
||||
if s.q != nil {
|
||||
ids, err = s.q.Due(ctx, now, s.batch)
|
||||
if err != nil {
|
||||
ids = nil // Redis 故障降级
|
||||
}
|
||||
}
|
||||
if ids == nil {
|
||||
var rows []entity.MessageTask
|
||||
if err = s.db.WithContext(ctx).
|
||||
Where("send_type = ? AND status = 0 AND audit_status IN (1, 3) AND schedule_at <= ?",
|
||||
SendTypeTimer, now).
|
||||
Order("schedule_at ASC").Limit(s.batch).Find(&rows).Error; err != nil {
|
||||
return enq, 0, 0, err
|
||||
}
|
||||
ids = make([]int64, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
}
|
||||
// ③ 原子认领 + ④ 分发终态。
|
||||
for _, id := range ids {
|
||||
ok, cerr := s.claim(ctx, id, now)
|
||||
if cerr != nil {
|
||||
err = cerr
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
s.reconcile(ctx, id) // 认领失败:按任务现状清理索引或重排(改期)
|
||||
continue
|
||||
}
|
||||
claimed++
|
||||
if s.dispatch(ctx, id) {
|
||||
done++
|
||||
}
|
||||
}
|
||||
return enq, claimed, done, nil
|
||||
}
|
||||
|
||||
// claim 原子认领:status 0→1(WHERE 审核可发+到点;RowsAffected=0 即被并发处理)。
|
||||
func (s *TimerScheduler) claim(ctx context.Context, id int64, now time.Time) (bool, error) {
|
||||
res := s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND send_type = ? AND status = 0 AND audit_status IN (1, 3) AND schedule_at <= ?",
|
||||
id, SendTypeTimer, now).
|
||||
Update("status", taskStSending)
|
||||
return res.RowsAffected == 1, res.Error
|
||||
}
|
||||
|
||||
// reconcile 认领失败善后:取消/终态/拒绝/超时/待审→出队;改期(未来)→按新时刻重排。
|
||||
func (s *TimerScheduler) reconcile(ctx context.Context, id int64) {
|
||||
if s.q == nil {
|
||||
return
|
||||
}
|
||||
var t entity.MessageTask
|
||||
if err := s.db.WithContext(ctx).Select("id", "status", "audit_status", "schedule_at").
|
||||
First(&t, id).Error; err != nil {
|
||||
_ = s.q.Remove(ctx, id) // 已删除任务:清索引
|
||||
return
|
||||
}
|
||||
if t.Status == 0 && (t.AuditStatus == 1 || t.AuditStatus == auditReadyExempt) &&
|
||||
t.ScheduleAt != nil && t.ScheduleAt.After(time.Now()) {
|
||||
_ = s.q.Enqueue(ctx, id, *t.ScheduleAt) // 改期:重排新时刻
|
||||
return
|
||||
}
|
||||
_ = s.q.Remove(ctx, id)
|
||||
}
|
||||
|
||||
// dispatch 分发并落终态:成功→status=2+计数+finished_at+出队;
|
||||
// 系统性错误→回滚 status 1→0(下轮重试,幂等由 claim 原子性保证)。
|
||||
func (s *TimerScheduler) dispatch(ctx context.Context, id int64) bool {
|
||||
var task entity.MessageTask
|
||||
if err := s.db.WithContext(ctx).First(&task, id).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
sent, failed, derr := s.dp.Dispatch(ctx, &task)
|
||||
if derr != nil {
|
||||
_ = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", id, taskStSending).
|
||||
Update("status", 0).Error
|
||||
return false
|
||||
}
|
||||
res := s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
||||
Where("id = ? AND status = ?", id, taskStSending).
|
||||
Updates(map[string]any{
|
||||
"status": taskStDone, "success_count": sent, "fail_count": failed,
|
||||
"finished_at": time.Now(),
|
||||
})
|
||||
if res.Error != nil || res.RowsAffected == 0 {
|
||||
return false
|
||||
}
|
||||
if s.q != nil {
|
||||
_ = s.q.Remove(ctx, id)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// markDetail 明细终态(status/channel/send_at/error_code;error_code 截 16 字符防列溢出)。
|
||||
func (d *ChannelDispatcher) markDetail(ctx context.Context, id int64, status int8,
|
||||
channelID int64, errCode string, at time.Time) {
|
||||
if ec := []rune(errCode); len(ec) > 16 {
|
||||
errCode = string(ec[:16])
|
||||
}
|
||||
_ = d.db.WithContext(ctx).Model(&entity.MessageDetail{}).Where("id = ?", id).
|
||||
Updates(map[string]any{
|
||||
"status": status, "channel_id": channelID,
|
||||
"error_code": errCode, "send_at": at,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// markDetails 批量明细终态(Day47 聚合器 flush 回写;同明细语义,error_code 同截断)。
|
||||
// Day48:注入 DetailWriter 时改走异步批量(不阻塞消费;入队失败回落直写)。
|
||||
func (d *ChannelDispatcher) markDetails(ctx context.Context, ids []int64, status int8,
|
||||
channelID int64, errCode string) {
|
||||
if len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
if d.writer != nil && d.writer.Add(DetailUpdate{
|
||||
IDs: ids, Status: status, ChannelID: channelID, ErrorCode: errCode,
|
||||
}) {
|
||||
return
|
||||
}
|
||||
if ec := []rune(errCode); len(ec) > 16 {
|
||||
errCode = string(ec[:16])
|
||||
}
|
||||
_ = d.db.WithContext(ctx).Model(&entity.MessageDetail{}).Where("id IN ?", ids).
|
||||
Updates(map[string]any{
|
||||
"status": status, "channel_id": channelID,
|
||||
"error_code": errCode, "send_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
// QueueKey 生产 ZSet key(装配与运维排查共用口径)。
|
||||
func QueueKey() string { return "go-sms:timer:tasks" }
|
||||
@@ -0,0 +1,250 @@
|
||||
// timer_test.go Day 45:定时调度单测——miniredis 真 ZSet 队列+sqlite:
|
||||
// 到点认领分发终态/幂等二轮/未来不入/改期重排/取消清理/纯 DB 降级/分发错误回滚重试。
|
||||
package send
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/cache"
|
||||
)
|
||||
|
||||
// newTimerDB 定时域测试库。
|
||||
func newTimerDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range []any{&entity.MessageTask{}, &entity.MessageDetail{}} {
|
||||
if err := db.Migrator().CreateTable(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// newTestQueue miniredis 真队列。
|
||||
func newTestQueue(t *testing.T) (*RedisZSetQueue, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rc, err := cache.New(cache.Options{Addrs: []string{mr.Addr()}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return NewRedisZSetQueue(rc, QueueKey()), mr
|
||||
}
|
||||
|
||||
// fakeDispatcher 测试分发器(记录调用;可注入系统性错误)。
|
||||
type fakeDispatcher struct {
|
||||
calls []int64
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeDispatcher) Dispatch(_ context.Context, task *entity.MessageTask) (int64, int64, error) {
|
||||
if f.err != nil {
|
||||
return 0, 0, f.err
|
||||
}
|
||||
f.calls = append(f.calls, task.ID)
|
||||
return int64(task.MobileCount), 0, nil
|
||||
}
|
||||
|
||||
var ttSeq int64
|
||||
|
||||
// mkTimerTask 直插定时任务(默认 免审/待发/2 号码)。
|
||||
func mkTimerTask(t *testing.T, db *gorm.DB, at time.Time, audit int8) *entity.MessageTask {
|
||||
t.Helper()
|
||||
ttSeq++
|
||||
task := &entity.MessageTask{
|
||||
TaskNo: "TT" + time.Now().Format("150405.000000000") + "_",
|
||||
AccountID: 1001, SendType: SendTypeTimer, Content: "【店】测试", Sign: "店",
|
||||
MobileCount: 2, AuditStatus: audit, Status: 0, ScheduleAt: &at,
|
||||
}
|
||||
task.TaskNo += time.Duration(ttSeq).String()
|
||||
if err := db.Create(task).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
d := entity.MessageDetail{TaskID: task.ID, AccountID: 1001,
|
||||
Mobile: "1380013800", Content: task.Content, Status: 0}
|
||||
d.ID = int64(9000000000 + task.ID*10 + int64(i))
|
||||
if err := db.Create(&d).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
func getTask(t *testing.T, db *gorm.DB, id int64) entity.MessageTask {
|
||||
t.Helper()
|
||||
var task entity.MessageTask
|
||||
if err := db.First(&task, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
// TestTimerDueClaimDispatch 到点认领→分发→终态→出队;二轮幂等。
|
||||
func TestTimerDueClaimDispatch(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
past := time.Now().Add(-time.Minute)
|
||||
task := mkTimerTask(t, db, past, 3) // 免审+已到点
|
||||
fd := &fakeDispatcher{}
|
||||
s := NewTimerScheduler(db, q, fd)
|
||||
enq, claimed, done, err := s.ScanOnce(ctx)
|
||||
if err != nil || enq != 1 || claimed != 1 || done != 1 {
|
||||
t.Fatalf("首轮 enq=%d claimed=%d done=%d err=%v", enq, claimed, done, err)
|
||||
}
|
||||
got := getTask(t, db, task.ID)
|
||||
if got.Status != 2 || got.SuccessCount != 2 || got.FinishedAt == nil {
|
||||
t.Fatalf("终态不符: status=%d success=%d finished=%v", got.Status, got.SuccessCount, got.FinishedAt)
|
||||
}
|
||||
if n, _ := q.rc.ZCard(ctx, QueueKey()).Result(); n != 0 {
|
||||
t.Fatalf("终态应出队, ZCard=%d", n)
|
||||
}
|
||||
// 二轮:幂等(无认领无重复分发)。
|
||||
_, c2, d2, err := s.ScanOnce(ctx)
|
||||
if err != nil || c2 != 0 || d2 != 0 || len(fd.calls) != 1 {
|
||||
t.Fatalf("二轮非幂等: c2=%d d2=%d calls=%d err=%v", c2, d2, len(fd.calls), err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimerFutureNotClaimed 未来任务仅入队不认领;Due 不含未来。
|
||||
func TestTimerFutureNotClaimed(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
mkTimerTask(t, db, time.Now().Add(time.Hour), 3)
|
||||
s := NewTimerScheduler(db, q, &fakeDispatcher{})
|
||||
enq, claimed, _, err := s.ScanOnce(ctx)
|
||||
if err != nil || enq != 1 || claimed != 0 {
|
||||
t.Fatalf("未来任务: enq=%d claimed=%d err=%v", enq, claimed, err)
|
||||
}
|
||||
if ids, _ := q.Due(ctx, time.Now(), 100); len(ids) != 0 {
|
||||
t.Fatalf("Due 误含未来: %v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimerRescheduleRequeue 改期:旧时刻到点认领失败→按新时刻重排→新到点发出。
|
||||
func TestTimerRescheduleRequeue(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
past := time.Now().Add(-time.Minute)
|
||||
task := mkTimerTask(t, db, past, 1) // 已通过+旧时刻已到
|
||||
if err := q.Enqueue(ctx, task.ID, past); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 改期到未来(模拟 Reschedule 只动 DB,ZSet 残留旧 score)。
|
||||
future := time.Now().Add(time.Hour)
|
||||
if err := db.Model(task).Update("schedule_at", future).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := NewTimerScheduler(db, q, &fakeDispatcher{})
|
||||
_, claimed, _, err := s.ScanOnce(ctx)
|
||||
if err != nil || claimed != 0 {
|
||||
t.Fatalf("旧时刻不应认领: claimed=%d err=%v", claimed, err)
|
||||
}
|
||||
// 补偿已按新 score 覆盖→模拟到点(新时刻调回过去)后应发出。
|
||||
if err := db.Model(task).Update("schedule_at", time.Now().Add(-time.Second)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, claimed2, done2, err := s.ScanOnce(ctx)
|
||||
if err != nil || claimed2 != 1 || done2 != 1 {
|
||||
t.Fatalf("新时刻应认领分发: claimed=%d done=%d err=%v", claimed2, done2, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimerCanceledRemoved 取消任务索引残留→认领失败→出队清理。
|
||||
func TestTimerCanceledRemoved(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
past := time.Now().Add(-time.Minute)
|
||||
task := mkTimerTask(t, db, past, 3)
|
||||
if err := db.Model(task).Update("status", 3).Error; err != nil { // 已取消
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := q.Enqueue(ctx, task.ID, past); err != nil { // 残留索引
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := NewTimerScheduler(db, q, &fakeDispatcher{})
|
||||
if _, claimed, _, err := s.ScanOnce(ctx); err != nil || claimed != 0 {
|
||||
t.Fatalf("取消任务不应认领: claimed=%d err=%v", claimed, err)
|
||||
}
|
||||
if n, _ := q.rc.ZCard(ctx, QueueKey()).Result(); n != 0 {
|
||||
t.Fatalf("取消应清理索引, ZCard=%d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimerDBFallback Redis 缺失(q=nil)纯 DB 扫描降级。
|
||||
func TestTimerDBFallback(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
ctx := context.Background()
|
||||
task := mkTimerTask(t, db, time.Now().Add(-time.Second), 3)
|
||||
s := NewTimerScheduler(db, nil, &fakeDispatcher{})
|
||||
_, claimed, done, err := s.ScanOnce(ctx)
|
||||
if err != nil || claimed != 1 || done != 1 {
|
||||
t.Fatalf("DB 降级模式: claimed=%d done=%d err=%v", claimed, done, err)
|
||||
}
|
||||
if got := getTask(t, db, task.ID); got.Status != 2 {
|
||||
t.Fatalf("降级模式终态: %d", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimerDispatchErrorRetry 分发系统性错误→status 回滚 0→下轮重试成功。
|
||||
func TestTimerDispatchErrorRetry(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
task := mkTimerTask(t, db, time.Now().Add(-time.Second), 3)
|
||||
fd := &fakeDispatcher{err: errTestSys}
|
||||
s := NewTimerScheduler(db, q, fd)
|
||||
if _, claimed, done, _ := s.ScanOnce(ctx); claimed != 1 || done != 0 {
|
||||
t.Fatalf("首轮应认领但分发失败: claimed=%d done=%d", claimed, done)
|
||||
}
|
||||
if got := getTask(t, db, task.ID); got.Status != 0 {
|
||||
t.Fatalf("分发失败应回滚待发: %d", got.Status)
|
||||
}
|
||||
fd.err = nil
|
||||
if _, c2, d2, _ := s.ScanOnce(ctx); c2 != 1 || d2 != 1 {
|
||||
t.Fatalf("二轮应重试成功: c2=%d d2=%d", c2, d2)
|
||||
}
|
||||
}
|
||||
|
||||
// errTestSys 测试用系统性错误。
|
||||
var errTestSys = &testSysErr{}
|
||||
|
||||
type testSysErr struct{}
|
||||
|
||||
func (e *testSysErr) Error() string { return "sys down" }
|
||||
|
||||
// TestTimerDiffCleanup 差集清理:取消任务未来时刻残留→下一轮即出队(不等到点)。
|
||||
func TestTimerDiffCleanup(t *testing.T) {
|
||||
db := newTimerDB(t)
|
||||
q, _ := newTestQueue(t)
|
||||
ctx := context.Background()
|
||||
future := time.Now().Add(time.Hour)
|
||||
task := mkTimerTask(t, db, future, 3)
|
||||
if err := db.Model(task).Update("status", 3).Error; err != nil { // 取消
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := q.Enqueue(ctx, task.ID, future); err != nil { // 残留(未来 score,永不到点)
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := NewTimerScheduler(db, q, &fakeDispatcher{})
|
||||
if _, _, _, err := s.ScanOnce(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, _ := q.rc.ZCard(ctx, QueueKey()).Result(); n != 0 {
|
||||
t.Fatalf("差集清理未生效, ZCard=%d", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Package send Day 41(阶段 4 起步):发送域——Submit DTO+发送校验器+计费预估。
|
||||
// Day 44 群发/个性/文件服务与 Day 46 HTTP API 提交接口复用本包校验。
|
||||
package send
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
errs "go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// 发送类型(与 MessageTask.SendType 对齐)。
|
||||
const (
|
||||
SendTypeBatch int8 = 1 // 群发
|
||||
SendTypePersonal int8 = 2 // 个性(变量)
|
||||
SendTypeTimer int8 = 3 // 定时
|
||||
SendTypeFile int8 = 4 // 文件
|
||||
)
|
||||
|
||||
// MaxMobiles 单次提交号码上限。
|
||||
const MaxMobiles = 10000
|
||||
|
||||
// MaxTextLen 内容上限(字符;账号级上限 Day42 拦截器接入,平台级先 1000)。
|
||||
const MaxTextLen = 1000
|
||||
|
||||
// SubmitReq 发送提交 DTO(HTTP API/内部服务共用)。
|
||||
type SubmitReq struct {
|
||||
TaskNo string `json:"task_no"` // 幂等键(缺省服务端生成)
|
||||
AccountID int64 `json:"account_id"`
|
||||
SendType int8 `json:"send_type"` // 1群发 2个性 3定时 4文件
|
||||
TemplateID int64 `json:"template_id"` // 模板短信必填
|
||||
Mobiles []string `json:"mobiles"` // 号码列表(个性短信=变量表,Day44)
|
||||
Content string `json:"content"` // 直发内容;模板短信可为空
|
||||
Variables map[string]string `json:"variables"` // 模板短信变量(群发单值)
|
||||
Sign string `json:"sign"` // 签名(如「公司名」或含于内容)
|
||||
SendAt string `json:"send_at"` // 定时(YYYY-MM-DD HH:mm;立即发送为空)
|
||||
Extend string `json:"extend"` //扩展码透传
|
||||
CallData string `json:"call_data"` // Day 46:用户回传数据(≤64,回执推送带回)
|
||||
Business string `json:"business"` // Day 49:sms(默认)/video 视频短信(biz_type 路由;账号须开通)
|
||||
Source int8 `json:"-"` // Day 60:受理来源打标(内部入口设置,不收外部输入;0→API 归一)
|
||||
PresetMsgID int64 `json:"-"` // 内部:预置首条 DetailID(入向长短信聚合组ID:片级 Resp/Deliver 回执/明细三口径同 ID;0=雪花默认;不收外部输入)
|
||||
// Day 70:计费口径分流(批次 2344043 少计 1 条根修)——CMPP 入向的真实
|
||||
// 上游片数与 GBK 出向拆分在 ASCII 混合内容下背离,fee≡上游真实片数
|
||||
// (决策②本意)须按来源编码分流;两字段仅内部链路设置,不收外部输入。
|
||||
ContentEncoding int8 `json:"-"` // 0=默认(GBK 口径,出向 SplitContent 同构);1=UCS2(MsgFmt=8)
|
||||
FeeSegments int `json:"-"` // 计费段数覆写(入向长短信聚合=客户端 pk_total=运营商计费依据;0=按口径计算)
|
||||
}
|
||||
|
||||
// 计费口径编码(Day 70)。
|
||||
const (
|
||||
ContentEncodingDefault int8 = 0 // GBK/出向拆分口径(ASCII 1B/GBK 2B,134B 预算)
|
||||
ContentEncodingUCS2 int8 = 1 // UCS2 运营商口径(每码元 2B,70 码元单片/67 码元每片)
|
||||
)
|
||||
|
||||
// 业务类型(Day 49 biz_type 路由;与技术方案 Kafka 消息 Business 字段对齐)。
|
||||
const (
|
||||
BusinessSMS = "sms"
|
||||
BusinessVideo = "video"
|
||||
)
|
||||
|
||||
// 任务受理来源(Day 60 · D24-25 下行明细页筛选维度;message_task.source)。
|
||||
const (
|
||||
TaskSourceAPI int8 = 1 // 外部 HTTP API(openapi sendMessageMass/One)
|
||||
TaskSourceCMPP int8 = 2 // CMPP 协议接入(access.Submit)
|
||||
TaskSourceSMPP int8 = 3 // SMPP 协议接入(access.SubmitSM)
|
||||
TaskSourceWeb int8 = 4 // Web 控制台(/send/submit)
|
||||
)
|
||||
|
||||
// NormalizeTaskSource 打标归一(0/非法→API 默认;入口显式传入,不收外部请求体)。
|
||||
func NormalizeTaskSource(s int8) int8 {
|
||||
if s < TaskSourceAPI || s > TaskSourceWeb {
|
||||
return TaskSourceAPI
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Estimate 计费预估(供 D17 群发工作台实时显示;与后端 SmsLength 同源)。
|
||||
type Estimate struct {
|
||||
ValidCount int `json:"valid_count"` // 合格号码数
|
||||
Chars int `json:"chars"` // 字符数
|
||||
Segments int `json:"segments"` // 单号码计费条数
|
||||
TotalFee int `json:"total_fee"` // 总条数=ValidCount×Segments
|
||||
}
|
||||
|
||||
// Validate 发送校验(拒绝路径逐条返回 ISC:400):
|
||||
// 号码非空/合法/去重上限 · 类型合法 · 内容(直发非空≤MaxTextLen/模板短信渲染非空) ·
|
||||
// 变量(直发禁变量/模板缺参拒绝) · 签名(非空,建议【】包裹;白名单校验 Day42 签名拦截器)。
|
||||
// tpl 为模板短信时必传(通过态),nil 表示直发。
|
||||
func (r *SubmitReq) Validate(tpl *entity.TemplateSMS) (*Estimate, error) {
|
||||
// ---- 号码 ----
|
||||
if len(r.Mobiles) == 0 {
|
||||
return nil, errs.InvalidParam.WithMsg("号码列表为空")
|
||||
}
|
||||
if len(r.Mobiles) > MaxMobiles {
|
||||
return nil, errs.InvalidParam.WithMsg(fmt.Sprintf("号码 %d 超单次上限 %d", len(r.Mobiles), MaxMobiles))
|
||||
}
|
||||
seen := make(map[string]struct{}, len(r.Mobiles))
|
||||
valid := make([]string, 0, len(r.Mobiles))
|
||||
for _, m := range r.Mobiles {
|
||||
n := util.NormalizeMobile(m)
|
||||
if !util.IsValidMainlandMobile(n) {
|
||||
return nil, errs.InvalidParam.WithMsg("非法手机号: " + m)
|
||||
}
|
||||
if _, dup := seen[n]; !dup {
|
||||
seen[n] = struct{}{}
|
||||
valid = append(valid, n)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 类型 ----
|
||||
if r.SendType == 0 {
|
||||
r.SendType = SendTypeBatch
|
||||
}
|
||||
// ---- 业务类型(Day 49 biz_type 路由):空规范化为 sms;账号开通校验在
|
||||
// Submit 落库前查 AccountConfig;video 内容合帧校验在内容合并后。----
|
||||
switch r.Business = strings.TrimSpace(r.Business); r.Business {
|
||||
case "":
|
||||
r.Business = BusinessSMS
|
||||
case BusinessSMS, BusinessVideo:
|
||||
default:
|
||||
return nil, errs.InvalidParam.WithMsg("business 仅支持 sms/video: " + r.Business)
|
||||
}
|
||||
if r.SendType < SendTypeBatch || r.SendType > SendTypeFile {
|
||||
return nil, errs.InvalidParam.WithMsg(fmt.Sprintf("发送类型 %d 非法", r.SendType))
|
||||
}
|
||||
if r.SendType == SendTypeTimer && r.SendAt == "" {
|
||||
return nil, errs.InvalidParam.WithMsg("定时发送须指定 send_at")
|
||||
}
|
||||
|
||||
// ---- 签名(可选:Day41 验收二变——UI 去独立签名框,内容=签名+正文一体;
|
||||
// sign 传空时内容须自带签名(如【公司名】),白名单校验 Day42 拦截器从内容提取) ----
|
||||
if len([]rune(r.Sign)) > 32 {
|
||||
return nil, errs.InvalidParam.WithMsg("签名超 32 字")
|
||||
}
|
||||
|
||||
// ---- 内容与变量 ----
|
||||
content := r.Content
|
||||
if r.TemplateID > 0 {
|
||||
if tpl == nil {
|
||||
return nil, errs.InvalidParam.WithMsg("模板不存在")
|
||||
}
|
||||
if tpl.Status != 1 {
|
||||
return nil, errs.InvalidParam.WithMsg("模板未过审,不可发送")
|
||||
}
|
||||
rendered, err := renderVars(tpl.Content, r.Variables)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content = rendered
|
||||
if vars := util.ExtractVariables(r.Sign); len(vars) > 0 {
|
||||
return nil, errs.InvalidParam.WithMsg("签名含变量占位符 " + strings.Join(vars, ",") + ",签名须为固定文本")
|
||||
}
|
||||
} else {
|
||||
if content == "" {
|
||||
return nil, errs.InvalidParam.WithMsg("内容为空")
|
||||
}
|
||||
}
|
||||
// Day41 验收 #2/#3 需求:签名与内容合并计入短信内容(原样拼接,零包装),
|
||||
// 字数/条数/长度上限全部按合并口径。
|
||||
merged := r.Sign + content
|
||||
if vars := util.ExtractVariables(merged); len(vars) > 0 && r.TemplateID == 0 {
|
||||
return nil, errs.InvalidParam.WithMsg("直发内容含变量占位符 " + strings.Join(vars, ",") + ",请走模板短信")
|
||||
}
|
||||
if n := len([]rune(merged)); n > MaxTextLen {
|
||||
return nil, errs.InvalidParam.WithMsg(fmt.Sprintf("签名+内容 %d 字超上限 %d", n, MaxTextLen))
|
||||
}
|
||||
// Day 49:视频短信合帧要素——文字+视频 URL(URL 可来自模板变量渲染)。
|
||||
if r.Business == BusinessVideo && !strings.Contains(merged, "http://") && !strings.Contains(merged, "https://") {
|
||||
return nil, errs.InvalidParam.WithMsg("视频短信内容须包含视频 URL(http/https,文字+URL 合帧)")
|
||||
}
|
||||
|
||||
// ---- 预估(合并口径;Day 70 按来源编码分流) ----
|
||||
// FeeSegments>0:上游已知段数直接采信(入向长短信聚合=客户端 pk_total,
|
||||
// 运营商即按此计费——比重算任何口径都准);UCS2 来源按 UCS2 口径;
|
||||
// 默认 GBK 口径(出向 SplitContent 同构=我方真实拆分片数)。
|
||||
var chars, seg int
|
||||
switch {
|
||||
case r.FeeSegments > 0:
|
||||
chars, seg = utf8.RuneCountInString(merged), r.FeeSegments
|
||||
case r.ContentEncoding == ContentEncodingUCS2:
|
||||
chars, seg = util.SmsLengthUCS2(merged)
|
||||
default:
|
||||
chars, seg = util.SmsLength(merged)
|
||||
}
|
||||
return &Estimate{ValidCount: len(valid), Chars: chars, Segments: seg, TotalFee: len(valid) * seg}, nil
|
||||
}
|
||||
|
||||
// renderVars 模板渲染(缺参拒绝;多余变量忽略)。
|
||||
func renderVars(tplContent string, vars map[string]string) (string, error) {
|
||||
for _, name := range util.ExtractVariables(tplContent) {
|
||||
if _, ok := vars[name]; !ok {
|
||||
return "", errs.InvalidParam.WithMsg("缺少模板变量 {" + name + "}")
|
||||
}
|
||||
}
|
||||
out := tplContent
|
||||
for k, v := range vars {
|
||||
out = strings.ReplaceAll(out, "{"+k+"}", v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SortedMobiles 归一去重后的有序号码(测试与落库批次用)。
|
||||
func SortedMobiles(mobiles []string) []string {
|
||||
seen := make(map[string]struct{}, len(mobiles))
|
||||
out := make([]string, 0, len(mobiles))
|
||||
for _, m := range mobiles {
|
||||
n := util.NormalizeMobile(m)
|
||||
if _, ok := seen[n]; !ok {
|
||||
seen[n] = struct{}{}
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// validator_test.go Day 41:发送校验器——长度/号码/变量/签名拒绝路径+预估条数。
|
||||
package send
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// tplOK 已过审模板。
|
||||
func tplOK() *entity.TemplateSMS {
|
||||
return &entity.TemplateSMS{AccountID: 1, Name: "n", Content: "您好{name},消费{amount}元", Variables: "name,amount", Status: 1}
|
||||
}
|
||||
|
||||
// TestValidateReject 验收:各拒绝路径逐条覆盖。
|
||||
func TestValidateReject(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
req SubmitReq
|
||||
tpl *entity.TemplateSMS
|
||||
}{
|
||||
{"空号码", SubmitReq{Mobiles: nil, Content: "hi", Sign: "【测】"}, nil},
|
||||
{"非法手机号", SubmitReq{Mobiles: []string{"12345"}, Content: "hi", Sign: "【测】"}, nil},
|
||||
{"直发空内容", SubmitReq{Mobiles: []string{"13800138000"}, Content: "", Sign: "【测】"}, nil},
|
||||
{"直发含变量", SubmitReq{Mobiles: []string{"13800138000"}, Content: "你好{name}", Sign: "【测】"}, nil},
|
||||
{"内容超长", SubmitReq{Mobiles: []string{"13800138000"}, Content: string(make([]byte, 0)) + repeatCn("长", 1001), Sign: "【测】"}, nil},
|
||||
{"签名超长", SubmitReq{Mobiles: []string{"13800138000"}, Content: "hi", Sign: repeatCn("签", 33)}, nil},
|
||||
{"模板缺参", SubmitReq{Mobiles: []string{"13800138000"}, TemplateID: 9, Variables: map[string]string{"name": "x"}, Sign: "【测】"}, tplOK()},
|
||||
{"模板未过审", SubmitReq{Mobiles: []string{"13800138000"}, TemplateID: 9, Variables: map[string]string{"name": "x", "amount": "1"}, Sign: "【测】"}, &entity.TemplateSMS{Content: "x", Status: 0}},
|
||||
{"定时缺时间", SubmitReq{Mobiles: []string{"13800138000"}, Content: "hi", Sign: "【测】", SendType: SendTypeTimer}, nil},
|
||||
{"非法类型", SubmitReq{Mobiles: []string{"13800138000"}, Content: "hi", Sign: "【测】", SendType: 9}, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if _, err := c.req.Validate(c.tpl); err == nil {
|
||||
t.Fatalf("%s: 应拒绝", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateEstimate 验收:预估条数与 SmsLength 同源(中文 70/67 拆分)。
|
||||
// Day41 验收 #2/#3 需求变更:签名+内容合并口径(原样拼接)。
|
||||
func TestValidateEstimate(t *testing.T) {
|
||||
// 群发 3 号码(1 重复归一) 中文 70 字+签名【测】3 字=73 字 → 2 条
|
||||
req := SubmitReq{Mobiles: []string{"13800138000", "13800138001", " 13800138000 "}, Content: repeatCn("汉", 70), Sign: "【测】"}
|
||||
est, err := req.Validate(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if est.ValidCount != 2 || est.Chars != 73 || est.Segments != 2 || est.TotalFee != 4 {
|
||||
t.Fatalf("预估错: %+v", est)
|
||||
}
|
||||
// 71 字中文+3 字签名=74 → 2 条
|
||||
req2 := SubmitReq{Mobiles: []string{"13800138000"}, Content: repeatCn("汉", 71), Sign: "【测】"}
|
||||
est2, _ := req2.Validate(nil)
|
||||
if est2.Chars != 74 || est2.Segments != 2 {
|
||||
t.Fatalf("71+签 应 74 字 2 条: %+v", est2)
|
||||
}
|
||||
// 跨拆分边界(本 bug 复现用例):正文 159 ASCII 单独=1 条,加 3 字签名=162 → 2 条
|
||||
reqB := SubmitReq{Mobiles: []string{"13800138000"}, Content: repeatCn("a", 159), Sign: "abc"}
|
||||
estB, _ := reqB.Validate(nil)
|
||||
if estB.Chars != 162 || estB.Segments != 2 {
|
||||
t.Fatalf("159+3 ASCII 应 162 字 2 条: %+v", estB)
|
||||
}
|
||||
// 跨拆分边界:正文 68 汉字单独=1 条,加 3 字签名=71 → 2 条
|
||||
reqC := SubmitReq{Mobiles: []string{"13800138000"}, Content: repeatCn("汉", 68), Sign: "【测】"}
|
||||
estC, _ := reqC.Validate(nil)
|
||||
if estC.Chars != 71 || estC.Segments != 2 {
|
||||
t.Fatalf("68+3 汉字 应 71 字 2 条: %+v", estC)
|
||||
}
|
||||
// Day41 验收二变:sign 可空,内容自带签名——预估=content 原口径
|
||||
reqD := SubmitReq{Mobiles: []string{"13800138000"}, Content: "【测】" + repeatCn("汉", 67), Sign: ""}
|
||||
estD, err := reqD.Validate(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if estD.Chars != 70 || estD.Segments != 2 {
|
||||
t.Fatalf("自带签名 70 字应 2 条(决策②:140B>134B 有效载荷,上游实付 2 片): %+v", estD)
|
||||
}
|
||||
// 模板渲染后预估(签名+渲染结果合并)
|
||||
req3 := SubmitReq{Mobiles: []string{"13800138000"}, TemplateID: 1, Variables: map[string]string{"name": "张三三", "amount": "100"}, Sign: "【测】"}
|
||||
est3, err := req3.Validate(tplOK())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "【测】您好张三三,消费100元"
|
||||
_, wantSeg := util.SmsLength(want)
|
||||
if est3.Segments != wantSeg || est3.Chars != len([]rune(want)) {
|
||||
t.Fatalf("模板预估与直发不同源: %+v want chars=%d", est3, len([]rune(want)))
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateFeeSplit Day 70:计费口径分流(批次 2344043 少计 1 条根修)——
|
||||
// FeeSegments>0 直接采信(聚合=客户端 pk_total=运营商计费依据);UCS2 来源
|
||||
// 按每码元 2B 口径;默认 GBK 口径(出向 SplitContent 同构)。
|
||||
func TestValidateFeeSplit(t *testing.T) {
|
||||
// 156 字符(90 ASCII+66 中文):GBK 口径 222B=2 条,UCS2 口径 312B=3 条。
|
||||
mix := strings.Repeat("a", 90) + strings.Repeat("汉", 66)
|
||||
|
||||
// 默认(GBK 口径,HTTP/SMPP/历史行为不变):2 条
|
||||
estDefault, err := (&SubmitReq{Mobiles: []string{"13800138000"}, Content: mix}).Validate(nil)
|
||||
if err != nil || estDefault.Segments != 2 {
|
||||
t.Fatalf("默认 GBK 口径应 2 条: est=%+v err=%v", estDefault, err)
|
||||
}
|
||||
// UCS2 编码(CMPP MsgFmt=8):3 条=上游真实片数
|
||||
estUCS2, err := (&SubmitReq{Mobiles: []string{"13800138000"}, Content: mix,
|
||||
ContentEncoding: ContentEncodingUCS2}).Validate(nil)
|
||||
if err != nil || estUCS2.Segments != 3 || estUCS2.TotalFee != 3 {
|
||||
t.Fatalf("UCS2 口径应 3 条: est=%+v err=%v", estUCS2, err)
|
||||
}
|
||||
// FeeSegments 覆写(聚合 pk_total 优先级最高,与内容无关)
|
||||
estOver, err := (&SubmitReq{Mobiles: []string{"13800138000", "13800138001"}, Content: mix,
|
||||
FeeSegments: 3}).Validate(nil)
|
||||
if err != nil || estOver.Segments != 3 || estOver.TotalFee != 6 {
|
||||
t.Fatalf("FeeSegments 覆写应 3 条/2 号=6: est=%+v err=%v", estOver, err)
|
||||
}
|
||||
// FeeSegments 与 UCS2 并存:覆写优先
|
||||
estBoth, err := (&SubmitReq{Mobiles: []string{"13800138000"}, Content: mix,
|
||||
ContentEncoding: ContentEncodingUCS2, FeeSegments: 2}).Validate(nil)
|
||||
if err != nil || estBoth.Segments != 2 {
|
||||
t.Fatalf("覆写应压过编码口径: est=%+v err=%v", estBoth, err)
|
||||
}
|
||||
// 外部输入不可注入:json 序列化字段名不暴露(带 json:"-" 的两字段)——
|
||||
// 结构体 tag 静态保证,不另测反射。
|
||||
}
|
||||
|
||||
// TestSortedMobiles 归一去重排序。
|
||||
func TestSortedMobiles(t *testing.T) {
|
||||
got := SortedMobiles([]string{"13800138001", "13800138000", "13800138001"})
|
||||
if len(got) != 2 || got[0] != "13800138000" {
|
||||
t.Fatalf("SortedMobiles 错: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateBusiness Day 49:biz_type 路由校验——空规范化 sms/枚举拒绝/
|
||||
// video 须含视频 URL(合帧要素,直发与模板渲染后均校验)。
|
||||
func TestValidateBusiness(t *testing.T) {
|
||||
// 空→sms 规范化(存量调用零破坏)。
|
||||
r := SubmitReq{Mobiles: []string{"13800138000"}, Content: "【测】hi", Sign: "【测】"}
|
||||
if _, err := r.Validate(nil); err != nil {
|
||||
t.Fatalf("默认 sms: %v", err)
|
||||
}
|
||||
if r.Business != BusinessSMS {
|
||||
t.Fatalf("空 business 应回填 sms: %q", r.Business)
|
||||
}
|
||||
// 非法枚举拒绝。
|
||||
r2 := SubmitReq{Mobiles: []string{"13800138000"}, Content: "x", Sign: "【测】", Business: "csp"}
|
||||
if _, err := r2.Validate(nil); err == nil {
|
||||
t.Fatal("business=csp 应拒绝")
|
||||
}
|
||||
// video 无 URL 拒绝(合帧要素)。
|
||||
r3 := SubmitReq{Mobiles: []string{"13800138000"}, Content: "【测】仅文字无链接", Sign: "【测】", Business: BusinessVideo}
|
||||
if _, err := r3.Validate(nil); err == nil {
|
||||
t.Fatal("video 无 URL 应拒绝")
|
||||
}
|
||||
// video 直发含 URL 通过。
|
||||
r4 := SubmitReq{Mobiles: []string{"13800138000"}, Content: "【测】新品发布 https://v.example.com/a.mp4", Sign: "【测】", Business: BusinessVideo}
|
||||
if _, err := r4.Validate(nil); err != nil {
|
||||
t.Fatalf("video 含 URL 应通过: %v", err)
|
||||
}
|
||||
if r4.Business != BusinessVideo {
|
||||
t.Fatalf("business 保持: %q", r4.Business)
|
||||
}
|
||||
// video 模板短信:URL 来自变量渲染,合并口径校验命中。
|
||||
tplVideo := &entity.TemplateSMS{AccountID: 1, Name: "v", Content: "观看 {url}", Variables: "url", Status: 1}
|
||||
r5 := SubmitReq{Mobiles: []string{"13800138000"}, TemplateID: 1,
|
||||
Variables: map[string]string{"url": "http://v.example.com/b.mp4"}, Sign: "【测】", Business: BusinessVideo}
|
||||
if _, err := r5.Validate(tplVideo); err != nil {
|
||||
t.Fatalf("模板变量渲染出的 URL 应被接受: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func repeatCn(s string, n int) string {
|
||||
out := make([]byte, 0, len(s)*n)
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, s...)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
Reference in New Issue
Block a user