Skip to content

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

:art: Improve handling of deleted notebook remnants after data synchronization https://github.com/siyuan-note/siyuan/issues/19102

Daniel90ed7fb4956e
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 219b5f988b..746c20c250 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -94,6 +94,13 @@ func StatJob() {
}
func ListNotebooks() (ret []*Box, err error) {
+ // 启用数据同步时,缺失配置可能表示其他设备已删除笔记本,不能在列表读取过程中自动重建。
+ repairMissingConf := nil != Conf && nil != Conf.Sync && !Conf.Sync.Enabled
+ ret, err = listNotebooks(repairMissingConf)
+ return
+}
+
+func listNotebooks(repairMissingConf bool) (ret []*Box, err error) {
ret = []*Box{}
dirs, err := os.ReadDir(util.DataDir)
if err != nil {
@@ -119,7 +126,6 @@ func ListNotebooks() (ret []*Box, err error) {
boxConfPath := filepath.Join(boxDirPath, ".siyuan", "conf.json")
isExistConf := filelock.IsExist(boxConfPath)
missingEncryptedIdentity := false
- repairLockHeld := false
if !isExistConf {
if !IsUserGuide(id) {
// conf.json 缺失时检查加密备份,确认是否为加密笔记本
@@ -147,19 +153,16 @@ func ListNotebooks() (ret []*Box, err error) {
setEncryptedBoxState(id, EncryptedBoxStateError)
logging.LogErrorf("encrypted notebook key identity is missing [%s]", boxDirPath)
} else {
- if !syncLock.TryLock() {
- logging.LogWarnf("deferred repairing box without conf while sync lock is occupied [%s]", boxDirPath)
+ if !repairMissingConf {
+ logging.LogWarnf("ignored a box without conf because automatic repair is disabled [%s]", boxDirPath)
continue
}
- repairLockHeld = true
hasDocuments, scanErr := hasLiveBoxDocuments(boxDirPath)
if scanErr != nil {
- syncLock.Unlock()
logging.LogErrorf("scan box without conf [%s] failed: %s", boxDirPath, scanErr)
continue
}
if !hasDocuments {
- syncLock.Unlock()
logging.LogWarnf("ignored a box without conf and documents [%s]", boxDirPath)
continue
}
@@ -234,15 +237,12 @@ func ListNotebooks() (ret []*Box, err error) {
if !isExistConf && !missingEncryptedIdentity {
// Automatically create notebook conf.json if not found it https://github.com/siyuan-note/siyuan/issues/9647
- if err := box.SaveConf(boxConf); err != nil {
- logging.LogErrorf("save box conf [%s] failed: %s", boxDirPath, err)
+ if saveErr := box.SaveConf(boxConf); saveErr != nil {
+ logging.LogErrorf("save box conf [%s] failed: %s", boxDirPath, saveErr)
}
box.Unindex()
logging.LogWarnf("fixed a corrupted box [%s]", boxDirPath)
}
- if repairLockHeld {
- syncLock.Unlock()
- }
ret = append(ret, box)
}
diff --git a/kernel/model/box_list_test.go b/kernel/model/box_list_test.go
index f939df6846..c0f56a9c38 100644
--- a/kernel/model/box_list_test.go
+++ b/kernel/model/box_list_test.go
@@ -31,6 +31,8 @@ func TestListNotebooksIgnoresBoxWithoutConfAndDocuments(t *testing.T) {
Conf = NewAppConf()
Conf.FileTree = conf.NewFileTree()
Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ Conf.Sync.Enabled = true
t.Cleanup(func() {
Conf, util.DataDir = oldConf, oldDataDir
})
@@ -65,12 +67,14 @@ func TestListNotebooksIgnoresBoxWithoutConfAndDocuments(t *testing.T) {
}
}
-func TestListNotebooksDefersRepairWhileSyncLockIsOccupied(t *testing.T) {
+func TestListNotebooksDoesNotRepairBoxWithDocuments(t *testing.T) {
oldConf, oldDataDir := Conf, util.DataDir
util.DataDir = t.TempDir()
Conf = NewAppConf()
Conf.FileTree = conf.NewFileTree()
Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ Conf.Sync.Enabled = true
t.Cleanup(func() {
Conf, util.DataDir = oldConf, oldDataDir
})
@@ -84,18 +88,16 @@ func TestListNotebooksDefersRepairWhileSyncLockIsOccupied(t *testing.T) {
t.Fatal(err)
}
- syncLock.Lock()
boxes, err := ListNotebooks()
- syncLock.Unlock()
if err != nil {
t.Fatal(err)
}
if 0 != len(boxes) {
- t.Fatalf("expected box repair to be deferred, got %+v", boxes)
+ t.Fatalf("expected box repair to require an explicit lifecycle step, got %+v", boxes)
}
confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
if _, err = os.Stat(confPath); !os.IsNotExist(err) {
- t.Fatalf("expected notebook conf not to be recreated while syncing: %v", err)
+ t.Fatalf("expected notebook conf not to be recreated while listing: %v", err)
}
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 7371d19425..da35b801ff 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -548,9 +548,6 @@ func InitConf() {
if nil == Conf.Onboarding {
Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}
}
- if boxes, listErr := ListNotebooks(); listErr == nil {
- prepareOnboardingForEmptyWorkspace(Conf.Onboarding, util.ReadOnly, len(boxes))
- }
if nil == Conf.System.NetworkProxy {
Conf.System.NetworkProxy = &conf.NetworkProxy{}
}
@@ -653,6 +650,9 @@ func InitConf() {
if util.ContainerDocker == util.Container {
Conf.Sync.Perception = false
}
+ if boxes, listErr := ListNotebooks(); listErr == nil {
+ prepareOnboardingForEmptyWorkspace(Conf.Onboarding, util.ReadOnly, len(boxes))
+ }
if nil == Conf.Api {
Conf.Api = conf.NewAPI()
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index e6076cecc9..197d8d4bec 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2015,6 +2015,9 @@ func bootSyncRepo() (err error) {
syncingFiles = sync.Map{}
syncingStorages.Store(false)
+ if 1 > len(fetchedFiles) {
+ cleanupSyncedBoxResiduals(nil)
+ }
for _, fetchedFile := range fetchedFiles {
name := path.Base(fetchedFile.Path)
if strings.HasSuffix(name, ".sy") {
@@ -2286,6 +2289,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
}
if !mergeResult.DataChanged() { // 没有数据变更
+ cleanupSyncedBoxResiduals(nil)
syncSameCount.Add(1)
if 10 < syncSameCount.Load() {
syncSameCount.Store(5)
@@ -2499,9 +2503,12 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
unindex(boxID)
removedEncryptedBox = true
needUnindexBoxes[boxID] = true
- delete(needIndexBoxes, boxID)
+ } else {
+ forgetRuntimeNormalBox(boxID)
}
+ delete(needIndexBoxes, boxID)
}
+ cleanupSyncedBoxResiduals(removedBoxConfs)
if removedEncryptedBox {
sql.FlushQueue()
}
@@ -2579,6 +2586,73 @@ func removeEmptyPackageDirs(basePath string, dirNames *hashset.Set) {
}
}
+// cleanupSyncedBoxResiduals 备份并删除同步确认移除的笔记本目录,以及不含正文的历史残留目录。
+func cleanupSyncedBoxResiduals(removedBoxIDs map[string]bool) {
+ boxIDs := map[string]bool{}
+ for boxID := range removedBoxIDs {
+ boxIDs[boxID] = true
+ }
+
+ dirs, err := os.ReadDir(util.DataDir)
+ if err != nil {
+ logging.LogErrorf("read data dir before cleaning up synced box residuals failed: %s", err)
+ return
+ }
+ for _, dir := range dirs {
+ boxID := dir.Name()
+ if !dir.IsDir() || !ast.IsNodeIDPattern(boxID) || boxIDs[boxID] {
+ continue
+ }
+ boxDirPath := filepath.Join(util.DataDir, boxID)
+ if filelock.IsExist(filepath.Join(boxDirPath, ".siyuan", "conf.json")) {
+ continue
+ }
+ hasDocuments, scanErr := hasLiveBoxDocuments(boxDirPath)
+ if scanErr != nil {
+ logging.LogErrorf("scan synced box residual [%s] failed: %s", boxDirPath, scanErr)
+ continue
+ }
+ if hasDocuments || IsEncryptedBox(boxID) {
+ continue
+ }
+ boxIDs[boxID] = true
+ }
+
+ var historyDir string
+ for boxID := range boxIDs {
+ if !ast.IsNodeIDPattern(boxID) {
+ continue
+ }
+ boxDirPath := filepath.Join(util.DataDir, boxID)
+ if !filelock.IsExist(boxDirPath) {
+ continue
+ }
+ if !gulu.File.IsDir(boxDirPath) {
+ logging.LogWarnf("refuse to clean up synced box residual because it is not a directory [%s]", boxDirPath)
+ continue
+ }
+
+ if "" == historyDir {
+ var err error
+ historyDir, err = getHistoryDir(HistoryOpDelete)
+ if err != nil {
+ logging.LogErrorf("create history before cleaning up synced box residuals failed: %s", err)
+ return
+ }
+ }
+ historyPath := filepath.Join(historyDir, boxID)
+ if err := filelock.Copy(boxDirPath, historyPath); err != nil {
+ logging.LogErrorf("backup synced box residual [%s] failed: %s", boxDirPath, err)
+ continue
+ }
+ if err := removeBoxDir(boxDirPath); err != nil {
+ logging.LogErrorf("remove synced box residual [%s] failed: %s", boxDirPath, err)
+ continue
+ }
+ logging.LogInfof("removed synced box residual [%s]", boxDirPath)
+ }
+}
+
func appendLANSyncTrafficStat(message string, trafficStat *dejavu.TrafficStat) string {
if nil == Conf.Sync || nil == Conf.Sync.LAN || !Conf.Sync.LAN.Enabled {
return message
diff --git a/kernel/model/repository_sync_test.go b/kernel/model/repository_sync_test.go
index ac28a143eb..cf27e4b46f 100644
--- a/kernel/model/repository_sync_test.go
+++ b/kernel/model/repository_sync_test.go
@@ -22,6 +22,7 @@ import (
"testing"
"github.com/emirpasic/gods/sets/hashset"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestRemoveEmptyPackageDirs(t *testing.T) {
@@ -47,3 +48,68 @@ func TestRemoveEmptyPackageDirs(t *testing.T) {
t.Fatalf("expected non-empty package directory to be preserved: %s", err)
}
}
+
+func TestCleanupSyncedBoxResidualsBacksUpFilesBeforeRemoval(t *testing.T) {
+ oldDataDir, oldHistoryDir := util.DataDir, util.HistoryDir
+ workspaceDir := t.TempDir()
+ util.DataDir = filepath.Join(workspaceDir, "data")
+ util.HistoryDir = filepath.Join(workspaceDir, "history")
+ t.Cleanup(func() {
+ util.DataDir, util.HistoryDir = oldDataDir, oldHistoryDir
+ })
+
+ boxID := "20260903120700-xyzabcd"
+ boxDirPath := filepath.Join(util.DataDir, boxID)
+ docPath := filepath.Join(boxDirPath, "20260903120800-efghijk.sy")
+ if err := os.MkdirAll(filepath.Dir(docPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(docPath, []byte("residual document"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(boxDirPath, ".DS_Store"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ documentlessBoxID := "20260903120900-lmnopqr"
+ documentlessBoxPath := filepath.Join(util.DataDir, documentlessBoxID)
+ if err := os.MkdirAll(filepath.Join(documentlessBoxPath, "20260903121000-stuvwxy"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(documentlessBoxPath, ".DS_Store"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ unconfirmedBoxID := "20260903121100-zabcdef"
+ unconfirmedDocPath := filepath.Join(util.DataDir, unconfirmedBoxID, "20260903121200-ghijklm.sy")
+ if err := os.MkdirAll(filepath.Dir(unconfirmedDocPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(unconfirmedDocPath, []byte("unconfirmed document"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cleanupSyncedBoxResiduals(map[string]bool{boxID: true})
+
+ if _, err := os.Stat(boxDirPath); !os.IsNotExist(err) {
+ t.Fatalf("expected synced box residual to be removed: %v", err)
+ }
+ historyDocs, err := filepath.Glob(filepath.Join(util.HistoryDir, "*-delete", boxID, filepath.Base(docPath)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if 1 != len(historyDocs) {
+ t.Fatalf("expected one residual document backup, got %v", historyDocs)
+ }
+ data, err := os.ReadFile(historyDocs[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if "residual document" != string(data) {
+ t.Fatalf("unexpected residual document backup: %q", data)
+ }
+ if _, err = os.Stat(documentlessBoxPath); !os.IsNotExist(err) {
+ t.Fatalf("expected documentless synced box residual to be removed: %v", err)
+ }
+ if _, err = os.Stat(unconfirmedDocPath); err != nil {
+ t.Fatalf("expected unconfirmed notebook documents to be preserved: %v", err)
+ }
+}