Skip to content

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

:sparkles: Bound Markdown import tree memory with encrypted staging https://github.com/siyuan-note/siyuan/issues/20347

Danieldffea446cb4e
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 32e4a4e1cd..a6c0a3dd1a 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -27,7 +27,6 @@ import (
_ "image/gif"
"image/jpeg"
"image/png"
- "io"
"io/fs"
"maps"
"net/url"
@@ -201,17 +200,6 @@ func importedSYRootIDs(importedDocs []*importedSYSortDoc) (ret []string) {
return
}
-func importedTreeRootIDs(trees []*parse.Tree, parentPath string) (ret []string) {
- for _, tree := range trees {
- if nil == tree || parentPath != path.Dir(tree.Path) {
- continue
- }
- ret = append(ret, tree.ID)
- }
- sort.Strings(ret)
- return
-}
-
func pushDocsImported(boxID, parentPath, format string, rootIDs []string) {
if 1 > len(rootIDs) {
return
@@ -1541,6 +1529,28 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
return
}
+ spool := &markdownImportSpool{searchLinks: map[string]string{}}
+ if gulu.File.IsDir(localPath) {
+ spool, err = newMarkdownImportSpool()
+ if err != nil {
+ return err
+ }
+ }
+ defer spool.close()
+ stagedCount, stagedBytes := 0, 0
+ stageTree := func(tree *parse.Tree) error {
+ if err := spool.add(tree); err != nil {
+ return err
+ }
+ stagedCount++
+ stagedBytes += spool.entries[len(spool.entries)-1].rawSize
+ if stagedCount >= markdownImportBatchDocuments || stagedBytes >= markdownImportBatchBytes {
+ debug.FreeOSMemory()
+ stagedCount, stagedBytes = 0, 0
+ }
+ return nil
+ }
+
hPathsIDs := map[string]string{}
idPaths := map[string]string{}
moveIDs := map[string]string{}
@@ -1549,7 +1559,7 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
targetPaths := map[string]string{}
count := 0
// md 转换 sy
- filelock.Walk(localPath, func(currentPath string, d fs.DirEntry, err error) error {
+ if err = filelock.Walk(localPath, func(currentPath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
@@ -1642,7 +1652,9 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
}
tree = treenode.NewTree(boxID, targetPath, hPath, title)
- importTrees = append(importTrees, tree)
+ if err := stageTree(tree); err != nil {
+ return err
+ }
return nil
}
@@ -1652,8 +1664,7 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
data, readErr := os.ReadFile(currentPath)
if nil != readErr {
- err = readErr
- return io.EOF
+ return readErr
}
tree, yfmRootID, yfmTitle, yfmUpdated := parseStdMd(data, true)
@@ -1777,7 +1788,9 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
})
reassignIDUpdated(tree, id, updated)
- importTrees = append(importTrees, tree)
+ if err := stageTree(tree); err != nil {
+ return err
+ }
hPathsIDs[tree.HPath] = tree.ID
idPaths[tree.ID] = tree.Path
@@ -1787,7 +1800,9 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
util.PushEndlessProgress(fmt.Sprintf(Conf.language(70), fmt.Sprintf("%s", tree.HPath)))
}
return nil
- })
+ }); err != nil {
+ return err
+ }
} else { // 导入单个文件
fileName := filepath.Base(localPath)
if !strings.HasSuffix(fileName, ".md") && !strings.HasSuffix(fileName, ".markdown") {
@@ -1915,35 +1930,38 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
reassignIDUpdated(tree, id, updated)
// 兜底校验:禁止跨加密边界块引(导入的 Markdown 可能含跨边界引用)
degradeCrossBoundaryBlockRefs(tree.Root, tree.Box)
- importTrees = append(importTrees, tree)
+ if err := stageTree(tree); err != nil {
+ return err
+ }
}
var importedRootIDs []string
- if 0 < len(importTrees) {
- for id, newID := range moveIDs {
- for _, importTree := range importTrees {
- importTree.ID = strings.ReplaceAll(importTree.ID, id, newID)
- importTree.Path = strings.ReplaceAll(importTree.Path, id, newID)
+ if len(spool.entries) > 0 {
+ spool.movePaths(moveIDs)
+ for _, entry := range spool.entries {
+ if _, ok := idPaths[entry.id]; ok {
+ idPaths[entry.id] = entry.path
}
}
-
- initSearchLinks()
- convertMdHyperlinks2WikiLinks()
- convertWikiLinksAndTags()
- mergeTextAndHandlerNestedInlines()
-
- for i, tree := range importTrees {
- indexWriteTreeIndexQueue(tree)
- if 0 == i%4 {
- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(66), fmt.Sprintf("%d/%d ", i, len(importTrees))+tree.HPath))
+ i := 0
+ if err = spool.finish(func(tree *parse.Tree) error {
+ if err := indexWriteTreeIndexQueue(tree); err != nil {
+ return err
}
+ if i%4 == 0 {
+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(66), fmt.Sprintf("%d/%d ", i, len(spool.entries))+tree.HPath))
+ }
+ i++
+ return nil
+ }, func() {
+ sql.FlushQueue()
+ debug.FreeOSMemory()
+ }); err != nil {
+ return err
}
refreshBoxDocInfoByBoxID(boxID)
util.PushClearProgress()
-
- importedRootIDs = importedTreeRootIDs(importTrees, baseTargetPath)
- importTrees = []*parse.Tree{}
- searchLinks = map[string]string{}
+ importedRootIDs = spool.rootIDs(baseTargetPath)
// 按照路径排序 Improve sort when importing markdown files https://github.com/siyuan-note/siyuan/issues/11390
var hPaths []string
@@ -2375,84 +2393,71 @@ func domAttrValue(n *html.Node, attrName string) string {
return ""
}
-var importTrees []*parse.Tree
-var searchLinks = map[string]string{}
-
-func initSearchLinks() {
- for _, tree := range importTrees {
- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering || (ast.NodeDocument != n.Type && ast.NodeHeading != n.Type) {
- return ast.WalkContinue
- }
+func addImportSearchLinks(tree *parse.Tree, searchLinks map[string]string) {
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || (ast.NodeDocument != n.Type && ast.NodeHeading != n.Type) {
+ return ast.WalkContinue
+ }
- nodePath := tree.HPath + "#"
- if ast.NodeHeading == n.Type {
- nodePath += n.Text()
- }
+ nodePath := tree.HPath + "#"
+ if ast.NodeHeading == n.Type {
+ nodePath += n.Text()
+ }
- searchLinks[nodePath] = n.ID
- return ast.WalkContinue
- })
- }
+ searchLinks[nodePath] = n.ID
+ return ast.WalkContinue
+ })
}
-func convertMdHyperlinks2WikiLinks() {
+func convertMdHyperlinks2WikiLinks(tree *parse.Tree) {
// Supports converting relative path hyperlinks into document block references after importing Markdown https://github.com/siyuan-note/siyuan/issues/13817
var unlinks []*ast.Node
- for _, tree := range importTrees {
- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering || ast.NodeTextMark != n.Type {
- return ast.WalkContinue
- }
-
- if "a" != n.TextMarkType {
- return ast.WalkContinue
- }
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeTextMark != n.Type {
+ return ast.WalkContinue
+ }
- linkText := n.TextMarkTextContent
- if "" == linkText {
- return ast.WalkContinue
- }
- linkDest := n.TextMarkAHref
- if "" == linkDest {
- return ast.WalkContinue
- }
- if strings.HasPrefix(linkDest, "assets/") {
- return ast.WalkContinue
- }
- if !strings.HasSuffix(linkDest, ".md") && !strings.HasSuffix(linkDest, ".markdown") {
- return ast.WalkContinue
- }
- linkDest = strings.TrimSuffix(linkDest, ".md")
- linkDest = strings.TrimSuffix(linkDest, ".markdown")
+ if "a" != n.TextMarkType {
+ return ast.WalkContinue
+ }
- buf := bytes.Buffer{}
- buf.WriteString("[[")
- buf.WriteString(linkDest)
- buf.WriteString("|")
- buf.WriteString(linkText)
- buf.WriteString("]]")
-
- wikilinkNode := &ast.Node{Type: ast.NodeText, Tokens: buf.Bytes()}
- n.InsertBefore(wikilinkNode)
- unlinks = append(unlinks, n)
+ linkText := n.TextMarkTextContent
+ if "" == linkText {
return ast.WalkContinue
- })
- }
+ }
+ linkDest := n.TextMarkAHref
+ if "" == linkDest {
+ return ast.WalkContinue
+ }
+ if strings.HasPrefix(linkDest, "assets/") {
+ return ast.WalkContinue
+ }
+ if !strings.HasSuffix(linkDest, ".md") && !strings.HasSuffix(linkDest, ".markdown") {
+ return ast.WalkContinue
+ }
+ linkDest = strings.TrimSuffix(linkDest, ".md")
+ linkDest = strings.TrimSuffix(linkDest, ".markdown")
+
+ buf := bytes.Buffer{}
+ buf.WriteString("[[")
+ buf.WriteString(linkDest)
+ buf.WriteString("|")
+ buf.WriteString(linkText)
+ buf.WriteString("]]")
+
+ wikilinkNode := &ast.Node{Type: ast.NodeText, Tokens: buf.Bytes()}
+ n.InsertBefore(wikilinkNode)
+ unlinks = append(unlinks, n)
+ return ast.WalkContinue
+ })
for _, n := range unlinks {
n.Unlink()
}
}
-func convertWikiLinksAndTags() {
- for _, tree := range importTrees {
- convertWikiLinksAndTags0(tree)
- }
-}
-
-func convertWikiLinksAndTags0(tree *parse.Tree) {
+func convertWikiLinksAndTags(tree *parse.Tree, searchLinks map[string]string) {
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || ast.NodeText != n.Type {
return ast.WalkContinue
@@ -2490,7 +2495,7 @@ func convertWikiLinksAndTags0(tree *parse.Tree) {
link += "#" // 在结尾统一带上锚点方便后续查找
}
- id := searchLinkID(link)
+ id := searchLinkID(link, searchLinks)
if "" == id {
start, end = end, length
continue
@@ -2544,7 +2549,7 @@ func convertTags(text string) (ret string) {
return string(tokens)
}
-func searchLinkID(link string) (id string) {
+func searchLinkID(link string, searchLinks map[string]string) (id string) {
id = searchLinks[link]
if "" != id {
return
@@ -2559,37 +2564,33 @@ func searchLinkID(link string) (id string) {
return
}
-func mergeTextAndHandlerNestedInlines() {
- luteEngine := NewLute()
- luteEngine.SetHTMLTag2TextMark(true)
- for _, tree := range importTrees {
- tree.MergeText()
-
- var unlinkTextNodes []*ast.Node
- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering || ast.NodeText != n.Type {
- return ast.WalkContinue
- }
+func mergeTextAndHandlerNestedInlines(tree *parse.Tree, luteEngine *lute.Lute) {
+ tree.MergeText()
- if nil == n.Tokens {
- return ast.WalkContinue
- }
+ var unlinkTextNodes []*ast.Node
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeText != n.Type {
+ return ast.WalkContinue
+ }
- t := parse.Inline("", n.Tokens, luteEngine.ParseOptions) // 使用行级解析
- parse.NestedInlines2FlattedSpans(t, false)
- var children []*ast.Node
- for c := t.Root.FirstChild.FirstChild; nil != c; c = c.Next {
- children = append(children, c)
- }
- for _, c := range children {
- n.InsertBefore(c)
- }
- unlinkTextNodes = append(unlinkTextNodes, n)
+ if nil == n.Tokens {
return ast.WalkContinue
- })
+ }
- for _, node := range unlinkTextNodes {
- node.Unlink()
+ t := parse.Inline("", n.Tokens, luteEngine.ParseOptions) // 使用行级解析
+ parse.NestedInlines2FlattedSpans(t, false)
+ var children []*ast.Node
+ for c := t.Root.FirstChild.FirstChild; nil != c; c = c.Next {
+ children = append(children, c)
+ }
+ for _, c := range children {
+ n.InsertBefore(c)
}
+ unlinkTextNodes = append(unlinkTextNodes, n)
+ return ast.WalkContinue
+ })
+
+ for _, node := range unlinkTextNodes {
+ node.Unlink()
}
}
diff --git a/kernel/model/import_markdown.go b/kernel/model/import_markdown.go
new file mode 100644
index 0000000000..be6938b6b0
--- /dev/null
+++ b/kernel/model/import_markdown.go
@@ -0,0 +1,186 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package model
+
+import (
+ "crypto/rand"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "sort"
+ "strings"
+
+ "github.com/88250/lute/parse"
+ "github.com/88250/lute/render"
+ "github.com/siyuan-note/dataparser"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const markdownImportBatchDocuments = 32
+const markdownImportBatchBytes = 8 * 1024 * 1024
+
+type markdownImportEntry struct {
+ id, box, path, hpath string
+ rootType string
+ hasRootType bool
+ offset int64
+ size, rawSize int
+}
+
+// markdownImportSpool 只在内存中保留路径和链接索引,文档树使用独立会话密钥加密暂存。
+// 临时文件不是恢复数据;来源 Markdown 保持原样,退出导入时关闭文件并清除会话密钥。
+type markdownImportSpool struct {
+ file *os.File
+ key []byte
+ singleTree *parse.Tree
+ entries []markdownImportEntry
+ searchLinks map[string]string
+}
+
+func newMarkdownImportSpool() (*markdownImportSpool, error) {
+ key := make([]byte, 32)
+ if _, err := rand.Read(key); err != nil {
+ return nil, err
+ }
+ file, err := os.CreateTemp(util.TempDir, "markdown-import-*")
+ if err != nil {
+ clear(key)
+ return nil, err
+ }
+ return &markdownImportSpool{file: file, key: key, searchLinks: map[string]string{}}, nil
+}
+
+func (spool *markdownImportSpool) close() {
+ clear(spool.key)
+ if spool.file != nil {
+ spool.file.Close()
+ os.Remove(spool.file.Name())
+ }
+}
+
+func markdownImportAAD(index int) []byte {
+ return []byte(fmt.Sprintf("siyuan/markdown-import/v1/%d", index))
+}
+
+func (spool *markdownImportSpool) add(tree *parse.Tree) error {
+ // 单文件导入只保留这一棵树,不创建临时文件或增加序列化开销。
+ if spool.file == nil {
+ if spool.singleTree != nil {
+ return fmt.Errorf("single-file Markdown import already contains a document")
+ }
+ spool.singleTree = tree
+ spool.entries = append(spool.entries, markdownImportEntry{
+ id: tree.ID, box: tree.Box, path: tree.Path, hpath: tree.HPath,
+ })
+ addImportSearchLinks(tree, spool.searchLinks)
+ return nil
+ }
+ luteEngine := util.NewLute()
+ raw := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()
+ ciphertext, err := util.EncryptWithAAD(spool.key, raw, markdownImportAAD(len(spool.entries)))
+ if err != nil {
+ return err
+ }
+ offset, err := spool.file.Seek(0, io.SeekCurrent)
+ if err != nil {
+ return err
+ }
+ if n, err := spool.file.Write(ciphertext); err != nil {
+ return err
+ } else if n != len(ciphertext) {
+ return io.ErrShortWrite
+ }
+ entry := markdownImportEntry{
+ id: tree.ID, box: tree.Box, path: tree.Path, hpath: tree.HPath,
+ offset: offset, size: len(ciphertext), rawSize: len(raw),
+ }
+ for _, attribute := range tree.Root.KramdownIAL {
+ if attribute[0] == "type" {
+ entry.rootType, entry.hasRootType = attribute[1], true
+ break
+ }
+ }
+ spool.entries = append(spool.entries, entry)
+ addImportSearchLinks(tree, spool.searchLinks)
+ return nil
+}
+
+func (spool *markdownImportSpool) load(index int) (*parse.Tree, error) {
+ if spool.singleTree != nil {
+ return spool.singleTree, nil
+ }
+ entry := spool.entries[index]
+ ciphertext := make([]byte, entry.size)
+ if _, err := spool.file.ReadAt(ciphertext, entry.offset); err != nil {
+ return nil, err
+ }
+ raw, err := util.DecryptWithAAD(spool.key, ciphertext, markdownImportAAD(index))
+ if err != nil {
+ return nil, err
+ }
+ tree, err := dataparser.ParseJSONWithoutFix(raw, util.NewLute().ParseOptions)
+ if err != nil {
+ return nil, err
+ }
+ tree.ID, tree.Box, tree.Path, tree.HPath = entry.id, entry.box, entry.path, entry.hpath
+ // 暂存往返保留来源属性,不将解析器补充的默认文档类型写回来源。
+ if entry.hasRootType {
+ tree.Root.SetIALAttr("type", entry.rootType)
+ } else {
+ tree.Root.RemoveIALAttr("type")
+ }
+ return tree, nil
+}
+
+func (spool *markdownImportSpool) movePaths(moveIDs map[string]string) {
+ for id, newID := range moveIDs {
+ for i := range spool.entries {
+ entry := &spool.entries[i]
+ entry.id = strings.ReplaceAll(entry.id, id, newID)
+ entry.path = strings.ReplaceAll(entry.path, id, newID)
+ }
+ }
+}
+
+func (spool *markdownImportSpool) rootIDs(parentPath string) (ret []string) {
+ for _, entry := range spool.entries {
+ if path.Dir(entry.path) == parentPath {
+ ret = append(ret, entry.id)
+ }
+ }
+ sort.Strings(ret)
+ return
+}
+
+func (spool *markdownImportSpool) finish(write func(*parse.Tree) error, flush func()) error {
+ luteEngine := NewLute()
+ luteEngine.SetHTMLTag2TextMark(true)
+ batchCount, batchBytes := 0, 0
+ defer func() {
+ if batchCount > 0 {
+ flush()
+ }
+ }()
+ for i, entry := range spool.entries {
+ tree, err := spool.load(i)
+ if err != nil {
+ return fmt.Errorf("read Markdown import staging entry %d: %w", i, err)
+ }
+ convertMdHyperlinks2WikiLinks(tree)
+ convertWikiLinksAndTags(tree, spool.searchLinks)
+ mergeTextAndHandlerNestedInlines(tree, luteEngine)
+ if err = write(tree); err != nil {
+ return err
+ }
+ batchCount++
+ batchBytes += entry.rawSize
+ if batchCount >= markdownImportBatchDocuments || batchBytes >= markdownImportBatchBytes {
+ flush()
+ batchCount, batchBytes = 0, 0
+ }
+ }
+ return nil
+}
diff --git a/kernel/model/import_markdown_batch_fts5_test.go b/kernel/model/import_markdown_batch_fts5_test.go
new file mode 100644
index 0000000000..dfa5c25566
--- /dev/null
+++ b/kernel/model/import_markdown_batch_fts5_test.go
@@ -0,0 +1,203 @@
+//go:build fts5 && sqlcipher
+
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
+ const boxID = "20261010000000-batch01"
+ setupExportRelatedTest(t, boxID)
+ Conf.Editor = conf.NewEditor()
+ setupNotebookDocumentImportDatabase(t)
+ t.Cleanup(func() { cache.ClearTreeCache(); cache.ClearDocsIAL(); cache.ClearBlocksIAL() })
+ if encrypted {
+ forgetRuntimeNormalBox(boxID)
+ markRuntimeEncryptedBox(boxID)
+ dek := bytes.Repeat([]byte{0x73}, 32)
+ setDEKForTest(boxID, dek)
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ boxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}
+ if err := encryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ t.Fatal(err)
+ }
+ config, err := json.Marshal(boxConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), config, 0600); err != nil {
+ t.Fatal(err)
+ }
+ mountedEncryptedBoxes.Store(boxID, true)
+ if err := sql.OpenEncryptedDB(boxID, dek); err != nil {
+ t.Fatal(err)
+ }
+ if err := treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ sql.CloseEncryptedDB(boxID)
+ treenode.CloseEncryptedBlockTreeDB(boxID)
+ mountedEncryptedBoxes.Delete(boxID)
+ encryptedBoxLifecycles.Delete(boxID)
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ })
+ }
+ source := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(source, "assets"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(source, "assets", "file.txt"), []byte("private asset content"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ count := 2*markdownImportBatchDocuments + 1
+ for i := range count {
+ markdown := fmt.Sprintf("# Heading %03d\n\n[[doc-%03d|next]] [[doc-%03d#Heading %03d|heading]] [[doc-%03d]]\n\n[asset](assets/file.txt)\n\nText[^note].\n\n[^note]: footnote %03d\n", i, (i+1)%count, (i+1)%count, (i+1)%count, (i+1)%count, i)
+ if err := os.WriteFile(filepath.Join(source, fmt.Sprintf("doc-%03d.md", i)), []byte(markdown), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.MkdirAll(filepath.Join(source, "parent"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(source, "parent.md"), []byte("---\ndate: 2020-01-02\ntitle: Renamed parent\n---\n\n[[parent/child|child]]"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(source, "parent", "child.markdown"), []byte("child content"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := ImportFromLocalPathSkipRoot(boxID, source, "/"); err != nil {
+ t.Fatal(err)
+ }
+ if staged, err := filepath.Glob(filepath.Join(util.TempDir, "markdown-import-*")); err != nil || len(staged) != 0 {
+ t.Fatalf("staging files remained after import: %v, %v", staged, err)
+ }
+ for i := range count {
+ current := treenode.GetBlockTreeRootByHPath(boxID, fmt.Sprintf("/doc-%03d", i))
+ next := treenode.GetBlockTreeRootByHPath(boxID, fmt.Sprintf("/doc-%03d", (i+1)%count))
+ if current == nil || next == nil {
+ t.Fatalf("missing imported document %d", i)
+ }
+ cache.ClearTreeCache()
+ tree, err := filesys.LoadTree(boxID, current.Path, util.NewLute())
+ if err != nil {
+ t.Fatal(err)
+ }
+ var documentRef, headingRef, dynamicRef, asset bool
+ footnotes := 0
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ if n.IsTextMarkType("block-ref") && n.TextMarkTextContent == "next" {
+ documentRef = n.TextMarkBlockRefID == next.ID
+ }
+ if n.IsTextMarkType("block-ref") && n.TextMarkTextContent == "heading" {
+ block := treenode.GetBlockTreeInBox(n.TextMarkBlockRefID, boxID)
+ headingRef = block != nil && block.RootID == next.ID && block.Type == "h"
+ }
+ if n.IsTextMarkType("block-ref") && n.TextMarkBlockRefSubtype == "d" {
+ dynamicRef = n.TextMarkBlockRefID == next.ID
+ }
+ if n.IsTextMarkType("a") && strings.HasPrefix(n.TextMarkAHref, "assets/") {
+ asset = !encrypted || strings.Contains(n.TextMarkAHref, "?box="+boxID)
+ }
+ if n.IsTextMarkType("block-ref") && n.IsTextMarkType("sup") {
+ footnotes++
+ if n.TextMarkBlockRefSubtype != "s" || treenode.GetNodeInTree(tree, n.TextMarkBlockRefID) == nil {
+ t.Error("footnote lost its local static target")
+ }
+ }
+ return ast.WalkContinue
+ })
+ if !documentRef || !headingRef || !dynamicRef || !asset {
+ t.Fatalf("document %d lost links: doc=%v heading=%v dynamic=%v asset=%v", i, documentRef, headingRef, dynamicRef, asset)
+ }
+ if footnotes != 1 {
+ t.Fatal("footnote did not survive staging")
+ }
+ data, err := os.ReadFile(filepath.Join(util.DataDir, boxID, current.Path))
+ if err != nil || encrypted && !IsEncryptedNotebookData(data) {
+ t.Fatal("encrypted import wrote a plaintext document")
+ }
+ }
+ parent := treenode.GetBlockTreeRootByHPath(boxID, "/Renamed parent")
+ child := treenode.GetBlockTreeRootByHPath(boxID, "/parent/child")
+ if parent == nil || child == nil || !strings.HasPrefix(child.Path, "/"+parent.ID+"/") {
+ t.Fatal("front matter root ID did not relocate child documents")
+ }
+ if _, err := os.Stat(filepath.Join(source, "doc-000.md")); err != nil {
+ t.Fatal("import altered source Markdown")
+ }
+ if encrypted {
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ if _, err := filesys.LoadTree(boxID, child.Path, util.NewLute()); err == nil {
+ t.Fatal("completed import bypassed locked-notebook access")
+ }
+ }
+ })
+ }
+}
+
+func TestMarkdownImportSingleFileSkipsStaging(t *testing.T) {
+ const boxID = "20261010000000-single1"
+ setupExportRelatedTest(t, boxID)
+ Conf.Editor = conf.NewEditor()
+ setupNotebookDocumentImportDatabase(t)
+ source := filepath.Join(t.TempDir(), "source.md")
+ original := []byte("# Single document\n\nContent")
+ if err := os.WriteFile(source, original, 0600); err != nil {
+ t.Fatal(err)
+ }
+ util.TempDir = source
+ if err := ImportFromLocalPath(boxID, source, "/"); err != nil {
+ t.Fatal(err)
+ }
+ if tree := treenode.GetBlockTreeRootByHPath(boxID, "/source"); tree == nil {
+ t.Fatal("single document was not imported")
+ }
+ if got, err := os.ReadFile(source); err != nil || !bytes.Equal(got, original) {
+ t.Fatal("single import changed source Markdown")
+ }
+}
+
+func TestMarkdownImportStagingFailurePreservesSource(t *testing.T) {
+ const boxID = "20261010000000-error01"
+ setupExportRelatedTest(t, boxID)
+ Conf.Editor = conf.NewEditor()
+ sourceDir := t.TempDir()
+ source := filepath.Join(sourceDir, "source.md")
+ original := []byte("# source content")
+ if err := os.WriteFile(source, original, 0600); err != nil {
+ t.Fatal(err)
+ }
+ util.TempDir = filepath.Join(util.TempDir, "missing", "directory")
+ if err := ImportFromLocalPath(boxID, sourceDir, "/"); err == nil {
+ t.Fatal("staging failure was reported as success")
+ }
+ if got, err := os.ReadFile(source); err != nil || !bytes.Equal(got, original) {
+ t.Fatal("failed import changed source Markdown")
+ }
+}
diff --git a/kernel/model/import_markdown_benchmark_test.go b/kernel/model/import_markdown_benchmark_test.go
new file mode 100644
index 0000000000..51d5fd38a0
--- /dev/null
+++ b/kernel/model/import_markdown_benchmark_test.go
@@ -0,0 +1,113 @@
+package model
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+ "runtime/debug"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/shirou/gopsutil/v4/process"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// BenchmarkMarkdownImportWorkingSet 对照保留全部树与加密暂存的工作集,不启动内核或访问用户工作空间。
+func BenchmarkMarkdownImportWorkingSet(b *testing.B) {
+ originalConf, originalTemp := Conf, util.TempDir
+ Conf = NewAppConf()
+ Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()
+ util.TempDir = b.TempDir()
+ b.Cleanup(func() { Conf, util.TempDir = originalConf, originalTemp })
+ markdown := "# Heading\n\n" + strings.Repeat("Paragraph with **bold**, *emphasis*, [a link](https://example.com) and `code`.\n\n", 540)
+ proc, err := process.NewProcess(int32(os.Getpid()))
+ if err != nil {
+ b.Fatal(err)
+ }
+ for _, count := range []int{100, 400} {
+ for _, staged := range []bool{false, true} {
+ mode := "retained"
+ if staged {
+ mode = "staged"
+ }
+ b.Run(fmt.Sprintf("%s/%d", mode, count), func(b *testing.B) {
+ debug.FreeOSMemory()
+ initial, err := proc.MemoryInfo()
+ if err != nil {
+ b.Fatal(err)
+ }
+ peakRSS := initial.RSS
+ sample := func() {
+ memory, err := proc.MemoryInfo()
+ if err != nil {
+ b.Fatal(err)
+ }
+ peakRSS = max(peakRSS, memory.RSS)
+ }
+ b.ResetTimer()
+ for iteration := 0; iteration < b.N; iteration++ {
+ var trees []*parse.Tree
+ var spool *markdownImportSpool
+ links := map[string]string{}
+ if staged {
+ spool, err = newMarkdownImportSpool()
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+ for i := range count {
+ tree, _, _, _ := parseStdMd([]byte(markdown), true)
+ id := ast.NewNodeID()
+ reassignIDUpdated(tree, id, "")
+ tree.Box, tree.Path, tree.HPath = "20261010000000-bench01", "/"+id+".sy", fmt.Sprintf("/document-%d", i)
+ tree.Root.Spec = treenode.CurrentSpec
+ if staged {
+ if err := spool.add(tree); err != nil {
+ b.Fatal(err)
+ }
+ } else {
+ trees = append(trees, tree)
+ addImportSearchLinks(tree, links)
+ }
+ if (i+1)%markdownImportBatchDocuments == 0 {
+ sample()
+ if staged {
+ debug.FreeOSMemory()
+ }
+ }
+ }
+ if staged {
+ var pending []*parse.Tree
+ if err := spool.finish(func(tree *parse.Tree) error {
+ pending = append(pending, tree)
+ return nil
+ }, func() {
+ sample()
+ pending = nil
+ debug.FreeOSMemory()
+ }); err != nil {
+ b.Fatal(err)
+ }
+ spool.close()
+ } else {
+ engine := NewLute()
+ engine.SetHTMLTag2TextMark(true)
+ for _, tree := range trees {
+ convertMdHyperlinks2WikiLinks(tree)
+ convertWikiLinksAndTags(tree, links)
+ mergeTextAndHandlerNestedInlines(tree, engine)
+ }
+ sample()
+ runtime.KeepAlive(trees)
+ }
+ }
+ b.ReportMetric(float64(peakRSS)/(1024*1024), "peak-RSS-MiB")
+ b.ReportMetric(float64(count*len(markdown))/(1024*1024), "input-MiB")
+ })
+ }
+ }
+}
diff --git a/kernel/model/import_markdown_spool_test.go b/kernel/model/import_markdown_spool_test.go
new file mode 100644
index 0000000000..47c636b46a
--- /dev/null
+++ b/kernel/model/import_markdown_spool_test.go
@@ -0,0 +1,241 @@
+package model
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/88250/lute/render"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func setupMarkdownSpoolTest(t *testing.T) {
+ t.Helper()
+ originalConf, originalTemp := Conf, util.TempDir
+ Conf = NewAppConf()
+ Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()
+ util.TempDir = t.TempDir()
+ t.Cleanup(func() { Conf, util.TempDir = originalConf, originalTemp })
+}
+
+func markdownSpoolFixture(markdown, title string, document int) *parse.Tree {
+ tree, _, _, _ := parseStdMd([]byte(markdown), true)
+ tree.Root.ID = tree.Root.IALAttr("id")
+ ids := map[string]string{}
+ count := 0
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n.ID != "" {
+ id := fmt.Sprintf("20261010000000-%07d", document*1000+count)
+ count++
+ ids[n.ID] = id
+ n.ID = id
+ n.SetIALAttr("id", id)
+ n.SetIALAttr("updated", "20261010000000")
+ }
+ return ast.WalkContinue
+ })
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && treenode.IsBlockRef(n) {
+ if id := ids[n.TextMarkBlockRefID]; id != "" {
+ n.TextMarkBlockRefID = id
+ }
+ }
+ return ast.WalkContinue
+ })
+ tree.ID, tree.Box = tree.Root.ID, "20261010000000-box0001"
+ tree.Path, tree.HPath = "/"+tree.ID+".sy", "/"+title
+ tree.Root.Spec = treenode.CurrentSpec
+ tree.Root.SetIALAttr("title", title)
+ return tree
+}
+
+func renderMarkdownSpoolFixture(tree *parse.Tree) []byte {
+ engine := util.NewLute()
+ return render.NewJSONRenderer(tree, engine.RenderOptions, engine.ParseOptions).Render()
+}
+
+func TestMarkdownImportSpoolPreservesConversion(t *testing.T) {
+ setupMarkdownSpoolTest(t)
+ spool, err := newMarkdownImportSpool()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer spool.close()
+ fixtures := []struct{ title, markdown string }{
+ {"one", "# Heading one\n\n[[two#Heading two|forward]] and [document](two.md).\n\n*em* **strong** `code` $x+y$ #tag\n\nText[^note].\n\n[^note]: Footnote **content**\n\n| a | b |\n| -- | -- |\n| 1 | 2 |\n\n```go\nfmt.Println(1)\n```\n\n<div>HTML <b>bold</b></div>\n"},
+ {"two", "# Heading two\n\n[[one#Heading one]] and [[missing]].\n\n> Quote\n\n- [x] Task\n- Item\n\n![image](assets/image.png)\n"},
+ }
+ links := map[string]string{}
+ var original []*parse.Tree
+ for i, fixture := range fixtures {
+ tree := markdownSpoolFixture(fixture.markdown, fixture.title, i+1)
+ original = append(original, tree)
+ addImportSearchLinks(tree, links)
+ if err := spool.add(markdownSpoolFixture(fixture.markdown, fixture.title, i+1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ engine := NewLute()
+ engine.SetHTMLTag2TextMark(true)
+ var expected [][]byte
+ for _, tree := range original {
+ convertMdHyperlinks2WikiLinks(tree)
+ convertWikiLinksAndTags(tree, links)
+ mergeTextAndHandlerNestedInlines(tree, engine)
+ expected = append(expected, renderMarkdownSpoolFixture(tree))
+ }
+ i := 0
+ if err := spool.finish(func(tree *parse.Tree) error {
+ if got := renderMarkdownSpoolFixture(tree); !bytes.Equal(got, expected[i]) {
+ t.Errorf("staging changed document %d\ngot: %s\nwant: %s", i, got, expected[i])
+ }
+ i++
+ return nil
+ }, func() {}); err != nil {
+ t.Fatal(err)
+ }
+ if i != len(fixtures) {
+ t.Fatal("conversion omitted a document")
+ }
+}
+
+func TestMarkdownImportSpoolBoundsQueuedTrees(t *testing.T) {
+ setupMarkdownSpoolTest(t)
+ spool, err := newMarkdownImportSpool()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer spool.close()
+ for i := range 2*markdownImportBatchDocuments + 1 {
+ if err := spool.add(markdownSpoolFixture("# Heading\n\ncontent", fmt.Sprint(i), i)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var queued []*parse.Tree
+ flushed := 0
+ if err := spool.finish(func(tree *parse.Tree) error {
+ queued = append(queued, tree)
+ if len(queued) > markdownImportBatchDocuments {
+ t.Fatal("queue retained more than one batch of trees")
+ }
+ return nil
+ }, func() {
+ flushed += len(queued)
+ queued = nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if flushed != len(spool.entries) || len(queued) != 0 {
+ t.Fatal("final indexing batch was not drained")
+ }
+}
+
+func TestMarkdownImportSpoolAuthenticatesAndCleansUp(t *testing.T) {
+ setupMarkdownSpoolTest(t)
+ spool, err := newMarkdownImportSpool()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer spool.close()
+ const secret = "private Markdown content must not be staged in plaintext"
+ if err := spool.add(markdownSpoolFixture(secret, "private", 1)); err != nil {
+ t.Fatal(err)
+ }
+ fileName := spool.file.Name()
+ ciphertext, err := os.ReadFile(fileName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(ciphertext, []byte(secret)) {
+ t.Fatal("staging file exposed plaintext")
+ }
+ if _, err := util.DecryptWithAAD(make([]byte, 32), ciphertext, markdownImportAAD(0)); err == nil {
+ t.Fatal("wrong key authenticated staged data")
+ }
+ if _, err := util.DecryptWithAAD(spool.key, ciphertext, markdownImportAAD(1)); err == nil {
+ t.Fatal("staged data was not bound to its entry")
+ }
+ ciphertext[len(ciphertext)-1] ^= 1
+ if _, err := spool.file.WriteAt(ciphertext, 0); err != nil {
+ t.Fatal(err)
+ }
+ if err := spool.finish(func(*parse.Tree) error {
+ t.Fatal("unauthenticated staged data reached the writer")
+ return nil
+ }, func() {}); err == nil {
+ t.Fatal("corrupted staging entry was accepted")
+ }
+ if got, err := os.ReadFile(fileName); err != nil || !bytes.Equal(got, ciphertext) {
+ t.Fatal("authentication failure rewrote staged ciphertext")
+ }
+ key := spool.key
+ spool.close()
+ if _, err := os.Stat(fileName); !os.IsNotExist(err) {
+ t.Fatal("temporary staging file was not removed")
+ }
+ if !bytes.Equal(key, make([]byte, len(key))) {
+ t.Fatal("staging key was not cleared")
+ }
+}
+
+func TestMarkdownImportSpoolFlushesOnWriteFailure(t *testing.T) {
+ setupMarkdownSpoolTest(t)
+ spool, err := newMarkdownImportSpool()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer spool.close()
+ for i := range 3 {
+ if err := spool.add(markdownSpoolFixture("content", fmt.Sprint(i), i)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writes, flushes := 0, 0
+ failure := errors.New("disk write failed")
+ err = spool.finish(func(*parse.Tree) error {
+ writes++
+ if writes == 2 {
+ return failure
+ }
+ return nil
+ }, func() { flushes++ })
+ if !errors.Is(err, failure) || writes != 2 || flushes != 1 {
+ t.Fatalf("write error or pending batch lost: %v, writes=%d, flushes=%d", err, writes, flushes)
+ }
+}
+
+func TestMarkdownImportSpoolFlushesByBytes(t *testing.T) {
+ setupMarkdownSpoolTest(t)
+ spool, err := newMarkdownImportSpool()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer spool.close()
+ if err := spool.add(markdownSpoolFixture(strings.Repeat("x", markdownImportBatchBytes), "large", 1)); err != nil {
+ t.Fatal(err)
+ }
+ if err := spool.add(markdownSpoolFixture("small", "small", 2)); err != nil {
+ t.Fatal(err)
+ }
+ writes, firstFlush := 0, 0
+ if err := spool.finish(func(*parse.Tree) error {
+ writes++
+ return nil
+ }, func() {
+ if firstFlush == 0 {
+ firstFlush = writes
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if firstFlush != 1 {
+ t.Fatal("large document did not drain the queue by its byte budget")
+ }
+}
diff --git a/kernel/model/import_test.go b/kernel/model/import_test.go
index 49da56f1df..69770efe4d 100644
--- a/kernel/model/import_test.go
+++ b/kernel/model/import_test.go
@@ -30,7 +30,6 @@ import (
"strings"
"testing"
- "github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/util"
"golang.org/x/image/bmp"
)
@@ -127,15 +126,13 @@ func TestImportedSYRootIDs(t *testing.T) {
}
func TestImportedTreeRootIDs(t *testing.T) {
- trees := []*parse.Tree{
- {ID: "root-b", Path: "/target/root-b.sy"},
- nil,
- {ID: "child", Path: "/target/root-b/child.sy"},
- {ID: "root-a", Path: "/target/root-a.sy"},
- {ID: "other", Path: "/other.sy"},
- }
-
- got := importedTreeRootIDs(trees, "/target")
+ spool := &markdownImportSpool{entries: []markdownImportEntry{
+ {id: "root-b", path: "/target/root-b.sy"},
+ {id: "child", path: "/target/root-b/child.sy"},
+ {id: "root-a", path: "/target/root-a.sy"},
+ {id: "other", path: "/other.sy"},
+ }}
+ got := spool.rootIDs("/target")
assertStringSlice(t, got, []string{"root-a", "root-b"})
}