Skip to content

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

:bug: Deduplicate sync perception and LAN triggers https://github.com/siyuan-note/siyuan/issues/18556

Daniele7bffd358a68
diff --git a/kernel/model/lan_sync.go b/kernel/model/lan_sync.go
index c28cb67a1b..b186da6ddc 100644
--- a/kernel/model/lan_sync.go
+++ b/kernel/model/lan_sync.go
@@ -243,11 +243,31 @@ func handleLANSyncCommitHint(latestID string) {
delay := time.Second + time.Duration(binary.BigEndian.Uint32(hash[:4])%5000)*time.Millisecond
time.AfterFunc(delay, func() {
if nil != Conf.Sync && nil != Conf.Sync.LAN && Conf.Sync.LAN.Enabled && Conf.Sync.Enabled && 1 == Conf.Sync.Mode {
- SyncData(false)
+ syncDataFromLAN(latestID)
}
})
}
+func syncDataFromLAN(latestID string) {
+ defer logging.Recover()
+ if !checkSync(false, false, false) {
+ return
+ }
+ scope := lanSyncScope()
+ _, _ = syncRemoteRequests.do(scope, latestID, func() error {
+ lockSync()
+ defer unlockSync()
+ if syncRemoteRequests.isCompleted(scope, latestID) {
+ return nil
+ }
+ err := syncDataLocked(false, false)
+ if nil == err {
+ completeCurrentSyncRemoteRequest(scope)
+ }
+ return err
+ })
+}
+
func SetSyncLAN(enabled bool, maxConcurrentReqs int) {
if nil == Conf.Sync {
Conf.Sync = conf.NewSync()
diff --git a/kernel/model/sync.go b/kernel/model/sync.go
index c4925fe705..6a12513acf 100644
--- a/kernel/model/sync.go
+++ b/kernel/model/sync.go
@@ -50,17 +50,41 @@ func SyncDataDownload() {
return
}
+ scope := lanSyncScope()
+ latestID := getSyncCloudLatestID()
+ if "" != latestID {
+ _, _ = syncRemoteRequests.do(scope, latestID, func() error {
+ lockSync()
+ defer unlockSync()
+ if syncRemoteRequests.isCompleted(scope, latestID) {
+ return nil
+ }
+ err := syncDataDownloadLocked()
+ if nil == err {
+ completeCurrentSyncRemoteRequest(scope)
+ }
+ return err
+ })
+ return
+ }
+
unlock, ok := lockSyncRequest(&syncDownloadRequests)
if !ok {
return
}
defer unlock()
+ if err := syncDataDownloadLocked(); nil == err {
+ completeCurrentSyncRemoteRequest(scope)
+ }
+}
+
+func syncDataDownloadLocked() (err error) {
util.BroadcastByType("main", "syncing", 0, Conf.Language(81), nil)
now := util.CurrentTimeMillis()
Conf.Sync.Synced = now
- err := syncRepoDownloadWithDNSRetry()
+ err = syncRepoDownloadWithDNSRetry()
code := 1
if err != nil {
code = 2
@@ -69,6 +93,40 @@ func SyncDataDownload() {
if 1 == code {
consumeShorthands()
}
+ return
+}
+
+func getSyncCloudLatestID() (ret string) {
+ // 同步感知消息不包含云端提交 ID,需要先读取最新索引,以便和局域网提交提示使用同一个去重键。
+ repo, err := newSyncRepository()
+ if nil != err {
+ logging.LogWarnf("create repo before perceived sync failed: %s", err)
+ return
+ }
+ latest, err := repo.GetCloudLatest(map[string]interface{}{})
+ if nil != err {
+ logging.LogWarnf("get cloud latest before perceived sync failed: %s", err)
+ return
+ }
+ if nil != latest {
+ ret = latest.ID
+ }
+ return
+}
+
+func completeCurrentSyncRemoteRequest(scope string) {
+ // 完整同步可能在合并本地变更后生成新的最新索引,同时记录实际结果可覆盖两类通知到达顺序相反的情况。
+ repo, err := newRepository()
+ if nil != err {
+ logging.LogWarnf("create repo after remote sync failed: %s", err)
+ return
+ }
+ latest, err := repo.Latest()
+ if nil != err {
+ logging.LogWarnf("get local latest after remote sync failed: %s", err)
+ return
+ }
+ syncRemoteRequests.complete(scope, latest.ID)
}
func SyncDataUpload() {
diff --git a/kernel/model/sync_dedup.go b/kernel/model/sync_dedup.go
new file mode 100644
index 0000000000..d6b4cf3d30
--- /dev/null
+++ b/kernel/model/sync_dedup.go
@@ -0,0 +1,134 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "sync"
+ "time"
+)
+
+const syncRemoteCompletedTTL = time.Minute
+
+type syncRemoteKey struct {
+ scope string
+ latestID string
+}
+
+type syncRemoteCall struct {
+ done chan struct{}
+ success bool
+}
+
+type syncRemoteDeduper struct {
+ lock sync.Mutex
+ running map[syncRemoteKey]*syncRemoteCall
+ completed map[syncRemoteKey]time.Time
+ ttl time.Duration
+ now func() time.Time
+}
+
+func newSyncRemoteDeduper(ttl time.Duration) *syncRemoteDeduper {
+ return &syncRemoteDeduper{
+ running: map[syncRemoteKey]*syncRemoteCall{},
+ completed: map[syncRemoteKey]time.Time{},
+ ttl: ttl,
+ now: time.Now,
+ }
+}
+
+// do 将同一同步作用域和云端提交的并发请求合并为一次,失败时允许等待中的请求接替重试。
+func (deduper *syncRemoteDeduper) do(scope, latestID string, action func() error) (executed bool, err error) {
+ key := syncRemoteKey{scope: scope, latestID: latestID}
+ for {
+ call, owner, completed := deduper.begin(key)
+ if completed {
+ return false, nil
+ }
+ if !owner {
+ <-call.done
+ if call.success {
+ return false, nil
+ }
+ continue
+ }
+
+ success := false
+ func() {
+ defer func() {
+ deduper.finish(key, call, success)
+ }()
+ err = action()
+ success = nil == err
+ }()
+ return true, err
+ }
+}
+
+func (deduper *syncRemoteDeduper) begin(key syncRemoteKey) (call *syncRemoteCall, owner, completed bool) {
+ deduper.lock.Lock()
+ defer deduper.lock.Unlock()
+
+ deduper.pruneCompletedLocked(deduper.now())
+ if _, ok := deduper.completed[key]; ok {
+ return nil, false, true
+ }
+ if call = deduper.running[key]; nil != call {
+ return call, false, false
+ }
+ call = &syncRemoteCall{done: make(chan struct{})}
+ deduper.running[key] = call
+ return call, true, false
+}
+
+func (deduper *syncRemoteDeduper) finish(key syncRemoteKey, call *syncRemoteCall, success bool) {
+ deduper.lock.Lock()
+ delete(deduper.running, key)
+ call.success = success
+ if success {
+ deduper.completed[key] = deduper.now()
+ }
+ close(call.done)
+ deduper.lock.Unlock()
+}
+
+func (deduper *syncRemoteDeduper) isCompleted(scope, latestID string) bool {
+ deduper.lock.Lock()
+ defer deduper.lock.Unlock()
+
+ deduper.pruneCompletedLocked(deduper.now())
+ _, ret := deduper.completed[syncRemoteKey{scope: scope, latestID: latestID}]
+ return ret
+}
+
+func (deduper *syncRemoteDeduper) complete(scope, latestID string) {
+ if "" == latestID {
+ return
+ }
+ deduper.lock.Lock()
+ deduper.completed[syncRemoteKey{scope: scope, latestID: latestID}] = deduper.now()
+ deduper.lock.Unlock()
+}
+
+func (deduper *syncRemoteDeduper) pruneCompletedLocked(now time.Time) {
+ for completedKey, completedAt := range deduper.completed {
+ if now.Sub(completedAt) >= deduper.ttl {
+ delete(deduper.completed, completedKey)
+ }
+ }
+}
+
+var syncRemoteRequests = newSyncRemoteDeduper(syncRemoteCompletedTTL)
diff --git a/kernel/model/sync_dedup_test.go b/kernel/model/sync_dedup_test.go
new file mode 100644
index 0000000000..40d6414db9
--- /dev/null
+++ b/kernel/model/sync_dedup_test.go
@@ -0,0 +1,167 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestSyncRemoteDeduperCoalescesConcurrentRequests(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ started := make(chan struct{})
+ release := make(chan struct{})
+ firstDone := make(chan error, 1)
+ secondDone := make(chan error, 1)
+ var firstRuns, secondRuns atomic.Int32
+
+ go func() {
+ _, err := deduper.do("scope", "latest", func() error {
+ firstRuns.Add(1)
+ close(started)
+ <-release
+ return nil
+ })
+ firstDone <- err
+ }()
+ <-started
+ go func() {
+ _, err := deduper.do("scope", "latest", func() error {
+ secondRuns.Add(1)
+ return nil
+ })
+ secondDone <- err
+ }()
+ close(release)
+
+ if err := <-firstDone; nil != err {
+ t.Fatalf("first request failed: %s", err)
+ }
+ if err := <-secondDone; nil != err {
+ t.Fatalf("second request failed: %s", err)
+ }
+ if 1 != firstRuns.Load() || 0 != secondRuns.Load() {
+ t.Fatalf("unexpected action counts [first=%d, second=%d]", firstRuns.Load(), secondRuns.Load())
+ }
+}
+
+func TestSyncRemoteDeduperRetriesAfterFailure(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ expected := errors.New("sync failed")
+ executed, err := deduper.do("scope", "latest", func() error {
+ return expected
+ })
+ if !executed || !errors.Is(err, expected) {
+ t.Fatalf("unexpected first result [executed=%t, err=%v]", executed, err)
+ }
+
+ executed, err = deduper.do("scope", "latest", func() error {
+ return nil
+ })
+ if !executed || nil != err {
+ t.Fatalf("unexpected retry result [executed=%t, err=%v]", executed, err)
+ }
+}
+
+func TestSyncRemoteDeduperSeparatesScopeAndLatest(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ var runs atomic.Int32
+ action := func() error {
+ runs.Add(1)
+ return nil
+ }
+
+ for _, request := range []syncRemoteKey{
+ {scope: "scope-a", latestID: "latest-a"},
+ {scope: "scope-a", latestID: "latest-b"},
+ {scope: "scope-b", latestID: "latest-a"},
+ } {
+ executed, err := deduper.do(request.scope, request.latestID, action)
+ if !executed || nil != err {
+ t.Fatalf("unexpected result for [%+v] [executed=%t, err=%v]", request, executed, err)
+ }
+ }
+ if 3 != runs.Load() {
+ t.Fatalf("unexpected action count [%d]", runs.Load())
+ }
+}
+
+func TestSyncRemoteDeduperExpiresCompletedRequest(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ now := time.Unix(100, 0)
+ deduper.now = func() time.Time {
+ return now
+ }
+ var runs atomic.Int32
+ action := func() error {
+ runs.Add(1)
+ return nil
+ }
+
+ if executed, err := deduper.do("scope", "latest", action); !executed || nil != err {
+ t.Fatalf("unexpected first result [executed=%t, err=%v]", executed, err)
+ }
+ if executed, err := deduper.do("scope", "latest", action); executed || nil != err {
+ t.Fatalf("unexpected cached result [executed=%t, err=%v]", executed, err)
+ }
+ now = now.Add(time.Minute)
+ if executed, err := deduper.do("scope", "latest", action); !executed || nil != err {
+ t.Fatalf("unexpected expired result [executed=%t, err=%v]", executed, err)
+ }
+ if 2 != runs.Load() {
+ t.Fatalf("unexpected action count [%d]", runs.Load())
+ }
+}
+
+func TestSyncRemoteDeduperCompletesActualLatest(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ executed, err := deduper.do("scope", "hinted-latest", func() error {
+ deduper.complete("scope", "actual-latest")
+ return nil
+ })
+ if !executed || nil != err {
+ t.Fatalf("unexpected hinted result [executed=%t, err=%v]", executed, err)
+ }
+
+ executed, err = deduper.do("scope", "actual-latest", func() error {
+ return nil
+ })
+ if executed || nil != err {
+ t.Fatalf("unexpected actual result [executed=%t, err=%v]", executed, err)
+ }
+}
+
+func TestSyncRemoteDeduperReleasesRequestAfterPanic(t *testing.T) {
+ deduper := newSyncRemoteDeduper(time.Minute)
+ func() {
+ defer func() {
+ _ = recover()
+ }()
+ _, _ = deduper.do("scope", "latest", func() error {
+ panic("sync panic")
+ })
+ }()
+
+ executed, err := deduper.do("scope", "latest", func() error {
+ return nil
+ })
+ if !executed || nil != err {
+ t.Fatalf("unexpected result after panic [executed=%t, err=%v]", executed, err)
+ }
+}