S1-B D2.5-P2: channel 拆 pool 子包——linkManager→pool.Manager(Deps 接口断环:Get/ListCMPPActive/LogChannel/EvaluateChannel/ReportSubmit/ReportDeliver 六适配);LogKind 常量随链路域移驻 pool;测试改 pool_test 外部包+helper 本地化(mini-CMPP 模拟器链);Service 补 Pool()/RestartLink()/DB()/FlushChannelLogs() 访问器;行为零改动(channel 77.3%+pool 62.3% -race 双绿)

This commit is contained in:
2026-11-13 16:49:42 +08:00
parent 5ce1d0940a
commit 234dc5ee57
13 changed files with 351 additions and 173 deletions
+6 -4
View File
@@ -2,6 +2,7 @@
// 复用 Day 27 余额预警的 SystemAlertRule(target_type=channel)+notify webhook 基建:
// - metric=link_down : 应建链而全断(running 且 healthy==0,或启用中 cmpp 通道未建链)→ 触发;
// - metric=fail_rate : 60s 窗口提交失败占比 > threshold(0~1,语义固定 gt)→ 触发;
//
// 触发后走 NotifyType/NotifyTo webhook(企微/钉钉),CooldownMin 冷却去重(LastAlertAt 锚点)。
package channel
@@ -14,6 +15,7 @@ import (
"go-sms/internal/model/entity"
"go-sms/internal/pkg/notify"
"go-sms/internal/service/channel/pool"
)
// 支持的通道告警指标。
@@ -32,14 +34,14 @@ type AlertScanResult struct {
type ChannelAlertService struct {
db *gorm.DB
mon *Monitor
links func(id int64) *LinkStatus
links func(id int64) *pool.LinkStatus
newNotifier func(typ, url string) notify.Notifier
onLogged func(channelID int64, kind string, level int8, msgID, detail string, latencyMs int)
}
// NewChannelAlertService 构造;links 为链路状态读取函数(解依赖环:linkManager ↔ alert)。
// newNotifier 为 nil 时用 notify.NewWebhook(测试注入 fake)。
func NewChannelAlertService(db *gorm.DB, mon *Monitor, links func(id int64) *LinkStatus,
func NewChannelAlertService(db *gorm.DB, mon *Monitor, links func(id int64) *pool.LinkStatus,
newNotifier func(typ, url string) notify.Notifier) *ChannelAlertService {
if newNotifier == nil {
newNotifier = func(typ, url string) notify.Notifier { return notify.NewWebhook(typ, url) }
@@ -125,7 +127,7 @@ func (s *ChannelAlertService) evaluate(ctx context.Context, rule *entity.SystemA
Where("id = ?", rule.ID).Update("last_alert_at", now).Error
// 告警留痕进通道日志(逐条)。
if s.onLogged != nil {
s.onLogged(ch.ID, LogKindAlert, 1, "", content, 0)
s.onLogged(ch.ID, pool.LogKindAlert, 1, "", content, 0)
}
return true
}
@@ -154,7 +156,7 @@ func (s *ChannelAlertService) alertContent(ch *entity.ChannelChannel, rule *enti
}
// linkStatus 链路状态读取(links 函数可为 nil→未建链)。
func (s *ChannelAlertService) linkStatus(id int64) *LinkStatus {
func (s *ChannelAlertService) linkStatus(id int64) *pool.LinkStatus {
if s.links == nil {
return nil
}
-1
View File
@@ -171,4 +171,3 @@ func TestChannelAlert_DisabledChannelSkipped(t *testing.T) {
t.Fatalf("停用通道不应告: %+v", res)
}
}
+9 -19
View File
@@ -12,29 +12,19 @@ import (
"go-sms/internal/model/entity"
"go-sms/internal/pkg/logger"
"go-sms/internal/service/channel/pool"
"go.uber.org/zap"
"gorm.io/gorm"
)
// 日志 kind 常量。
const (
LogKindConnect = "connect" // 建链成功
LogKindDisconnect = "disconnect" // 连接断开(重连前)
LogKindStop = "stop" // 主动拆除
LogKindSubmit = "submit" // 提交成功(窗口聚合)
LogKindSubmitFail = "submit_fail" // 提交失败(逐条)
LogKindDeliver = "deliver" // 回执 DELIVRD(窗口聚合)
LogKindDeliverFail = "deliver_fail" // 回执非成功态(逐条)
LogKindDeliverMO = "deliver_mo" // 上行短信(逐条)
LogKindAlert = "alert" // 告警留痕
)
// 日志 kind 常量:定义随链路域移驻 pool 子包(S1-B P2),此处经 pool.LogKind* 引用。
const (
logQueueCap = 2048 // 内存队列容量(满则丢弃,绝不阻塞提交)
logFlushBatch = 200 // 批量落库条数
logFlushEvery = 2 * time.Second // 刷库周期
logQueueCap = 2048 // 内存队列容量(满则丢弃,绝不阻塞提交)
logFlushBatch = 200 // 批量落库条数
logFlushEvery = 2 * time.Second // 刷库周期
logAggWindow = 10 * time.Second // submit/deliver 聚合窗口
)
@@ -58,9 +48,9 @@ type aggKey struct {
// aggVal 聚合累计值。
type aggVal struct {
count int
latSum int
firstAt time.Time
count int
latSum int
firstAt time.Time
}
// ChannelLogger 通道日志落库器(nil 安全:未注入时全部 no-op)。
@@ -171,7 +161,7 @@ func (l *ChannelLogger) run() {
// ingest 单事件处理:可聚合 kind 进桶(返回空),其余返回待写行。
func (l *ChannelLogger) ingest(e logEvent) []entity.ChannelLog {
switch e.Kind {
case LogKindSubmit, LogKindDeliver:
case pool.LogKindSubmit, pool.LogKindDeliver:
k := aggKey{ChannelID: e.ChannelID, Kind: e.Kind, Bucket: e.At.Unix() / int64(logAggWindow/time.Second)}
l.mu.Lock()
v, ok := l.agg[k]
+11 -10
View File
@@ -5,6 +5,7 @@ import (
"testing"
"go-sms/internal/model/entity"
"go-sms/internal/service/channel/pool"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
@@ -30,11 +31,11 @@ func TestChannelLogger_AggregateAndPersist(t *testing.T) {
defer l.Close()
// 3 条成功提交(延迟 10/20/30 → 均值 20)+1 条失败+1 条断连。
l.Log(7, LogKindSubmit, 0, "m1", "", 10)
l.Log(7, LogKindSubmit, 0, "m2", "", 20)
l.Log(7, LogKindSubmit, 0, "m3", "", 30)
l.Log(7, LogKindSubmitFail, 2, "", "上游拒绝: result=8", 5)
l.Log(7, LogKindDisconnect, 2, "", "conn#0: read eof", 0)
l.Log(7, pool.LogKindSubmit, 0, "m1", "", 10)
l.Log(7, pool.LogKindSubmit, 0, "m2", "", 20)
l.Log(7, pool.LogKindSubmit, 0, "m3", "", 30)
l.Log(7, pool.LogKindSubmitFail, 2, "", "上游拒绝: result=8", 5)
l.Log(7, pool.LogKindDisconnect, 2, "", "conn#0: read eof", 0)
l.FlushNow()
var rows []entity.ChannelLog
@@ -48,13 +49,13 @@ func TestChannelLogger_AggregateAndPersist(t *testing.T) {
for _, r := range rows {
byKind[r.Kind] = r
}
if s := byKind[LogKindSubmit]; s.Count != 3 || s.LatencyMs != 20 {
if s := byKind[pool.LogKindSubmit]; s.Count != 3 || s.LatencyMs != 20 {
t.Fatalf("submit 聚合行: %+v", s)
}
if f := byKind[LogKindSubmitFail]; f.Count != 1 || f.Level != 2 || f.Detail == "" {
if f := byKind[pool.LogKindSubmitFail]; f.Count != 1 || f.Level != 2 || f.Detail == "" {
t.Fatalf("submit_fail 逐条行: %+v", f)
}
if d := byKind[LogKindDisconnect]; d.Level != 2 || d.ChannelID != 7 {
if d := byKind[pool.LogKindDisconnect]; d.Level != 2 || d.ChannelID != 7 {
t.Fatalf("disconnect 逐条行: %+v", d)
}
}
@@ -63,7 +64,7 @@ func TestChannelLogger_AggregateAndPersist(t *testing.T) {
func TestChannelLogger_CloseFlush(t *testing.T) {
db := newLogDB(t)
l := NewChannelLogger(db)
l.Log(9, LogKindConnect, 0, "", "pool started", 0)
l.Log(9, pool.LogKindConnect, 0, "", "pool started", 0)
l.Close()
var n int64
db.Model(&entity.ChannelLog{}).Count(&n)
@@ -77,7 +78,7 @@ func TestChannelLogger_CloseFlush(t *testing.T) {
// TestChannelLogger_NilSafe nil 接收者全部 no-op(不 panic)。
func TestChannelLogger_NilSafe(t *testing.T) {
var l *ChannelLogger
l.Log(1, LogKindSubmit, 0, "", "", 1)
l.Log(1, pool.LogKindSubmit, 0, "", "", 1)
l.FlushNow()
l.Close()
}
+14 -14
View File
@@ -10,8 +10,8 @@ import (
)
const (
monWindowSec = 60 // 统计滑窗(秒)
monLatCap = 256 // 延迟样本环形容量
monWindowSec = 60 // 统计滑窗(秒)
monLatCap = 256 // 延迟样本环形容量
)
// bucket 单秒桶。
@@ -33,18 +33,18 @@ type chanStat struct {
// ChannelSnapshot 单通道实时快照(WS/轮询视图)。
type ChannelSnapshot struct {
ChannelID int64 `json:"channel_id"`
Name string `json:"name"`
Protocol string `json:"protocol"`
Status int8 `json:"status"`
Running bool `json:"running"`
Total int `json:"total"`
Healthy int `json:"healthy"`
SubmitPs float64 `json:"submit_ps"` // 60s 窗口均值(条/秒)
DeliverPs float64 `json:"deliver_ps"` // 60s 窗口均值(条/秒)
FailRate float64 `json:"fail_rate"` // 60s 窗口失败占比(0~1;无提交=0)
LatencyP50 int `json:"latency_p50_ms"` // 最近样本中位数
UpdatedAt string `json:"updated_at"`
ChannelID int64 `json:"channel_id"`
Name string `json:"name"`
Protocol string `json:"protocol"`
Status int8 `json:"status"`
Running bool `json:"running"`
Total int `json:"total"`
Healthy int `json:"healthy"`
SubmitPs float64 `json:"submit_ps"` // 60s 窗口均值(条/秒)
DeliverPs float64 `json:"deliver_ps"` // 60s 窗口均值(条/秒)
FailRate float64 `json:"fail_rate"` // 60s 窗口失败占比(0~1;无提交=0)
LatencyP50 int `json:"latency_p50_ms"` // 最近样本中位数
UpdatedAt string `json:"updated_at"`
}
// Monitor 通道统计中心(Service 内嵌单例;线程安全)。
@@ -2,7 +2,11 @@
// 每通道一池常驻长连接(登录+心跳+断线指数退避重连);提交走池化连接;
// Deliver 回执结构化日志+环形缓冲(入库留待阶段 5 Day 51 message_report)。
// 为阶段 4 发送主路径(路由引擎经链路提交)与阶段 5 回执落地奠基。
package channel
//
// 2026-11-13 S1-B P2:自 service/channel 拆为 pool 子包(搬运清单 B「拆 pool/limiter」;
// 域内限速实现在 send/pacer,本包=连接池域)。channel.Service 经 Deps 适配断环,
// 行为零改动(仅移动+重命名 linkManager→Manager)。
package pool
import (
"context"
@@ -19,6 +23,23 @@ import (
"go.uber.org/zap"
)
// Deps 通道元数据与可观测出口(由 channel.Service 适配实现;
// 断 pool↔channel 循环依赖,口径与拆分前 svc.* 调用一一对应)。
type Deps interface {
// Get 通道元数据(原 svc.Get)。
Get(ctx context.Context, id int64) (*entity.ChannelChannel, error)
// ListCMPPActive 启用中的 CMPP 通道清单(原 svc.List(ctx,&ListQuery{cmpp,1}))。
ListCMPPActive(ctx context.Context) ([]entity.ChannelChannel, error)
// LogChannel 通道日志(原 svc.logs.Log)。
LogChannel(channelID int64, kind string, level int8, msgID, detail string, latencyMs int)
// EvaluateChannel 告警评估(原 svc.alerts.EvaluateChannel)。
EvaluateChannel(ctx context.Context, channelID int64)
// ReportSubmit 提交计数(原 svc.mon.ReportSubmit)。
ReportSubmit(channelID int64, ok bool, latencyMs int)
// ReportDeliver 回执计数(原 svc.mon.ReportDeliver)。
ReportDeliver(channelID int64, ok bool)
}
// deliverLogSample 回执日志采样计数器(P1:1/100 采样,DELIVRD 之外全量)。
var deliverLogSample atomic.Uint64
@@ -60,13 +81,13 @@ type link struct {
startedAt time.Time
}
// linkManager 链路管理器(Service 内嵌单例)。
type linkManager struct {
svc *Service
// Manager 链路管理器(Service 内嵌单例;S1-B P2 由 linkManager 更名)。
type Manager struct {
deps Deps
mu sync.RWMutex
links map[int64]*link
rmu sync.Mutex
reports []Receipt // 环形缓冲(全通道最近 receiptCap 条)
reports []Receipt // 环形缓冲(全通道最近 receiptCap 条)
uplink UplinkSink // Day 49:上行出口(码号分配+落库+sms-up;nil=仅日志)
report ReportSink // Day 56:回执出口(sms-report 投递;nil=仅日志/环形)
}
@@ -76,17 +97,37 @@ const receiptCap = 100
// linkReady 链路就绪等待上限(首次建链/断线重连窗口)。
const linkReady = 5 * time.Second
func newLinkManager(svc *Service) *linkManager {
return &linkManager{svc: svc, links: map[int64]*link{}}
// 日志 kind 常量(S1-B P2 随 link 域迁入 pool;channel/log.go 反向引用保持单一事实源)。
const (
LogKindConnect = "connect" // 建链成功
LogKindDisconnect = "disconnect" // 连接断开(重连前)
LogKindStop = "stop" // 主动拆除
LogKindSubmit = "submit" // 提交成功(窗口聚合)
LogKindSubmitFail = "submit_fail" // 提交失败(逐条)
LogKindDeliver = "deliver" // 回执 DELIVRD(窗口聚合)
LogKindDeliverFail = "deliver_fail" // 回执非成功态(逐条)
LogKindDeliverMO = "deliver_mo" // 上行短信(逐条)
LogKindAlert = "alert" // 告警留痕
)
// NewManager 构造(deps 由 channel.Service 适配提供)。
func NewManager(deps Deps) *Manager {
return &Manager{deps: deps, links: map[int64]*link{}}
}
// SetUplinkSink 注入上行处理器(Day 49;装配层调用,须在 StartLink 前)。
func (m *linkManager) SetUplinkSink(u UplinkSink) {
func (m *Manager) SetUplinkSink(u UplinkSink) {
m.mu.Lock()
m.uplink = u
m.mu.Unlock()
}
// UplinkSink 上行处理出口(Day 49:Deliver MO→码号分配+落库+sms-up 投递;
// 由 service/uplink.Service 实现,pool 只依赖接口避免包循环)。
type UplinkSink interface {
Ingest(ctx context.Context, channelID int64, destCode, srcMobile, content string) (int64, error)
}
// ReportSink 回执出口(Day 56):状态报告经 Kafka sms-report 异步归一化
// (消费者按 msg_id+mobile 段级配对→聚合判 detail 终态)。
type ReportSink interface {
@@ -94,7 +135,7 @@ type ReportSink interface {
}
// SetReportSink 注入回执出口(Day 56;装配层调用;nil=维持 Day55 前行为)。
func (m *linkManager) SetReportSink(r ReportSink) {
func (m *Manager) SetReportSink(r ReportSink) {
m.mu.Lock()
m.report = r
m.mu.Unlock()
@@ -111,20 +152,20 @@ type BatchAck struct {
}
// observe 便捷埋点:通道日志 + 监控统计(失败时)。
func (m *linkManager) observe(channelID int64, kind string, level int8, msgID, detail string, latencyMs int) {
m.svc.logs.Log(channelID, kind, level, msgID, detail, latencyMs)
func (m *Manager) observe(channelID int64, kind string, level int8, msgID, detail string, latencyMs int) {
m.deps.LogChannel(channelID, kind, level, msgID, detail, latencyMs)
}
// onDrop 断连事件:日志 + 告警即时评估(异步,不阻塞重连路径)。
func (m *linkManager) onDrop(channelID int64, idx int, err error) {
func (m *Manager) onDrop(channelID int64, idx int, err error) {
detail := fmt.Sprintf("conn#%d: %v", idx, err)
m.observe(channelID, LogKindDisconnect, 2, "", detail, 0)
go m.svc.alerts.EvaluateChannel(context.Background(), channelID)
go m.deps.EvaluateChannel(context.Background(), channelID)
}
// Bootstrap 启动时为全部「启用中的 cmpp 通道」建链(异步;单通道失败仅告警)。
func (m *linkManager) Bootstrap(ctx context.Context) {
list, _, err := m.svc.List(ctx, &ListQuery{Page: 1, PageSize: 100, Protocol: "cmpp", Status: 1})
func (m *Manager) Bootstrap(ctx context.Context) {
list, err := m.deps.ListCMPPActive(ctx)
if err != nil {
logger.L().Warn("link_bootstrap_list_failed", zap.Error(err))
return
@@ -155,7 +196,7 @@ func poolConfig(ch *entity.ChannelChannel) cmpp.Config {
}
// Shutdown 全部拆除(进程退出)。
func (m *linkManager) Shutdown() {
func (m *Manager) Shutdown() {
m.mu.Lock()
ids := make([]int64, 0, len(m.links))
for id := range m.links {
@@ -168,7 +209,7 @@ func (m *linkManager) Shutdown() {
}
// StartLink 为通道建立常驻链路(已存在则幂等返回)。
func (m *linkManager) StartLink(ctx context.Context, id int64) (*LinkStatus, error) {
func (m *Manager) StartLink(ctx context.Context, id int64) (*LinkStatus, error) {
m.mu.Lock()
if _, ok := m.links[id]; ok {
m.mu.Unlock()
@@ -176,7 +217,7 @@ func (m *linkManager) StartLink(ctx context.Context, id int64) (*LinkStatus, err
}
m.mu.Unlock()
ch, err := m.svc.Get(context.Background(), id)
ch, err := m.deps.Get(context.Background(), id)
if err != nil {
return nil, err
}
@@ -195,7 +236,7 @@ func (m *linkManager) StartLink(ctx context.Context, id int64) (*LinkStatus, err
size = 1
}
pool := cmpp.NewPool(poolConfig(ch), size)
pool.OnDeliver(func(d *cmpp.Deliver) { m.handleDeliver(id, d) })
pool.OnDeliver(func(d *cmpp.Deliver) { m.HandleDeliver(id, d) })
pool.OnDisconnected(func(i int, err error) { m.onDrop(id, i, err) })
runCtx, cancel := context.WithCancel(context.Background())
pool.Start(runCtx)
@@ -216,7 +257,7 @@ func (m *linkManager) StartLink(ctx context.Context, id int64) (*LinkStatus, err
}
// StopLink 拆除链路(不存在则幂等)。
func (m *linkManager) StopLink(id int64) {
func (m *Manager) StopLink(id int64) {
m.mu.Lock()
l, ok := m.links[id]
if ok {
@@ -232,13 +273,13 @@ func (m *linkManager) StopLink(id int64) {
}
// RestartLink 参数变更后重建。
func (m *linkManager) RestartLink(ctx context.Context, id int64) (*LinkStatus, error) {
func (m *Manager) RestartLink(ctx context.Context, id int64) (*LinkStatus, error) {
m.StopLink(id)
return m.StartLink(ctx, id)
}
// Status 查询链路状态(未建链返回 Running=false)。
func (m *linkManager) Status(id int64) *LinkStatus {
func (m *Manager) Status(id int64) *LinkStatus {
m.mu.RLock()
l, ok := m.links[id]
m.mu.RUnlock()
@@ -255,7 +296,7 @@ func (m *linkManager) Status(id int64) *LinkStatus {
// SubmitViaLink 经常驻链路提交(未建链自动建立);返回上游 MsgID。
// SubmitViaLink 单号提交;返回各段 msg_id(顺序=PkNumber 1..N,单条=1 个;
// Day 56 段级回执配对:每片独立 msg_id,提交侧据此逐段登记 message_report_seg)。
func (m *linkManager) SubmitViaLink(ctx context.Context, id int64, mobile, content string) ([]string, error) {
func (m *Manager) SubmitViaLink(ctx context.Context, id int64, mobile, content string) ([]string, error) {
m.mu.RLock()
l, ok := m.links[id]
m.mu.RUnlock()
@@ -278,7 +319,7 @@ func (m *linkManager) SubmitViaLink(ctx context.Context, id int64, mobile, conte
if l.pool.Healthy() == 0 {
return nil, ErrLinkUnavailable
}
ch, err := m.svc.Get(context.Background(), id)
ch, err := m.deps.Get(context.Background(), id)
if err != nil {
return nil, err
}
@@ -316,16 +357,16 @@ func (m *linkManager) SubmitViaLink(ctx context.Context, id int64, mobile, conte
})
lat := int(time.Since(t0).Milliseconds())
if err != nil {
m.svc.mon.ReportSubmit(id, false, 0)
m.deps.ReportSubmit(id, false, 0)
m.observe(id, LogKindSubmitFail, 2, lastOK, fmt.Sprintf("%v", err), lat)
return msgIDs, err
}
if resp.Result != 0 {
m.svc.mon.ReportSubmit(id, false, 0)
m.deps.ReportSubmit(id, false, 0)
m.observe(id, LogKindSubmitFail, 2, lastOK, fmt.Sprintf("上游拒绝: result=%d", resp.Result), lat)
return msgIDs, fmt.Errorf("上游拒绝: result=%d", resp.Result)
}
m.svc.mon.ReportSubmit(id, true, lat)
m.deps.ReportSubmit(id, true, lat)
m.observe(id, LogKindSubmit, 0, fmt.Sprintf("%d", resp.MsgID), "", lat)
msgIDs = append(msgIDs, fmt.Sprintf("%d", resp.MsgID))
lastOK = msgIDs[len(msgIDs)-1]
@@ -339,7 +380,7 @@ func (m *linkManager) SubmitViaLink(ctx context.Context, id int64, mobile, conte
// 调用方可回退逐号保送达)。
// Day 56:返回包级回执 acks(每包 msg_id+包内号码+总片数)——提交侧据此
// 逐段登记 message_report_seg,长短信每片独立成包独立 msg_id。
func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
func (m *Manager) SubmitBatchViaLink(ctx context.Context, id int64,
mobiles []string, content string) ([]BatchAck, error) {
if len(mobiles) == 0 {
return nil, nil
@@ -365,7 +406,7 @@ func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
if l.pool.Healthy() == 0 {
return nil, ErrLinkUnavailable
}
ch, err := m.svc.Get(context.Background(), id)
ch, err := m.deps.Get(context.Background(), id)
if err != nil {
return nil, err
}
@@ -404,7 +445,7 @@ func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
})
lat := int(time.Since(t0).Milliseconds())
if serr != nil {
m.svc.mon.ReportSubmit(id, false, 0)
m.deps.ReportSubmit(id, false, 0)
m.observe(id, LogKindSubmitFail, 2, "", fmt.Sprintf("batch: %v", serr), lat)
if firstErr == nil {
firstErr = serr
@@ -412,7 +453,7 @@ func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
continue
}
if resp.Result != 0 {
m.svc.mon.ReportSubmit(id, false, 0)
m.deps.ReportSubmit(id, false, 0)
m.observe(id, LogKindSubmitFail, 2, fmt.Sprintf("%d", resp.MsgID),
fmt.Sprintf("batch 上游拒绝: result=%d", resp.Result), lat)
if firstErr == nil {
@@ -420,7 +461,7 @@ func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
}
continue
}
m.svc.mon.ReportSubmit(id, true, lat)
m.deps.ReportSubmit(id, true, lat)
m.observe(id, LogKindSubmit, 0, fmt.Sprintf("%d×%d", resp.MsgID, len(dest)), "", lat)
acks = append(acks, BatchAck{
MsgID: fmt.Sprintf("%d", resp.MsgID),
@@ -432,7 +473,7 @@ func (m *linkManager) SubmitBatchViaLink(ctx context.Context, id int64,
}
return acks, firstErr
}
func (m *linkManager) Receipts(channelID int64, n int) []Receipt {
func (m *Manager) Receipts(channelID int64, n int) []Receipt {
m.rmu.Lock()
defer m.rmu.Unlock()
var out []Receipt
@@ -454,14 +495,14 @@ func decodeMOContent(content []byte, msgFmt uint8) string {
return string(content)
}
// handleDeliver 回执/上行处理:结构化日志 + 环形缓冲 + 监控/通道日志(Day 40)。
func (m *linkManager) handleDeliver(channelID int64, d *cmpp.Deliver) {
// HandleDeliver 回执/上行处理:结构化日志 + 环形缓冲 + 监控/通道日志(Day 40;S1-B P2 导出:回执注入点,装配层/测试同入口)。
func (m *Manager) HandleDeliver(channelID int64, d *cmpp.Deliver) {
r := Receipt{ChannelID: channelID, IsReport: d.IsReport, At: time.Now().Format("2006-01-02 15:04:05")}
if d.IsReport && d.Report != nil {
r.MsgID = fmt.Sprintf("%d", d.Report.MsgID)
r.Stat, r.SubmitTime, r.DoneTime, r.Dest = d.Report.Stat, d.Report.SubmitTime, d.Report.DoneTime, d.Report.DestTerminalID
ok := d.Report.Stat == "DELIVRD"
m.svc.mon.ReportDeliver(channelID, ok)
m.deps.ReportDeliver(channelID, ok)
if ok {
m.observe(channelID, LogKindDeliver, 0, r.MsgID, r.Stat, 0)
} else {
@@ -1,6 +1,6 @@
// link_day40_test.go Day 40(A-3.5):真网断线重连演练——网关进程消失→心跳断链→
// 同端口复活→指数退避重连→提交恢复。断言全程远小于 30s 重连上限,并留痕 channel_log。
package channel
package pool_test
import (
"context"
@@ -10,10 +10,12 @@ import (
"time"
"go-sms/internal/model/entity"
"go-sms/internal/service/channel"
"go-sms/internal/service/channel/pool"
)
// waitLinkFor 限期等待健康连接数(演练用:期限可调)。
func waitLinkFor(t *testing.T, s *Service, id int64, want int, d time.Duration) bool {
func waitLinkFor(t *testing.T, s *channel.Service, id int64, want int, d time.Duration) bool {
t.Helper()
deadline := time.Now().Add(d)
for time.Now().Before(deadline) {
@@ -100,7 +102,7 @@ func (g *killableGW) restart(t *testing.T) {
// → ④同端口复活 → ⑤退避重连恢复健康(断言 <10s,验收线 30s) → ⑥提交恢复
// → ⑦channel_log 留痕 disconnect。
func TestLinkReconnectAfterGatewayRestart(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ctx := context.Background()
@@ -146,8 +148,8 @@ func TestLinkReconnectAfterGatewayRestart(t *testing.T) {
var disConns int64
by := time.Now().Add(2 * time.Second)
for time.Now().Before(by) {
s.logs.FlushNow()
s.db.Model(&entity.ChannelLog{}).Where("channel_id = ? AND kind = ?", ch.ID, LogKindDisconnect).Count(&disConns)
s.FlushChannelLogs()
s.DB().Model(&entity.ChannelLog{}).Where("channel_id = ? AND kind = ?", ch.ID, pool.LogKindDisconnect).Count(&disConns)
if disConns > 0 {
break
}
@@ -1,6 +1,6 @@
// link_split_test.go Day 39 验收:常驻链路提交中文 → GBK(0x0F);超长 → UDH 分片多笔提交。
// recordingMini 在迷你网关基础上记录收到的 Submit(PkTotal/PkNumber/TP_udhi/MsgFmt/Content)。
package channel
package pool_test
import (
"context"
@@ -103,7 +103,7 @@ func waitSubmits(t *testing.T, caps *[]submitCapture, n int) []submitCapture {
// TestSubmitViaLinkChinese 中文提交:Msg_Fmt=0x0F(15) + GBK 内容可还原。
func TestSubmitViaLinkChinese(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, caps := listenRecordingMini(t)
ctx := context.Background()
@@ -111,7 +111,7 @@ func TestSubmitViaLinkChinese(t *testing.T) {
if _, err := s.StartLink(ctx, ch.ID); err != nil {
t.Fatal(err)
}
if _, err := s.links.SubmitViaLink(ctx, ch.ID, "13800001111", "验证码9527,请勿泄露"); err != nil {
if _, err := s.SubmitViaLink(ctx, ch.ID, "13800001111", "验证码9527,请勿泄露"); err != nil {
t.Fatal(err)
}
got := waitSubmits(t, caps, 1)
@@ -126,7 +126,7 @@ func TestSubmitViaLinkChinese(t *testing.T) {
// TestSubmitViaLinkLongSMS 超长中文:拆 2 片,UDH 头/TP_udhi=1/序号连续,去头拼接还原。
func TestSubmitViaLinkLongSMS(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, caps := listenRecordingMini(t)
ctx := context.Background()
@@ -135,7 +135,7 @@ func TestSubmitViaLinkLongSMS(t *testing.T) {
t.Fatal(err)
}
content := strings.Repeat("长短信测试", 17) // 85 汉字=170B → 2 片
if _, err := s.links.SubmitViaLink(ctx, ch.ID, "13800001111", content); err != nil {
if _, err := s.SubmitViaLink(ctx, ch.ID, "13800001111", content); err != nil {
t.Fatal(err)
}
got := waitSubmits(t, caps, 2)
@@ -1,6 +1,6 @@
// link_test.go Day 31+:通道常驻链路管理测试——建链/守卫/提交/回执缓冲/引导/拆除。
// 链路经真实 TCP 连接 service_test.go 的迷你 CMPP 网关(listenMiniCMPP:密钥 pw,Submit 固定 MsgID=777)。
package channel
package pool_test
import (
"context"
@@ -10,13 +10,16 @@ import (
"testing"
"time"
"github.com/glebarez/sqlite"
"go-sms/internal/model/entity"
"go-sms/internal/protocol/cmpp"
"go-sms/internal/service/channel"
"gorm.io/gorm"
)
// TestLinkStartStop 验收:建链(池连通)→ 状态视图 → 幂等 → 拆除(重复幂等)。
func TestLinkStartStop(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, _ := listenMiniCMPP(t)
ctx := context.Background()
@@ -51,7 +54,7 @@ func TestLinkStartStop(t *testing.T) {
// TestLinkGuard 验收:协议/状态/版本/不存在守卫。
func TestLinkGuard(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ctx := context.Background()
@@ -75,7 +78,7 @@ func TestLinkGuard(t *testing.T) {
ln30, _ := netListen()
t.Cleanup(func() { _ = ln30.Close() })
ch30 := mustCreateLinkable(t, s, "lg-30", ln30)
if res := s.db.WithContext(ctx).Model(&entity.ChannelChannel{}).Where("id = ?", ch30.ID).Update("protocol_version", int8(30)); res.Error != nil {
if res := s.DB().WithContext(ctx).Model(&entity.ChannelChannel{}).Where("id = ?", ch30.ID).Update("protocol_version", int8(30)); res.Error != nil {
t.Fatal(res.Error)
}
if _, err := s.StartLink(ctx, ch30.ID); err == nil || !strings.Contains(err.Error(), "CMPP 3.0") {
@@ -85,7 +88,7 @@ func TestLinkGuard(t *testing.T) {
// TestSubmitViaLink 验收:经常驻链路提交返回上游 MsgID(迷你网关固定 777)。
func TestSubmitViaLink(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, _ := listenMiniCMPP(t)
ctx := context.Background()
@@ -97,7 +100,7 @@ func TestSubmitViaLink(t *testing.T) {
st := s.LinkStatus(ch.ID)
t.Fatalf("建链失败: status=%+v", st)
}
msgIDs, err := s.links.SubmitViaLink(ctx, ch.ID, "13800001111", "hello")
msgIDs, err := s.SubmitViaLink(ctx, ch.ID, "13800001111", "hello")
if err != nil {
t.Fatal(err)
}
@@ -109,8 +112,8 @@ func TestSubmitViaLink(t *testing.T) {
// TestLinkReceiptsPersist Day 56:持久化回执查询——seg(状态报告)与
// message_uplink(上行)按时间倒序归并;channel 过滤与 limit 截断。
func TestLinkReceiptsPersist(t *testing.T) {
s := newSvc35(t)
if err := s.db.AutoMigrate(&entity.MessageReportSeg{}, &entity.MessageUplink{}); err != nil {
s := newSvc(t)
if err := s.DB().AutoMigrate(&entity.MessageReportSeg{}, &entity.MessageUplink{}); err != nil {
t.Fatal(err)
}
base := time.Now().Add(-time.Hour)
@@ -122,7 +125,7 @@ func TestLinkReceiptsPersist(t *testing.T) {
{DetailID: 3, ChannelID: 8, MsgID: "a3", Mobile: "13700003333", PkTotal: 1, ReportAt: ptrTime(mk(5))},
}
for i := range segs {
if err := s.db.Create(&segs[i]).Error; err != nil {
if err := s.DB().Create(&segs[i]).Error; err != nil {
t.Fatal(err)
}
}
@@ -131,7 +134,7 @@ func TestLinkReceiptsPersist(t *testing.T) {
{DestCode: "10086", SrcMobile: "13611113333", Content: "hi", AccountID: 1, ChannelID: 9, RecvAt: mk(15)},
}
for i := range mos {
if err := s.db.Create(&mos[i]).Error; err != nil {
if err := s.DB().Create(&mos[i]).Error; err != nil {
t.Fatal(err)
}
}
@@ -166,15 +169,15 @@ func ptrTime(t time.Time) *time.Time { return &t }
// TestDeliverReportSink Day 56:状态报告注入 ReportSink(goroutine 派发,
// 读循环零阻塞红线);上行不派发;未注入维持旧行为(nil 安全)。
func TestDeliverReportSink(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
ch1 := mustCreateCh(t, s, "rs-1")
got := make(chan []string, 4)
s.links.SetReportSink(sinkFunc(func(channelID int64, msgID, stat, dest, doneTime string) {
s.SetReportSink(sinkFunc(func(channelID int64, msgID, stat, dest, doneTime string) {
got <- []string{msgID, stat, dest, doneTime}
}))
defer s.links.SetReportSink(nil)
defer s.SetReportSink(nil)
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 9, DestID: "10086", MsgFmt: cmpp.MsgFmtASCII,
IsReport: true,
Report: &cmpp.ReportInfo{MsgID: 9, Stat: "DELIVRD",
@@ -189,7 +192,7 @@ func TestDeliverReportSink(t *testing.T) {
}
// 上行不派发。
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 10, DestID: "10086", MsgFmt: cmpp.MsgFmtASCII,
SrcTerminal: "13700008888", Content: []byte("MO")})
select {
@@ -208,21 +211,21 @@ func (f sinkFunc) IngestReport(_ context.Context, channelID int64, msgID, stat,
// TestDeliverReceipts 验收:回执/上行注入环形缓冲,查询倒序 + 按通道过滤。
func TestDeliverReceipts(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
ch1 := mustCreateCh(t, s, "rc-1") // http 通道亦可(handleDeliver 只消费 id)
ch2 := mustCreateCh(t, s, "rc-2")
// 状态报告
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 1, DestID: "10086", MsgFmt: cmpp.MsgFmtASCII, SrcTerminal: "13800001111",
IsReport: true,
Report: &cmpp.ReportInfo{MsgID: 1, Stat: "DELIVRD", SubmitTime: "0904113001",
DoneTime: "0904113005", DestTerminalID: "13800001111", SMSCSequence: 7}})
// 上行(通道2)
s.links.handleDeliver(ch2.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch2.ID, &cmpp.Deliver{
MsgID: 2, DestID: "10086", MsgFmt: cmpp.MsgFmtASCII, SrcTerminal: "13900002222",
Content: []byte("TD")})
// 上行(通道1)
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 3, DestID: "10086", MsgFmt: cmpp.MsgFmtASCII, SrcTerminal: "13700003333",
Content: []byte("hi")})
@@ -250,17 +253,17 @@ func TestDeliverReceipts(t *testing.T) {
// TestDeliverMODecode 上行按 Msg_Fmt 解码(Day52 编码复盘补齐):GBK(0x0F)/UCS2(0x08)
// 注入 → 环形缓冲还原 UTF-8 中文;此前 string(d.Content) 原样直灌致真实上游中文上行乱码。
func TestDeliverMODecode(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
ch := mustCreateCh(t, s, "mo-dec")
// GBK 上行:复用 EncodeContent 编码「退订」
gbk, fmtGbk, err := cmpp.EncodeContent("退订")
if err != nil {
t.Fatal(err)
}
s.links.handleDeliver(ch.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch.ID, &cmpp.Deliver{
MsgID: 1, DestID: "10086", MsgFmt: fmtGbk, SrcTerminal: "13800001111", Content: gbk})
// UCS2 上行:「停」U+505C
s.links.handleDeliver(ch.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch.ID, &cmpp.Deliver{
MsgID: 2, DestID: "10086", MsgFmt: cmpp.MsgFmtUCS2, SrcTerminal: "13900002222",
Content: []byte{0x50, 0x5C}})
all := s.LinkReceipts(0, 10)
@@ -277,10 +280,10 @@ func TestDeliverMODecode(t *testing.T) {
// TestReceiptsCap 验收:环形缓冲上限(最近 100 条)。
func TestReceiptsCap(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
ch := mustCreateCh(t, s, "cap")
for i := 0; i < 120; i++ {
s.links.handleDeliver(ch.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch.ID, &cmpp.Deliver{
MsgID: uint64(i), DestID: "10086", MsgFmt: cmpp.MsgFmtASCII,
SrcTerminal: "13800001111", Content: fmt.Appendf(nil, "c%d", i)})
}
@@ -295,7 +298,7 @@ func TestReceiptsCap(t *testing.T) {
// TestBootstrapLinks 验收:启动引导仅对启用中 cmpp 建链(禁用/他协议跳过);Shutdown 全拆。
func TestBootstrapLinks(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, _ := listenMiniCMPP(t)
ctx := context.Background()
@@ -331,7 +334,7 @@ func TestBootstrapLinks(t *testing.T) {
// TestRestartLink 验收:参数变更重建(Stop+Start)后链路可用。
func TestRestartLink(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
t.Cleanup(func() { s.ShutdownLinks() })
ln, _ := listenMiniCMPP(t)
ctx := context.Background()
@@ -342,7 +345,7 @@ func TestRestartLink(t *testing.T) {
if !waitLink(t, s, ch.ID, 1) {
t.Fatal("初始建链失败")
}
st, err := s.links.RestartLink(ctx, ch.ID)
st, err := s.RestartLink(ctx, ch.ID)
if err != nil {
t.Fatal(err)
}
@@ -352,16 +355,16 @@ func TestRestartLink(t *testing.T) {
if !waitLink(t, s, ch.ID, 1) {
t.Fatalf("restart 后链路未就绪: %+v", s.LinkStatus(ch.ID))
}
msgIDs, err := s.links.SubmitViaLink(ctx, ch.ID, "13800001111", "again")
msgIDs, err := s.SubmitViaLink(ctx, ch.ID, "13800001111", "again")
if err != nil || len(msgIDs) != 1 || msgIDs[0] != "777" {
t.Fatalf("restart 后提交: msg=%v err=%v", msgIDs, err)
}
}
// mustCreateLinkable 建一条可建链的 cmpp 通道(密码与迷你网关密钥 pw 校准)。
func mustCreateLinkable(t *testing.T, s *Service, code string, ln net.Listener) *entity.ChannelChannel {
func mustCreateLinkable(t *testing.T, s *channel.Service, code string, ln net.Listener) *entity.ChannelChannel {
t.Helper()
ch, err := s.Create(context.Background(), &CreateReq{
ch, err := s.Create(context.Background(), &channel.CreateReq{
Name: code, Code: code, Protocol: "cmpp",
Host: "127.0.0.1", Port: portOf(ln), Username: "901234", Password: "pw",
ConnCount: 1, HeartbeatInterval: 1})
@@ -372,7 +375,7 @@ func mustCreateLinkable(t *testing.T, s *Service, code string, ln net.Listener)
}
// waitLink 轮询等待链路健康连接达到期望值(t 预留测试上下文)。
func waitLink(_ *testing.T, s *Service, id int64, want int) bool {
func waitLink(_ *testing.T, s *channel.Service, id int64, want int) bool {
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if st := s.LinkStatus(id); st.Running && st.Healthy >= want {
@@ -400,17 +403,17 @@ func (u *uplinkCapture) Ingest(_ context.Context, channelID int64, destCode, src
// TestHandleDeliverUplinkSink Day 49 验收:Deliver MO 派发上行出口
// (码号/手机号/内容透传);状态报告不派发;未注入(nil)不派发维持旧行为。
func TestHandleDeliverUplinkSink(t *testing.T) {
s := newSvc35(t)
s := newSvc(t)
ch1 := mustCreateCh(t, s, "up-1")
// 未注入:无 panic 无派发。
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 1, DestID: "10690001", SrcTerminal: "13800001111", Content: []byte("TD")})
cap := newUplinkCapture()
s.SetUplinkSink(cap)
// 上行 MO:派发(异步 goroutine)。
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 2, DestID: "10690001", SrcTerminal: "13800001111", Content: []byte("TD")})
select {
case got := <-cap.ch:
@@ -421,11 +424,30 @@ func TestHandleDeliverUplinkSink(t *testing.T) {
t.Fatal("MO 未派发上行出口")
}
// 状态报告:不派发。
s.links.handleDeliver(ch1.ID, &cmpp.Deliver{
s.Pool().HandleDeliver(ch1.ID, &cmpp.Deliver{
MsgID: 3, IsReport: true, Report: &cmpp.ReportInfo{MsgID: 3, Stat: "DELIVRD"}})
select {
case got := <-cap.ch:
t.Fatalf("状态报告不应派发上行: %v", got)
case <-time.After(150 * time.Millisecond):
}
}
}
// newSvc pool 链路测试构造(S1-B P2 自 channel/service_test.go newSvc35 同体复制;
// 外部测试包断环后本地化,口径与原实现一致)。
func newSvc(t *testing.T) *channel.Service {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if sqlDB, e := db.DB(); e == nil {
sqlDB.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.ChannelChannel{}, &entity.ChannelLog{}, &entity.SystemAlertRule{}); err != nil {
t.Fatal(err)
}
s := channel.NewService(db)
t.Cleanup(s.Close) // Day 40:冲刷通道日志 writer,防 goroutine/连接泄漏
return s
}
@@ -0,0 +1,77 @@
// testhelpers_test.go S1-B P2:mini-CMPP 模拟器链自 channel/service_test.go(177-229 行)
// 原样复制——pool_test 外部包断环后测试基建本地化,语义零改动。
package pool_test
import (
"context"
"net"
"testing"
"go-sms/internal/model/entity"
"go-sms/internal/protocol/cmpp"
"go-sms/internal/service/channel"
)
func netListen() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }
func portOf(ln net.Listener) int { return ln.Addr().(*net.TCPAddr).Port }
// listenMiniCMPP 起一个仅处理 connect/submit/active 的迷你网关(复用 cmpp 编解码)。
// serveMiniConn 单连接处理循环(connect/submit/active_test 三响应)。
func serveMiniConn(conn net.Conn) {
defer func() { _ = conn.Close() }()
for {
h, body, err := cmpp.ReadPacket(conn)
if err != nil {
return
}
switch h.CommandID {
case cmpp.CmdConnect:
addr, auth, ts, _ := cmpp.ParseConnect(body)
st := byte(0)
if !cmpp.VerifyAuth(addr, "pw", ts, auth) {
st = 1
}
resp := &cmpp.ConnectResp{Status: st, Secret: "pw", AuthenticatorClient: auth}
_ = cmpp.WritePacket(conn, &cmpp.Header{CommandID: cmpp.CmdConnectResp, SequenceID: h.SequenceID}, resp.Marshal())
case cmpp.CmdSubmit:
_ = cmpp.WritePacket(conn, &cmpp.Header{CommandID: cmpp.CmdSubmitResp, SequenceID: h.SequenceID},
(&cmpp.SubmitResp{MsgID: 777, Result: 0}).Marshal())
case cmpp.CmdActiveTest:
_ = cmpp.WritePacket(conn, &cmpp.Header{CommandID: cmpp.CmdActiveTestResp, SequenceID: h.SequenceID}, cmpp.ActiveTestResp(0))
}
}
}
// serveMiniCMPP 在给定 listener 上跑迷你 CMPP 网关 accept 循环
// (Day 40 抽出:断线重连演练需在「同端口」重启网关复用此循环)。
func serveMiniCMPP(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go serveMiniConn(conn)
}
}
func listenMiniCMPP(t *testing.T) (net.Listener, error) {
t.Helper()
ln, err := netListen()
if err != nil {
return nil, err
}
go serveMiniCMPP(ln)
t.Cleanup(func() { _ = ln.Close() })
return ln, nil
}
// mustCreateCh 快速建通道(自 channel/service_test.go 同体复制;类型改 channel.* 前缀)。
func mustCreateCh(t *testing.T, s *channel.Service, code string) *entity.ChannelChannel {
t.Helper()
ch, err := s.Create(context.Background(), &channel.CreateReq{
Name: code, Code: code, Protocol: "http", Host: "http://upstream", Weight: 1})
if err != nil {
t.Fatal(err)
}
return ch
}
+1 -1
View File
@@ -79,4 +79,4 @@ func (s *Service) CurrentPrice(ctx context.Context, chID int64, t time.Time) (fl
return 0, err
}
return ch.Price, nil // 回退实体默认价
}
}
+1 -1
View File
@@ -88,4 +88,4 @@ func newSvcPrice(t *testing.T) *Service {
t.Fatal(err)
}
return s
}
}
+85 -41
View File
@@ -19,6 +19,7 @@ import (
"go-sms/internal/protocol/sgip"
"go-sms/internal/protocol/smpp"
"go-sms/internal/repository/mysql"
"go-sms/internal/service/channel/pool"
)
// 支持的接入协议。
@@ -40,7 +41,7 @@ type Service struct {
mu sync.Mutex
dayCnt map[int64]*dayCounter // 通道当日计数(单实例;生产切 Redis)
links *linkManager // 常驻链路(Day 31+:cmpp.Pool 业务挂载)
links *pool.Manager // 常驻链路(Day 31+:cmpp.Pool 业务挂载;S1-B P2 拆 pool 子包)
logs *ChannelLogger // 通道日志(Day 40 · A-3.14;db nil 时为 nil=no-op)
mon *Monitor // 实时统计(Day 40 · A-3.13;WS 2s 推送源)
alerts *ChannelAlertService // 通道告警(Day 40 · A-3.12)
@@ -58,7 +59,7 @@ func NewService(db *gorm.DB) *Service {
if db != nil {
s.logs = NewChannelLogger(db)
}
s.links = newLinkManager(s)
s.links = pool.NewManager(s)
s.alerts = NewChannelAlertService(db, s.mon, s.links.Status, nil)
s.alerts.SetLogHook(func(channelID int64, kind string, level int8, msgID, detail string, latencyMs int) {
s.logs.Log(channelID, kind, level, msgID, detail, latencyMs)
@@ -66,25 +67,64 @@ func NewService(db *gorm.DB) *Service {
return s
}
// UplinkSink 上行处理出口(Day 49:Deliver MO→码号分配+落库+sms-up 投递;
// 由 service/uplink.Service 实现,channel 只依赖接口避免包循环)。
type UplinkSink interface {
Ingest(ctx context.Context, channelID int64, destCode, srcMobile, content string) (int64, error)
}
// SetUplinkSink 注入上行处理器(nil=维持 Day48 前仅日志/环形缓冲行为)。
func (s *Service) SetUplinkSink(u UplinkSink) { s.links.SetUplinkSink(u) }
// SetUplinkSink 注入上行处理器(nil=维持 Day48 前仅日志/环形缓冲行为;接口定义在 pool 包)。
func (s *Service) SetUplinkSink(u pool.UplinkSink) { s.links.SetUplinkSink(u) }
// SetReportSink 注入回执出口(Day 56;nil=维持 Day55 前仅日志/环形缓冲行为)。
func (s *Service) SetReportSink(r ReportSink) { s.links.SetReportSink(r) }
func (s *Service) SetReportSink(r pool.ReportSink) { s.links.SetReportSink(r) }
// ---- pool.Deps 适配(S1-B P2:pool 子包断环;口径与拆分前 linkManager 经 svc.* 直调
// 一一对应;Get 直接复用既有方法,此处补齐其余五个适配) ----
// Pool 常驻链路管理器访问器(S1-B P2;装配层/链路测试注入回执用)。
func (s *Service) Pool() *pool.Manager { return s.links }
// RestartLink 重建链路(S1-B P2 补齐包装:与 StartLink/StopLink 家族对齐)。
func (s *Service) RestartLink(ctx context.Context, id int64) (*pool.LinkStatus, error) {
return s.links.RestartLink(ctx, id)
}
// ListCMPPActive 启用中的 CMPP 通道清单(pool.Deps;原 Bootstrap 内联查询)。
func (s *Service) ListCMPPActive(ctx context.Context) ([]entity.ChannelChannel, error) {
list, _, err := s.List(ctx, &ListQuery{Page: 1, PageSize: 100, Protocol: "cmpp", Status: 1})
return list, err
}
// LogChannel 通道日志(pool.Deps;原 svc.logs.Log)。
func (s *Service) LogChannel(channelID int64, kind string, level int8, msgID, detail string, latencyMs int) {
s.logs.Log(channelID, kind, level, msgID, detail, latencyMs)
}
// EvaluateChannel 告警评估(pool.Deps;原 svc.alerts.EvaluateChannel)。
func (s *Service) EvaluateChannel(ctx context.Context, channelID int64) {
s.alerts.EvaluateChannel(ctx, channelID)
}
// ReportSubmit 提交计数(pool.Deps;原 svc.mon.ReportSubmit)。
func (s *Service) ReportSubmit(channelID int64, ok bool, latencyMs int) {
s.mon.ReportSubmit(channelID, ok, latencyMs)
}
// ReportDeliver 回执计数(pool.Deps;原 svc.mon.ReportDeliver)。
func (s *Service) ReportDeliver(channelID int64, ok bool) { s.mon.ReportDeliver(channelID, ok) }
// DB 只读访问器(S1-B P2:pool_test 外部包断环后,链路测试直查库断言用)。
func (s *Service) DB() *gorm.DB { return s.db }
// FlushChannelLogs 立即冲刷通道日志缓冲(nil 安全;pool_test 演练断言用)。
func (s *Service) FlushChannelLogs() {
if s.logs != nil {
s.logs.FlushNow()
}
}
// LinkReceiptsPersist 持久化回执查询(Day 56):状态报告=message_report_seg
// (report_at 非空行),上行=message_uplink;按时间倒序归并截取 n 条。
// 重启后回执可查(环形缓冲 100 条/进程内,本方法为持久层真源);
// 查询失败返回 error(调用方降级内存环形)。
func (s *Service) LinkReceiptsPersist(ctx context.Context, channelID int64, n int) ([]Receipt, error) {
func (s *Service) LinkReceiptsPersist(ctx context.Context, channelID int64, n int) ([]pool.Receipt, error) {
if s.db == nil || n <= 0 {
return []Receipt{}, nil
return []pool.Receipt{}, nil
}
var segs []entity.MessageReportSeg
if err := s.db.WithContext(ctx).
@@ -98,16 +138,16 @@ func (s *Service) LinkReceiptsPersist(ctx context.Context, channelID int64, n in
Order("recv_at DESC").Limit(n).Find(&mos).Error; err != nil {
return nil, err
}
out := make([]Receipt, 0, len(segs)+len(mos))
out := make([]pool.Receipt, 0, len(segs)+len(mos))
for _, sg := range segs {
at := sg.ReportAt.Format("2006-01-02 15:04:05")
out = append(out, Receipt{
out = append(out, pool.Receipt{
ChannelID: channelID, IsReport: true, MsgID: sg.MsgID,
Stat: sg.RawCode, Dest: sg.Mobile, At: at,
})
}
for _, mo := range mos {
out = append(out, Receipt{
out = append(out, pool.Receipt{
ChannelID: channelID, IsReport: false,
Src: mo.SrcMobile, Content: mo.Content,
At: mo.RecvAt.Format("2006-01-02 15:04:05"),
@@ -144,8 +184,8 @@ func (s *Service) MonitorSnapshot(ctx context.Context) ([]ChannelSnapshot, error
submit, fail, deliver, _, latP50 := s.mon.Stats(ch.ID)
snap := ChannelSnapshot{
ChannelID: ch.ID, Name: ch.Name, Protocol: ch.Protocol, Status: ch.Status,
SubmitPs: float64(submit) / float64(monWindowSec),
DeliverPs: float64(deliver) / float64(monWindowSec),
SubmitPs: float64(submit) / float64(monWindowSec),
DeliverPs: float64(deliver) / float64(monWindowSec),
LatencyP50: latP50, UpdatedAt: now,
}
if submit > 0 {
@@ -162,7 +202,7 @@ func (s *Service) MonitorSnapshot(ctx context.Context) ([]ChannelSnapshot, error
// ListLogs 通道日志查询(A-3.14:连接/提交/回执完整记录;倒序分页)。
func (s *Service) ListLogs(ctx context.Context, channelID int64, kind string, page, pageSize int) ([]entity.ChannelLog, int64, error) {
if s.db == nil {
return nil, 0, ErrLinkUnavailable
return nil, 0, pool.ErrLinkUnavailable
}
q := s.db.WithContext(ctx).Model(&entity.ChannelLog{}).Where("channel_id = ?", channelID)
if kind != "" {
@@ -188,16 +228,20 @@ func (s *Service) ListLogs(ctx context.Context, channelID int64, kind string, pa
// ---- 常驻链路(Day 31+):导出包装 ----
// StartLink 为通道建立常驻长连接(幂等)。
func (s *Service) StartLink(ctx context.Context, id int64) (*LinkStatus, error) { return s.links.StartLink(ctx, id) }
func (s *Service) StartLink(ctx context.Context, id int64) (*pool.LinkStatus, error) {
return s.links.StartLink(ctx, id)
}
// StopLink 拆除链路(幂等)。
func (s *Service) StopLink(id int64) { s.links.StopLink(id) }
// LinkStatus 链路状态。
func (s *Service) LinkStatus(id int64) *LinkStatus { return s.links.Status(id) }
func (s *Service) LinkStatus(id int64) *pool.LinkStatus { return s.links.Status(id) }
// LinkReceipts 最近 n 条回执(倒序;channelID 过滤)。
func (s *Service) LinkReceipts(channelID int64, n int) []Receipt { return s.links.Receipts(channelID, n) }
func (s *Service) LinkReceipts(channelID int64, n int) []pool.Receipt {
return s.links.Receipts(channelID, n)
}
// BootstrapLinks 启动时为启用中的 cmpp 通道建链。
func (s *Service) BootstrapLinks(ctx context.Context) { go s.links.Bootstrap(ctx) }
@@ -207,27 +251,27 @@ func (s *Service) ShutdownLinks() { s.links.Shutdown() }
// CreateReq 创建通道请求。
type CreateReq struct {
Name string `json:"name" binding:"required"`
Code string `json:"code" binding:"required"`
Protocol string `json:"protocol" binding:"required"`
Host string `json:"host" binding:"required"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
Speed int `json:"speed"`
ConnCount int `json:"conn_count"` // Day 31 联调补:此前缺失导致提交值被忽略(落默认 1)
UpstreamID int64 `json:"upstream_id"`
Priority int `json:"priority"`
Weight int `json:"weight"`
IsDefault int8 `json:"is_default"`
Remark string `json:"remark"`
Name string `json:"name" binding:"required"`
Code string `json:"code" binding:"required"`
Protocol string `json:"protocol" binding:"required"`
Host string `json:"host" binding:"required"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
Speed int `json:"speed"`
ConnCount int `json:"conn_count"` // Day 31 联调补:此前缺失导致提交值被忽略(落默认 1)
UpstreamID int64 `json:"upstream_id"`
Priority int `json:"priority"`
Weight int `json:"weight"`
IsDefault int8 `json:"is_default"`
Remark string `json:"remark"`
// 协议接入参数(Day 31)。
SpID string `json:"sp_id"` // 企业代码(cmpp/sgip;cmpp ≤6B)
ProtocolVersion int8 `json:"protocol_version"` // cmpp:20|30 sgip:12 smpp:34(缺省按协议填充)
HeartbeatInterval int `json:"heartbeat_interval"`
ReconnectMax int `json:"reconnect_max"`
ServiceID string `json:"service_id"`
SpID string `json:"sp_id"` // 企业代码(cmpp/sgip;cmpp ≤6B)
ProtocolVersion int8 `json:"protocol_version"` // cmpp:20|30 sgip:12 smpp:34(缺省按协议填充)
HeartbeatInterval int `json:"heartbeat_interval"`
ReconnectMax int `json:"reconnect_max"`
ServiceID string `json:"service_id"`
// 运营属性(Day 31)。
Carrier string `json:"carrier"` // 逗号分隔 cmcc,cucc,ctcc