Files
go-sms-V2/internal/protocol/smpp/client.go
T

257 lines
6.5 KiB
Go

// client.go SMPP 客户端(Day 34):bind_transceiver 握手、enquire_link 周期保活、
// submit_sm 在途窗口流控(令牌;窗口满时按超时等待)、deliver_sm 接收(自动回 resp)。
package smpp
import (
"context"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
)
// ErrBindRejected 绑定被拒。
var ErrBindRejected = errors.New("smpp: 网关拒绝绑定")
// ErrWindowFull 流控窗口满(等待令牌超时)。
var ErrWindowFull = errors.New("smpp: 流控窗口已满(在途 submit 达上限)")
// Config 客户端配置。
type Config struct {
Addr string
SystemID string
Password string
WindowSize int // 在途 submit 上限(默认 10;≤0 取默认)
HeartbeatInterval time.Duration // enquire_link 周期(默认 30s)
WindowWait time.Duration // 窗口满等待时长(默认 3s)
Timeout time.Duration // bind/应答超时(默认 5s)
}
func (c *Config) withDefaults() {
if c.WindowSize <= 0 {
c.WindowSize = 10
}
if c.HeartbeatInterval <= 0 {
c.HeartbeatInterval = 30 * time.Second
}
if c.WindowWait <= 0 {
c.WindowWait = 3 * time.Second
}
if c.Timeout <= 0 {
c.Timeout = 5 * time.Second
}
}
// Client SMPP 客户端。
type Client struct {
cfg Config
mu sync.Mutex
conn net.Conn
seq atomic.Uint32
done atomic.Bool
window chan struct{} // 在途令牌(容量=WindowSize)
pending sync.Map // seq -> chan submitResult
hbCh chan struct{}
// OnDeliver 下发回调(上行/回执;自动回 deliver_sm_resp)。
OnDeliver func(d *Deliver)
OnHeartbeat func()
}
// submitResult submit 应答。
type submitResult struct {
messageID string
status Status
}
// NewClient 构造。
func NewClient(cfg Config) *Client {
cfg.withDefaults()
return &Client{
cfg: cfg,
window: make(chan struct{}, cfg.WindowSize),
hbCh: make(chan struct{}, 1),
}
}
// nextSeq 自增流水号。
func (c *Client) nextSeq() uint32 { return c.seq.Add(1) }
// Connect 建立 TCP + bind_transceiver(status=OK)。
func (c *Client) Connect(ctx context.Context) error {
d := net.Dialer{Timeout: c.cfg.Timeout}
conn, err := d.DialContext(ctx, "tcp", c.cfg.Addr)
if err != nil {
return fmt.Errorf("smpp: 连接网关失败: %w", err)
}
bind := &Bind{SystemID: c.cfg.SystemID, Password: c.cfg.Password, SystemType: "SMPP"}
seq := c.nextSeq()
if err := WritePDU(conn, &Header{CommandID: CmdBindTransceiver, SequenceNo: seq}, bind.Marshal()); err != nil {
_ = conn.Close()
return err
}
_ = conn.SetReadDeadline(time.Now().Add(c.cfg.Timeout))
h, body, err := ReadPDU(conn)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
_ = conn.Close()
return fmt.Errorf("smpp: 读取 bind_resp 失败: %w", err)
}
if h.CommandID != CmdBindTransceiverResp {
_ = conn.Close()
return fmt.Errorf("smpp: 期望 bind_resp 实际 cmd=0x%08x", uint32(h.CommandID))
}
if h.Status != StatusOK {
_ = conn.Close()
return fmt.Errorf("%w: status=0x%08x", ErrBindRejected, uint32(h.Status))
}
_, _ = ParseBindResp(body) // system_id(诊断用)
c.mu.Lock()
c.conn = conn
c.mu.Unlock()
go c.readLoop(conn)
return nil
}
// readLoop 常驻读循环:enquire_link_resp→心跳信号;submit_sm_resp→pending 分发;
// deliver_sm→解析+自动回 resp+回调;enquire_link(网关探测)→应答;unbind→回应并退出。
func (c *Client) readLoop(conn net.Conn) {
for {
h, body, err := ReadPDU(conn)
if err != nil {
return
}
switch h.CommandID {
case CmdEnquireLinkResp:
select {
case c.hbCh <- struct{}{}:
default:
}
case CmdSubmitSMResp:
if v, ok := c.pending.LoadAndDelete(h.SequenceNo); ok {
if ch, ok := v.(chan submitResult); ok {
id, _ := ParseSubmitResp(body)
select {
case ch <- submitResult{messageID: id, status: h.Status}:
default:
}
}
}
case CmdDeliverSM:
d, err := ParseDeliver(body)
if err != nil {
continue // 坏包跳过
}
_ = WritePDU(conn, &Header{CommandID: CmdDeliverSMResp, SequenceNo: h.SequenceNo, Status: StatusOK}, nil)
if c.OnDeliver != nil {
c.OnDeliver(d)
}
case CmdEnquireLink: // 网关主动探测
_ = WritePDU(conn, &Header{CommandID: CmdEnquireLinkResp, SequenceNo: h.SequenceNo, Status: StatusOK}, nil)
case CmdUnbind:
_ = WritePDU(conn, &Header{CommandID: CmdUnbindResp, SequenceNo: h.SequenceNo, Status: StatusOK}, nil)
_ = conn.Close()
return
}
}
}
// heartbeat 发一次 enquire_link 并等应答(链路探测保活)。
func (c *Client) heartbeat() error {
c.mu.Lock()
conn := c.conn
c.mu.Unlock()
if conn == nil {
return errors.New("smpp: 未连接")
}
seq := c.nextSeq()
select { // 清历史信号
case <-c.hbCh:
default:
}
if err := WritePDU(conn, &Header{CommandID: CmdEnquireLink, SequenceNo: seq}, nil); err != nil {
return fmt.Errorf("smpp: enquire 发送失败: %w", err)
}
select {
case <-c.hbCh:
return nil
case <-time.After(c.cfg.Timeout):
return errors.New("smpp: enquire 应答超时")
}
}
// Keepalive 周期 enquire_link 保活;失败返回(链路失效)。
func (c *Client) Keepalive(ctx context.Context) error {
t := time.NewTicker(c.cfg.HeartbeatInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
if err := c.heartbeat(); err != nil {
_ = c.Close()
return err
}
if c.OnHeartbeat != nil {
c.OnHeartbeat()
}
}
}
}
// Submit 提交短消息:流控窗口限速(在途令牌)→ 发 submit_sm → 等配对 resp。
// 验收:窗口满时阻塞等待(WindowWait 超时返回 ErrWindowFull)。
func (c *Client) Submit(req *SubmitReq) (string, Status, error) {
c.mu.Lock()
conn := c.conn
c.mu.Unlock()
if conn == nil {
return "", 0, errors.New("smpp: 未连接")
}
// 流控:取在途令牌(窗口满则等待)
select {
case c.window <- struct{}{}:
default:
select {
case c.window <- struct{}{}:
case <-time.After(c.cfg.WindowWait):
return "", 0, ErrWindowFull
}
}
defer func() { <-c.window }() // 完成归还令牌
seq := c.nextSeq()
ch := make(chan submitResult, 1)
c.pending.Store(seq, ch)
defer c.pending.Delete(seq)
if err := WritePDU(conn, &Header{CommandID: CmdSubmitSM, SequenceNo: seq}, req.Marshal()); err != nil {
return "", 0, fmt.Errorf("smpp: submit 发送失败: %w", err)
}
select {
case r := <-ch:
return r.messageID, r.status, nil
case <-time.After(c.cfg.Timeout):
return "", 0, errors.New("smpp: submit_resp 超时")
}
}
// Close 关闭连接。
func (c *Client) Close() error {
c.done.Store(true)
c.mu.Lock()
conn := c.conn
c.conn = nil
c.mu.Unlock()
if conn != nil {
return conn.Close()
}
return nil
}