551 lines
19 KiB
Go
551 lines
19 KiB
Go
// link.go Day 31+:通道常驻链路管理(Day 32 cmpp.Pool 的业务挂载)。
|
||
// 每通道一池常驻长连接(登录+心跳+断线指数退避重连);提交走池化连接;
|
||
// Deliver 回执结构化日志+环形缓冲(入库留待阶段 5 Day 51 message_report)。
|
||
// 为阶段 4 发送主路径(路由引擎经链路提交)与阶段 5 回执落地奠基。
|
||
//
|
||
// 2026-11-13 S1-B P2:自 service/channel 拆为 pool 子包(搬运清单 B「拆 pool/limiter」;
|
||
// 域内限速实现在 send/pacer,本包=连接池域)。channel.Service 经 Deps 适配断环,
|
||
// 行为零改动(仅移动+重命名 linkManager→Manager)。
|
||
package pool
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"sync"
|
||
"sync/atomic"
|
||
"time"
|
||
|
||
"go-sms/internal/model/entity"
|
||
"go-sms/internal/pkg/logger"
|
||
"go-sms/internal/protocol/cmpp"
|
||
|
||
"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
|
||
|
||
// 链路域错误。
|
||
var (
|
||
ErrLinkUnavailable = errors.New("通道链路不可用")
|
||
ErrChannelDisabled = errors.New("通道已停用,无法建立链路")
|
||
errCMPPOnly = errors.New("常驻链路当前仅支持 cmpp 通道(sgip/smpp 后续任务)")
|
||
errCMPP30 = errors.New("CMPP 3.0 协议栈未实现(当前仅支持 2.0)")
|
||
)
|
||
|
||
// Receipt 一条网关回执/上行(内存视图)。
|
||
type Receipt struct {
|
||
ChannelID int64 `json:"channel_id"`
|
||
MsgID string `json:"msg_id"`
|
||
IsReport bool `json:"is_report"` // true=状态报告 false=上行短信
|
||
Stat string `json:"stat,omitempty"`
|
||
SubmitTime string `json:"submit_time,omitempty"`
|
||
DoneTime string `json:"done_time,omitempty"`
|
||
Dest string `json:"dest,omitempty"`
|
||
Src string `json:"src,omitempty"` // 上行来源号码
|
||
Content string `json:"content,omitempty"`
|
||
At string `json:"at"`
|
||
}
|
||
|
||
// LinkStatus 链路状态视图。
|
||
type LinkStatus struct {
|
||
ChannelID int64 `json:"channel_id"`
|
||
Running bool `json:"running"`
|
||
Total int `json:"total"` // 池内连接总数
|
||
Healthy int `json:"healthy"` // 当前已连接数
|
||
StartedAt string `json:"started_at,omitempty"`
|
||
}
|
||
|
||
// link 一条通道的常驻链路(池 + 根 context 取消)。
|
||
type link struct {
|
||
pool *cmpp.Pool
|
||
cancel context.CancelFunc
|
||
startedAt time.Time
|
||
}
|
||
|
||
// Manager 链路管理器(Service 内嵌单例;S1-B P2 由 linkManager 更名)。
|
||
type Manager struct {
|
||
deps Deps
|
||
mu sync.RWMutex
|
||
links map[int64]*link
|
||
rmu sync.Mutex
|
||
reports []Receipt // 环形缓冲(全通道最近 receiptCap 条)
|
||
uplink UplinkSink // Day 49:上行出口(码号分配+落库+sms-up;nil=仅日志)
|
||
report ReportSink // Day 56:回执出口(sms-report 投递;nil=仅日志/环形)
|
||
}
|
||
|
||
const receiptCap = 100
|
||
|
||
// linkReady 链路就绪等待上限(首次建链/断线重连窗口)。
|
||
const linkReady = 5 * time.Second
|
||
|
||
// 日志 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 *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 {
|
||
IngestReport(ctx context.Context, channelID int64, msgID, stat, dest, doneTime string)
|
||
}
|
||
|
||
// SetReportSink 注入回执出口(Day 56;装配层调用;nil=维持 Day55 前行为)。
|
||
func (m *Manager) SetReportSink(r ReportSink) {
|
||
m.mu.Lock()
|
||
m.report = r
|
||
m.mu.Unlock()
|
||
}
|
||
|
||
// BatchAck 一次批量提交的「包×片」级回执(Day 56):CMPP 合包下一个
|
||
// Submit 包共享一个 msg_id;长短信每片独立成包独立 msg_id——段级配对
|
||
// 按 (msg_id, mobile) 精确定位,PkNumber/PkTotal 描述该片在整信中的位置。
|
||
type BatchAck struct {
|
||
MsgID string
|
||
Mobiles []string // 该包内号码(与提交顺序一致)
|
||
PkNumber int // 片序(1 起)
|
||
PkTotal int // 该内容总片数(单条=1,长短信 1~9)
|
||
}
|
||
|
||
// observe 便捷埋点:通道日志 + 监控统计(失败时)。
|
||
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 *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.deps.EvaluateChannel(context.Background(), channelID)
|
||
}
|
||
|
||
// Bootstrap 启动时为全部「启用中的 cmpp 通道」建链(异步;单通道失败仅告警)。
|
||
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
|
||
}
|
||
for _, ch := range list {
|
||
if _, err := m.StartLink(ctx, ch.ID); err != nil {
|
||
logger.L().Warn("link_bootstrap_channel_failed", zap.Int64("channel_id", ch.ID), zap.Error(err))
|
||
} else {
|
||
logger.L().Info("link_bootstrap_channel_started", zap.Int64("channel_id", ch.ID), zap.String("name", ch.Name))
|
||
}
|
||
}
|
||
}
|
||
|
||
// poolConfig 通道实体 → CMPP 客户端配置(sp_id 优先,回退 username 兼容)。
|
||
func poolConfig(ch *entity.ChannelChannel) cmpp.Config {
|
||
sourceAddr := ch.SpID
|
||
if sourceAddr == "" {
|
||
sourceAddr = ch.Username
|
||
}
|
||
return cmpp.Config{
|
||
Addr: fmt.Sprintf("%s:%d", ch.Host, ch.Port),
|
||
SourceAddr: sourceAddr,
|
||
Secret: ch.Password,
|
||
HeartbeatInterval: time.Duration(ch.HeartbeatInterval) * time.Second,
|
||
ReconnectMax: time.Duration(ch.ReconnectMax) * time.Second,
|
||
LoginTimeout: 10 * time.Second,
|
||
}
|
||
}
|
||
|
||
// Shutdown 全部拆除(进程退出)。
|
||
func (m *Manager) Shutdown() {
|
||
m.mu.Lock()
|
||
ids := make([]int64, 0, len(m.links))
|
||
for id := range m.links {
|
||
ids = append(ids, id)
|
||
}
|
||
m.mu.Unlock()
|
||
for _, id := range ids {
|
||
m.StopLink(id)
|
||
}
|
||
}
|
||
|
||
// StartLink 为通道建立常驻链路(已存在则幂等返回)。
|
||
func (m *Manager) StartLink(ctx context.Context, id int64) (*LinkStatus, error) {
|
||
m.mu.Lock()
|
||
if _, ok := m.links[id]; ok {
|
||
m.mu.Unlock()
|
||
return m.Status(id), nil
|
||
}
|
||
m.mu.Unlock()
|
||
|
||
ch, err := m.deps.Get(context.Background(), id)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if ch.Protocol != "cmpp" {
|
||
return nil, errCMPPOnly
|
||
}
|
||
if ch.Status != 1 {
|
||
return nil, ErrChannelDisabled
|
||
}
|
||
if ch.ProtocolVersion == 30 {
|
||
return nil, errCMPP30
|
||
}
|
||
|
||
size := ch.ConnCount
|
||
if size < 1 {
|
||
size = 1
|
||
}
|
||
pool := cmpp.NewPool(poolConfig(ch), size)
|
||
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)
|
||
|
||
m.mu.Lock()
|
||
// 并发双检:后到者拆除重复池。
|
||
if _, ok := m.links[id]; ok {
|
||
m.mu.Unlock()
|
||
cancel()
|
||
pool.Stop()
|
||
return m.Status(id), nil
|
||
}
|
||
m.links[id] = &link{pool: pool, cancel: cancel, startedAt: time.Now()}
|
||
m.mu.Unlock()
|
||
m.observe(id, LogKindConnect, 0, "", fmt.Sprintf("pool started(size=%d host=%s:%d)", size, ch.Host, ch.Port), 0)
|
||
logger.L().Info("link_started", zap.Int64("channel_id", id), zap.String("name", ch.Name), zap.Int("size", size))
|
||
return m.Status(id), nil
|
||
}
|
||
|
||
// StopLink 拆除链路(不存在则幂等)。
|
||
func (m *Manager) StopLink(id int64) {
|
||
m.mu.Lock()
|
||
l, ok := m.links[id]
|
||
if ok {
|
||
delete(m.links, id)
|
||
}
|
||
m.mu.Unlock()
|
||
if ok {
|
||
l.cancel()
|
||
l.pool.Stop()
|
||
m.observe(id, LogKindStop, 0, "", "link stopped", 0)
|
||
logger.L().Info("link_stopped", zap.Int64("channel_id", id))
|
||
}
|
||
}
|
||
|
||
// RestartLink 参数变更后重建。
|
||
func (m *Manager) RestartLink(ctx context.Context, id int64) (*LinkStatus, error) {
|
||
m.StopLink(id)
|
||
return m.StartLink(ctx, id)
|
||
}
|
||
|
||
// Status 查询链路状态(未建链返回 Running=false)。
|
||
func (m *Manager) Status(id int64) *LinkStatus {
|
||
m.mu.RLock()
|
||
l, ok := m.links[id]
|
||
m.mu.RUnlock()
|
||
if !ok {
|
||
return &LinkStatus{ChannelID: id}
|
||
}
|
||
return &LinkStatus{
|
||
ChannelID: id, Running: true,
|
||
Total: l.pool.Size(), Healthy: l.pool.Healthy(),
|
||
StartedAt: l.startedAt.Format("2006-01-02 15:04:05"),
|
||
}
|
||
}
|
||
|
||
// SubmitViaLink 经常驻链路提交(未建链自动建立);返回上游 MsgID。
|
||
// SubmitViaLink 单号提交;返回各段 msg_id(顺序=PkNumber 1..N,单条=1 个;
|
||
// Day 56 段级回执配对:每片独立 msg_id,提交侧据此逐段登记 message_report_seg)。
|
||
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()
|
||
if !ok {
|
||
if _, err := m.StartLink(ctx, id); err != nil {
|
||
return nil, err
|
||
}
|
||
m.mu.RLock()
|
||
l, ok = m.links[id]
|
||
m.mu.RUnlock()
|
||
if !ok {
|
||
return nil, ErrLinkUnavailable
|
||
}
|
||
}
|
||
// 链路就绪窗口:池刚启动/断线重连期,有界等待至少一条健康连接(超时报不可用)。
|
||
ready := time.Now().Add(linkReady)
|
||
for l.pool.Healthy() == 0 && time.Now().Before(ready) {
|
||
time.Sleep(20 * time.Millisecond)
|
||
}
|
||
if l.pool.Healthy() == 0 {
|
||
return nil, ErrLinkUnavailable
|
||
}
|
||
ch, err := m.deps.Get(context.Background(), id)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
sourceAddr := ch.SpID
|
||
if sourceAddr == "" {
|
||
sourceAddr = ch.Username
|
||
}
|
||
srcID := ch.Code
|
||
if srcID == "" {
|
||
srcID = sourceAddr
|
||
}
|
||
svcID := ch.ServiceID
|
||
if svcID == "" {
|
||
svcID = "TEST"
|
||
}
|
||
// 内容编码+长短信分片(Day 39:ASCII 原样/中文 GBK;超 134B 拆 UDH 片)。
|
||
frags, err := cmpp.SplitContent(content)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(frags) > 1 {
|
||
logger.L().Info("submit_split_long_sms",
|
||
zap.Int64("channel_id", id), zap.Int("frags", len(frags)), zap.Int("bytes", len(content)))
|
||
}
|
||
msgIDs := make([]string, 0, len(frags))
|
||
var lastOK string
|
||
for _, f := range frags {
|
||
t0 := time.Now()
|
||
resp, err := l.pool.Submit(&cmpp.SubmitReq{
|
||
ServiceID: svcID, MsgFmt: f.MsgFmt, TPUdhi: f.TPUdhi,
|
||
PkTotal: f.PkTotal, PkNumber: f.PkNumber,
|
||
MsgSrc: sourceAddr, FeeType: "01", SrcID: srcID,
|
||
DestTerminalIDs: []string{mobile},
|
||
Content: f.Content, RegisteredDelivery: 1,
|
||
})
|
||
lat := int(time.Since(t0).Milliseconds())
|
||
if err != nil {
|
||
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.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.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]
|
||
}
|
||
return msgIDs, nil
|
||
}
|
||
|
||
// SubmitBatchViaLink Day47 合包批量提交:同内容多号码合入 CMPP Submit 包
|
||
// (规范单包 ≤100 号码,超量自动切包),一次批量调用替代 N 次单号调用——
|
||
// 提交调用次数 ÷100(合包聚合器出口;错误语义:任一包失败返回聚合错误,
|
||
// 调用方可回退逐号保送达)。
|
||
// Day 56:返回包级回执 acks(每包 msg_id+包内号码+总片数)——提交侧据此
|
||
// 逐段登记 message_report_seg,长短信每片独立成包独立 msg_id。
|
||
func (m *Manager) SubmitBatchViaLink(ctx context.Context, id int64,
|
||
mobiles []string, content string) ([]BatchAck, error) {
|
||
if len(mobiles) == 0 {
|
||
return nil, nil
|
||
}
|
||
m.mu.RLock()
|
||
l, ok := m.links[id]
|
||
m.mu.RUnlock()
|
||
if !ok {
|
||
if _, err := m.StartLink(ctx, id); err != nil {
|
||
return nil, err
|
||
}
|
||
m.mu.RLock()
|
||
l, ok = m.links[id]
|
||
m.mu.RUnlock()
|
||
if !ok {
|
||
return nil, ErrLinkUnavailable
|
||
}
|
||
}
|
||
ready := time.Now().Add(linkReady)
|
||
for l.pool.Healthy() == 0 && time.Now().Before(ready) {
|
||
time.Sleep(20 * time.Millisecond)
|
||
}
|
||
if l.pool.Healthy() == 0 {
|
||
return nil, ErrLinkUnavailable
|
||
}
|
||
ch, err := m.deps.Get(context.Background(), id)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
sourceAddr := ch.SpID
|
||
if sourceAddr == "" {
|
||
sourceAddr = ch.Username
|
||
}
|
||
srcID := ch.Code
|
||
if srcID == "" {
|
||
srcID = sourceAddr
|
||
}
|
||
svcID := ch.ServiceID
|
||
if svcID == "" {
|
||
svcID = "TEST"
|
||
}
|
||
frags, err := cmpp.SplitContent(content)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var acks []BatchAck
|
||
var firstErr error
|
||
for start := 0; start < len(mobiles); start += cmpp.MaxDestPerSubmit {
|
||
end := start + cmpp.MaxDestPerSubmit
|
||
if end > len(mobiles) {
|
||
end = len(mobiles)
|
||
}
|
||
dest := mobiles[start:end]
|
||
for pn, f := range frags {
|
||
t0 := time.Now()
|
||
resp, serr := l.pool.Submit(&cmpp.SubmitReq{
|
||
ServiceID: svcID, MsgFmt: f.MsgFmt, TPUdhi: f.TPUdhi,
|
||
PkTotal: f.PkTotal, PkNumber: f.PkNumber,
|
||
MsgSrc: sourceAddr, FeeType: "01", SrcID: srcID,
|
||
DestTerminalIDs: dest,
|
||
Content: f.Content, RegisteredDelivery: 1,
|
||
})
|
||
lat := int(time.Since(t0).Milliseconds())
|
||
if serr != nil {
|
||
m.deps.ReportSubmit(id, false, 0)
|
||
m.observe(id, LogKindSubmitFail, 2, "", fmt.Sprintf("batch: %v", serr), lat)
|
||
if firstErr == nil {
|
||
firstErr = serr
|
||
}
|
||
continue
|
||
}
|
||
if resp.Result != 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 {
|
||
firstErr = fmt.Errorf("上游拒绝: result=%d", resp.Result)
|
||
}
|
||
continue
|
||
}
|
||
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),
|
||
Mobiles: dest,
|
||
PkNumber: pn + 1,
|
||
PkTotal: len(frags),
|
||
})
|
||
}
|
||
}
|
||
return acks, firstErr
|
||
}
|
||
func (m *Manager) Receipts(channelID int64, n int) []Receipt {
|
||
m.rmu.Lock()
|
||
defer m.rmu.Unlock()
|
||
var out []Receipt
|
||
for i := len(m.reports) - 1; i >= 0 && len(out) < n; i-- {
|
||
if channelID == 0 || m.reports[i].ChannelID == channelID {
|
||
out = append(out, m.reports[i])
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// decodeMOContent 上行短消息内容按 Msg_Fmt 解码为 UTF-8;失败降级原样并告警(不丢消息)。
|
||
func decodeMOContent(content []byte, msgFmt uint8) string {
|
||
if text, err := cmpp.DecodeContent(content, msgFmt); err == nil {
|
||
return text
|
||
}
|
||
logger.L().Warn("deliver_mo_decode_fallback",
|
||
zap.Uint8("msg_fmt", msgFmt), zap.Int("bytes", len(content)))
|
||
return string(content)
|
||
}
|
||
|
||
// 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.deps.ReportDeliver(channelID, ok)
|
||
if ok {
|
||
m.observe(channelID, LogKindDeliver, 0, r.MsgID, r.Stat, 0)
|
||
} else {
|
||
m.observe(channelID, LogKindDeliverFail, 1, r.MsgID, r.Stat, 0)
|
||
}
|
||
// P1 压测优化(09-27):逐条 info 在回执洪峰下 5000 行/分钟打爆 HDD
|
||
// (与 DB 写同盘竞争);降为 1/100 采样观测,非 DELIVRD 全量保留(异常可观测)。
|
||
if !ok || deliverLogSample.Add(1)%100 == 1 {
|
||
logger.L().Info("deliver_report",
|
||
zap.Int64("channel_id", channelID), zap.String("msg_id", r.MsgID),
|
||
zap.String("stat", r.Stat), zap.String("done_time", r.DoneTime), zap.String("dest", r.Dest))
|
||
}
|
||
// Day 56:回执进回执域(sms-report→消费者归一化+段级配对→detail 终态)。
|
||
// 读循环严禁阻塞(Kafka 投递与读解耦),goroutine 派发;失败在 Ingest 内记日志。
|
||
m.mu.RLock()
|
||
rp := m.report
|
||
m.mu.RUnlock()
|
||
if rp != nil {
|
||
go rp.IngestReport(context.Background(), channelID, r.MsgID, r.Stat, r.Dest, r.DoneTime)
|
||
}
|
||
} else {
|
||
// 上行内容按 Msg_Fmt 解码为 UTF-8(Day52 乱码复盘补齐):
|
||
// 此前 string(d.Content) 原样直灌,真实上游 GBK(15)/UCS2(8) 中文上行必乱码
|
||
// 入库(channel_log/message_uplink→sms-up);解码失败降级原样+Warn 不丢消息。
|
||
r.Src = d.SrcTerminal
|
||
r.Content = decodeMOContent(d.Content, d.MsgFmt)
|
||
m.observe(channelID, LogKindDeliverMO, 0, "", fmt.Sprintf("src=%s %s", r.Src, r.Content), 0)
|
||
logger.L().Info("deliver_mo",
|
||
zap.Int64("channel_id", channelID), zap.String("src", r.Src), zap.String("content", r.Content))
|
||
// Day 49:上行进上行域(码号分配→message_uplink→sms-up)。读循环严禁
|
||
// 阻塞(DB/Kafka 延迟与通道读解耦),goroutine 派发;失败在 Ingest 内部记日志。
|
||
m.mu.RLock()
|
||
u := m.uplink
|
||
m.mu.RUnlock()
|
||
if u != nil {
|
||
go u.Ingest(context.Background(), channelID, d.DestID, d.SrcTerminal, r.Content)
|
||
}
|
||
}
|
||
m.rmu.Lock()
|
||
m.reports = append(m.reports, r)
|
||
if len(m.reports) > receiptCap {
|
||
m.reports = m.reports[len(m.reports)-receiptCap:]
|
||
}
|
||
m.rmu.Unlock()
|
||
}
|