An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve kernel plugin file watchers https://github.com/siyuan-note/siyuan/issues/18387
Danieldb22cc464004
diff --git a/kernel/plugin/manager.go b/kernel/plugin/manager.goindex 02941455d9..f1585b5f50 100644--- a/kernel/plugin/manager.go+++ b/kernel/plugin/manager.go@@ -45,6 +45,8 @@ type PluginManager struct {context context.Context // Context for managing plugin manager lifecyclewatcher *fsnotify.Watcher // watcher for kernel plugin source file changes, to trigger hot reload+ sourceWatch pluginSourceWatchState+plugins sync.Map // map[string]*KernelPluginpluginsMu sync.Map // map[string]*sync.Mutex, one per plugin name, to serialize start/stop of the same plugin while allowing concurrent start/stop of different plugins@@ -80,10 +82,33 @@ func GetManager() *PluginManager {managerOnce.Do(func() {context := context.Background()- watcher, err := fsnotify.NewWatcher()- if err != nil {- logging.LogErrorf("failed to create kernel plugin source file watcher: %s", err)- } else if watcher != nil {+ var watcher *fsnotify.Watcher+ if isPluginFileWatchSupported() {+ var err error+ watcher, err = fsnotify.NewWatcher()+ if err != nil {+ logging.LogErrorf("failed to create kernel plugin source file watcher: %s", err)+ }+ }++ manager = &PluginManager{+ state: PluginManagerStateStopped,++ pluginsDir: filepath.Join(util.DataDir, "plugins"),++ context: context,+ watcher: watcher,+ }+ manager.sourceWatch = newPluginSourceWatchState(func(name string) {+ petal := model.GetPetalByName(name)+ if petal == nil || !petal.Enabled {+ return+ }+ logging.LogInfof("[plugin:%s] source file kernel.js changed, reloading plugin", petal.Name)+ model.SetPetalEnabled(petal.Name, petal.Enabled)+ })++ if watcher != nil {go func() {defer watcher.Close()@@ -95,19 +120,7 @@ func GetManager() *PluginManager {if !ok {return}-- pluginDir, fileName := filepath.Split(event.Name)- pluginName := filepath.Base(pluginDir)- if fileName == "kernel.js" {- switch event.Op {- case fsnotify.Create, fsnotify.Write:- petal := model.GetPetalByName(pluginName)- if petal != nil && petal.Enabled {- logging.LogInfof("[plugin:%s] source file kernel.js changed, reloading plugin", petal.Name)- go model.SetPetalEnabled(petal.Name, petal.Enabled)- }- }- }+ manager.handlePluginSourceEvent(event)case err, ok := <-watcher.Errors:if !ok {return@@ -117,15 +130,6 @@ func GetManager() *PluginManager {}}()}-- manager = &PluginManager{- state: PluginManagerStateStopped,-- pluginsDir: filepath.Join(util.DataDir, "plugins"),-- context: context,- watcher: watcher,- }})return manager}@@ -246,7 +250,7 @@ func (m *PluginManager) StartPlugin(petal *model.Petal) (ok bool) {// Stop any running instance inside the same lock so that concurrent hot-reload goroutines queue here and each one sees the instance started by the previous.m.stopLocked(petal.Name)- m.addPluginSourceWatch(petal.Name)+ m.addPluginSourceWatch(petal.Name, petal.Kernel.JS)p := NewKernelPlugin(m.context, petal)@@ -342,18 +346,21 @@ func (m *PluginManager) GetLoadedPluginsInfo() (plugins []*PluginInfo) {}// addPluginSourceWatch adds the plugin's base directory to the fsnotify watcher to watch for source file changes for hot reload.-func (m *PluginManager) addPluginSourceWatch(name string) {+func (m *PluginManager) addPluginSourceWatch(name, source string) {if m.watcher == nil {return}path := filepath.Join(m.pluginsDir, name)if err := m.watcher.Add(path); err != nil {logging.LogErrorf("failed to add kernel plugin source path [%s] to watcher: %s", path, err)+ return}+ m.sourceWatch.register(name, filepath.Join(path, "kernel.js"), source)}// removePluginSourceWatch removes the plugin's base directory from the fsnotify watcher when the plugin is stopped.func (m *PluginManager) removePluginSourceWatch(name string) (err error) {+ m.sourceWatch.unregister(name)if m.watcher == nil {return}diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex 26053ff7af..f9832c1c37 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -100,7 +100,10 @@ type KernelPlugin struct {worker Worker // Worker for serializing plugin js-call-go (e.g. logger) and go-call-js (e.g. RPC calls) tasks on a single goroutineruntime *eventloop.EventLoop // goja event loop runtime for this plugin- watcher *fsnotify.Watcher // watcher for kernel plugin storage file changes++ watcherMu sync.Mutex+ watcher *fsnotify.Watcher // watcher for kernel plugin storage file changes+ watcherDone chan struct{}state atomic.Int64 // PluginState@@ -124,11 +127,6 @@ func NewKernelPlugin(ctx context.Context, petal *model.Petal) *KernelPlugin {context, cancel := context.WithCancel(ctx)- watcher, err := fsnotify.NewWatcher()- if err != nil {- logging.LogErrorf("[plugin:%s] failed to create storage watcher: %s", petal.Name, err)- }-plugin := &KernelPlugin{Petal: petal,token: token,@@ -137,8 +135,6 @@ func NewKernelPlugin(ctx context.Context, petal *model.Petal) *KernelPlugin {pluginDir: filepath.Join(util.DataDir, "plugins", petal.Name),storageDir: filepath.Join(util.DataDir, "storage", "petal", petal.Name),- watcher: watcher,-context: context,cancel: cancel,@@ -232,8 +228,10 @@ func (p *KernelPlugin) close() (err error) {}}()- if p.runtime != nil {- p.runtime.Stop() // Stops the event loop and waits for it to finish.+ 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.}return@@ -241,6 +239,10 @@ func (p *KernelPlugin) close() (err error) {// error sets the plugin state to errored and frees the goja runtime.func (p *KernelPlugin) error() {+ if p.cancel != nil {+ p.cancel()+ }+ p.closeStorageWatcher()p.Clear()if err := p.close(); err != nil {@@ -254,9 +256,11 @@ func (p *KernelPlugin) error() {func (p *KernelPlugin) start() (err error) {defer func() {if r := recover(); r != nil {- p.error()err = fmt.Errorf("goja panic during start: %v", r)}+ if err != nil {+ p.error()+ }}()p.updateState(PluginStateLoading)@@ -267,17 +271,13 @@ func (p *KernelPlugin) start() (err error) {}if runtimeErr := p.InitRuntime(); runtimeErr != nil {- p.error()return fmt.Errorf("start runtime: %v", runtimeErr)}if subscribeErr := p.subscribeEventHandlers(); subscribeErr != nil {- p.error()return fmt.Errorf("subscribe plugin events: %v", subscribeErr)}- go p.startStorageWatch()-p.onLoad()p.updateState(PluginStateRunning)p.onRunning()@@ -312,6 +312,7 @@ func (p *KernelPlugin) stop() (ok bool, err error) {p.Clear()p.cancel()+ p.closeStorageWatcher()p.socketsMu.Lock()for c := range p.sockets {@@ -724,35 +725,30 @@ func (p *KernelPlugin) UntrackRpcSocket(conn *gws.Conn) {}// startStorageWatch starts a goroutine to watch for file changes in the plugin's storage directory and dispatches events to the plugin.-func (p *KernelPlugin) startStorageWatch() {- if p.watcher == nil {- return- }-- defer p.watcher.Close()+func (p *KernelPlugin) startStorageWatch(watcher *fsnotify.Watcher, done chan struct{}) {+ defer p.finishStorageWatcher(watcher, done)for {select {case <-p.context.Done():return- case event, ok := <-p.watcher.Events:+ case event, ok := <-watcher.Events:if !ok {return}- switch event.Op {- case fsnotify.Create, fsnotify.Write, fsnotify.Rename, fsnotify.Remove:+ for _, operation := range storageWatchOperations(event) {path, relErr := filepath.Rel(p.storageDir, event.Name)if relErr != nil {logging.LogErrorf("[plugin:%s] failed to get relative storage path for [%s]: %v", p.Name, event.Name, relErr)return}p.bus.Publish(EventBusTopicRuntime, createEventMessage("fs-notify", R{- "operation": event.Op.String(),+ "operation": operation,"path": path,}))}- case err, ok := <-p.watcher.Errors:+ case err, ok := <-watcher.Errors:if !ok {return}@@ -763,9 +759,23 @@ func (p *KernelPlugin) startStorageWatch() {// addStorageWatch adds a path to the fsnotify watcher to watch for storage file/directory changes.func (p *KernelPlugin) addStorageWatch(path string) (err error) {+ if !isPluginFileWatchSupported() {+ return errPluginFileWatchUnsupported+ }++ p.watcherMu.Lock()+ defer p.watcherMu.Unlock()++ if contextErr := p.context.Err(); contextErr != nil {+ return fmt.Errorf("plugin stopped: %w", contextErr)+ }if p.watcher == nil {- err = fmt.Errorf("fsnotify watcher not initialized")- return+ p.watcher, err = fsnotify.NewWatcher()+ if err != nil {+ return fmt.Errorf("initialize fsnotify watcher: %w", err)+ }+ p.watcherDone = make(chan struct{})+ go p.startStorageWatch(p.watcher, p.watcherDone)}err = p.watcher.Add(path)@@ -774,6 +784,13 @@ func (p *KernelPlugin) addStorageWatch(path string) (err error) {// removeStorageWatch removes a path from the fsnotify watcher to stop watching for storage file/directory changes.func (p *KernelPlugin) removeStorageWatch(path string) (err error) {+ if !isPluginFileWatchSupported() {+ return errPluginFileWatchUnsupported+ }++ p.watcherMu.Lock()+ defer p.watcherMu.Unlock()+if p.watcher == nil {err = fmt.Errorf("fsnotify watcher not initialized")return@@ -783,6 +800,43 @@ func (p *KernelPlugin) removeStorageWatch(path string) (err error) {return}+func (p *KernelPlugin) closeStorageWatcher() {+ p.watcherMu.Lock()+ watcher := p.watcher+ done := p.watcherDone+ p.watcher = nil+ p.watcherDone = nil+ p.watcherMu.Unlock()++ if watcher != nil {+ watcher.Close()+ }+ if done != nil {+ <-done+ }+}++func (p *KernelPlugin) finishStorageWatcher(watcher *fsnotify.Watcher, done chan struct{}) {+ watcher.Close()++ p.watcherMu.Lock()+ if p.watcher == watcher {+ p.watcher = nil+ p.watcherDone = nil+ }+ p.watcherMu.Unlock()+ close(done)+}++func storageWatchOperations(event fsnotify.Event) (ret []string) {+ for _, operation := range []fsnotify.Op{fsnotify.Create, fsnotify.Write, fsnotify.Rename, fsnotify.Remove} {+ if event.Has(operation) {+ ret = append(ret, operation.String())+ }+ }+ return+}+// invokeHook calls a lifecycle hook (e.g. onload) if it exists, awaiting if it returns a Promise.func (p *KernelPlugin) invokeHook(name string) {var err errordiff --git a/kernel/plugin/source_watcher.go b/kernel/plugin/source_watcher.gonew file mode 100644index 0000000000..78e3b92506--- /dev/null+++ b/kernel/plugin/source_watcher.go@@ -0,0 +1,152 @@+// 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 plugin++import (+ "crypto/sha256"+ "errors"+ "os"+ "path/filepath"+ "sync"+ "time"++ "github.com/fsnotify/fsnotify"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const pluginSourceReloadDelay = 300 * time.Millisecond++var errPluginFileWatchUnsupported = errors.New("plugin file watcher is not supported on mobile")++type pluginSourceWatchEntry struct {+ path string+ signature [sha256.Size]byte+ generation uint64+ timer *time.Timer+}++type pluginSourceWatchState struct {+ mu sync.Mutex+ entries map[string]*pluginSourceWatchEntry+ delay time.Duration+ reload func(name string)+}++func newPluginSourceWatchState(reload func(name string)) pluginSourceWatchState {+ return pluginSourceWatchState{+ entries: map[string]*pluginSourceWatchEntry{},+ delay: pluginSourceReloadDelay,+ reload: reload,+ }+}++func isPluginFileWatchSupported() bool {+ return !util.IsMobileContainer()+}++func (s *pluginSourceWatchState) register(name, path, source string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if old := s.entries[name]; old != nil && old.timer != nil {+ old.timer.Stop()+ }+ s.entries[name] = &pluginSourceWatchEntry{+ path: path,+ signature: sha256.Sum256([]byte(source)),+ }+}++func (s *pluginSourceWatchState) unregister(name string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if entry := s.entries[name]; entry != nil && entry.timer != nil {+ entry.timer.Stop()+ }+ delete(s.entries, name)+}++func (s *pluginSourceWatchState) schedule(name string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ entry := s.entries[name]+ if entry == nil {+ return+ }+ entry.generation+++ generation := entry.generation+ if entry.timer != nil {+ entry.timer.Stop()+ }+ entry.timer = time.AfterFunc(s.delay, func() {+ s.reloadIfChanged(name, generation)+ })+}++func (s *pluginSourceWatchState) reloadIfChanged(name string, generation uint64) {+ s.mu.Lock()+ entry := s.entries[name]+ if entry == nil || entry.generation != generation {+ s.mu.Unlock()+ return+ }+ path := entry.path+ previous := entry.signature+ s.mu.Unlock()++ data, err := os.ReadFile(path)+ if err != nil {+ if !os.IsNotExist(err) {+ logging.LogWarnf("read kernel plugin source file [%s] failed: %s", path, err)+ }+ return+ }+ signature := sha256.Sum256(data)+ if signature == previous {+ return+ }++ s.mu.Lock()+ entry = s.entries[name]+ if entry == nil || entry.generation != generation {+ s.mu.Unlock()+ return+ }+ entry.signature = signature+ entry.timer = nil+ reload := s.reload+ s.mu.Unlock()++ if reload != nil {+ reload(name)+ }+}++func (m *PluginManager) handlePluginSourceEvent(event fsnotify.Event) {+ if filepath.Base(event.Name) != "kernel.js" {+ return+ }+ if !event.Has(fsnotify.Create) && !event.Has(fsnotify.Write) &&+ !event.Has(fsnotify.Rename) && !event.Has(fsnotify.Remove) {+ return+ }++ m.sourceWatch.schedule(filepath.Base(filepath.Dir(event.Name)))+}diff --git a/kernel/plugin/watcher_test.go b/kernel/plugin/watcher_test.gonew file mode 100644index 0000000000..09c6a0478b--- /dev/null+++ b/kernel/plugin/watcher_test.go@@ -0,0 +1,228 @@+// 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 plugin++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "reflect"+ "testing"+ "time"++ "github.com/asaskevich/EventBus"+ "github.com/fsnotify/fsnotify"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPluginSourceWatchStateDebouncesChangedContent(t *testing.T) {+ pluginsDir := t.TempDir()+ name := "test-plugin"+ pluginDir := filepath.Join(pluginsDir, name)+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ sourcePath := filepath.Join(pluginDir, "kernel.js")+ if err := os.WriteFile(sourcePath, []byte("initial"), 0644); err != nil {+ t.Fatal(err)+ }++ reloaded := make(chan string, 4)+ state := newPluginSourceWatchState(func(pluginName string) {+ reloaded <- pluginName+ })+ state.delay = 20 * time.Millisecond+ state.register(name, sourcePath, "initial")+ t.Cleanup(func() {+ state.unregister(name)+ })++ if err := os.WriteFile(sourcePath, []byte("changed"), 0644); err != nil {+ t.Fatal(err)+ }+ state.schedule(name)+ state.schedule(name)+ state.schedule(name)+ waitForPluginReload(t, reloaded, name)+ expectNoPluginReload(t, reloaded)++ state.schedule(name)+ expectNoPluginReload(t, reloaded)++ if err := os.Remove(sourcePath); err != nil {+ t.Fatal(err)+ }+ state.schedule(name)+ expectNoPluginReload(t, reloaded)++ if err := os.WriteFile(sourcePath, []byte("recreated"), 0644); err != nil {+ t.Fatal(err)+ }+ state.schedule(name)+ waitForPluginReload(t, reloaded, name)+}++func TestHandlePluginSourceEventSupportsCombinedOperations(t *testing.T) {+ pluginsDir := t.TempDir()+ name := "test-plugin"+ pluginDir := filepath.Join(pluginsDir, name)+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ sourcePath := filepath.Join(pluginDir, "kernel.js")+ if err := os.WriteFile(sourcePath, []byte("initial"), 0644); err != nil {+ t.Fatal(err)+ }++ reloaded := make(chan string, 1)+ manager := &PluginManager{+ pluginsDir: pluginsDir,+ sourceWatch: newPluginSourceWatchState(func(pluginName string) {+ reloaded <- pluginName+ }),+ }+ manager.sourceWatch.delay = 20 * time.Millisecond+ manager.sourceWatch.register(name, sourcePath, "initial")+ t.Cleanup(func() {+ manager.sourceWatch.unregister(name)+ })++ if err := os.WriteFile(sourcePath, []byte("changed"), 0644); err != nil {+ t.Fatal(err)+ }+ manager.handlePluginSourceEvent(fsnotify.Event{+ Name: sourcePath,+ Op: fsnotify.Create | fsnotify.Write,+ })+ waitForPluginReload(t, reloaded, name)+}++func TestStorageWatcherIsCreatedLazilyAndClosedIdempotently(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ storageDir := t.TempDir()+ plugin := &KernelPlugin{+ Petal: &model.Petal{Name: "test-plugin"},+ storageDir: storageDir,+ context: ctx,+ cancel: cancel,+ bus: EventBus.New(),+ }++ if plugin.watcher != nil {+ t.Fatal("storage watcher must not be initialized before the first add")+ }+ if err := plugin.removeStorageWatch(storageDir); err == nil {+ t.Fatal("removing a path before watcher initialization must fail")+ }+ if plugin.watcher != nil {+ t.Fatal("remove must not initialize the storage watcher")+ }++ if err := plugin.addStorageWatch(storageDir); err != nil {+ t.Fatalf("add storage watch failed: %v", err)+ }+ plugin.watcherMu.Lock()+ watcher := plugin.watcher+ plugin.watcherMu.Unlock()+ if watcher == nil {+ t.Fatal("storage watcher was not initialized by add")+ }++ cancel()+ plugin.closeStorageWatcher()+ plugin.closeStorageWatcher()++ plugin.watcherMu.Lock()+ watcher = plugin.watcher+ plugin.watcherMu.Unlock()+ if watcher != nil {+ t.Fatal("storage watcher was not cleared")+ }+ if err := plugin.addStorageWatch(storageDir); err == nil {+ t.Fatal("adding a path after plugin cancellation must fail")+ }+}++func TestStorageWatchOperationsExpandsCombinedOperations(t *testing.T) {+ event := fsnotify.Event{+ Op: fsnotify.Create | fsnotify.Write | fsnotify.Remove,+ }+ got := storageWatchOperations(event)+ want := []string{"CREATE", "WRITE", "REMOVE"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("storageWatchOperations() = %v, want %v", got, want)+ }+}++func TestPluginFileWatchIsDisabledOnMobile(t *testing.T) {+ originalContainer := util.Container+ t.Cleanup(func() {+ util.Container = originalContainer+ })++ for _, container := range []string{util.ContainerAndroid, util.ContainerIOS, util.ContainerHarmony} {+ util.Container = container+ if isPluginFileWatchSupported() {+ t.Fatalf("plugin file watcher must be disabled on mobile container [%s]", container)+ }++ ctx, cancel := context.WithCancel(context.Background())+ storageDir := t.TempDir()+ plugin := &KernelPlugin{+ Petal: &model.Petal{Name: "test-plugin"},+ storageDir: storageDir,+ context: ctx,+ cancel: cancel,+ bus: EventBus.New(),+ }+ if err := plugin.addStorageWatch(storageDir); !errors.Is(err, errPluginFileWatchUnsupported) {+ t.Fatalf("addStorageWatch() error = %v, want %v", err, errPluginFileWatchUnsupported)+ }+ if err := plugin.removeStorageWatch(storageDir); !errors.Is(err, errPluginFileWatchUnsupported) {+ t.Fatalf("removeStorageWatch() error = %v, want %v", err, errPluginFileWatchUnsupported)+ }+ if plugin.watcher != nil {+ t.Fatalf("storage watcher must not be initialized on mobile container [%s]", container)+ }+ cancel()+ }+}++func waitForPluginReload(t *testing.T, reloaded <-chan string, want string) {+ t.Helper()++ select {+ case got := <-reloaded:+ if got != want {+ t.Fatalf("reloaded plugin = %q, want %q", got, want)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for plugin reload")+ }+}++func expectNoPluginReload(t *testing.T, reloaded <-chan string) {+ t.Helper()++ select {+ case got := <-reloaded:+ t.Fatalf("unexpected plugin reload for %q", got)+ case <-time.After(80 * time.Millisecond):+ }+}