Skip to content

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

:sparkles: Command Line Interface https://github.com/siyuan-note/siyuan/issues/17674

Danielb6ba091f7dbe
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.go
index 897dbb8711..95c7755025 100644
--- a/kernel/cli/cmd/document.go
+++ b/kernel/cli/cmd/document.go
@@ -87,6 +87,7 @@ var documentCreateCmd = &cobra.Command{
if err != nil {
return err
}
+ model.AppendPushEntry("create", notebook, docPath)
fmt.Println(id)
return nil
},
@@ -151,6 +152,7 @@ var documentRemoveCmd = &cobra.Command{
return err
}
model.RemoveDoc(tree.Box, tree.Path)
+ model.AppendPushEntry("reloadFiletree", "", "")
fmt.Println(id)
return nil
},
@@ -175,6 +177,7 @@ var documentRenameCmd = &cobra.Command{
if err := model.RenameDoc(tree.Box, tree.Path, title); err != nil {
return err
}
+ model.AppendPushEntry("reloadFiletree", "", "")
return nil
},
}
diff --git a/kernel/job/cron.go b/kernel/job/cron.go
index b4df3a5be1..8f19abe1dd 100644
--- a/kernel/job/cron.go
+++ b/kernel/job/cron.go
@@ -39,6 +39,8 @@ func StartCron() {
go every(util.SQLFlushInterval, sql.FlushTxJob)
go every(util.SQLFlushInterval, sql.FlushHistoryTxJob)
go every(util.SQLFlushInterval, sql.FlushAssetContentTxJob)
+ go every(util.SQLFlushInterval, sql.PollWAL)
+ go every(50*time.Microsecond, model.PollPushQueue)
go every(10*time.Minute, model.IndexEmbedBlockJob)
go every(10*time.Minute, model.CacheVirtualBlockRefJob)
go every(30*time.Second, model.OCRAssetsJob)
diff --git a/kernel/model/push_queue.go b/kernel/model/push_queue.go
new file mode 100644
index 0000000000..72d795b8a9
--- /dev/null
+++ b/kernel/model/push_queue.go
@@ -0,0 +1,148 @@
+// SiYuan - Refactor your thinking
+// 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.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "bufio"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/gofrs/flock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type pushEntry struct {
+ Action string `json:"action"`
+ Box string `json:"box,omitempty"`
+ Path string `json:"path,omitempty"`
+}
+
+var (
+ pushMu sync.Mutex
+ pushFlock *flock.Flock
+ pushQueuePath string
+)
+
+func ensurePushQueue() {
+ if "" != pushQueuePath {
+ return
+ }
+ pushQueuePath = filepath.Join(util.TempDir, "push.queue")
+ pushFlock = flock.New(pushQueuePath + ".lock")
+}
+
+func AppendPushEntry(action, box, p string) {
+ ensurePushQueue()
+
+ entry := pushEntry{Action: action, Box: box, Path: p}
+ data, err := json.Marshal(entry)
+ if err != nil {
+ logging.LogErrorf("marshal push entry failed: %s", err)
+ return
+ }
+ data = append(data, '\n')
+
+ pushMu.Lock()
+ defer pushMu.Unlock()
+
+ _ = pushFlock.Lock()
+ defer func() { _ = pushFlock.Unlock() }()
+
+ f, err := os.OpenFile(pushQueuePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ logging.LogErrorf("open push queue for append failed: %s", err)
+ return
+ }
+ defer f.Close()
+
+ if _, err = f.Write(data); err != nil {
+ logging.LogErrorf("write push queue failed: %s", err)
+ }
+}
+
+func PollPushQueue() {
+ ensurePushQueue()
+
+ _ = pushFlock.Lock()
+ defer func() { _ = pushFlock.Unlock() }()
+
+ entries := loadPushQueue()
+ if 1 > len(entries) {
+ return
+ }
+
+ logging.LogInfof("polling [%d] push queue operations", len(entries))
+
+ for _, e := range entries {
+ switch e.Action {
+ case "create":
+ box := Conf.Box(e.Box)
+ if nil == box {
+ logging.LogWarnf("push queue create: box [%s] not found", e.Box)
+ continue
+ }
+ PushCreate(box, e.Path, nil)
+ case "reloadFiletree":
+ util.BroadcastByType("filetree", "reloadFiletree", 0, "", nil)
+ }
+ }
+
+ clearPushQueue()
+}
+
+func loadPushQueue() (entries []pushEntry) {
+ f, err := os.Open(pushQueuePath)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ logging.LogErrorf("open push queue for reading failed: %s", err)
+ }
+ return
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if 0 == len(line) {
+ continue
+ }
+ var entry pushEntry
+ if err = json.Unmarshal(line, &entry); err != nil {
+ logging.LogWarnf("skip corrupted push queue line: %s", err)
+ continue
+ }
+ entries = append(entries, entry)
+ }
+ if err = scanner.Err(); err != nil {
+ logging.LogErrorf("scan push queue failed: %s", err)
+ }
+ return
+}
+
+func clearPushQueue() {
+ pushMu.Lock()
+ defer pushMu.Unlock()
+
+ if err := os.Truncate(pushQueuePath, 0); err != nil {
+ if !os.IsNotExist(err) {
+ logging.LogErrorf("clear push queue failed: %s", err)
+ }
+ }
+}
diff --git a/kernel/sql/queue_wal.go b/kernel/sql/queue_wal.go
index cbf15fe73a..ec0a32f6fa 100644
--- a/kernel/sql/queue_wal.go
+++ b/kernel/sql/queue_wal.go
@@ -27,6 +27,7 @@ import (
"github.com/88250/gulu"
"github.com/88250/lute"
"github.com/88250/lute/parse"
+ "github.com/gofrs/flock"
"github.com/siyuan-note/dataparser"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
@@ -34,8 +35,10 @@ import (
)
var (
- walMu sync.Mutex
- walSize atomic.Int64
+ walMu sync.Mutex
+ walSize atomic.Int64
+ skipWALAppend atomic.Bool
+ walFlock *flock.Flock
)
type walEntry struct {
@@ -49,6 +52,7 @@ type walEntry struct {
func initQueueWAL() {
walPath := filepath.Join(util.TempDir, "queue.wal")
+ walFlock = flock.New(walPath + ".lock")
fi, err := os.Stat(walPath)
if err != nil {
if !os.IsNotExist(err) {
@@ -62,6 +66,10 @@ func initQueueWAL() {
func closeQueueWAL() {}
func appendToWAL(op *dbQueueOperation) {
+ if skipWALAppend.Load() {
+ return
+ }
+
entry := dbOpToWALEntry(op)
if nil == entry {
return
@@ -77,6 +85,9 @@ func appendToWAL(op *dbQueueOperation) {
walMu.Lock()
defer walMu.Unlock()
+ _ = walFlock.Lock()
+ defer func() { _ = walFlock.Unlock() }()
+
walPath := filepath.Join(util.TempDir, "queue.wal")
f, err := os.OpenFile(walPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
@@ -132,8 +143,8 @@ func clearWAL(snapshotSize int64) {
walPath := filepath.Join(util.TempDir, "queue.wal")
var preserved []walEntry
- currentSize := walSize.Load()
- if currentSize > snapshotSize {
+ fi, err := os.Stat(walPath)
+ if err == nil && fi.Size() > snapshotSize {
preserved = readWALEntriesFrom(walPath, snapshotSize)
}
@@ -192,6 +203,27 @@ func clearWALEntries() {
walSize.Store(0)
}
+func PollWAL() {
+ if skipWALAppend.Load() {
+ return
+ }
+
+ _ = walFlock.Lock()
+ defer func() { _ = walFlock.Unlock() }()
+
+ entries := loadWAL()
+ if 1 > len(entries) {
+ return
+ }
+
+ skipWALAppend.Store(true)
+ defer skipWALAppend.Store(false)
+
+ logging.LogInfof("polling [%d] external WAL operations", len(entries))
+ processWALEntries(entries, "poll WAL")
+ clearWALEntries()
+}
+
func loadWAL() (entries []walEntry) {
walPath := filepath.Join(util.TempDir, "queue.wal")
f, err := os.Open(walPath)
@@ -229,50 +261,53 @@ func recoverWAL() {
}
logging.LogInfof("recovering [%d] WAL operations", len(entries))
+ processWALEntries(entries, "recover WAL")
+ logging.LogInfof("recovered [%d] WAL operations, will be flushed soon", len(entries))
+}
+func processWALEntries(entries []walEntry, prefix string) {
luteEngine := lute.New()
-
for _, e := range entries {
switch e.Action {
case "upsert":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL upsert: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s upsert: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
UpsertTreeQueue(tree)
case "index":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL index: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s index: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
IndexTreeQueue(tree)
case "rename":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL rename: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s rename: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
RenameTreeQueue(tree)
case "move":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL move: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s move: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
MoveTreeQueue(tree)
case "update_refs":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL update_refs: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s update_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
UpdateRefsTreeQueue(tree)
case "delete_refs":
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
if err != nil {
- logging.LogWarnf("recover WAL delete_refs: load tree [%s/%s] failed: %s", e.Box, e.Path, err)
+ logging.LogWarnf("%s delete_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
continue
}
DeleteRefsTreeQueue(tree)
@@ -292,8 +327,6 @@ func recoverWAL() {
IndexNodeQueue(e.ID)
}
}
-
- logging.LogInfof("recovered [%d] WAL operations, will be flushed soon", len(entries))
}
func loadTreeFromDisk(box, p string, luteEngine *lute.Lute) (tree *parse.Tree, err error) {