Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a14ca0d08d |
+3
-1
@@ -335,7 +335,9 @@ func runServe(ctx context.Context, cfg config.Config) error {
|
||||
drainCancel()
|
||||
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
_ = brk.Shutdown(shutCtx)
|
||||
if shutErr := brk.Shutdown(shutCtx); shutErr != nil && !errors.Is(shutErr, context.DeadlineExceeded) && !errors.Is(shutErr, context.Canceled) {
|
||||
slog.Error("broker shutdown", "err", shutErr)
|
||||
}
|
||||
shutCancel()
|
||||
|
||||
secondDrain := drainBudget - time.Since(drainStart)
|
||||
|
||||
+7
-7
@@ -1719,12 +1719,12 @@ issue #3 未关闭,`feat/fix-3-downlink-deadlock` 未合入 `main`。下面是
|
||||
- 备选方案:为每个未测子项补验收用例(本波不做,避免为变绿放松断言)。
|
||||
- 影响:汇总改为通过 19、部分通过 4(F03/F08/F21/F22)、失败 0。F19 仍引用仓库内 SDK 清单、本波不重跑。
|
||||
|
||||
### 复审修复 R3-01
|
||||
### 复审修复 R3-02
|
||||
|
||||
1. **推送 worker 漏唤醒:定时分发回执、超限后续、撤回腾窗**
|
||||
1. **积压时 fatal/logout 与停机 0x8B 须等本帧写出**
|
||||
- 日期:2026-09-30
|
||||
- 原条款:Gitea #65;推送 worker 只在 `WakePush` 时跑一轮 `PushPending`。
|
||||
- 实际做法:`dispatchDueBatch` 本条已分发时除 pending 接收方外始终 `WakePush` 发送方;`PushPending` 遇 `too_large` 等跳过且本轮未占满窗口时再 `WakePush` 当前接收方(不在同一次递归扫表);`Recall` 成功改成 `recalled` 的接收方各 `WakePush` 一次,已推送撤回仍走 `flushRevokes`。不改 `PublishDown` 签名。
|
||||
- 原因:终态回执、超限后的后续 pending、撤回腾出窗口后都依赖再唤醒,否则空闲在线端收不到。
|
||||
- 备选方案:在同一次 `PushPending` 里循环扫完整 pending 表(否决,指令要求合并唤醒下一轮)。
|
||||
- 影响:仅 `internal/app/message/`;相关单测见 `review_r3_65_test.go`。
|
||||
- 原条款:Gitea #66;B-04 / B-08。
|
||||
- 实际做法:带断开的下行帧用本帧 `OnPacketSent` 完成信号(优先 packet id,否则按载荷匹配),不再用连接级 `sentPub` 总数。`Shutdown` 在 ctx 未取消时先等下行队列与 `wirePending` 排空,再 `DisconnectClient` 发 `0x8B` 并在截止前等连接拆掉;ctx 已取消则发完即 `Close`。`serve` 仍给 5 秒预算并记录非超时错误。未合 `feat/fix-3-downlink-deadlock`。
|
||||
- 原因:前面 PUBLISH 的 `OnPacketSent` 会让总数等待提前返回;`Shutdown` 对 ctx 非阻塞 select 使 5 秒预算用不上,有 outbound 积压时 `0x8B` 只进 outbuf 随 `Stop` 丢掉。
|
||||
- 备选方案:恢复固定 `Sleep`(否决);改 `PublishDown` 签名(否决)。
|
||||
- 影响:队列/outbound 有积压时 fatal、logout 先到客户端再断开;停机在预算内尽量发出 `0x8B`,超时返回 ctx 错误而非空等。
|
||||
|
||||
@@ -90,7 +90,6 @@ func (a *App) Recall(ctx context.Context, senderID string, req *protocol.Recall)
|
||||
nowMs := a.now().UnixMilli()
|
||||
var data protocol.RecallData
|
||||
var revokes []revokeJob
|
||||
var wakeReceivers []string
|
||||
err := a.db.Queue.Do(ctx, func(tx *sql.Tx) error {
|
||||
var seq int64
|
||||
var state string
|
||||
@@ -157,7 +156,6 @@ WHERE seq = ? AND endpoint_id = ? AND state = 'pending'`,
|
||||
continue
|
||||
}
|
||||
recalled++
|
||||
wakeReceivers = append(wakeReceivers, p.ep)
|
||||
if p.pushed.Valid && p.pushed.String != "" {
|
||||
revokes = append(revokes, revokeJob{
|
||||
endpointID: p.ep,
|
||||
@@ -192,9 +190,6 @@ SELECT COUNT(*) FROM deliveries WHERE seq = ? AND state IN ('expired','dropped',
|
||||
a.pendingRevoke = append(a.pendingRevoke, revokes...)
|
||||
a.mu.Unlock()
|
||||
a.flushRevokes(ctx)
|
||||
for _, ep := range wakeReceivers {
|
||||
a.WakePush(ep)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,6 @@ LIMIT ?`, nowMs, limit)
|
||||
}
|
||||
mu.Lock()
|
||||
n++
|
||||
wake[d.senderID] = struct{}{}
|
||||
mu.Unlock()
|
||||
rows2, qErr := a.db.Read.QueryContext(ctx, `
|
||||
SELECT DISTINCT endpoint_id FROM deliveries WHERE seq = ? AND state = 'pending'`, d.seq)
|
||||
@@ -204,10 +203,8 @@ LIMIT ?`, endpointID, room)
|
||||
}
|
||||
|
||||
var toClaim []pushItem
|
||||
skipped := false
|
||||
for _, it := range items {
|
||||
if it.body == nil {
|
||||
skipped = true
|
||||
continue
|
||||
}
|
||||
msg := protocol.Msg{
|
||||
@@ -230,7 +227,6 @@ LIMIT ?`, endpointID, room)
|
||||
return rejErr
|
||||
}
|
||||
a.WakePush(it.senderID)
|
||||
skipped = true
|
||||
continue
|
||||
}
|
||||
it.payload = payload
|
||||
@@ -256,10 +252,6 @@ LIMIT ?`, endpointID, room)
|
||||
a.observeDispatchToPush(it.sendAt, nowMs)
|
||||
}
|
||||
}
|
||||
// 超限等跳过未占满窗口时再唤醒本端,让 worker 下一轮取后续 pending(不在本轮递归扫表)。
|
||||
if skipped && len(claimed) < room {
|
||||
a.WakePush(endpointID)
|
||||
}
|
||||
return a.pushReceipts(ctx, endpointID, connID, nowMs)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/nixevol/NixMsg/internal/app/port"
|
||||
"git.asio.asia/nixevol/NixMsg/internal/protocol"
|
||||
)
|
||||
|
||||
// 定时到点且接收方离线成终态时,在线发送方经 WakePush 拿到回执。
|
||||
func TestR365DispatchDueWakesSenderForReceipt(t *testing.T) {
|
||||
t.Parallel()
|
||||
e := openDeliveryEnv(t, nil)
|
||||
insertEndpoint(t, e.db, "alice", "", 1, 0)
|
||||
insertEndpoint(t, e.db, "bob", "", 1, 0)
|
||||
_ = e.db.Queue.Do(context.Background(), func(tx *sql.Tx) error {
|
||||
_, err := tx.Exec(`UPDATE endpoints SET offline_since = ? WHERE id=?`, e.nowMs-120_000, "bob")
|
||||
return err
|
||||
})
|
||||
ctx := context.Background()
|
||||
aliceConn := LiveConn{ConnID: "c-alice", Ready: true}
|
||||
e.conns.Set("alice", aliceConn)
|
||||
if err := e.app.OnHandshakeComplete(ctx, "alice", aliceConn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { e.app.stopPushWorker("alice", "") })
|
||||
|
||||
delay := int64(5000)
|
||||
req := baseSend("due-rcpt", "bob")
|
||||
req.DelayMs = &delay
|
||||
if _, err := e.app.Submit(ctx, "alice", port.ConnInfo{}, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, _ := e.msgState("alice", "due-rcpt")
|
||||
if st != StateScheduled {
|
||||
t.Fatalf("want scheduled got %s", st)
|
||||
}
|
||||
if e.down.FilterType(protocol.TypeReceipt) != 0 {
|
||||
t.Fatal("receipt before due")
|
||||
}
|
||||
|
||||
e.setNow(e.nowMs + 5000)
|
||||
if _, err := e.app.DispatchDue(ctx, e.nowMs, 10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if e.down.FilterType(protocol.TypeReceipt) > 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("sender got no receipt after scheduled dispatch, receipts=%d", e.down.FilterType(protocol.TypeReceipt))
|
||||
}
|
||||
|
||||
// 窗口内首条超限拒收后,同连接后续小消息仍被 worker 推送。
|
||||
func TestR365TooLargeThenSmallContinuesPush(t *testing.T) {
|
||||
t.Parallel()
|
||||
e := openDeliveryEnv(t, func(l *Limits) { l.DeliveryWindow = 1 })
|
||||
insertEndpoint(t, e.db, "alice", "", 1, 0)
|
||||
insertEndpoint(t, e.db, "bob", "", 1, 0)
|
||||
ctx := context.Background()
|
||||
// 整帧上限:小消息能过,大正文整帧超限被拒。
|
||||
bobConn := LiveConn{ConnID: "c-bob", Ready: true, MaxReceiveBytes: 200}
|
||||
e.conns.Set("bob", bobConn)
|
||||
if err := e.app.OnHandshakeComplete(ctx, "bob", bobConn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { e.app.stopPushWorker("bob", "") })
|
||||
|
||||
big := baseSend("big-skip", "bob")
|
||||
b := make([]byte, 400)
|
||||
for i := range b {
|
||||
b[i] = 'A'
|
||||
}
|
||||
big.Body.Data = string(b)
|
||||
if _, err := e.app.Submit(ctx, "alice", port.ConnInfo{}, big); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
small := baseSend("small-ok", "bob")
|
||||
small.Body.Data = "hi"
|
||||
if _, err := e.app.Submit(ctx, "alice", port.ConnInfo{}, small); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
foundSmall := false
|
||||
for _, p := range e.down.Snapshots() {
|
||||
if payloadType(p.Payload) != protocol.TypeMsg {
|
||||
continue
|
||||
}
|
||||
var m struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(p.Payload, &m)
|
||||
if m.ID == "small-ok" {
|
||||
foundSmall = true
|
||||
}
|
||||
}
|
||||
if foundSmall {
|
||||
seqBig := e.seqOf("alice", "big-skip")
|
||||
st, reason := e.deliveryState(seqBig, "bob")
|
||||
if st != DeliveryRejected || reason != ReasonTooLarge {
|
||||
t.Fatalf("big: %s/%s", st, reason)
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("small msg not pushed after too_large; msgs=%d snapshots=%d",
|
||||
e.down.FilterType(protocol.TypeMsg), len(e.down.Snapshots()))
|
||||
}
|
||||
|
||||
// 撤回已推在途消息后,同连接更晚的 pending 继续推。
|
||||
func TestR365RecallFreesWindowForLaterPending(t *testing.T) {
|
||||
t.Parallel()
|
||||
e := openDeliveryEnv(t, func(l *Limits) { l.DeliveryWindow = 1 })
|
||||
insertEndpoint(t, e.db, "alice", "", 1, 0)
|
||||
insertEndpoint(t, e.db, "bob", "", 1, 0)
|
||||
ctx := context.Background()
|
||||
bobConn := LiveConn{ConnID: "c-bob", Ready: true}
|
||||
e.conns.Set("bob", bobConn)
|
||||
if err := e.app.OnHandshakeComplete(ctx, "bob", bobConn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { e.app.stopPushWorker("bob", "") })
|
||||
|
||||
if _, err := e.app.Submit(ctx, "alice", port.ConnInfo{}, baseSend("first-in-flight", "bob")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.app.Submit(ctx, "alice", port.ConnInfo{}, baseSend("second-wait", "bob")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if e.down.FilterType(protocol.TypeMsg) >= 1 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if e.down.FilterType(protocol.TypeMsg) < 1 {
|
||||
t.Fatal("first msg not pushed")
|
||||
}
|
||||
seq1 := e.seqOf("alice", "first-in-flight")
|
||||
var pushed sql.NullString
|
||||
_ = e.db.Read.QueryRow(`SELECT pushed_conn FROM deliveries WHERE seq=? AND endpoint_id='bob'`, seq1).Scan(&pushed)
|
||||
if !pushed.Valid {
|
||||
t.Fatal("first not in-flight")
|
||||
}
|
||||
|
||||
if _, err := e.app.Recall(ctx, "alice", &protocol.Recall{
|
||||
V: protocol.Version, Type: protocol.TypeRecall, RID: "r1", ID: "first-in-flight",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deadline = time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
for _, p := range e.down.Snapshots() {
|
||||
if payloadType(p.Payload) != protocol.TypeMsg {
|
||||
continue
|
||||
}
|
||||
var m struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(p.Payload, &m)
|
||||
if m.ID == "second-wait" {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("second pending not pushed after recall; msgs=%d", e.down.FilterType(protocol.TypeMsg))
|
||||
}
|
||||
@@ -87,6 +87,50 @@ func TestPublishThenDisconnectWritesThenCloses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishThenDisconnectAfterQueuedFrame(t *testing.T) {
|
||||
b, w, done := startTCPClient(t, "ep-ptd-q")
|
||||
defer func() { _ = b.Close() }()
|
||||
defer func() {
|
||||
_ = w.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
}()
|
||||
writeConnect(t, w, "ep-ptd-q", 30, 0)
|
||||
readExactPacket(t, w, packets.Connack, 3*time.Second)
|
||||
writeSubscribe(t, w, downTopic("ep-ptd-q"))
|
||||
readExactPacket(t, w, packets.Suback, 3*time.Second)
|
||||
waitSession(t, b, "ep-ptd-q")
|
||||
|
||||
first := []byte(`{"v":1,"type":"msg","id":"queued-ahead"}`)
|
||||
fatal := []byte(`{"v":1,"type":"fatal","reason":"disabled"}`)
|
||||
if err := b.PublishDown(context.Background(), "ep-ptd-q", "", first, port.PublishOpts{QoS: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.PublishThenDisconnect(context.Background(), "ep-ptd-q", "", fatal, 1, port.DisconnectFatal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
gotFirst := readDownPayload(t, w, 3*time.Second)
|
||||
if !bytes.Equal(gotFirst, first) {
|
||||
t.Fatalf("first got %s", gotFirst)
|
||||
}
|
||||
gotFatal := readDownPayload(t, w, 3*time.Second)
|
||||
if !bytes.Equal(gotFatal, fatal) {
|
||||
t.Fatalf("fatal got %s want %s (disconnected before fatal frame)", gotFatal, fatal)
|
||||
}
|
||||
_ = w.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
buf := make([]byte, 64)
|
||||
n, err := io.ReadAtLeast(w, buf, 2)
|
||||
if err != nil && n == 0 {
|
||||
return
|
||||
}
|
||||
if n > 0 && buf[0]>>4 == packets.Disconnect {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownUsesServerShuttingDown(t *testing.T) {
|
||||
b, w, done := startTCPClient(t, "ep-shut")
|
||||
defer func() {
|
||||
@@ -116,6 +160,120 @@ func TestShutdownUsesServerShuttingDown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownWithBacklogDeliversServerShuttingDown(t *testing.T) {
|
||||
b, w, done := startTCPClient(t, "ep-shut-bl")
|
||||
defer func() {
|
||||
_ = w.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
}()
|
||||
writeConnect(t, w, "ep-shut-bl", 30, 0)
|
||||
readExactPacket(t, w, packets.Connack, 3*time.Second)
|
||||
writeSubscribe(t, w, downTopic("ep-shut-bl"))
|
||||
readExactPacket(t, w, packets.Suback, 3*time.Second)
|
||||
waitSession(t, b, "ep-shut-bl")
|
||||
|
||||
payload := bytes.Repeat([]byte("b"), 1024)
|
||||
for i := 0; i < 8; i++ {
|
||||
if err := b.PublishDown(context.Background(), "ep-shut-bl", "", payload, port.PublishOpts{QoS: 1}); err != nil {
|
||||
t.Fatalf("publish %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
saw8B := make(chan bool, 1)
|
||||
go func() {
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
_ = w.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
hdr := make([]byte, 1)
|
||||
if _, err := io.ReadFull(w, hdr); err != nil {
|
||||
continue
|
||||
}
|
||||
rem, err := readRemainingLengthConn(w)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
body := make([]byte, rem)
|
||||
if _, err := io.ReadFull(w, body); err != nil {
|
||||
continue
|
||||
}
|
||||
switch hdr[0] >> 4 {
|
||||
case packets.Publish:
|
||||
qos := (hdr[0] >> 1) & 0x3
|
||||
if qos > 0 {
|
||||
pk := new(packets.Packet)
|
||||
pk.ProtocolVersion = 5
|
||||
pk.FixedHeader = packets.FixedHeader{Type: packets.Publish, Remaining: rem, Qos: qos}
|
||||
if decErr := pk.PublishDecode(body); decErr == nil {
|
||||
ack := packets.Packet{
|
||||
FixedHeader: packets.FixedHeader{Type: packets.Puback},
|
||||
ProtocolVersion: 5,
|
||||
PacketID: pk.PacketID,
|
||||
}
|
||||
var ab bytes.Buffer
|
||||
_ = ack.PubackEncode(&ab)
|
||||
_, _ = w.Write(ab.Bytes())
|
||||
}
|
||||
}
|
||||
case packets.Disconnect:
|
||||
if rem >= 1 && body[0] == packets.ErrServerShuttingDown.Code {
|
||||
saw8B <- true
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
saw8B <- false
|
||||
}()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
err := b.Shutdown(ctx)
|
||||
|
||||
got := false
|
||||
select {
|
||||
case got = <-saw8B:
|
||||
case <-time.After(4 * time.Second):
|
||||
t.Fatal("reader hung")
|
||||
}
|
||||
if got {
|
||||
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("shutdown after 0x8B: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("expected 0x8B or shutdown deadline error, got neither")
|
||||
}
|
||||
if !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("shutdown err=%v want deadline/cancel when 0x8B not seen", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownCancelledContextReturnsQuickly(t *testing.T) {
|
||||
b, w, done := startTCPClient(t, "ep-shut-cancel")
|
||||
defer func() {
|
||||
_ = w.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
}()
|
||||
writeConnect(t, w, "ep-shut-cancel", 30, 0)
|
||||
readExactPacket(t, w, packets.Connack, 3*time.Second)
|
||||
waitSession(t, b, "ep-shut-cancel")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
start := time.Now()
|
||||
_ = b.Shutdown(ctx)
|
||||
if time.Since(start) > 500*time.Millisecond {
|
||||
t.Fatalf("cancelled shutdown took %s", time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectivePayloadLimitSubtractsOverhead(t *testing.T) {
|
||||
got := EffectivePayloadLimit(200, 0)
|
||||
if got != 200-packetOverheadBudget {
|
||||
|
||||
@@ -141,9 +141,14 @@ type connState struct {
|
||||
downStop chan struct{}
|
||||
downDone chan struct{}
|
||||
downBytes atomic.Int64
|
||||
sentPub atomic.Int64
|
||||
wirePending atomic.Int64 // Publish 入 mochi outbound 后、OnPacketSent 前
|
||||
mu sync.Mutex
|
||||
|
||||
// 带断开的下行帧:只等本帧 OnPacketSent,不用连接级计数。
|
||||
writeWaitCh chan struct{}
|
||||
writeWaitPayload []byte
|
||||
writeWaitPID uint16 // 非 0 时优先按 packet id 匹配
|
||||
|
||||
handshakeTimer *time.Timer
|
||||
}
|
||||
|
||||
@@ -232,28 +237,105 @@ func (b *Broker) Close() error {
|
||||
}
|
||||
|
||||
// Shutdown 向所有连接发 MQTT 5 0x8B 后关闭。完整 HTTP 停机顺序见 L-03。
|
||||
// ctx 未取消时先等下行队列与 wirePending 排空,再 DisconnectClient(此时 outbound 空,
|
||||
// 0x8B 直写套接字),并在截止前等连接拆掉;ctx 已取消则发完即 Close,不等待。
|
||||
func (b *Broker) Shutdown(ctx context.Context) error {
|
||||
if b.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
b.connsMu.RLock()
|
||||
states := make([]*connState, 0, len(b.byClient))
|
||||
clients := make([]*mqtt.Client, 0, len(b.byClient))
|
||||
for cl := range b.byClient {
|
||||
for cl, st := range b.byClient {
|
||||
if cl != nil {
|
||||
clients = append(clients, cl)
|
||||
}
|
||||
if st != nil {
|
||||
states = append(states, st)
|
||||
}
|
||||
}
|
||||
b.connsMu.RUnlock()
|
||||
|
||||
for _, st := range states {
|
||||
st.mu.Lock()
|
||||
st.closing = true
|
||||
st.mu.Unlock()
|
||||
}
|
||||
|
||||
alreadyCancelled := false
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
alreadyCancelled = true
|
||||
default:
|
||||
}
|
||||
|
||||
var waitErr error
|
||||
if !alreadyCancelled {
|
||||
if !b.waitConnsQuiet(ctx, states) {
|
||||
waitErr = ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
for _, cl := range clients {
|
||||
_ = b.server.DisconnectClient(cl, packets.ErrServerShuttingDown)
|
||||
}
|
||||
if ctx != nil {
|
||||
|
||||
if !alreadyCancelled && waitErr == nil {
|
||||
waitErr = b.waitConnsGone(ctx)
|
||||
}
|
||||
|
||||
closeErr := b.Close()
|
||||
if waitErr != nil {
|
||||
return waitErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
||||
func (b *Broker) waitConnsQuiet(ctx context.Context, states []*connState) bool {
|
||||
for {
|
||||
quiet := true
|
||||
for _, st := range states {
|
||||
if st.wirePending.Load() > 0 {
|
||||
quiet = false
|
||||
break
|
||||
}
|
||||
st.mu.Lock()
|
||||
ch := st.downCh
|
||||
st.mu.Unlock()
|
||||
if ch != nil && len(ch) > 0 {
|
||||
quiet = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if quiet {
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
return false
|
||||
case <-time.After(2 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Broker) waitConnsGone(ctx context.Context) error {
|
||||
for {
|
||||
b.connsMu.RLock()
|
||||
n := len(b.byClient)
|
||||
b.connsMu.RUnlock()
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(2 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
return b.Close()
|
||||
}
|
||||
|
||||
// AttachTCP 把裸 TCP/TLS 连接交给 mochi;阻塞到连接结束。
|
||||
|
||||
+115
-12
@@ -1,10 +1,12 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/nixevol/NixMsg/internal/app/port"
|
||||
"github.com/mochi-mqtt/server/v2/packets"
|
||||
)
|
||||
|
||||
type downItem struct {
|
||||
@@ -130,7 +132,11 @@ func (st *connState) sendOne(b *Broker, item downItem) {
|
||||
st.mu.Unlock()
|
||||
}
|
||||
topic := downTopic(st.endpointID)
|
||||
before := st.sentPub.Load()
|
||||
var waitCh chan struct{}
|
||||
if item.disconnect != "" {
|
||||
waitCh = st.armWriteWait(item.payload)
|
||||
}
|
||||
st.wirePending.Add(1)
|
||||
var err error
|
||||
for !b.closed.Load() {
|
||||
select {
|
||||
@@ -150,6 +156,14 @@ func (st *connState) sendOne(b *Broker, item downItem) {
|
||||
}
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
st.wirePending.Add(-1)
|
||||
st.clearWriteWait(waitCh)
|
||||
} else if waitCh != nil {
|
||||
if pid, ok := st.lookupInflightPID(item.payload); ok {
|
||||
st.setWriteWaitPID(waitCh, pid)
|
||||
}
|
||||
}
|
||||
if large {
|
||||
b.finishLargePublish(st)
|
||||
}
|
||||
@@ -158,23 +172,112 @@ func (st *connState) sendOne(b *Broker, item downItem) {
|
||||
}
|
||||
st.signalSent(item)
|
||||
if err == nil && item.disconnect != "" {
|
||||
st.waitPacketWritten(before)
|
||||
st.waitWriteDone(waitCh)
|
||||
_ = b.Disconnect(context.Background(), st.endpointID, st.connID, item.disconnect)
|
||||
}
|
||||
}
|
||||
|
||||
func (st *connState) waitPacketWritten(before int64) {
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if st.sentPub.Load() > before {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-st.downStop:
|
||||
return
|
||||
case <-time.After(2 * time.Millisecond):
|
||||
func (st *connState) armWriteWait(payload []byte) chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
st.mu.Lock()
|
||||
st.writeWaitCh = ch
|
||||
st.writeWaitPayload = payload
|
||||
st.writeWaitPID = 0
|
||||
st.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (st *connState) setWriteWaitPID(ch chan struct{}, pid uint16) {
|
||||
st.mu.Lock()
|
||||
if st.writeWaitCh == ch {
|
||||
st.writeWaitPID = pid
|
||||
}
|
||||
st.mu.Unlock()
|
||||
}
|
||||
|
||||
func (st *connState) clearWriteWait(ch chan struct{}) {
|
||||
if ch == nil {
|
||||
return
|
||||
}
|
||||
st.mu.Lock()
|
||||
if st.writeWaitCh == ch {
|
||||
st.writeWaitCh = nil
|
||||
st.writeWaitPayload = nil
|
||||
st.writeWaitPID = 0
|
||||
}
|
||||
st.mu.Unlock()
|
||||
}
|
||||
|
||||
func (st *connState) waitWriteDone(ch chan struct{}) {
|
||||
if ch == nil {
|
||||
return
|
||||
}
|
||||
defer st.clearWriteWait(ch)
|
||||
deadline := time.NewTimer(2 * time.Second)
|
||||
defer deadline.Stop()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-st.downStop:
|
||||
case <-deadline.C:
|
||||
}
|
||||
}
|
||||
|
||||
func (st *connState) notePacketSent(pk packets.Packet) {
|
||||
if pk.FixedHeader.Type == packets.Publish {
|
||||
for {
|
||||
cur := st.wirePending.Load()
|
||||
if cur <= 0 {
|
||||
break
|
||||
}
|
||||
if st.wirePending.CompareAndSwap(cur, cur-1) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
st.mu.Lock()
|
||||
ch := st.writeWaitCh
|
||||
pid := st.writeWaitPID
|
||||
want := st.writeWaitPayload
|
||||
st.mu.Unlock()
|
||||
if ch == nil || pk.FixedHeader.Type != packets.Publish {
|
||||
return
|
||||
}
|
||||
match := false
|
||||
if pid != 0 {
|
||||
match = pk.PacketID == pid
|
||||
} else if want != nil {
|
||||
match = bytes.Equal(pk.Payload, want)
|
||||
}
|
||||
if !match {
|
||||
return
|
||||
}
|
||||
st.mu.Lock()
|
||||
if st.writeWaitCh == ch {
|
||||
st.writeWaitCh = nil
|
||||
st.writeWaitPayload = nil
|
||||
st.writeWaitPID = 0
|
||||
}
|
||||
st.mu.Unlock()
|
||||
select {
|
||||
case <-ch:
|
||||
default:
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
|
||||
func (st *connState) lookupInflightPID(payload []byte) (uint16, bool) {
|
||||
if st.client == nil || st.client.State.Inflight == nil {
|
||||
return 0, false
|
||||
}
|
||||
for _, pk := range st.client.State.Inflight.GetAll(false) {
|
||||
if pk.FixedHeader.Type != packets.Publish {
|
||||
continue
|
||||
}
|
||||
if bytes.Equal(pk.Payload, payload) {
|
||||
return pk.PacketID, pk.PacketID != 0
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (st *connState) signalSent(item downItem) {
|
||||
|
||||
@@ -175,14 +175,11 @@ func (h *nixHook) OnSubscribed(cl *mqtt.Client, pk packets.Packet, reasonCodes [
|
||||
}
|
||||
|
||||
func (h *nixHook) OnPacketSent(cl *mqtt.Client, pk packets.Packet, _ []byte) {
|
||||
if pk.FixedHeader.Type != packets.Publish {
|
||||
return
|
||||
}
|
||||
h.b.connsMu.RLock()
|
||||
st := h.b.byClient[cl]
|
||||
h.b.connsMu.RUnlock()
|
||||
if st != nil {
|
||||
st.sentPub.Add(1)
|
||||
st.notePacketSent(pk)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +251,7 @@ func (h *nixHook) OnDisconnect(cl *mqtt.Client, err error, _ bool) {
|
||||
lk.Lock()
|
||||
st.stopDownLoop()
|
||||
lk.Unlock()
|
||||
st.wirePending.Store(0)
|
||||
h.b.releaseAllLarge(st)
|
||||
h.b.cancelHandshakeDeadline(st.endpointID, st.connID)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user