Skip to content

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

:bug: Drain kernel plugin storage writes before closing https://github.com/siyuan-note/siyuan/issues/20986

Daniel1689f0f0d8c5
diff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.go
index b0389a5399..2d7b6f6a07 100644
--- a/kernel/plugin/api_storage.go
+++ b/kernel/plugin/api_storage.go
@@ -291,7 +291,12 @@ func bindStoragePut(p *KernelPlugin, rt *goja.Runtime, storage *goja.Object, res
return
}
+ done, admissionErr := p.beginStorageWrite()
+ if admissionErr != nil {
+ return nil, admissionErr
+ }
go func() (result any, err error) {
+ defer done()
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic during siyuan.storage.put: %v", r)
@@ -375,7 +380,12 @@ func bindStorageRemove(p *KernelPlugin, rt *goja.Runtime, storage *goja.Object,
return
}
+ done, admissionErr := p.beginStorageWrite()
+ if admissionErr != nil {
+ return nil, admissionErr
+ }
go func() (result any, err error) {
+ defer done()
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic during siyuan.storage.remove: %v", r)
diff --git a/kernel/plugin/api_storage_test.go b/kernel/plugin/api_storage_test.go
index 4c582e76a1..7ed28d36f1 100644
--- a/kernel/plugin/api_storage_test.go
+++ b/kernel/plugin/api_storage_test.go
@@ -20,10 +20,90 @@ import (
"os"
"path/filepath"
"testing"
+ "time"
"github.com/dop251/goja"
+ "github.com/siyuan-note/filelock"
)
+func TestStoragePutDrainsBeforeRuntimeClose(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ p.storageDir = t.TempDir()
+ path := filepath.Join(p.storageDir, "state.json")
+ filelock.Lock(path)
+ locked := true
+ defer func() {
+ if locked {
+ filelock.Unlock(path)
+ }
+ }()
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ siyuan := rt.NewObject()
+ if err := injectStorage(p, rt, siyuan); err != nil {
+ return nil, err
+ }
+ if err := rt.Set("siyuan", siyuan); err != nil {
+ return nil, err
+ }
+ _, err := rt.RunString(`siyuan.storage.put("state.json", "old").catch(() => {});`)
+ return nil, err
+ })
+ // The put executor is ahead of this barrier and registers I/O before launch.
+ rpcCancellationTestRun(t, p, func(*goja.Runtime) (any, error) { return nil, nil })
+ closed := make(chan error, 1)
+ go func() { closed <- p.close() }()
+ select {
+ case err := <-closed:
+ t.Fatalf("runtime close returned while storage.put was still blocked: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+ filelock.Unlock(path)
+ locked = false
+ select {
+ case err := <-closed:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("runtime close did not drain storage.put")
+ }
+ if data, err := os.ReadFile(path); err != nil || string(data) != "old" {
+ t.Fatalf("admitted mutation was not completed before close: %q, %v", data, err)
+ }
+ if done, err := p.beginStorageWrite(); err == nil {
+ done()
+ t.Fatal("closed plugin admitted a new storage mutation")
+ }
+}
+
+func TestStorageRemoveAndWriteFailureReleaseAdmission(t *testing.T) {
+ p, r := newDataObjectTestPlugin(t)
+ p.storageDir = t.TempDir()
+ r.withRuntime(func(rt *goja.Runtime) {
+ siyuan := rt.NewObject()
+ if err := injectStorage(p, rt, siyuan); err != nil {
+ t.Fatal(err)
+ }
+ if err := rt.Set("siyuan", siyuan); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if got := r.await(`(async () => {
+ await siyuan.storage.put("state", "value");
+ try { await siyuan.storage.put("state/blocked", "fail"); } catch (_) {}
+ await siyuan.storage.remove("state");
+ return "done";
+ })()`); got != "done" {
+ t.Fatal(got)
+ }
+ if err := p.close(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(p.storageDir, "state")); !os.IsNotExist(err) {
+ t.Fatalf("remove did not finish: %v", err)
+ }
+}
+
func TestStorageGetResolvesFileContents(t *testing.T) {
p, r := newDataObjectTestPlugin(t)
p.storageDir = t.TempDir()
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
index 15860c2e84..59cef36f4a 100644
--- a/kernel/plugin/plugin.go
+++ b/kernel/plugin/plugin.go
@@ -112,6 +112,10 @@ type KernelPlugin struct {
watcher *fsnotify.Watcher // watcher for kernel plugin storage file changes
watcherDone chan struct{}
+ storageWritesMu sync.Mutex
+ storageWrites sync.WaitGroup
+ storageWritesClosed bool
+
state atomic.Int64 // PluginState
context context.Context // Context for managing plugin lifecycle and cancellation
@@ -235,17 +239,34 @@ func (p *KernelPlugin) close() (err error) {
}
}()
+ p.storageWritesMu.Lock()
+ p.storageWritesClosed = true
+ p.storageWritesMu.Unlock()
+
runtime := p.runtime
p.runtime = nil
if runtime != nil {
runtime.Stop() // Stops the event loop and waits for it to finish.
// p.runtime.Terminate() // Interrupts the runtime and causes all executing code to throw an exception.
}
+ // Detached file I/O can continue after the event loop stops. Keep the stop
+ // boundary (and pending RPC leases) until every admitted mutation has ended.
+ p.storageWrites.Wait()
// Promise 可能永不完成;运行时停止后已无法继续写入,释放其剩余租约。
p.releaseRPCWrites()
return
}
+func (p *KernelPlugin) beginStorageWrite() (func(), error) {
+ p.storageWritesMu.Lock()
+ defer p.storageWritesMu.Unlock()
+ if p.storageWritesClosed || (p.context != nil && p.context.Err() != nil) {
+ return nil, fmt.Errorf("plugin storage is stopping")
+ }
+ p.storageWrites.Add(1)
+ return p.storageWrites.Done, nil
+}
+
// error sets the plugin state to errored and frees the goja runtime.
func (p *KernelPlugin) error() {
if p.cancel != nil {