413 lines
15 KiB
Go
413 lines
15 KiB
Go
// access.go Day 47:客户协议接入域服务(api/open/protocol)。
|
|
// 职责:①CMPP/SMPP 连接鉴权(复用账号体系:username + AccountConfig.ApiSecret
|
|
//
|
|
// 32hex 串即共享密钥,与 Day46 HTTP 验签同源凭据)②Submit 业务适配——
|
|
//
|
|
// 通道号前缀校验(SrcID 须以账号 ext_code 为前缀,开发计划「UT:0012」语义)
|
|
// →openapi.Service.SendMass 复用受理链(校验/计费/落库/审核分流/Kafka 事件)。
|
|
package access
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"go-sms/internal/model/entity"
|
|
"go-sms/internal/pkg/logger"
|
|
"go-sms/internal/protocol/cmpp"
|
|
"go-sms/internal/protocol/smpp"
|
|
"go-sms/internal/service/account"
|
|
"go-sms/internal/service/openapi"
|
|
"go-sms/internal/service/report"
|
|
"go-sms/internal/service/send"
|
|
"go-sms/internal/service/sysconfig"
|
|
"go.uber.org/zap"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// submitStatsT Day62d:CMPP 接入受理埋点(盲区修复:客户 20 链压测全程零留痕,
|
|
// 吞吐排查只能靠 DB 倒推;30s 汇总 qps/均值/慢占比,拒绝分支另有 cmpp_submit_rejected)。
|
|
type submitStatsT struct {
|
|
start sync.Once
|
|
count atomic.Int64
|
|
slow atomic.Int64 // >200ms 受理耗时(SLOW SQL/在途链路观测锚点)
|
|
ms atomic.Int64 // 累计耗时
|
|
}
|
|
|
|
var submitStats submitStatsT
|
|
|
|
func (s *submitStatsT) record(el time.Duration) {
|
|
s.count.Add(1)
|
|
s.ms.Add(el.Milliseconds())
|
|
if el > 200*time.Millisecond {
|
|
s.slow.Add(1)
|
|
}
|
|
}
|
|
|
|
// report 惰性启动 30s 汇总上报(首条 Submit 触发;零流量静默不刷屏)。
|
|
func (s *submitStatsT) report() {
|
|
s.start.Do(func() {
|
|
go func() {
|
|
tk := time.NewTicker(30 * time.Second)
|
|
defer tk.Stop()
|
|
for range tk.C {
|
|
c := s.count.Swap(0)
|
|
if c == 0 {
|
|
continue
|
|
}
|
|
logger.L().Info("cmpp_submit_stats",
|
|
zap.Int64("count_30s", c),
|
|
zap.Float64("qps", float64(c)/30),
|
|
zap.Int64("avg_ms", s.ms.Swap(0)/c),
|
|
zap.Int64("slow_gt_200ms", s.slow.Swap(0)))
|
|
}
|
|
}()
|
|
})
|
|
}
|
|
|
|
// Service 客户接入服务(db 只读鉴权 + 提交转发)。
|
|
type Service struct {
|
|
db *gorm.DB
|
|
api *openapi.Service
|
|
limits SystemLimits // Day 62:CMPP 接入系统默认(账号级 0 时回退)
|
|
// P0-1(Day 63)受理热路径账号缓存:username→(user,cfg),TTL 30s。
|
|
// Submit/ConnLimit/SubmitRateLimit 每条提交调用,原每次 2 次 SELECT
|
|
// (~5ms/条)为快路径最后 DB 残留;连接级鉴权 Connect 不走缓存(实时)。
|
|
accCache sync.Map // string → *accountCacheEntry
|
|
accTTL time.Duration
|
|
// 长短信片聚合器(批次 2278141 修复):入向 UDH 拼接多片按组聚合,
|
|
// 到齐合并为一条逻辑 task;超时逐片退化直发。见 longsms.go。
|
|
grouper *longSmsGrouper
|
|
// sysCfg Issue#3 方案B:系统配置源(账号 ext_code 空时回退系统默认接入码
|
|
// cmpp.default_ext_code);nil=无系统回退(行为不变,测试/降级场景)。
|
|
sysCfg SystemConfigGetter
|
|
}
|
|
|
|
// SystemConfigGetter 系统配置读取接口(由 sysconfig.Service 实现;解耦包依赖)。
|
|
type SystemConfigGetter interface {
|
|
Get(ctx context.Context, key string) string
|
|
}
|
|
|
|
// SetSystemConfig 注入系统配置源(可选;gateway 装配调用,nil=无系统回退)。
|
|
func (s *Service) SetSystemConfig(g SystemConfigGetter) { s.sysCfg = g }
|
|
|
|
// accountCacheEntry 账号缓存条目(u/cfg nil=查无,负缓存防穿透)。
|
|
type accountCacheEntry struct {
|
|
u, cfg any // *entity.AccountUser | *entity.AccountConfig | nil
|
|
expireAt time.Time
|
|
}
|
|
|
|
const accountCacheTTL = 30 * time.Second
|
|
|
|
// SystemLimits CMPP 接入系统默认值(来自服务端 config;账号级配置 0 时回退)。
|
|
type SystemLimits struct {
|
|
MaxConns int // 每账号最大连接数(≤0=不限)
|
|
SubmitRate int // 单链提交限速 条/s(≤0=不限)
|
|
// LongSmsWindow Day 71:入向长短信挂起窗(≤0=默认 72h;到期不齐失败终态)。
|
|
LongSmsWindow time.Duration
|
|
}
|
|
|
|
// New 构造(api=openapi 提交服务,复用 SendMass 受理链;limits=系统默认配额)。
|
|
func New(db *gorm.DB, api *openapi.Service, limits SystemLimits) *Service {
|
|
g := newLongSmsGrouper(db)
|
|
if limits.LongSmsWindow > 0 {
|
|
g.window = limits.LongSmsWindow
|
|
}
|
|
return &Service{db: db, api: api, limits: limits, accTTL: accountCacheTTL,
|
|
grouper: g}
|
|
}
|
|
|
|
// StartLongSmsMaintenance Day 71:长短信挂起制启动(重启恢复+72h 到期扫描器;
|
|
// gateway 装配调用,CMPP 无挂起行时零成本)。push=nil 只落失败记录不推回执
|
|
// (producer 降级场景);every<=0 默认 1min。
|
|
func (s *Service) StartLongSmsMaintenance(ctx context.Context,
|
|
push report.PushSink, every time.Duration) {
|
|
if n := s.grouper.restore(s.restoreLongSmsAuth); n > 0 {
|
|
logger.L().Info("cmpp_longsms_restored", zap.Int("groups", n))
|
|
}
|
|
go newLongSmsReaper(s.grouper, s.api, s.db, push, s.restoreLongSmsAuth).Run(ctx, every)
|
|
}
|
|
|
|
// restoreLongSmsAuth 挂起组 auth 重建(restore/reaper 共用;账号删除/停用
|
|
// 返回 nil——restore 跳过该组/remerge 走失败终态)。
|
|
func (s *Service) restoreLongSmsAuth(username string, accountID int64) *openapi.AuthContext {
|
|
u, cfg := s.loadAccount(context.Background(), username)
|
|
if u == nil || cfg == nil {
|
|
return nil
|
|
}
|
|
return &openapi.AuthContext{AccountID: u.ID, Username: username, Config: cfg,
|
|
Source: send.TaskSourceCMPP}
|
|
}
|
|
|
|
// ConnLimit 实现 cmpp.ConnLimiter(Day 62):账号级最大连接数,
|
|
// account_config.cmpp_max_conns(0=回退系统默认;负值兜底不限)。
|
|
func (s *Service) ConnLimit(sourceAddr string) int {
|
|
_, cfg := s.loadAccountDB(context.Background(), sourceAddr)
|
|
if cfg == nil {
|
|
return s.limits.MaxConns // 账号缺失时鉴权必拒,取系统默认不放大窗口
|
|
}
|
|
if cfg.CmppMaxConns > 0 {
|
|
return cfg.CmppMaxConns
|
|
}
|
|
return s.limits.MaxConns
|
|
}
|
|
|
|
// SubmitRateLimit 实现 cmpp.SubmitRateLimiter(Day 62):账号级单链限速 条/s,
|
|
// account_config.cmpp_speed(0=回退系统默认)。
|
|
func (s *Service) SubmitRateLimit(sourceAddr string) int {
|
|
_, cfg := s.loadAccountDB(context.Background(), sourceAddr)
|
|
if cfg == nil {
|
|
return s.limits.SubmitRate
|
|
}
|
|
if cfg.CmppSpeed > 0 {
|
|
return cfg.CmppSpeed
|
|
}
|
|
return s.limits.SubmitRate
|
|
}
|
|
|
|
// loadAccount 按用户名装载账号+业务配置(不存在/停用/无配置统一拒绝)。
|
|
// P0-1(Day 63)热路径缓存(TTL 30s,负缓存防穿透;Connect 鉴权路径不走缓存)。
|
|
func (s *Service) loadAccount(ctx context.Context, username string) (*entity.AccountUser, *entity.AccountConfig) {
|
|
if s.accTTL > 0 {
|
|
if v, ok := s.accCache.Load(username); ok {
|
|
e := v.(*accountCacheEntry)
|
|
if time.Now().Before(e.expireAt) {
|
|
var u *entity.AccountUser
|
|
var cfg *entity.AccountConfig
|
|
if e.u != nil {
|
|
u = e.u.(*entity.AccountUser)
|
|
}
|
|
if e.cfg != nil {
|
|
cfg = e.cfg.(*entity.AccountConfig)
|
|
}
|
|
return u, cfg
|
|
}
|
|
}
|
|
}
|
|
u, cfg := s.loadAccountDB(ctx, username)
|
|
if s.accTTL > 0 {
|
|
s.accCache.Store(username, &accountCacheEntry{
|
|
u: accountPtr(u), cfg: configPtr(cfg), expireAt: time.Now().Add(s.accTTL),
|
|
})
|
|
}
|
|
return u, cfg
|
|
}
|
|
|
|
// accountPtr/configPtr nil→any(nil) 规整(避免 typed-nil 断言歧义)。
|
|
func accountPtr(u *entity.AccountUser) any {
|
|
if u == nil {
|
|
return nil
|
|
}
|
|
return u
|
|
}
|
|
|
|
func configPtr(c *entity.AccountConfig) any {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
return c
|
|
}
|
|
|
|
// loadAccountDB 原直查路径(缓存未命中回源)。
|
|
func (s *Service) loadAccountDB(ctx context.Context, username string) (*entity.AccountUser, *entity.AccountConfig) {
|
|
var u entity.AccountUser
|
|
if err := s.db.WithContext(ctx).Where("username = ?", username).
|
|
First(&u).Error; err != nil {
|
|
return nil, nil
|
|
}
|
|
if u.Status != 1 {
|
|
return &u, nil
|
|
}
|
|
var cfg entity.AccountConfig
|
|
if err := s.db.WithContext(ctx).
|
|
Where("account_id = ? AND business = ?", u.ID, "sms").
|
|
First(&cfg).Error; err != nil {
|
|
return &u, nil
|
|
}
|
|
return &u, &cfg
|
|
}
|
|
|
|
// ---- CMPP ----
|
|
|
|
// Connect 实现 cmpp.ServerHandler:CMPP authenticator 鉴权(MD5 链路见 cmpp/body.go)。
|
|
// Day62b 可观测:各失败分支落 warn 日志(source_addr/client_ip/ts/status)——
|
|
// 旧版静默回状态码,客户连接被拒时服务端零痕迹(真机排查 -1 报障时暴露盲区)。
|
|
func (s *Service) Connect(sourceAddr string, ts uint32, authenticator []byte, clientIP string) byte {
|
|
ctx := context.Background()
|
|
u, cfg := s.loadAccountDB(ctx, sourceAddr)
|
|
if u == nil {
|
|
logger.L().Warn("cmpp_conn_auth_failed",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", clientIP),
|
|
zap.Uint32("ts", ts), zap.Uint8("status", cmpp.ConnectBadAuth)) // 不泄露存在性,码值 2
|
|
return cmpp.ConnectBadAuth // 不泄露存在性
|
|
}
|
|
if cfg == nil {
|
|
logger.L().Warn("cmpp_conn_disabled",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", clientIP),
|
|
zap.Uint8("status", cmpp.ConnectDisabled))
|
|
return cmpp.ConnectDisabled
|
|
}
|
|
if !account.IPAllowed(u.IPBind, clientIP) {
|
|
logger.L().Warn("cmpp_conn_bad_ip",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", clientIP),
|
|
zap.Uint8("status", cmpp.ConnectBadIP))
|
|
return cmpp.ConnectBadIP
|
|
}
|
|
if cfg.ApiSecret == "" {
|
|
logger.L().Warn("cmpp_conn_auth_failed",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", clientIP),
|
|
zap.Uint32("ts", ts), zap.Uint8("status", cmpp.ConnectBadAuth),
|
|
zap.String("reason", "secret_not_issued"))
|
|
return cmpp.ConnectBadAuth
|
|
}
|
|
if !cmpp.VerifyAuth(sourceAddr, cfg.ApiSecret, ts, authenticator) {
|
|
logger.L().Warn("cmpp_conn_auth_failed",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", clientIP),
|
|
zap.Uint32("ts", ts), zap.Uint8("status", cmpp.ConnectBadAuth)) // 密码不匹配(不输出库值/指纹)
|
|
return cmpp.ConnectBadAuth
|
|
}
|
|
return cmpp.ConnectOK
|
|
}
|
|
|
|
// Submit 实现 cmpp.ServerHandler:账号/通道号前缀校验→SendMass 受理。
|
|
// 长短信片(udh 非 nil 且单目的码)改走聚合器:按组拼接合并为一条逻辑
|
|
// 短信单次受理(批次 2278141 修复,决策①A/②A/③——详见 longsms.go);其余
|
|
// (普通提交/多目的码片)走原直发路径不变。
|
|
func (s *Service) Submit(sourceAddr, srcID string, dest []string,
|
|
content string, udh *cmpp.UDHInfo, registeredDelivery uint8, msgFmt uint8) (uint64, byte) {
|
|
submitStats.report()
|
|
t0 := time.Now()
|
|
defer func() { submitStats.record(time.Since(t0)) }()
|
|
ctx := context.Background()
|
|
if udh != nil && udh.Total > 1 && len(dest) == 1 {
|
|
cfg, ext, result := s.precheck(ctx, sourceAddr, srcID)
|
|
if cfg == nil {
|
|
return 0, result
|
|
}
|
|
return s.grouper.submitFragment(s.api, cfg, ext, sourceAddr, srcID,
|
|
dest[0], content, udh, msgFmt == cmpp.MsgFmtUCS2)
|
|
}
|
|
return s.submitDirect(ctx, sourceAddr, srcID, dest, content, msgFmt)
|
|
}
|
|
|
|
// precheck 账号加载+通道号校验(cfg=nil 时返回值为 CMPP 拒绝码)。
|
|
// 直发与长短信聚合共用(聚合组以首片账号快照为准)。
|
|
// Issue#3 方案B:返回生效校验前缀 ext——账号 ext_code 优先,空则回退系统默认
|
|
// cmpp.default_ext_code(账号级定制>系统级统一;两层均空=不校验)。
|
|
func (s *Service) precheck(ctx context.Context, sourceAddr, srcID string) (*entity.AccountConfig, string, byte) {
|
|
_, cfg := s.loadAccount(ctx, sourceAddr)
|
|
if cfg == nil {
|
|
return nil, "", cmpp.SubmitRejected
|
|
}
|
|
ext := s.effectiveExtCode(ctx, cfg)
|
|
// 通道号前缀:ext 非空时 SrcID 必须以其为前缀(UT:0012 语义;系统默认同)。
|
|
if ext != "" && !strings.HasPrefix(srcID, ext) {
|
|
logger.L().Warn("cmpp_submit_src_prefix_mismatch",
|
|
zap.String("source_addr", sourceAddr), zap.String("src_id", srcID),
|
|
zap.String("ext_code", ext),
|
|
zap.Bool("from_system_default", cfg.ExtCode == ""))
|
|
return nil, "", cmpp.SubmitBadCode
|
|
}
|
|
return cfg, ext, cmpp.SubmitOK
|
|
}
|
|
|
|
// effectiveExtCode 生效校验前缀:账号 ext_code 优先;空则回退系统默认
|
|
// (Issue#3 方案B;sysCfg 未注入/系统键未配置=空=不校验)。
|
|
func (s *Service) effectiveExtCode(ctx context.Context, cfg *entity.AccountConfig) string {
|
|
if cfg.ExtCode != "" {
|
|
return cfg.ExtCode
|
|
}
|
|
if s.sysCfg != nil {
|
|
return s.sysCfg.Get(ctx, sysconfig.KeyDefaultExtCode)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// submitDirect 普通提交(原 Submit 主体):P0-1(Day 63)快路径受理。
|
|
// RegisteredDelivery 语义不变:回执由 Day61 push 链按明细驱动,受理参数不传递。
|
|
func (s *Service) submitDirect(ctx context.Context, sourceAddr, srcID string,
|
|
dest []string, content string, msgFmt uint8) (uint64, byte) {
|
|
tAcc := time.Now()
|
|
cfg, ext, result := s.precheck(ctx, sourceAddr, srcID)
|
|
tAccCost := time.Since(tAcc)
|
|
if cfg == nil {
|
|
return 0, result
|
|
}
|
|
t0 := time.Now()
|
|
resp := s.api.SendMassFast(ctx, &openapi.AuthContext{
|
|
AccountID: cfg.AccountID, Username: sourceAddr, Config: cfg,
|
|
Source: send.TaskSourceCMPP, // Day 60:受理来源打标(CMPP 接入)
|
|
}, &openapi.MassReq{
|
|
PhoneList: dest,
|
|
Content: content,
|
|
SignName: "", // CMPP 内容自带【签名】,与 Day41 验收二变口径一致
|
|
ExtCode: strings.TrimPrefix(srcID, ext),
|
|
// Day 70:按 MsgFmt 分流计费口径(UCS2=8:每码元 2B;fee≡上游真实片数)。
|
|
ContentEncoding: ucs2Encoding(msgFmt == cmpp.MsgFmtUCS2),
|
|
}, remoteIPPlaceholder)
|
|
if resp.Code != openapi.CodeOK {
|
|
logger.L().Warn("cmpp_submit_rejected",
|
|
zap.String("source_addr", sourceAddr), zap.Int("code", resp.Code),
|
|
zap.String("message", resp.Message))
|
|
return 0, cmpp.SubmitRejected
|
|
}
|
|
// P0-1 诊断:分段耗时(loadAccount/受理链),>100ms 打点(临时,Day63 复压定位)。
|
|
if d := time.Since(t0); d > 100*time.Millisecond {
|
|
logger.L().Warn("cmpp_submit_slow_seg",
|
|
zap.Duration("total", d), zap.Duration("load_account", tAccCost),
|
|
zap.Duration("fast_path", d-tAccCost),
|
|
zap.String("source_addr", sourceAddr))
|
|
}
|
|
return uint64(resp.MsgID), cmpp.SubmitOK
|
|
}
|
|
|
|
// remoteIPPlaceholder 提交侧 IP 留痕(接入 IP 由协议层日志记录;SendMass 仅落库用)。
|
|
const remoteIPPlaceholder = "protocol"
|
|
|
|
// Bind 实现 smpp.ServerHandler:明文密码常数时间比对(ApiSecret 即密码)。
|
|
func (s *Service) Bind(systemID, password, clientIP string) smpp.Status {
|
|
ctx := context.Background()
|
|
u, cfg := s.loadAccount(ctx, systemID)
|
|
if u == nil || cfg == nil {
|
|
return smpp.StatusBindFail
|
|
}
|
|
if !account.IPAllowed(u.IPBind, clientIP) {
|
|
return smpp.StatusBindFail
|
|
}
|
|
if cfg.ApiSecret == "" ||
|
|
subtle.ConstantTimeCompare([]byte(cfg.ApiSecret), []byte(password)) != 1 {
|
|
return smpp.StatusBindFail
|
|
}
|
|
return smpp.StatusOK
|
|
}
|
|
|
|
// SubmitSM 实现 smpp.ServerHandler:源地址校验(账号 ext_code 优先,空回退系统
|
|
// 默认接入码——Issue#3 方案B,与 CMPP precheck 同口径)→SendMass 受理。
|
|
func (s *Service) SubmitSM(systemID, srcAddr, destAddr, content string,
|
|
registeredDelivery uint8) (string, smpp.Status) {
|
|
ctx := context.Background()
|
|
_, cfg := s.loadAccount(ctx, systemID)
|
|
if cfg == nil {
|
|
return "", smpp.StatusSysErr
|
|
}
|
|
ext := s.effectiveExtCode(ctx, cfg)
|
|
if ext != "" && !strings.HasPrefix(srcAddr, ext) {
|
|
return "", smpp.StatusSysErr
|
|
}
|
|
resp := s.api.SendMass(ctx, &openapi.AuthContext{
|
|
AccountID: cfg.AccountID, Username: systemID, Config: cfg,
|
|
Source: send.TaskSourceSMPP, // Day 60:受理来源打标(SMPP 接入)
|
|
}, &openapi.MassReq{
|
|
PhoneList: []string{destAddr},
|
|
Content: content,
|
|
ExtCode: strings.TrimPrefix(srcAddr, ext),
|
|
}, remoteIPPlaceholder)
|
|
if resp.Code != openapi.CodeOK {
|
|
return "", smpp.StatusSysErr
|
|
}
|
|
return resp.TaskNo, smpp.StatusOK
|
|
}
|