Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a588ce12b |
+7
-8
@@ -1719,12 +1719,11 @@ issue #3 未关闭,`feat/fix-3-downlink-deadlock` 未合入 `main`。下面是
|
||||
- 备选方案:为每个未测子项补验收用例(本波不做,避免为变绿放松断言)。
|
||||
- 影响:汇总改为通过 19、部分通过 4(F03/F08/F21/F22)、失败 0。F19 仍引用仓库内 SDK 清单、本波不重跑。
|
||||
|
||||
### ¸´ÉóÐÞ¸´ R3-03
|
||||
### 复审修复 R3-04
|
||||
|
||||
1. **д¶ÓÁÐÂúʱ Close ²»ÔÙÓë enqueue ËÀËø**
|
||||
- ÈÕÆÚ£º2026-09-30
|
||||
- ÔÌõ¿î£ºissue #67£»Í£»úÐè Drain/Close ÔÚ³¬Ê±ÄÚ·µ»Ø£»ÒÑÈë¶ÓÈÎÎñÈÔÓÉд goroutine ´¦ÀíÍê¡£
|
||||
- ʵ¼Ê×ö·¨£ºQueue Ôö¼Ó closing Ðźš£enqueue ÔÚ³Ö sendMu.RLock ʱ select ͬʱµÈ´ý q.ch¡¢closing Óë ctx.Done()£¬Í¨µÀÂúʱ²»ÔÙÎÞÏÞ×èÈû¡£Close ÏÈ Swap(closed) ²¢ close(closing) »½ÐÑÔÚ;·¢ËÍ·½ÊͷŶÁËø£¬ÔÙÔÚÐ´ËøÄÚ close(q.ch)£¬×îºóµÈ loop Í˳ö¡£²»ÏòÒÑ¹Ø±Õ channel ·¢ËÍ¡£
|
||||
- ÔÒò£ºÍ¨µÀÂúʱ²¢·¢ Do Õ¼×ŶÁËø¶ÂÔÚ·¢ËÍÉÏ£¬Close µÄÐ´ËøÄò»µ½£¬Í£»ú¿¨ËÀ£»Î´Ìá½»µÄÔÚ;дҲ»á¶ª¡£
|
||||
- ±¸Ñ¡·½°¸£ºÈë¶Ó¸ÄΪ·Ç×èÈû£¬ÂúÔòÁ¢¼´ ErrBusy£¨·ñ¾ö£º¸Ä±ä±³Ñ¹ÓïÒ壬Õý³£¸ß·å»áÎóÉËÌá½»£©¡£
|
||||
- Ó°Ï죺½ö internal/store/queue.go Óë²âÊÔ£»²»¸ÄÇ¨ÒÆ±àºÅ¡£
|
||||
- 日期:2026-09-30
|
||||
- 原条款:Gitea #68;`dispatchSend` 在 `PublishUp` 失败且未停止重连时清 inflight 后静默 return,`Send` 永久挂起。
|
||||
- 实际做法:失败且未 `stopReconnect` 时保留 id/body/send_at_ms,经 `regenerateSendLocked` 换新 rid,清本次 inflight 并 `drainSendQueue` 继续泵;已停止重连时仍 `finishSend` 返回错误。
|
||||
- 原因:条目已不在途,重连时的 `requeueInflightLocked` 不会捡回,调用方一直等 `result`。
|
||||
- 备选方案:失败即 `finishSend` 报错(否决,与断线/限速重交语义不一致);只换 rid 不唤醒队列(否决,等同 JS #69)。
|
||||
- 影响:仅 `sdk/go`;假传输可模拟 send 发布失败一次。
|
||||
|
||||
+9
-22
@@ -36,11 +36,10 @@ type writeJob struct {
|
||||
type Queue struct {
|
||||
db *sql.DB
|
||||
|
||||
ch chan writeJob
|
||||
done chan struct{}
|
||||
closing chan struct{} // Close 时关闭,唤醒持读锁阻塞在发送上的 enqueue
|
||||
closed atomic.Bool
|
||||
sendMu sync.RWMutex
|
||||
ch chan writeJob
|
||||
done chan struct{}
|
||||
closed atomic.Bool
|
||||
sendMu sync.RWMutex
|
||||
|
||||
mu sync.Mutex
|
||||
ready bool
|
||||
@@ -53,16 +52,11 @@ type Queue struct {
|
||||
|
||||
// NewQueue 创建合并写入队列并启动写 goroutine。
|
||||
func NewQueue(db *sql.DB) *Queue {
|
||||
return newQueue(db, queueBuffSize)
|
||||
}
|
||||
|
||||
func newQueue(db *sql.DB, buffSize int) *Queue {
|
||||
q := &Queue{
|
||||
db: db,
|
||||
ch: make(chan writeJob, buffSize),
|
||||
done: make(chan struct{}),
|
||||
closing: make(chan struct{}),
|
||||
ready: true,
|
||||
db: db,
|
||||
ch: make(chan writeJob, queueBuffSize),
|
||||
done: make(chan struct{}),
|
||||
ready: true,
|
||||
}
|
||||
go q.loop()
|
||||
return q
|
||||
@@ -121,15 +115,10 @@ func (q *Queue) enqueue(job writeJob) error {
|
||||
return ErrQueueClosed
|
||||
}
|
||||
q.addPending(1)
|
||||
// 通道满时不得只堵在发送上持有读锁:Close 需要写锁关闭 q.ch。
|
||||
select {
|
||||
case q.ch <- job:
|
||||
q.sendMu.RUnlock()
|
||||
return nil
|
||||
case <-q.closing:
|
||||
q.addPending(-1)
|
||||
q.sendMu.RUnlock()
|
||||
return ErrQueueClosed
|
||||
case <-job.ctx.Done():
|
||||
q.addPending(-1)
|
||||
q.sendMu.RUnlock()
|
||||
@@ -387,13 +376,11 @@ func (q *Queue) Drain(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// Close 关闭队列:不再接受新任务,并等待写 goroutine 处理完已入队任务后退出。
|
||||
// 先关闭 closing 唤醒因通道满而阻塞的发送方并释放读锁,再在无发送者时关闭数据通道,
|
||||
// 避免向已关闭 channel 发送而 panic,也避免与持读锁的 enqueue 死锁。
|
||||
// 在写锁内关闭数据通道,避免并发 Do 向已关闭 channel 发送而 panic。
|
||||
func (q *Queue) Close() error {
|
||||
if q.closed.Swap(true) {
|
||||
return nil
|
||||
}
|
||||
close(q.closing)
|
||||
q.sendMu.Lock()
|
||||
close(q.ch)
|
||||
q.sendMu.Unlock()
|
||||
|
||||
@@ -289,137 +289,3 @@ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.upd
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// openSmallQueue 用小缓冲队列替换默认队列,便于测满通道时的 Close/Drain。
|
||||
func openSmallQueue(t *testing.T, buf int) *DB {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
db, err := Open(dir, "FULL")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Queue.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.Queue = newQueue(db.Write, buf)
|
||||
return db
|
||||
}
|
||||
|
||||
func TestQueueCloseUnblocksFullChannel(t *testing.T) {
|
||||
t.Parallel()
|
||||
const buf = 4
|
||||
db := openSmallQueue(t, buf)
|
||||
defer func() { _ = db.Close() }()
|
||||
q := db.Queue
|
||||
|
||||
hold := make(chan struct{})
|
||||
blockerStarted := make(chan struct{})
|
||||
blockerErr := make(chan error, 1)
|
||||
go func() {
|
||||
blockerErr <- q.Do(context.Background(), func(tx *sql.Tx) error {
|
||||
close(blockerStarted)
|
||||
<-hold
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
<-blockerStarted
|
||||
|
||||
ctx := context.Background()
|
||||
var fillWG sync.WaitGroup
|
||||
for i := 0; i < buf; i++ {
|
||||
fillWG.Add(1)
|
||||
go func() {
|
||||
defer fillWG.Done()
|
||||
_ = q.Do(ctx, func(tx *sql.Tx) error { return nil })
|
||||
}()
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for q.Len() < buf+1 && time.Now().Before(deadline) {
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
if q.Len() < buf+1 {
|
||||
t.Fatalf("channel not full: len=%d", q.Len())
|
||||
}
|
||||
|
||||
blockedErr := make(chan error, 1)
|
||||
go func() {
|
||||
blockedErr <- q.Do(ctx, func(tx *sql.Tx) error { return nil })
|
||||
}()
|
||||
// 等额外 Do 堵在 enqueue(pending 超过通道容量+正在执行的一条)。
|
||||
deadline = time.Now().Add(2 * time.Second)
|
||||
for q.Len() < buf+2 && time.Now().Before(deadline) {
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
|
||||
closeDone := make(chan error, 1)
|
||||
go func() { closeDone <- q.Close() }()
|
||||
|
||||
select {
|
||||
case err := <-blockedErr:
|
||||
if !errors.Is(err, ErrQueueClosed) {
|
||||
t.Fatalf("blocked Do: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Close did not unblock full-channel enqueue")
|
||||
}
|
||||
|
||||
close(hold)
|
||||
select {
|
||||
case err := <-closeDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Close hung after writer released")
|
||||
}
|
||||
<-blockerErr
|
||||
fillWG.Wait()
|
||||
}
|
||||
|
||||
func TestQueueDrainTimeoutWhileWriterBlocked(t *testing.T) {
|
||||
t.Parallel()
|
||||
const buf = 4
|
||||
db := openSmallQueue(t, buf)
|
||||
defer func() { _ = db.Close() }()
|
||||
q := db.Queue
|
||||
|
||||
hold := make(chan struct{})
|
||||
started := make(chan struct{})
|
||||
go func() {
|
||||
_ = q.Do(context.Background(), func(tx *sql.Tx) error {
|
||||
close(started)
|
||||
<-hold
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
<-started
|
||||
|
||||
ctx := context.Background()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < buf; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = q.Do(ctx, func(tx *sql.Tx) error { return nil })
|
||||
}()
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for q.Len() < buf+1 && time.Now().Before(deadline) {
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
|
||||
drainCtx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := q.Drain(drainCtx)
|
||||
elapsed := time.Since(start)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("Drain err=%v want deadline", err)
|
||||
}
|
||||
if elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("Drain took %s, should return on timeout", elapsed)
|
||||
}
|
||||
|
||||
close(hold)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
@@ -156,6 +156,66 @@ func TestFrameTooLargeLocal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishUpFailRetriesWithNewRID(t *testing.T) {
|
||||
fake := NewFakeTransport()
|
||||
fake.FailSendPublishN(1)
|
||||
c := connectFake(t, fake)
|
||||
defer c.Close()
|
||||
|
||||
at := time.UnixMilli(1_700_000_000_000)
|
||||
fixedID := "msg-publish-retry"
|
||||
done := make(chan struct{})
|
||||
var firstRID, secondRID string
|
||||
|
||||
go func() {
|
||||
defer close(done)
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
sends := fake.FindUp("send")
|
||||
if len(sends) < 2 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
first, second := sends[0], sends[1]
|
||||
firstRID, _ = first["rid"].(string)
|
||||
secondRID, _ = second["rid"].(string)
|
||||
if first["id"] != fixedID || second["id"] != fixedID {
|
||||
t.Errorf("id changed: %v -> %v", first["id"], second["id"])
|
||||
}
|
||||
if first["send_at_ms"] != second["send_at_ms"] {
|
||||
t.Errorf("send_at_ms changed: %v -> %v", first["send_at_ms"], second["send_at_ms"])
|
||||
}
|
||||
body1, _ := json.Marshal(first["body"])
|
||||
body2, _ := json.Marshal(second["body"])
|
||||
if string(body1) != string(body2) {
|
||||
t.Errorf("body changed: %s -> %s", body1, body2)
|
||||
}
|
||||
if firstRID == "" || firstRID == secondRID {
|
||||
t.Errorf("rid not regenerated: %q -> %q", firstRID, secondRID)
|
||||
}
|
||||
fake.ReplyOK(secondRID, map[string]any{
|
||||
"id": fixedID, "send_at_ms": second["send_at_ms"], "state": "scheduled",
|
||||
})
|
||||
return
|
||||
}
|
||||
t.Error("timed out waiting for send retry")
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
res, err := c.Send(ctx, Target{Kind: "endpoint", ID: "b"}, Body{Enc: "utf8", Data: "hi"}, SendOptions{ID: fixedID, SendAt: &at})
|
||||
<-done
|
||||
if err != nil {
|
||||
t.Fatalf("Send hung or failed: %v", err)
|
||||
}
|
||||
if res.ID != fixedID {
|
||||
t.Fatalf("result id=%q want %q", res.ID, fixedID)
|
||||
}
|
||||
if firstRID == "" || secondRID == "" || firstRID == secondRID {
|
||||
t.Fatalf("rids=%q/%q", firstRID, secondRID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendKeepsIDAndSendAt(t *testing.T) {
|
||||
fake := NewFakeTransport()
|
||||
c := connectFake(t, fake)
|
||||
|
||||
@@ -3,6 +3,7 @@ package nixmsg
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -29,6 +30,8 @@ type FakeTransport struct {
|
||||
MaxFrameBytes int
|
||||
HelloDelay time.Duration
|
||||
ReceiveMaximumSet bool
|
||||
// failSendLeft 接下来若干次 type=send 的 PublishUp 返回错误(仍记入 up)。
|
||||
failSendLeft int
|
||||
}
|
||||
|
||||
type fakeConnect struct {
|
||||
@@ -65,6 +68,13 @@ func (f *FakeTransport) Start(ctx context.Context, cfg transportConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FailSendPublishN 让接下来 n 次 send 帧 PublishUp 失败(hello 等其它类型不受影响)。
|
||||
func (f *FakeTransport) FailSendPublishN(n int) {
|
||||
f.mu.Lock()
|
||||
f.failSendLeft = n
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *FakeTransport) PublishUp(payload []byte) error {
|
||||
f.mu.Lock()
|
||||
cp := append([]byte(nil), payload...)
|
||||
@@ -80,6 +90,17 @@ func (f *FakeTransport) PublishUp(payload []byte) error {
|
||||
if auto && head.Type == "hello" && head.RID != "" {
|
||||
f.replyHello(head.RID)
|
||||
}
|
||||
if head.Type == "send" {
|
||||
f.mu.Lock()
|
||||
fail := f.failSendLeft > 0
|
||||
if fail {
|
||||
f.failSendLeft--
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if fail {
|
||||
return errors.New("publish failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+16
-11
@@ -202,19 +202,24 @@ func (c *Client) dispatchSend(tr transport, item *sendItem, rid string, payload
|
||||
if err := tr.PublishUp(payload); err != nil {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, rid)
|
||||
if item.epoch == epoch && item.inflight {
|
||||
item.inflight = false
|
||||
if c.inflight > 0 {
|
||||
c.inflight--
|
||||
}
|
||||
if c.stopReconnect {
|
||||
errStop := c.stopErrLocked()
|
||||
c.mu.Unlock()
|
||||
c.finishSend(item, SendResult{}, errStop)
|
||||
return
|
||||
}
|
||||
if item.epoch != epoch || !item.inflight {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
item.inflight = false
|
||||
if c.inflight > 0 {
|
||||
c.inflight--
|
||||
}
|
||||
if c.stopReconnect {
|
||||
errStop := c.stopErrLocked()
|
||||
c.mu.Unlock()
|
||||
c.finishSend(item, SendResult{}, errStop)
|
||||
return
|
||||
}
|
||||
// 保留 id/body/send_at_ms,换新 rid 后继续泵,避免 Send 永久挂起。
|
||||
c.regenerateSendLocked(item)
|
||||
c.mu.Unlock()
|
||||
c.drainSendQueue()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user