Skip to content

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

:bug: Return validation and execution errors from block APIs https://github.com/siyuan-note/siyuan/issues/19210

Daniel3c114c6cf4f7
diff --git a/kernel/api/block_op.go b/kernel/api/block_op.go
index d099219be4..af55e1565c 100644
--- a/kernel/api/block_op.go
+++ b/kernel/api/block_op.go
@@ -571,16 +571,20 @@ func appendBlock(c *gin.Context) {
return
}
- data := arg["data"].(string)
- dataType := arg["dataType"].(string)
- parentID := arg["parentID"].(string)
- if util.InvalidIDPattern(parentID, ret) {
+ var data, dataType, parentID string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("data", &data, true, false),
+ util.BindJsonArg("dataType", &dataType, true, true),
+ util.BindJsonArg("parentID", &parentID, true, true),
+ ) {
return
}
- // append 只用 parentID 定位目标,目标必须是容器块,否则非法嵌套
- if err := treenode.CheckContainerParent(parentID); err != nil {
+ if dataType != "markdown" && dataType != "dom" {
ret.Code = -1
- ret.Msg = err.Error()
+ ret.Msg = "dataType must be markdown or dom"
+ return
+ }
+ if util.InvalidIDPattern(parentID, ret) {
return
}
if "markdown" == dataType {
@@ -594,21 +598,17 @@ func appendBlock(c *gin.Context) {
}
}
- transactions := []*model.Transaction{
- {
- DoOperations: []*model.Operation{
- {
- Action: "appendInsert",
- Data: data,
- ParentID: parentID,
- },
- },
- },
+ transactions, err := model.PerformBlockOperation(&model.Operation{
+ Action: "appendInsert",
+ Data: data,
+ ParentID: parentID,
+ })
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
}
- model.PerformTransactions(&transactions)
- model.FlushTxQueue()
-
ret.Data = transactions
broadcastTransactions(transactions)
}
@@ -781,37 +781,31 @@ func insertBlock(c *gin.Context) {
return
}
- data := arg["data"].(string)
- dataType := arg["dataType"].(string)
- var parentID, previousID, nextID string
- if nil != arg["parentID"] {
- parentID = arg["parentID"].(string)
- if "" != parentID && util.InvalidIDPattern(parentID, ret) {
- return
- }
+ var data, dataType, parentID, previousID, nextID string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("data", &data, true, false),
+ util.BindJsonArg("dataType", &dataType, true, true),
+ util.BindJsonArg("parentID", &parentID, false, false),
+ util.BindJsonArg("previousID", &previousID, false, false),
+ util.BindJsonArg("nextID", &nextID, false, false),
+ ) {
+ return
}
- if nil != arg["previousID"] {
- previousID = arg["previousID"].(string)
- if "" != previousID && util.InvalidIDPattern(previousID, ret) {
- return
- }
+ if dataType != "markdown" && dataType != "dom" {
+ ret.Code = -1
+ ret.Msg = "dataType must be markdown or dom"
+ return
}
- if nil != arg["nextID"] {
- nextID = arg["nextID"].(string)
- if "" != nextID && util.InvalidIDPattern(nextID, ret) {
- return
- }
+ if parentID == "" && previousID == "" && nextID == "" {
+ ret.Code = -1
+ ret.Msg = "at least one of parentID, previousID or nextID is required"
+ return
}
-
- // 仅靠 parentID 定位目标时(无 previousID/nextID),目标必须是容器块,否则非法嵌套
- if "" != parentID && "" == previousID && "" == nextID {
- if err := treenode.CheckContainerParent(parentID); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
+ for _, id := range []string{parentID, previousID, nextID} {
+ if id != "" && util.InvalidIDPattern(id, ret) {
return
}
}
-
if "markdown" == dataType {
luteEngine := util.NewLute()
var err error
@@ -823,23 +817,19 @@ func insertBlock(c *gin.Context) {
}
}
- transactions := []*model.Transaction{
- {
- DoOperations: []*model.Operation{
- {
- Action: "insert",
- Data: data,
- ParentID: parentID,
- PreviousID: previousID,
- NextID: nextID,
- },
- },
- },
+ transactions, err := model.PerformBlockOperation(&model.Operation{
+ Action: "insert",
+ Data: data,
+ ParentID: parentID,
+ PreviousID: previousID,
+ NextID: nextID,
+ })
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
}
- model.PerformTransactions(&transactions)
- model.FlushTxQueue()
-
ret.Data = transactions
broadcastTransactions(transactions)
}
@@ -994,24 +984,24 @@ func deleteBlock(c *gin.Context) {
return
}
- id := arg["id"].(string)
+ var id string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
+ return
+ }
if util.InvalidIDPattern(id, ret) {
return
}
- transactions := []*model.Transaction{
- {
- DoOperations: []*model.Operation{
- {
- Action: "delete",
- ID: id,
- },
- },
- },
+ transactions, err := model.PerformBlockOperation(&model.Operation{
+ Action: "delete",
+ ID: id,
+ })
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
}
- model.PerformTransactions(&transactions)
-
ret.Data = transactions
broadcastTransactions(transactions)
}
diff --git a/kernel/api/block_op_test.go b/kernel/api/block_op_test.go
new file mode 100644
index 0000000000..b2b3ab451e
--- /dev/null
+++ b/kernel/api/block_op_test.go
@@ -0,0 +1,77 @@
+// SiYuan - From thought to insight, with agents
+// 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.
+
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestBlockOperationsRejectInvalidArguments(t *testing.T) {
+ originalPath := util.BlockTreeDBPath
+ util.BlockTreeDBPath = filepath.Join(t.TempDir(), "blocktree.db")
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ util.BlockTreeDBPath = originalPath
+ if originalPath != "" {
+ treenode.InitBlockTree(false)
+ }
+ })
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.Use(model.Recover)
+ engine.POST("/append", appendBlock)
+ engine.POST("/insert", insertBlock)
+ engine.POST("/delete", deleteBlock)
+ for _, test := range []struct{ path, body string }{
+ {"/append", `{"id":"20260908000000-parent1","data":"test","dataType":"markdown"}`},
+ {"/append", `{"parentID":42,"data":"test","dataType":"markdown"}`},
+ {"/append", `{"parentID":"20260908000000-parent1","data":null,"dataType":"markdown"}`},
+ {"/append", `{"parentID":"20260908000000-parent1","data":"test","dataType":"html"}`},
+ {"/insert", `{"previousID":"20260908000000-parent1","data":"test"}`},
+ {"/insert", `{"data":"test","dataType":"markdown"}`},
+ {"/insert", `{"previousID":42,"data":"test","dataType":"markdown"}`},
+ {"/insert", `{"previousID":"invalid","data":"test","dataType":"markdown"}`},
+ {"/insert", `{"previousID":"20260908000000-parent1","data":"test","dataType":"html"}`},
+ {"/delete", `{}`},
+ {"/delete", `{"id":42}`},
+ {"/delete", `{"id":""}`},
+ {"/append", `{"parentID":"20260908000000-missing","data":"test","dataType":"markdown"}`},
+ {"/insert", `{"previousID":"20260908000000-missing","data":"test","dataType":"markdown"}`},
+ {"/delete", `{"id":"20260908000000-missing"}`},
+ } {
+ t.Run(test.path+test.body, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+ var response struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ Data any `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if recorder.Code != http.StatusOK || response.Code == 0 || response.Msg == "" || response.Data != nil {
+ t.Fatalf("expected explicit error without operations, got %s", recorder.Body.String())
+ }
+ })
+ }
+}
diff --git a/kernel/model/block_operation.go b/kernel/model/block_operation.go
new file mode 100644
index 0000000000..123632ff9f
--- /dev/null
+++ b/kernel/model/block_operation.go
@@ -0,0 +1,60 @@
+// SiYuan - From thought to insight, with agents
+// 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.
+
+package model
+
+import (
+ "fmt"
+
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+// PerformBlockOperation 在事务串行区内校验并执行外部块操作,返回实际执行结果。
+func PerformBlockOperation(operation *Operation) (transactions []*Transaction, err error) {
+ flushLock.Lock()
+ isFlushing.Store(true)
+ defer func() {
+ isFlushing.Store(false)
+ flushLock.Unlock()
+ }()
+
+ // 先处理已入队的修改,确保目标校验和执行使用一致的文档状态。
+ for _, queued := range takeQueuedTransactions() {
+ flushTx(queued)
+ }
+
+ switch operation.Action {
+ case "appendInsert", "insert":
+ if operation.Action == "appendInsert" || operation.PreviousID == "" && operation.NextID == "" {
+ if err = treenode.CheckContainerParent(operation.ParentID); err != nil {
+ return nil, err
+ }
+ }
+ case "delete":
+ // 外部删除请求必须命中现存节点,编辑器内部仍可使用幂等删除。
+ tree, loadErr := LoadTreeByBlockID(operation.ID)
+ if loadErr != nil {
+ return nil, loadErr
+ }
+ node := treenode.GetNodeInTree(tree, operation.ID)
+ if node == nil {
+ return nil, fmt.Errorf("block not found [%s]", operation.ID)
+ }
+ if node == tree.Root {
+ return nil, fmt.Errorf("document cannot be deleted as a block [%s]", operation.ID)
+ }
+ default:
+ return nil, fmt.Errorf("unsupported block operation [%s]", operation.Action)
+ }
+
+ tx := &Transaction{DoOperations: []*Operation{operation}}
+ if err = performTxSyncLocked(tx); err != nil {
+ return nil, err
+ }
+ return []*Transaction{tx}, nil
+}
diff --git a/kernel/model/block_operation_test.go b/kernel/model/block_operation_test.go
new file mode 100644
index 0000000000..98dd6fd490
--- /dev/null
+++ b/kernel/model/block_operation_test.go
@@ -0,0 +1,93 @@
+// SiYuan - From thought to insight, with agents
+// 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.
+
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPerformBlockOperationPersistsBeforeReturning(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ const firstID = "20260908000000-first01"
+ const secondID = "20260908000000-second1"
+ dom := func(id string) string {
+ return util.NewLute().Md2BlockDOM("test\n{: id=\""+id+"\"}", false)
+ }
+ for index, op := range []*Operation{
+ {Action: "appendInsert", ParentID: fixture.sourceID, Data: dom(firstID)},
+ {Action: "insert", PreviousID: firstID, Data: dom(secondID)},
+ {Action: "delete", ID: firstID},
+ } {
+ transactions, err := PerformBlockOperation(op)
+ if err != nil || len(transactions) != 1 {
+ t.Fatalf("operation %s failed: %v", op.Action, err)
+ }
+ cache.RemoveTreeData(fixture.sourceID)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if op.Action == "delete" {
+ if treenode.GetNodeInTree(tree, firstID) != nil {
+ t.Fatal("deleted block is still present after returning")
+ }
+ } else {
+ id := firstID
+ if index == 1 {
+ id = secondID
+ }
+ if treenode.GetNodeInTree(tree, id) == nil {
+ t.Fatalf("inserted block %s is missing after returning", id)
+ }
+ }
+ }
+
+ // 后续同步删除必须先执行队列中的追加,不能将尚未执行的目标误判为不存在。
+ queued := []*Transaction{{DoOperations: []*Operation{{
+ Action: "appendInsert", ParentID: fixture.sourceID, Data: dom(firstID),
+ }}}}
+ PerformTransactions(&queued)
+ if _, err := PerformBlockOperation(&Operation{Action: "delete", ID: firstID}); err != nil {
+ t.Fatalf("delete after queued append failed: %v", err)
+ }
+ cache.RemoveTreeData(fixture.sourceID)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if treenode.GetNodeInTree(tree, firstID) != nil {
+ t.Fatal("queued append was applied after synchronous delete")
+ }
+}
+
+func TestPerformBlockOperationReturnsErrors(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ listID, _ := addOrderedListForStructureTest(t, fixture.sourceID)
+ for _, op := range []*Operation{
+ {Action: "appendInsert", ParentID: "20260908000000-missing", Data: ""},
+ {Action: "insert", PreviousID: "20260908000000-missing", Data: ""},
+ {Action: "insert", ParentID: listID, Data: util.NewLute().Md2BlockDOM("invalid child", false)},
+ {Action: "appendInsert", ParentID: fixture.sourceID, Data: ""},
+ {Action: "delete", ID: "20260908000000-missing"},
+ {Action: "delete", ID: fixture.sourceID},
+ } {
+ transactions, err := PerformBlockOperation(op)
+ if err == nil || transactions != nil {
+ t.Fatalf("expected failed operation without success data: %+v, %v", op, err)
+ }
+ }
+}