diff --git a/internal/service/doc.go b/internal/service/doc.go new file mode 100644 index 00000000..4ed9fcc8 --- /dev/null +++ b/internal/service/doc.go @@ -0,0 +1,3 @@ +// Package service 业务服务实现层(账号/通道/发送/路由/审核/计费/统计/结算等)。 +// 阶段 2 起逐步填充。 +package service diff --git a/internal/service/uplink/consumer.go b/internal/service/uplink/consumer.go new file mode 100644 index 00000000..9a968822 --- /dev/null +++ b/internal/service/uplink/consumer.go @@ -0,0 +1,58 @@ +// consumer.go Day 49:sms-up 消费者——15 天窗口匹配下行明细,回填 +// message_uplink.match_task_id(需求 2.5"只匹配 15 天内发送数据")。 +// 客户推送(CMPP 优先/HTTP,uplink_url)与上行自动拉黑属阶段 5(Day 54)。 +package uplink + +import ( + "context" + "encoding/json" + "time" + + "go-sms/internal/model/entity" + + "gorm.io/gorm" +) + +// MatchWindow 上行↔下行匹配窗口(15 天,需求 2.5)。 +const MatchWindow = 15 * 24 * time.Hour + +// Consumer sms-up 消费者。 +type Consumer struct { + db *gorm.DB +} + +// NewConsumer 构造。 +func NewConsumer(db *gorm.DB) *Consumer { return &Consumer{db: db} } + +// HandlePayload 消费入口(Kafka handler;载荷即 Event JSON)。 +func (c *Consumer) HandlePayload(_ context.Context, value []byte) error { + var ev Event + if err := json.Unmarshal(value, &ev); err != nil { + return err // 非法载荷交由消费组重试→死信(与 submit 消费者同口径) + } + return c.MatchAndFill(context.Background(), &ev) +} + +// MatchAndFill 匹配并回填:同账号+同手机号、recv_at 前 15 天窗口内最近一条 +// 下行明细 → match_task_id。幂等:仅覆写 match_task_id=0 的行。 +func (c *Consumer) MatchAndFill(ctx context.Context, ev *Event) error { + recvAt, err := time.Parse(time.RFC3339, ev.RecvAt) + if err != nil { + return err + } + var detail entity.MessageDetail + q := c.db.WithContext(ctx). + Where("account_id = ? AND mobile = ? AND created_at BETWEEN ? AND ?", + ev.AccountID, ev.SrcMobile, recvAt.Add(-MatchWindow), recvAt). + Order("id DESC").Limit(1) + if err := q.First(&detail).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil // 窗口内无下行:保留 match_task_id=0(未匹配,页面可筛) + } + return err + } + return c.db.WithContext(ctx). + Model(&entity.MessageUplink{}). + Where("id = ? AND match_task_id = 0", ev.UplinkID). + Update("match_task_id", detail.TaskID).Error +} diff --git a/internal/service/uplink/uplink.go b/internal/service/uplink/uplink.go new file mode 100644 index 00000000..b82cc317 --- /dev/null +++ b/internal/service/uplink/uplink.go @@ -0,0 +1,196 @@ +// Package uplink Day 49(阶段 4):上行域——码号分配(精确>前缀>admin 兜底, +// A-4.18)+上行落库 message_uplink+Kafka sms-up 投递。 +// 消费者(15 天窗口匹配回填 match_task_id)见 consumer.go; +// 客户推送(CMPP 优先/HTTP)与上行自动拉黑属阶段 5(Day 54)。 +package uplink + +import ( + "context" + "encoding/json" + "strings" + "sync" + "time" + + "go-sms/internal/model/entity" + "go-sms/internal/pkg/logger" + "go-sms/internal/pkg/queue" + + "go.uber.org/zap" + "gorm.io/gorm" +) + +// AdminFallbackAccount 匹配失败兜底归属(内置超管账户 1;需求 2.5"匹配失败归 admin")。 +const AdminFallbackAccount int64 = 1 + +// 匹配类型(与 uplink_code.match_type 对齐)。 +const ( + MatchExact int8 = 1 // 精确:码号全串相等 + MatchPrefix int8 = 2 // 前缀:码号前段命中(多条取最长) +) + +// DefaultReloadEvery 缓存刷新周期(码号表变更最迟生效窗口)。 +const DefaultReloadEvery = 30 * time.Second + +// Producer Kafka 出口(装配层注入 queue.Producer;nil=仅落库不投递,降级)。 +type Producer interface { + Send(topic string, key, value []byte) error +} + +// Event sms-up 事件载荷(消费者 15 天窗口匹配;阶段 5 推送/拉黑复用)。 +type Event struct { + UplinkID int64 `json:"uplink_id"` + DestCode string `json:"dest_code"` + SrcMobile string `json:"src_mobile"` + Content string `json:"content"` + AccountID int64 `json:"account_id"` + ChannelID int64 `json:"channel_id"` + RecvAt string `json:"recv_at"` // RFC3339 +} + +type prefixEntry struct { + code string + accountID int64 +} + +// Assigner 码号分配器:uplink_code 全量内存缓存(定时刷新+手动 Reload), +// 两级匹配——①精确 map 命中;②前缀表按码长降序取最长命中;③均未命中由调用方兜底 admin。 +type Assigner struct { + db *gorm.DB + + mu sync.RWMutex + exact map[string]int64 + prefixes []prefixEntry // 码长降序(最长前缀优先) +} + +// NewAssigner 构造(首次 Reload 失败仅记日志,缓存空=全部走 admin 兜底)。 +func NewAssigner(db *gorm.DB) *Assigner { + return &Assigner{db: db, exact: map[string]int64{}} +} + +// Reload 全量重载码号表(全量行数级千位,整表置换原子切换)。 +func (a *Assigner) Reload(ctx context.Context) error { + var rows []entity.UplinkCode + if err := a.db.WithContext(ctx).Find(&rows).Error; err != nil { + return err + } + exact := make(map[string]int64, len(rows)) + var prefixes []prefixEntry + for _, r := range rows { + code := strings.TrimSpace(r.Code) + if code == "" { + continue + } + switch r.MatchType { + case MatchPrefix: + prefixes = append(prefixes, prefixEntry{code: code, accountID: r.AccountID}) + default: // 精确(含历史脏数据 0) + exact[code] = r.AccountID + } + } + // 前缀按码长降序:遍历首个命中即最长前缀。 + for i := len(prefixes) - 1; i > 0; i-- { + for j := 0; j < i; j++ { + if len(prefixes[j].code) < len(prefixes[j+1].code) { + prefixes[j], prefixes[j+1] = prefixes[j+1], prefixes[j] + } + } + } + a.mu.Lock() + a.exact, a.prefixes = exact, prefixes + a.mu.Unlock() + return nil +} + +// Start 定时刷新(caller 起 goroutine;ctx 取消即退出)。 +func (a *Assigner) Start(ctx context.Context, every time.Duration) { + if every <= 0 { + every = DefaultReloadEvery + } + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + if err := a.Reload(ctx); err != nil { + logger.L().Warn("uplink_code_reload_failed", zap.Error(err)) + } + } + } +} + +// Match 两级匹配。返回归属账号与命中方式;code 空或未命中 matched=false +// (调用方按需求兜底 AdminFallbackAccount)。 +func (a *Assigner) Match(code string) (accountID int64, exact, matched bool) { + code = strings.TrimSpace(code) + if code == "" { + return 0, false, false + } + a.mu.RLock() + defer a.mu.RUnlock() + if id, ok := a.exact[code]; ok { + return id, true, true + } + for _, p := range a.prefixes { // 码长降序,首个命中=最长前缀 + if strings.HasPrefix(code, p.code) { + return p.accountID, false, true + } + } + return 0, false, false +} + +// Service 上行入口:通道 Deliver MO → 码号分配 → 落库 message_uplink +// → 投递 sms-up(key=src_mobile)。Ingest 由通道链路读循环 goroutine 调用, +// 内部失败仅记日志不上抛(上行不阻断通道读循环)。 +type Service struct { + db *gorm.DB + asg *Assigner + prod Producer +} + +// NewService 构造(asg=nil 时自建并立即装载;prod=nil 仅落库不投递)。 +func NewService(db *gorm.DB, asg *Assigner, prod Producer) *Service { + if asg == nil { + asg = NewAssigner(db) + } + if err := asg.Reload(context.Background()); err != nil { + logger.L().Warn("uplink_code_initial_reload_failed", zap.Error(err)) + } + return &Service{db: db, asg: asg, prod: prod} +} + +// Ingest 上行受理:返回落库记录 ID。 +func (s *Service) Ingest(ctx context.Context, channelID int64, destCode, srcMobile, content string) (int64, error) { + destCode = strings.TrimSpace(destCode) + srcMobile = strings.TrimSpace(srcMobile) + accountID, _, matched := s.asg.Match(destCode) + if !matched { + accountID = AdminFallbackAccount + } + now := time.Now() + row := entity.MessageUplink{ + DestCode: destCode, SrcMobile: srcMobile, + Content: content, AccountID: accountID, + ChannelID: channelID, RecvAt: now, + } + if err := s.db.WithContext(ctx).Create(&row).Error; err != nil { + return 0, err + } + logger.L().Info("uplink_ingested", + zap.Int64("uplink_id", row.ID), zap.Int64("channel_id", channelID), + zap.String("dest_code", destCode), zap.String("src_mobile", srcMobile), + zap.Int64("account_id", accountID), zap.Bool("matched", matched)) + if s.prod != nil { + payload, _ := json.Marshal(Event{ + UplinkID: row.ID, DestCode: destCode, SrcMobile: srcMobile, + Content: content, AccountID: accountID, ChannelID: channelID, + RecvAt: now.Format(time.RFC3339), + }) + if err := s.prod.Send(queue.TopicUp, []byte(srcMobile), payload); err != nil { + // 记录已落库:投递失败不回滚(15 天匹配可由 DB 补偿任务回填,阶段5推送同理)。 + logger.L().Warn("uplink_kafka_send_failed", zap.Int64("uplink_id", row.ID), zap.Error(err)) + } + } + return row.ID, nil +} diff --git a/internal/service/uplink/uplink_test.go b/internal/service/uplink/uplink_test.go new file mode 100644 index 00000000..e7caf797 --- /dev/null +++ b/internal/service/uplink/uplink_test.go @@ -0,0 +1,220 @@ +// uplink_test.go Day 49:码号分配两级匹配(A-4.18)+Ingest 落库投递+15 天窗口匹配。 +package uplink + +import ( + "context" + "encoding/json" + "testing" + "time" + + "go-sms/internal/model/entity" + "go-sms/internal/pkg/queue" + + "github.com/glebarez/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +func newTestDB(t *testing.T) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatalf("打开内存库失败: %v", err) + } + if err := db.AutoMigrate(&entity.UplinkCode{}, &entity.MessageUplink{}, &entity.MessageDetail{}); err != nil { + t.Fatalf("AutoMigrate 失败: %v", err) + } + return db +} + +// capProd 生产者捕获(断言 topic/key/载荷)。 +type capProd struct { + topics []string + keys [][]byte + vals [][]byte +} + +func (p *capProd) Send(topic string, key, value []byte) error { + p.topics = append(p.topics, topic) + p.keys = append(p.keys, key) + p.vals = append(p.vals, value) + return nil +} + +// TestAssignerMatch 两级匹配验收:精确 > 最长前缀 > 未命中(兜底归调用方)。 +func TestAssignerMatch(t *testing.T) { + db := newTestDB(t) + db.Create([]*entity.UplinkCode{ + {AccountID: 10, Code: "106901", MatchType: MatchExact}, + {AccountID: 20, Code: "1069", MatchType: MatchPrefix}, + {AccountID: 30, Code: "10690", MatchType: MatchPrefix}, + {AccountID: 40, Code: "1069001", MatchType: MatchPrefix}, + }) + a := NewAssigner(db) + if err := a.Reload(context.Background()); err != nil { + t.Fatalf("Reload: %v", err) + } + // ① 精确优先:106901 同时命中精确码与前缀 10690/1069,取精确账号 10。 + if id, exact, ok := a.Match("106901"); !ok || !exact || id != 10 { + t.Fatalf("精确优先: id=%d exact=%v ok=%v, 期望 10/true/true", id, exact, ok) + } + // ② 最长前缀:106900123 命中 1069001(40) 而非 10690(30)/1069(20)。 + if id, exact, ok := a.Match("106900123"); !ok || exact || id != 40 { + t.Fatalf("最长前缀: id=%d exact=%v ok=%v, 期望 40/false/true", id, exact, ok) + } + // ③ 次长前缀:106905 命中 10690(30)。 + if id, _, ok := a.Match("106905"); !ok || id != 30 { + t.Fatalf("次长前缀: id=%d ok=%v, 期望 30", id, ok) + } + // ④ 前缀码等值串:1069 无精确码,前缀自匹配(HasPrefix 等值)命中 20。 + if id, exact, ok := a.Match("1069"); !ok || exact || id != 20 { + t.Fatalf("前缀等值: id=%d exact=%v ok=%v, 期望 20/false/true", id, exact, ok) + } + // ⑤ 未命中/空码号。 + if _, _, ok := a.Match("107"); ok { + t.Fatal("107 不应命中") + } + if _, _, ok := a.Match(" "); ok { + t.Fatal("空码号不应命中") + } + // ⑥ Reload 增量生效(缓存刷新窗口)。 + db.Create(&entity.UplinkCode{AccountID: 50, Code: "10086", MatchType: MatchExact}) + if _, _, ok := a.Match("10086"); ok { + t.Fatal("未 Reload 前新码号不应命中") + } + if err := a.Reload(context.Background()); err != nil { + t.Fatalf("二次 Reload: %v", err) + } + if id, exact, ok := a.Match("10086"); !ok || !exact || id != 50 { + t.Fatalf("Reload 后: id=%d exact=%v ok=%v, 期望 50/true/true", id, exact, ok) + } +} + +// TestServiceIngest 落库+分配+兜底 admin+sms-up 投递(载荷/键)+prod=nil 降级。 +func TestServiceIngest(t *testing.T) { + db := newTestDB(t) + db.Create(&entity.UplinkCode{AccountID: 10, Code: "10690", MatchType: MatchPrefix}) + prod := &capProd{} + svc := NewService(db, nil, prod) // asg=nil 自建并装载 + + id, err := svc.Ingest(context.Background(), 7, "10690001", "13812345678", "TD") + if err != nil || id == 0 { + t.Fatalf("Ingest: id=%d err=%v", id, err) + } + var row entity.MessageUplink + if err := db.First(&row, id).Error; err != nil { + t.Fatalf("落库查询: %v", err) + } + if row.AccountID != 10 || row.DestCode != "10690001" || row.SrcMobile != "13812345678" || + row.Content != "TD" || row.ChannelID != 7 { + t.Fatalf("落库字段: %+v", row) + } + // Kafka:topic=sms-up,key=src_mobile,载荷字段对齐。 + if len(prod.topics) != 1 || prod.topics[0] != queue.TopicUp { + t.Fatalf("topic: %v", prod.topics) + } + if string(prod.keys[0]) != "13812345678" { + t.Fatalf("key: %s", prod.keys[0]) + } + var ev Event + if err := json.Unmarshal(prod.vals[0], &ev); err != nil { + t.Fatalf("载荷解析: %v", err) + } + if ev.UplinkID != id || ev.AccountID != 10 || ev.ChannelID != 7 || ev.DestCode != "10690001" { + t.Fatalf("载荷字段: %+v", ev) + } + if _, perr := time.Parse(time.RFC3339, ev.RecvAt); perr != nil { + t.Fatalf("recv_at 非 RFC3339: %q", ev.RecvAt) + } + + // 未命中兜底 admin(需求 2.5)。 + id2, err := svc.Ingest(context.Background(), 7, "99999", "13900001111", "R") + if err != nil { + t.Fatalf("Ingest 兜底: %v", err) + } + var row2 entity.MessageUplink + db.First(&row2, id2) + if row2.AccountID != AdminFallbackAccount { + t.Fatalf("兜底归属: %d, 期望 %d", row2.AccountID, AdminFallbackAccount) + } + + // prod=nil 降级:仅落库不投递,不 panic。 + svc2 := NewService(db, nil, nil) + if _, err := svc2.Ingest(context.Background(), 7, "10690002", "13800002222", "TD"); err != nil { + t.Fatalf("prod=nil: %v", err) + } +} + +// TestConsumerMatchWindow 15 天窗口匹配:窗口内最近一条回填;窗口外保留 0; +// 已匹配行不覆写(幂等)。 +func TestConsumerMatchWindow(t *testing.T) { + db := newTestDB(t) + now := time.Now() + db.Create([]*entity.MessageDetail{ + {SnowflakeModel: entity.SnowflakeModel{ID: 1001, CreatedAt: now.Add(-10 * 24 * time.Hour)}, TaskID: 77, AccountID: 10, Mobile: "13812345678"}, + {SnowflakeModel: entity.SnowflakeModel{ID: 1002, CreatedAt: now.Add(-20 * 24 * time.Hour)}, TaskID: 66, AccountID: 10, Mobile: "13812345678"}, + }) + up := entity.MessageUplink{ID: 55, DestCode: "10690001", SrcMobile: "13812345678", + AccountID: 10, ChannelID: 7, RecvAt: now} + db.Create(&up) + c := NewConsumer(db) + + // ① 窗口内(10 天前)最近一条=task 77;窗口外(20 天前)不参与。 + ev := &Event{UplinkID: 55, AccountID: 10, SrcMobile: "13812345678", RecvAt: now.Format(time.RFC3339)} + if err := c.MatchAndFill(context.Background(), ev); err != nil { + t.Fatalf("MatchAndFill: %v", err) + } + var got entity.MessageUplink + db.First(&got, 55) + if got.MatchTaskID != 77 { + t.Fatalf("回填: %d, 期望 77", got.MatchTaskID) + } + + // ② 幂等:窗口内出现更新明细(1 小时前 task 88),已匹配行(=77)不覆写。 + db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 1003, CreatedAt: now.Add(-time.Hour)}, TaskID: 88, AccountID: 10, Mobile: "13812345678"}) + if err := c.MatchAndFill(context.Background(), ev); err != nil { + t.Fatalf("二次 MatchAndFill: %v", err) + } + db.First(&got, 55) + if got.MatchTaskID != 77 { + t.Fatalf("覆写破坏幂等: %d", got.MatchTaskID) + } + + // ③ 窗口外独一条:保留 0(未匹配可筛)。 + db.Create(&entity.MessageUplink{ID: 56, DestCode: "99999", SrcMobile: "13900001111", + AccountID: 30, ChannelID: 7, RecvAt: now}) + db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 1004, CreatedAt: now.Add(-20 * 24 * time.Hour)}, TaskID: 99, AccountID: 30, Mobile: "13900001111"}) + if err := c.MatchAndFill(context.Background(), &Event{ + UplinkID: 56, AccountID: 30, SrcMobile: "13900001111", RecvAt: now.Format(time.RFC3339), + }); err != nil { + t.Fatalf("窗口外 MatchAndFill: %v", err) + } + var got2 entity.MessageUplink + db.First(&got2, 56) + if got2.MatchTaskID != 0 { + t.Fatalf("窗口外应保留 0: %d", got2.MatchTaskID) + } +} + +// TestHandlePayload JSON 载荷消费路径(含非法载荷报错交由消费组死信)。 +func TestHandlePayload(t *testing.T) { + db := newTestDB(t) + now := time.Now() + c := NewConsumer(db) + payload, _ := json.Marshal(Event{ + UplinkID: 66, AccountID: 40, SrcMobile: "13700003333", RecvAt: now.Format(time.RFC3339), + }) + db.Create(&entity.MessageUplink{ID: 66, SrcMobile: "13700003333", AccountID: 40, RecvAt: now}) + db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 2001, CreatedAt: now.Add(-time.Hour)}, TaskID: 123, AccountID: 40, Mobile: "13700003333"}) + if err := c.HandlePayload(context.Background(), payload); err != nil { + t.Fatalf("HandlePayload: %v", err) + } + var got entity.MessageUplink + db.First(&got, 66) + if got.MatchTaskID != 123 { + t.Fatalf("回填: %d, 期望 123", got.MatchTaskID) + } + if err := c.HandlePayload(context.Background(), []byte("{bad")); err == nil { + t.Fatal("非法载荷应报错(死信路径)") + } +}