// client_test.go Day 34:模拟 SMPP 网关——bind/submit/enquire/流控窗口/deliver。 package smpp import ( "context" "fmt" "net" "sync" "sync/atomic" "testing" "time" ) // fakeSMSC 模拟 SMPP 网关:bind 校验;submit 延迟应答(测流控);enquire 应答;deliver 下发。 type fakeSMSC struct { ln net.Listener systemID string password string delay time.Duration // submit 应答延迟(制造在途) mu sync.Mutex conns map[net.Conn]struct{} submitSlow bool // true:按 delay 延迟应答 binds atomic.Int32 submits atomic.Int32 inflight atomic.Int32 // 当前在途 submit inflightPk atomic.Int32 // 在途峰值 delivAcks atomic.Int32 enquires atomic.Int32 } func newFakeSMSC(t *testing.T, systemID, password string, delay time.Duration) *fakeSMSC { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } g := &fakeSMSC{ln: ln, systemID: systemID, password: password, delay: delay, conns: map[net.Conn]struct{}{}} go g.serve() t.Cleanup(func() { _ = ln.Close() }) return g } func (g *fakeSMSC) serve() { for { conn, err := g.ln.Accept() if err != nil { return } go g.handle(conn) } } func (g *fakeSMSC) handle(conn net.Conn) { g.mu.Lock() g.conns[conn] = struct{}{} g.mu.Unlock() defer func() { g.mu.Lock() delete(g.conns, conn) g.mu.Unlock() _ = conn.Close() }() for { h, body, err := ReadPDU(conn) if err != nil { return } switch h.CommandID { case CmdBindTransceiver: sid, pw, _, err := ParseBind(body) st := StatusOK if err != nil || sid != g.systemID || pw != g.password { st = StatusBindFail } _ = WritePDU(conn, &Header{CommandID: CmdBindTransceiverResp, SequenceNo: h.SequenceNo, Status: st}, BindResp("fakesmsc")) if st == StatusOK { g.binds.Add(1) } case CmdSubmitSM: g.submits.Add(1) cur := g.inflight.Add(1) for { // 更新峰值 pk := g.inflightPk.Load() if cur <= pk || g.inflightPk.CompareAndSwap(pk, cur) { break } } reply := func() { g.inflight.Add(-1) _ = WritePDU(conn, &Header{CommandID: CmdSubmitSMResp, SequenceNo: h.SequenceNo, Status: StatusOK}, SubmitResp(fmt.Sprintf("m-%d", h.SequenceNo))) } g.mu.Lock() slow := g.submitSlow g.mu.Unlock() if slow { go func() { time.Sleep(g.delay); reply() }() } else { reply() } case CmdEnquireLink: g.enquires.Add(1) _ = WritePDU(conn, &Header{CommandID: CmdEnquireLinkResp, SequenceNo: h.SequenceNo, Status: StatusOK}, nil) case CmdDeliverSMResp: g.delivAcks.Add(1) case CmdUnbind: _ = WritePDU(conn, &Header{CommandID: CmdUnbindResp, SequenceNo: h.SequenceNo, Status: StatusOK}, nil) return } } } // pushDeliver 向全部活跃连接下发 deliver_sm。 func (g *fakeSMSC) pushDeliver(d *Deliver) { body := d.Marshal() g.mu.Lock() conns := make([]net.Conn, 0, len(g.conns)) for c := range g.conns { conns = append(conns, c) } g.mu.Unlock() for _, c := range conns { _ = WritePDU(c, &Header{CommandID: CmdDeliverSM, SequenceNo: 500}, body) } } func fastSMPPCfg(addr string, window int) Config { return Config{ Addr: addr, SystemID: "esme1", Password: "pw123", WindowSize: window, HeartbeatInterval: 60 * time.Millisecond, WindowWait: 2 * time.Second, Timeout: 2 * time.Second, } } // TestSMPP_BindAndSubmit 验收:Bind 成功 + Submit 拿 message_id/status=OK。 func TestSMPP_BindAndSubmit(t *testing.T) { g := newFakeSMSC(t, "esme1", "pw123", 0) c := NewClient(fastSMPPCfg(g.ln.Addr().String(), 10)) if err := c.Connect(context.Background()); err != nil { t.Fatalf("bind: %v", err) } defer func() { _ = c.Close() }() // Day42(P1⑦):fake server bind 计数在 handler goroutine 异步递增, // 全量并发负载下可能晚于 Connect 返回——轮询等待(≤2s)替代即时断言。 deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) && g.binds.Load() < 1 { time.Sleep(20 * time.Millisecond) } if g.binds.Load() < 1 { t.Fatal("网关未见 bind") } mid, st, err := c.Submit(&SubmitReq{ Source: Addr{Ton: 1, Npi: 1, Address: "10086"}, Dest: Addr{Ton: 1, Npi: 1, Address: "13800001111"}, ShortMessage: []byte("x"), RegisteredDelivery: 1, }) if err != nil || st != StatusOK || mid == "" { t.Fatalf("submit: id=%q st=0x%08x err=%v", mid, uint32(st), err) } // 错密码 bind 被拒 bad := NewClient(Config{Addr: g.ln.Addr().String(), SystemID: "esme1", Password: "wrong", Timeout: time.Second}) if err := bad.Connect(context.Background()); err == nil { t.Fatal("错密码应被拒") } } // TestSMPP_Keepalive 验收:链路探测保活(enquire_link 周期往返)。 func TestSMPP_Keepalive(t *testing.T) { g := newFakeSMSC(t, "esme1", "pw123", 0) c := NewClient(fastSMPPCfg(g.ln.Addr().String(), 10)) if err := c.Connect(context.Background()); err != nil { t.Fatal(err) } defer func() { _ = c.Close() }() ctx, cancel := context.WithCancel(context.Background()) defer cancel() beats := make(chan struct{}, 8) c.OnHeartbeat = func() { beats <- struct{}{} } go func() { _ = c.Keepalive(ctx) }() deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) && g.enquires.Load() < 2 { time.Sleep(20 * time.Millisecond) } if g.enquires.Load() < 2 { t.Fatalf("enquire 计数 = %d, 期望 ≥2", g.enquires.Load()) } select { case <-beats: default: t.Fatal("未触发心跳回调") } } // TestSMPP_WindowThrottle 验收:流控窗口限速(在途峰值 ≤ WindowSize,全部成功)。 func TestSMPP_WindowThrottle(t *testing.T) { g := newFakeSMSC(t, "esme1", "pw123", 80*time.Millisecond) // 慢应答制造在途 g.mu.Lock() g.submitSlow = true g.mu.Unlock() c := NewClient(fastSMPPCfg(g.ln.Addr().String(), 2)) // 窗口=2 if err := c.Connect(context.Background()); err != nil { t.Fatal(err) } defer func() { _ = c.Close() }() var wg sync.WaitGroup errs := make(chan error, 8) for i := 0; i < 8; i++ { wg.Add(1) go func() { defer wg.Done() _, st, err := c.Submit(&SubmitReq{ Source: Addr{Address: "10086"}, Dest: Addr{Address: "13800001111"}, ShortMessage: []byte("w"), }) if err != nil || st != StatusOK { errs <- err } }() } wg.Wait() select { case err := <-errs: t.Fatalf("窗口内提交失败: %v", err) default: } if pk := g.inflightPk.Load(); pk > 2 { t.Fatalf("在途峰值 = %d, 超过窗口 2", pk) } if g.submits.Load() != 8 { t.Fatalf("submit 总数 = %d", g.submits.Load()) } } // TestSMPP_WindowFull 窗口满且网关停止应答 → 等待超时返回 ErrWindowFull。 func TestSMPP_WindowFull(t *testing.T) { g := newFakeSMSC(t, "esme1", "pw123", time.Hour) // 极慢:占满窗口 g.mu.Lock() g.submitSlow = true g.mu.Unlock() c := NewClient(Config{ Addr: g.ln.Addr().String(), SystemID: "esme1", Password: "pw123", WindowSize: 1, WindowWait: 150 * time.Millisecond, Timeout: 2 * time.Second, }) if err := c.Connect(context.Background()); err != nil { t.Fatal(err) } defer func() { _ = c.Close() }() // 第 1 个占用唯一令牌(网关慢应答);第 2 个窗口满等待超时 go func() { _, _, _ = c.Submit(&SubmitReq{Source: Addr{Address: "a"}, Dest: Addr{Address: "b"}, ShortMessage: []byte("1")}) }() time.Sleep(100 * time.Millisecond) // 确保第 1 个已取令牌 if _, _, err := c.Submit(&SubmitReq{Source: Addr{Address: "a"}, Dest: Addr{Address: "b"}, ShortMessage: []byte("2")}); err == nil { t.Fatal("窗口满应报错") } } // TestSMPP_Deliver deliver 下发解析(回执/上行)+ 自动回 resp。 func TestSMPP_Deliver(t *testing.T) { g := newFakeSMSC(t, "esme1", "pw123", 0) c := NewClient(fastSMPPCfg(g.ln.Addr().String(), 10)) if err := c.Connect(context.Background()); err != nil { t.Fatal(err) } defer func() { _ = c.Close() }() got := make(chan *Deliver, 2) c.OnDeliver = func(d *Deliver) { got <- d } g.pushDeliver(&Deliver{ESMClass: 0x04, Source: Addr{Address: "10086"}, Dest: Addr{Address: "13800001111"}, ShortMessage: []byte("id:ABC sub:001 dlvrd:001 submit date:2609041130 done date:2609041131 stat:DELIVRD err:000 text:")}) g.pushDeliver(&Deliver{ESMClass: 0, Source: Addr{Address: "13800001111"}, Dest: Addr{Address: "10086"}, ShortMessage: []byte("TD")}) var report, uplink *Deliver timeout := time.After(2 * time.Second) for report == nil || uplink == nil { select { case d := <-got: if d.IsReport() { report = d } else { uplink = d } case <-timeout: t.Fatalf("未收到: report=%v uplink=%v", report != nil, uplink != nil) } } if ReportStat(report.ShortMessage) != "DELIVRD" { t.Fatalf("回执 stat: %q", ReportStat(report.ShortMessage)) } if string(uplink.ShortMessage) != "TD" || uplink.Source.Address != "13800001111" { t.Fatalf("上行: %+v", uplink) } deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) && g.delivAcks.Load() < 2 { time.Sleep(20 * time.Millisecond) } if g.delivAcks.Load() < 2 { t.Fatalf("deliver_sm_resp = %d, 期望 2", g.delivAcks.Load()) } }