Skip to content

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

:bug: Preserve flash shorthands until documents are persisted https://github.com/siyuan-note/siyuan/issues/19040

Danielf3020db169e3
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 63e312cec9..7d3e73ab63 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -2391,6 +2391,14 @@ func cleanBoxDocDir(p string) string {
}
func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree, err error) {
+ return createDoc0(boxID, p, title, dom, titleEmpty, false)
+}
+
+func createDocSync(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree, err error) {
+ return createDoc0(boxID, p, title, dom, titleEmpty, true)
+}
+
+func createDoc0(boxID, p, title, dom string, titleEmpty, syncWrite bool) (tree *parse.Tree, err error) {
validation, err := validateCreateDoc(boxID, p, title, titleEmpty)
if nil != err {
return
@@ -2451,7 +2459,20 @@ func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree,
unlink.Unlink()
}
+ err = performCreateDocTransaction(tree, syncWrite)
+ return
+}
+
+func performCreateDocTransaction(tree *parse.Tree, syncWrite bool) (err error) {
transaction := &Transaction{DoOperations: []*Operation{{Action: "create", Data: tree}}}
+ if syncWrite {
+ if err = PerformTxSync(transaction); nil != err {
+ // 事务在写文件前会更新块树,失败时清理未落盘文档的索引。
+ treenode.RemoveBlockTreesByRootID(tree.Box, tree.ID)
+ return
+ }
+ return
+ }
PerformTransactions(&[]*Transaction{transaction})
FlushTxQueue()
return
diff --git a/kernel/model/file_test.go b/kernel/model/file_test.go
index d1bf2f1566..9f75e77dec 100644
--- a/kernel/model/file_test.go
+++ b/kernel/model/file_test.go
@@ -619,6 +619,24 @@ func TestCreateDocsByHPathKeepsHPathFallbackForDifferentParent(t *testing.T) {
}
}
+func TestPerformCreateDocTransactionSyncReturnsWriteError(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ docID := "20260718000009-abcdefg"
+ tree := treenode.NewTree(fixture.box.ID, "/"+docID+".sy", "/Shorthand", "Shorthand")
+ treenode.UpsertBlockTree(tree)
+ if bt := treenode.GetBlockTree(docID); nil == bt {
+ t.Fatalf("test document block tree [%s] not found before write", docID)
+ }
+ tree.Path = "/\x00/" + docID + ".sy"
+
+ if err := performCreateDocTransaction(tree, true); nil == err {
+ t.Fatal("expected synchronous document creation to return the write error")
+ }
+ if bt := treenode.GetBlockTree(docID); nil != bt {
+ t.Fatalf("failed document block tree [%s] was not removed", docID)
+ }
+}
+
func TestGetBoxesByPathsStrictRejectsInvalidPaths(t *testing.T) {
fixture := setupFileOperationTest(t)
tests := []struct {
diff --git a/kernel/model/path.go b/kernel/model/path.go
index f410be95e2..fa7b42a627 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -34,6 +34,15 @@ import (
)
func createDocsByHPath(boxID, hPath, content, parentID, id string, titleEmpty bool) (retID string, err error) {
+ return createDocsByHPath0(boxID, hPath, content, parentID, id, titleEmpty, createDoc)
+}
+
+func createDocsByHPathSync(boxID, hPath, content, parentID, id string, titleEmpty bool) (retID string, err error) {
+ return createDocsByHPath0(boxID, hPath, content, parentID, id, titleEmpty, createDocSync)
+}
+
+func createDocsByHPath0(boxID, hPath, content, parentID, id string, titleEmpty bool,
+ createDocFn func(boxID, p, title, dom string, titleEmpty bool) (*parse.Tree, error)) (retID string, err error) {
if "" == id {
id = ast.NewNodeID()
}
@@ -53,7 +62,7 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string, titleEmpty bo
if nil != preferredParent && preferredParent.RootID == parentID {
// 如果父文档存在且 ID 一致,则直接在父文档下创建
p := strings.TrimSuffix(preferredParent.Path, ".sy") + "/" + id + ".sy"
- if _, err = createDoc(boxID, p, name, content, titleEmpty); err != nil {
+ if _, err = createDocFn(boxID, p, name, content, titleEmpty); err != nil {
logging.LogErrorf("create doc [%s] failed: %s", p, err)
}
return
@@ -99,11 +108,11 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string, titleEmpty bo
pathBuilder.WriteString(rootID)
docP := pathBuilder.String() + ".sy"
if isNotLast {
- if _, err = createDoc(boxID, docP, part, "", false); err != nil {
+ if _, err = createDocFn(boxID, docP, part, "", false); err != nil {
return
}
} else {
- if _, err = createDoc(boxID, docP, part, content, titleEmpty); err != nil {
+ if _, err = createDocFn(boxID, docP, part, content, titleEmpty); err != nil {
return
}
}
diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.go
index 3dfef53dd5..946d95d6d3 100644
--- a/kernel/model/shortcuts.go
+++ b/kernel/model/shortcuts.go
@@ -19,6 +19,7 @@ package model
import (
"bytes"
"errors"
+ "fmt"
"os"
"path"
"path/filepath"
@@ -32,6 +33,7 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -41,6 +43,11 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
if !gulu.File.IsDir(shorthandsDir) {
return
}
+ if !syncLock.TryLock() {
+ err = errors.New(Conf.Language(222))
+ return
+ }
+ defer syncLock.Unlock()
entries, err := os.ReadDir(shorthandsDir)
if nil != err {
@@ -289,15 +296,13 @@ func createShorthandDocByDOM(boxID, hPath, dom, docID string) (retID string, err
}
FlushTxQueue()
- retID, err = createDocsByHPath(box.ID, hPath, dom, "", docID, false)
+ retID, err = createDocsByHPathSync(box.ID, hPath, dom, "", docID, false)
if nil != err {
return
}
- FlushTxQueue()
bt := treenode.GetBlockTree(retID)
- if nil == bt {
- logging.LogWarnf("get block tree by id [%s] failed after create", retID)
+ if err = verifyShorthandDocPersisted(bt, retID); nil != err {
return
}
box.setSortByConf(path.Dir(bt.Path), retID)
@@ -307,6 +312,22 @@ func createShorthandDocByDOM(boxID, hPath, dom, docID string) (retID string, err
return
}
+func verifyShorthandDocPersisted(bt *treenode.BlockTree, expectedID string) (err error) {
+ if nil == bt {
+ return fmt.Errorf("get block tree by id [%s] failed after create", expectedID)
+ }
+ // 清除写入缓存,确保从文件系统重新读取并验证文档。
+ cache.RemoveTreeDataInBox(expectedID, bt.BoxID)
+ persisted, err := loadTreeByBlockTree(bt)
+ if nil != err {
+ return fmt.Errorf("load created shorthand document [%s] failed: %w", expectedID, err)
+ }
+ if nil == persisted || persisted.ID != expectedID {
+ return fmt.Errorf("verify created shorthand document [%s] failed", expectedID)
+ }
+ return nil
+}
+
var consumeShorthandsLock = sync.Mutex{}
var shorthandSaveBoxUnavailableNotified bool
@@ -340,6 +361,9 @@ func consumeShorthands() {
if !util.IsMobileContainer() {
return
}
+ if isSyncing.Load() {
+ return
+ }
// 消费速记涉及读取临时文件、创建/追加文档、删除临时文件等非原子操作,
// 启动同步、同步流程、定时任务都可能并发调用,这里串行化避免重复消费或丢失
diff --git a/kernel/model/shortcuts_test.go b/kernel/model/shortcuts_test.go
index c51569e044..8d55243dec 100644
--- a/kernel/model/shortcuts_test.go
+++ b/kernel/model/shortcuts_test.go
@@ -16,7 +16,14 @@
package model
-import "testing"
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
func TestSelectShorthandSaveBox(t *testing.T) {
boxes := []*Box{
@@ -57,3 +64,48 @@ func TestSelectShorthandSaveBoxSkipsUserGuide(t *testing.T) {
t.Fatalf("no shorthand box should be selected: %v", got)
}
}
+
+func TestMoveLocalShorthandsKeepsSourceWhileSyncing(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Lang = "en"
+ originalShortcutsPath := util.ShortcutsPath
+ util.ShortcutsPath = t.TempDir()
+ t.Cleanup(func() {
+ util.ShortcutsPath = originalShortcutsPath
+ })
+
+ shorthandsDir := filepath.Join(util.ShortcutsPath, "shorthands")
+ if err := os.MkdirAll(shorthandsDir, 0755); nil != err {
+ t.Fatalf("create shorthand directory failed: %v", err)
+ }
+ shorthandPath := filepath.Join(shorthandsDir, "1788062238740.md")
+ if err := os.WriteFile(shorthandPath, []byte("retained shorthand"), 0644); nil != err {
+ t.Fatalf("write shorthand file failed: %v", err)
+ }
+
+ syncLock.Lock()
+ _, err := MoveLocalShorthands(fixture.box.ID)
+ syncLock.Unlock()
+ if nil == err {
+ t.Fatal("expected shorthand move to pause while syncing")
+ }
+ if _, statErr := os.Stat(shorthandPath); nil != statErr {
+ t.Fatalf("shorthand source was not retained: %v", statErr)
+ }
+}
+
+func TestVerifyShorthandDocPersisted(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ bt := treenode.GetBlockTree(fixture.sourceID)
+ if err := verifyShorthandDocPersisted(bt, fixture.sourceID); nil != err {
+ t.Fatalf("verify persisted shorthand document failed: %v", err)
+ }
+
+ docPath := filepath.Join(util.DataDir, fixture.box.ID, bt.Path)
+ if err := os.Remove(docPath); nil != err {
+ t.Fatalf("remove persisted document failed: %v", err)
+ }
+ if err := verifyShorthandDocPersisted(bt, fixture.sourceID); nil == err {
+ t.Fatal("expected missing persisted shorthand document to fail verification")
+ }
+}
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 899c87bb17..e6d1cc8311 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -63,9 +63,9 @@ func FlushTxQueue() {
}
}
-// PerformTxSync 同步执行单笔事务并返回错误,供 undo/redo 重放使用。
+// PerformTxSync 同步执行单笔事务并返回错误,供需要获知落盘结果的调用方使用。
// 与异步入队的 PerformTransactions 不同,这里直接持有 flushLock 串行执行 performTx,
-// 失败时返回原始错误(不转成推送消息),调用方据此回滚撤销栈状态。
+// 失败时返回原始错误(不转成推送消息),调用方可以保留待处理数据或回滚状态。
func PerformTxSync(tx *Transaction) (err error) {
defer logging.Recover()
flushLock.Lock()