Skip to content

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

:bug: Preserve asset events and schedule sync for replacements https://github.com/siyuan-note/siyuan/issues/20863

Daniel98f3c070117d
diff --git a/kernel/cache/asset.go b/kernel/cache/asset.go
index 18c945099a..e86210e351 100644
--- a/kernel/cache/asset.go
+++ b/kernel/cache/asset.go
@@ -79,6 +79,7 @@ func SetAssetHash(hash, path string) {
return
}
+ removeAssetHashByPath(path)
assetHashCache[hash] = &AssetHash{Hash: hash, Path: path}
assetPathHashCache[path] = &AssetHash{Hash: hash, Path: path}
}
diff --git a/kernel/cache/asset_test.go b/kernel/cache/asset_test.go
index a762f12202..1840df4665 100644
--- a/kernel/cache/asset_test.go
+++ b/kernel/cache/asset_test.go
@@ -47,3 +47,17 @@ func TestRemoveAssetHashByPath(t *testing.T) {
}
}
}
+
+func TestSetAssetHashReplacesPath(t *testing.T) {
+ originalHashes, originalPaths := assetHashCache, assetPathHashCache
+ t.Cleanup(func() { assetHashCache, assetPathHashCache = originalHashes, originalPaths })
+ assetHashCache, assetPathHashCache = map[string]*AssetHash{}, map[string]*AssetHash{}
+ SetAssetHash("old-hash", "assets/replaced.png")
+ SetAssetHash("new-hash", "assets/replaced.png")
+ if _, exists := assetHashCache["old-hash"]; exists {
+ t.Fatal("replaced contents retain the old hash")
+ }
+ if asset := assetPathHashCache["assets/replaced.png"]; asset == nil || asset.Hash != "new-hash" {
+ t.Fatalf("new contents were not cached: %v", asset)
+ }
+}
diff --git a/kernel/model/assets_remove_fts5_test.go b/kernel/model/assets_remove_fts5_test.go
index 73b111ade2..170426a888 100644
--- a/kernel/model/assets_remove_fts5_test.go
+++ b/kernel/model/assets_remove_fts5_test.go
@@ -51,7 +51,11 @@ func TestHandleAssetsRemoveEvent(t *testing.T) {
assertIndexed := func(t *testing.T, p string, want bool) {
t.Helper()
rows, err := sql.QueryAssetContentNoLimitArgs("SELECT path FROM asset_contents_fts_case_insensitive WHERE path = ?", p)
- if err != nil || (len(rows) == 1) != want {
+ wantCount := 0
+ if want {
+ wantCount = 1
+ }
+ if err != nil || len(rows) != wantCount {
t.Fatalf("index for %s: rows=%v err=%v, want present=%v", p, rows, err, want)
}
}
diff --git a/kernel/model/assets_watcher.go b/kernel/model/assets_watcher.go
index b4479e9082..bc28cad84b 100644
--- a/kernel/model/assets_watcher.go
+++ b/kernel/model/assets_watcher.go
@@ -26,7 +26,6 @@ import (
"github.com/88250/gulu"
"github.com/fsnotify/fsnotify"
"github.com/siyuan-note/logging"
- "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -61,47 +60,40 @@ func watchAssets() {
return
}
- go func() {
- defer logging.Recover()
-
- var (
- timer *time.Timer
- lastEvent fsnotify.Event
- )
- timer = time.NewTimer(100 * time.Millisecond)
- <-timer.C // timer should be expired at first
-
- for {
- select {
- case event, ok := <-assetsWatcher.Events:
- if !ok {
- return
- }
-
- lastEvent = event
- timer.Reset(time.Millisecond * 100)
- case err, ok := <-assetsWatcher.Errors:
- if !ok {
- return
- }
- logging.LogErrorf("watch assets failed: %s", err)
- case <-timer.C:
- //logging.LogInfof("assets changed: %s", lastEvent)
- if lastEvent.Op&fsnotify.Write == fsnotify.Write {
- IncSync()
- }
+ go watchAssetEvents(assetsWatcher)
+}
- // 重新缓存资源文件,以便使用 /资源 搜索
- go cache.LoadAssets()
+func (batch assetWatchBatch) addFSNotifyEvent(event fsnotify.Event) {
+ const changes = fsnotify.Create | fsnotify.Write | fsnotify.Remove | fsnotify.Rename
+ if event.Op&(changes|fsnotify.Chmod) != 0 {
+ batch.add(event.Name, event.Op&changes != 0)
+ }
+}
- if lastEvent.Op&fsnotify.Remove == fsnotify.Remove {
- HandleAssetsRemoveEvent(lastEvent.Name)
- } else {
- HandleAssetsChangeEvent(lastEvent.Name)
- }
+func watchAssetEvents(watcher *fsnotify.Watcher) {
+ defer logging.Recover()
+ timer := time.NewTimer(100 * time.Millisecond)
+ timer.Stop()
+ defer timer.Stop()
+ batch := assetWatchBatch{}
+ for {
+ select {
+ case event, ok := <-watcher.Events:
+ if !ok {
+ return
}
+ batch.addFSNotifyEvent(event)
+ timer.Reset(100 * time.Millisecond)
+ case err, ok := <-watcher.Errors:
+ if !ok {
+ return
+ }
+ logging.LogErrorf("watch assets failed: %s", err)
+ case <-timer.C:
+ batch.flush()
+ batch = assetWatchBatch{}
}
- }()
+ }
}
func CloseWatchAssets() {
diff --git a/kernel/model/assets_watcher_darwin.go b/kernel/model/assets_watcher_darwin.go
index d1f432156d..9a356e0f92 100644
--- a/kernel/model/assets_watcher_darwin.go
+++ b/kernel/model/assets_watcher_darwin.go
@@ -26,7 +26,6 @@ import (
"github.com/88250/gulu"
"github.com/radovskyb/watcher"
"github.com/siyuan-note/logging"
- "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -55,45 +54,49 @@ func watchAssets() {
return
}
+ watcherInstance := assetsWatcher
go func() {
defer logging.Recover()
for {
select {
- case event, ok := <-assetsWatcher.Event:
+ case event, ok := <-watcherInstance.Event:
if !ok {
return
}
- if watcher.Write == event.Op {
- IncSync()
- }
-
- // 重新缓存资源文件,以便使用 /资源 搜索
- go cache.LoadAssets()
-
- if watcher.Remove == event.Op {
- HandleAssetsRemoveEvent(event.Path)
- } else {
- HandleAssetsChangeEvent(event.Path)
- }
- case err, ok := <-assetsWatcher.Error:
+ batch := assetWatchBatch{}
+ batch.addDarwinEvent(event)
+ batch.flush()
+ case err, ok := <-watcherInstance.Error:
if !ok {
return
}
logging.LogErrorf("watch assets failed: %s", err)
- case <-assetsWatcher.Closed:
+ case <-watcherInstance.Closed:
return
}
}
}()
- if err := assetsWatcher.Start(10 * time.Second); err != nil {
+ if err := watcherInstance.Start(10 * time.Second); err != nil {
logging.LogErrorf("start assets watcher for folder [%s] failed: %s", assetsDir, err)
return
}
}
+func (batch assetWatchBatch) addDarwinEvent(event watcher.Event) {
+ switch event.Op {
+ case watcher.Create, watcher.Write, watcher.Remove:
+ batch.add(event.Path, true)
+ case watcher.Rename, watcher.Move:
+ batch.add(event.OldPath, true)
+ batch.add(event.Path, true)
+ case watcher.Chmod:
+ batch.add(event.Path, false)
+ }
+}
+
func CloseWatchAssets() {
if nil != assetsWatcher {
assetsWatcher.Close()
diff --git a/kernel/model/assets_watcher_darwin_test.go b/kernel/model/assets_watcher_darwin_test.go
new file mode 100644
index 0000000000..56c7961103
--- /dev/null
+++ b/kernel/model/assets_watcher_darwin_test.go
@@ -0,0 +1,40 @@
+//go:build darwin
+
+package model
+
+import (
+ "testing"
+
+ "github.com/radovskyb/watcher"
+)
+
+func TestAssetWatcherDarwinEventBatch(t *testing.T) {
+ for _, op := range []watcher.Op{watcher.Create, watcher.Write, watcher.Remove} {
+ t.Run(op.String(), func(t *testing.T) {
+ batch := assetWatchBatch{}
+ batch.addDarwinEvent(watcher.Event{Path: "asset", Op: op})
+ if len(batch) != 1 || !batch["asset"] {
+ t.Fatalf("content event did not retain its sync trigger: %v", batch)
+ }
+ })
+ }
+ for _, op := range []watcher.Op{watcher.Rename, watcher.Move} {
+ t.Run(op.String(), func(t *testing.T) {
+ batch := assetWatchBatch{}
+ batch.addDarwinEvent(watcher.Event{OldPath: "old", Path: "new", Op: op})
+ if len(batch) != 2 || !batch["old"] || !batch["new"] {
+ t.Fatalf("renamed resource lost a path: %v", batch)
+ }
+ })
+ }
+ batch := assetWatchBatch{}
+ batch.addDarwinEvent(watcher.Event{Path: "metadata", Op: watcher.Chmod})
+ if changed, exists := batch["metadata"]; !exists || changed {
+ t.Fatalf("metadata-only event changed sync scheduling: %v", batch)
+ }
+ batch.addDarwinEvent(watcher.Event{Path: "asset", Op: watcher.Write})
+ batch.addDarwinEvent(watcher.Event{Path: "asset", Op: watcher.Chmod})
+ if !batch["asset"] {
+ t.Fatal("metadata change discarded a content change")
+ }
+}
diff --git a/kernel/model/assets_watcher_events.go b/kernel/model/assets_watcher_events.go
new file mode 100644
index 0000000000..8a8f89e5e9
--- /dev/null
+++ b/kernel/model/assets_watcher_events.go
@@ -0,0 +1,51 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// assetWatchBatch 按路径保留事件,并记录是否需要重新安排同步。
+type assetWatchBatch map[string]bool
+
+func (batch assetWatchBatch) add(path string, changed bool) {
+ if path != "" {
+ batch[path] = batch[path] || changed
+ }
+}
+
+func (batch assetWatchBatch) flush() {
+ if len(batch) == 0 {
+ return
+ }
+ needSync := false
+ for path, changed := range batch {
+ if strings.HasPrefix(filepath.Base(path), ".") || util.IsOfficeTempFile(path) || strings.HasSuffix(path, ".tmp") {
+ continue
+ }
+ info, err := os.Stat(path)
+ if info != nil && filelock.IsHidden(path) {
+ continue
+ }
+ needSync = needSync || changed
+ if os.IsNotExist(err) {
+ HandleAssetsRemoveEvent(path)
+ } else if err != nil {
+ logging.LogErrorf("stat changed asset [%s] failed: %s", path, err)
+ } else {
+ // 原路径可能已经被新文件替换,按处理时的最终状态更新索引和缓存。
+ HandleAssetsChangeEvent(path)
+ }
+ }
+ if needSync {
+ IncSync()
+ }
+ // 每批只刷新一次资源列表,以便使用 /资源 搜索。
+ cache.LoadAssets()
+}
diff --git a/kernel/model/assets_watcher_fts5_test.go b/kernel/model/assets_watcher_fts5_test.go
new file mode 100644
index 0000000000..75b2a82900
--- /dev/null
+++ b/kernel/model/assets_watcher_fts5_test.go
@@ -0,0 +1,152 @@
+//go:build fts5 && !darwin
+
+package model
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAssetWatcherFileEvents(t *testing.T) {
+ const childEnv = "SIYUAN_TEST_ASSET_WATCHER_EVENTS"
+ if os.Getenv(childEnv) == "" {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestAssetWatcherFileEvents$", "-test.v", "-test.timeout=60s")
+ cmd.Env = append(os.Environ(), childEnv+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("%v\n%s", err, output)
+ }
+ return
+ }
+ setupFileOperationTest(t)
+ util.TempDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ assetsDir := filepath.Join(util.DataDir, "assets")
+ if err := os.MkdirAll(assetsDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ write := func(p, content string) {
+ t.Helper()
+ if err := os.WriteFile(p, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ indexed := func(name, content string) bool {
+ sql.FlushAssetContentQueue()
+ rows, err := sql.QueryAssetContentNoLimitArgs("SELECT path FROM asset_contents_fts_case_insensitive WHERE path = ? AND content = ?", "assets/"+name, content)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return len(rows) > 0
+ }
+ waitFor := func(name string, condition func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if condition() {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("timed out waiting for %s", name)
+ }
+ for _, name := range []string{"existing.txt", "removed-a.txt", "removed-b.txt", "photo.png"} {
+ p := filepath.Join(assetsDir, name)
+ write(p, "old contents")
+ HandleAssetsChangeEvent(p)
+ }
+ sql.FlushAssetContentQueue()
+ thumbnail := filepath.Join(util.TempDir, "thumbnails", "assets", "photo.png")
+ if err := os.MkdirAll(filepath.Dir(thumbnail), 0755); err != nil {
+ t.Fatal(err)
+ }
+ write(thumbnail, "cached image")
+ cache.LoadAssets()
+
+ // 属性变化和临时文件不应把同步计划视为内容变更。
+ revision := pendingSync.begin()
+ batch := assetWatchBatch{}
+ batch.add(filepath.Join(assetsDir, "existing.txt"), false)
+ batch.add(filepath.Join(assetsDir, ".hidden.txt"), true)
+ batch.add(filepath.Join(assetsDir, "~$office.txt"), true)
+ batch.add(filepath.Join(assetsDir, "save.tmp"), true)
+ batch.flush()
+ if pendingSync.begin() != revision {
+ t.Fatal("metadata or temporary paths scheduled sync")
+ }
+
+ watchAssets()
+ t.Cleanup(CloseWatchAssets)
+ staging := t.TempDir()
+ staged := filepath.Join(staging, "incoming.txt")
+ write(staged, "new contents")
+ planSyncAfter(time.Hour)
+ revision = pendingSync.begin()
+ if err := os.Rename(staged, filepath.Join(assetsDir, "created.txt")); err != nil {
+ t.Fatal(err)
+ }
+ waitFor("create-only event to schedule sync and index contents", func() bool {
+ return pendingSync.begin() > revision && cache.ExistAsset("assets/created.txt") && indexed("created.txt", "new contents")
+ })
+ syncPlanTimeLock.Lock()
+ planned := syncPlanTime
+ syncPlanTimeLock.Unlock()
+ if !planned.Before(time.Now().Add(time.Minute)) {
+ t.Fatal("asset creation did not advance the sync plan")
+ }
+
+ revision = pendingSync.begin()
+ if err := os.Rename(filepath.Join(assetsDir, "created.txt"), filepath.Join(assetsDir, "renamed.txt")); err != nil {
+ t.Fatal(err)
+ }
+ waitFor("rename to clean the old path and index the new path", func() bool {
+ return pendingSync.begin() > revision && !cache.ExistAsset("assets/created.txt") &&
+ cache.ExistAsset("assets/renamed.txt") && !indexed("created.txt", "new contents") && indexed("renamed.txt", "new contents")
+ })
+
+ existing := filepath.Join(assetsDir, "existing.txt")
+ oldHash, err := util.GetEtag(existing)
+ if err != nil {
+ t.Fatal(err)
+ }
+ write(staged, "replacement contents")
+ revision = pendingSync.begin()
+ if err = os.Remove(existing); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Rename(staged, existing); err != nil {
+ t.Fatal(err)
+ }
+ waitFor("replacement to index final contents", func() bool {
+ return pendingSync.begin() > revision && indexed("existing.txt", "replacement contents")
+ })
+ if cached := cache.GetAssetHash(oldHash); cached != nil && cached.Path == "assets/existing.txt" {
+ t.Fatal("replacement retains the original contents' hash")
+ }
+
+ revision = pendingSync.begin()
+ for _, name := range []string{"removed-a.txt", "removed-b.txt", "photo.png"} {
+ if err = os.Remove(filepath.Join(assetsDir, name)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ waitFor("consecutive deletions to clean every path and schedule sync", func() bool {
+ _, thumbnailErr := os.Stat(thumbnail)
+ return pendingSync.begin() > revision && !cache.ExistAsset("assets/removed-a.txt") &&
+ !cache.ExistAsset("assets/removed-b.txt") && !cache.ExistAsset("assets/photo.png") && !indexed("removed-a.txt", "old contents") &&
+ !indexed("removed-b.txt", "old contents") && os.IsNotExist(thumbnailErr)
+ })
+}
diff --git a/kernel/model/assets_watcher_test.go b/kernel/model/assets_watcher_test.go
new file mode 100644
index 0000000000..a6dd6365a5
--- /dev/null
+++ b/kernel/model/assets_watcher_test.go
@@ -0,0 +1,33 @@
+//go:build !darwin
+
+package model
+
+import (
+ "testing"
+
+ "github.com/fsnotify/fsnotify"
+)
+
+func TestAssetWatcherEventBatch(t *testing.T) {
+ for _, op := range []fsnotify.Op{fsnotify.Create, fsnotify.Write, fsnotify.Rename, fsnotify.Remove,
+ fsnotify.Write | fsnotify.Remove, fsnotify.Create | fsnotify.Chmod} {
+ t.Run(op.String(), func(t *testing.T) {
+ batch := assetWatchBatch{}
+ batch.addFSNotifyEvent(fsnotify.Event{Name: "asset", Op: op})
+ if len(batch) != 1 || !batch["asset"] {
+ t.Fatalf("content event did not retain its sync trigger: %v", batch)
+ }
+ })
+ }
+ batch := assetWatchBatch{}
+ batch.addFSNotifyEvent(fsnotify.Event{Name: "metadata", Op: fsnotify.Chmod})
+ if changed, exists := batch["metadata"]; !exists || changed {
+ t.Fatalf("metadata-only event changed sync scheduling: %v", batch)
+ }
+ batch.addFSNotifyEvent(fsnotify.Event{Name: "first", Op: fsnotify.Write})
+ batch.addFSNotifyEvent(fsnotify.Event{Name: "first", Op: fsnotify.Chmod})
+ batch.addFSNotifyEvent(fsnotify.Event{Name: "second", Op: fsnotify.Remove})
+ if len(batch) != 3 || !batch["first"] || !batch["second"] {
+ t.Fatalf("later events discarded an earlier path or sync trigger: %v", batch)
+ }
+}