Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve active sync sessions during reconnects https://github.com/siyuan-note/siyuan/issues/20819

Daniel9db756fe8818
diff --git a/kernel/model/boot_sync_test.go b/kernel/model/boot_sync_test.go
index 8795345bdc..62c037299e 100644
--- a/kernel/model/boot_sync_test.go
+++ b/kernel/model/boot_sync_test.go
@@ -44,10 +44,14 @@ func TestBootSyncUIWaitSurvivesSlowStartupAndRefresh(t *testing.T) {
t.Fatalf("slow initialization ended the readiness wait: %v", err)
default:
}
- for _, id := range []string{"refresh-1", "refresh-2", "refresh-3"} {
- util.RemovePushChan(first)
+ for _, id := range []string{"first", "refresh-1", "refresh-2", "refresh-3"} {
+ previous := first
first = addBootSyncSession(t, id)
+ util.RemovePushChan(previous)
time.Sleep(time.Second)
+ if syncUIReady(false) {
+ t.Fatal("late disconnect hid the loading replacement connection")
+ }
}
first.Set("uiReady", true)
time.Sleep(time.Second)
diff --git a/kernel/model/sync_checkout_state_test.go b/kernel/model/sync_checkout_state_test.go
index ae851cdf71..8088d9d9e5 100644
--- a/kernel/model/sync_checkout_state_test.go
+++ b/kernel/model/sync_checkout_state_test.go
@@ -65,6 +65,29 @@ func TestSyncCheckoutPreparationCanCancelWhileLoading(t *testing.T) {
})
}
+func TestSyncCheckoutPreparationRejectsReplacedConnection(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ task := prepareSyncCheckoutStateTest(t)
+ old := addBootSyncSession(t, "reconnecting")
+ old.Set("uiReady", true)
+ done := make(chan error, 1)
+ go func() { done <- task.prepareApply() }()
+ synctest.Wait()
+ state := GetSyncCheckout("boot-sync-test", "reconnecting").Task
+ if state.Phase != "preparing" || state.Token == "" {
+ t.Fatalf("ready connection did not receive a save confirmation: %+v", state)
+ }
+ addBootSyncSession(t, "reconnecting")
+ util.RemovePushChan(old)
+ if !ConfirmSyncCheckout(task.id, state.Token, true) {
+ t.Fatal("pending confirmation was unexpectedly rejected")
+ }
+ if err := <-done; !errors.Is(err, dejavu.ErrIndexFileChanged) || task.releaseWrites != nil {
+ t.Fatalf("the previous connection's confirmation bypassed the replacement window: %v", err)
+ }
+ })
+}
+
func prepareSyncCheckoutStateTest(t *testing.T) *syncCheckoutTask {
t.Helper()
prepareSyncDirectoryTest(t)
diff --git a/kernel/util/websocket.go b/kernel/util/websocket.go
index dade19dbfb..c6d4d01148 100644
--- a/kernel/util/websocket.go
+++ b/kernel/util/websocket.go
@@ -53,6 +53,8 @@ var (
// map[string]map[string]*melody.Session{}
sessions = sync.Map{} // {appId, {sessionId, session}}
authSessions = sync.Map{}
+ // 注册与清理必须串行,避免最后一个旧连接断开时删掉并发注册的新连接。
+ pushChanLock sync.Mutex
// ReloadDocInfoGuard 由 model 层注入,在广播 docInfo 前检查 box 是否仍处于可广播状态。
// 加密笔记本锁定后返回 false,防止 500ms 延迟任务在锁定后泄漏明文元数据。
@@ -182,6 +184,8 @@ func AddPushChan(session *melody.Session) {
session.Set("uiReady", false)
}
+ pushChanLock.Lock()
+ defer pushChanLock.Unlock()
if IsAuthSession(session) {
if appSessions, ok := authSessions.Load(appID); !ok {
appSess := &sync.Map{}
@@ -242,11 +246,15 @@ func RemovePushChan(session *melody.Session) {
return
}
+ pushChanLock.Lock()
+ defer pushChanLock.Unlock()
if IsAuthSession(session) {
appSess, _ := authSessions.Load(app)
if nil != appSess {
appSessions := appSess.(*sync.Map)
- appSessions.Delete(id)
+ if !appSessions.CompareAndDelete(id, session) {
+ return
+ }
if 1 > lenOfSyncMap(appSessions) {
authSessions.Delete(app)
}
@@ -255,7 +263,9 @@ func RemovePushChan(session *melody.Session) {
appSess, _ := sessions.Load(app)
if nil != appSess {
appSessions := appSess.(*sync.Map)
- appSessions.Delete(id)
+ if !appSessions.CompareAndDelete(id, session) {
+ return
+ }
if 1 > lenOfSyncMap(appSessions) {
sessions.Delete(app)
}
diff --git a/kernel/util/websocket_test.go b/kernel/util/websocket_test.go
index 8a735fc653..2fffe13532 100644
--- a/kernel/util/websocket_test.go
+++ b/kernel/util/websocket_test.go
@@ -19,6 +19,7 @@ package util
import (
"fmt"
"io"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
@@ -31,6 +32,86 @@ import (
"github.com/siyuan-note/logging"
)
+func TestPushChanReconnectPreservesCurrentSession(t *testing.T) {
+ for _, auth := range []bool{false, true} {
+ t.Run(fmt.Sprintf("auth=%t", auth), func(t *testing.T) {
+ registry := &sessions
+ if auth {
+ registry = &authSessions
+ }
+ connect := func() *melody.Session {
+ session := &melody.Session{Request: httptest.NewRequest("GET", "/ws?app=reconnect-test&id=main&type=main&ready=false", nil)}
+ session.Set("authSession", auth)
+ AddPushChan(session)
+ t.Cleanup(func() { RemovePushChan(session) })
+ return session
+ }
+ old := connect()
+ old.Set("uiReady", true)
+ current := connect()
+ RemovePushChan(old)
+ RemovePushChan(old)
+ appSessions, ok := registry.Load("reconnect-test")
+ if !ok {
+ t.Fatal("late disconnect removed the reconnected application")
+ }
+ if got, _ := appSessions.(*sync.Map).Load("main"); got != current || IsSessionReady(current) {
+ t.Fatal("late disconnect lost the current connection or reused its predecessor's readiness")
+ }
+ RemovePushChan(current)
+ if _, ok := registry.Load("reconnect-test"); ok {
+ t.Fatal("last disconnect retained the empty application")
+ }
+ })
+ }
+}
+
+func TestPushChanConcurrentReconnect(t *testing.T) {
+ for _, auth := range []bool{false, true} {
+ t.Run(fmt.Sprintf("auth=%t", auth), func(t *testing.T) {
+ registry := &sessions
+ if auth {
+ registry = &authSessions
+ }
+ for round := range 50 {
+ appID := fmt.Sprintf("concurrent-reconnect-%t-%d", auth, round)
+ connect := func(id int) *melody.Session {
+ session := &melody.Session{Request: httptest.NewRequest("GET", fmt.Sprintf("/ws?app=%s&id=%d&type=main&ready=false", appID, id), nil)}
+ session.Set("authSession", auth)
+ AddPushChan(session)
+ return session
+ }
+ old := connect(0)
+ const count = 16
+ current := make([]*melody.Session, count)
+ start := make(chan struct{})
+ var workers sync.WaitGroup
+ workers.Go(func() { <-start; RemovePushChan(old) })
+ for i := range current {
+ workers.Go(func() { <-start; current[i] = connect(i) })
+ }
+ close(start)
+ workers.Wait()
+ appSessions, ok := registry.Load(appID)
+ for i, session := range current {
+ if !ok {
+ t.Error("concurrent registration lost the application")
+ } else if got, _ := appSessions.(*sync.Map).Load(fmt.Sprint(i)); got != session {
+ t.Errorf("concurrent registration lost session %d", i)
+ }
+ RemovePushChan(session)
+ }
+ if _, ok := registry.Load(appID); ok {
+ t.Error("disconnects retained an empty application")
+ }
+ if t.Failed() {
+ return
+ }
+ }
+ })
+ }
+}
+
func TestLogWebSocketError(t *testing.T) {
originalPath := logging.LogPath
t.Cleanup(func() { logging.SetLogPath(originalPath) })