feat(plugins): load plugin and secret-engine files without a restart

docs/prds/plugin-settings-live.md: a `plugin-settings` change now applies
live for plugin_dir, module_dir and secret_engine_dir, and a file dropped
into any of those directories loads on the reconciliation tick.

- PluginSettingsKind moves to ApplyMode "live" and joins
  runtimeResourceKinds, so a stored directory change re-layers immediately.
- A reconciler re-runs the directory loads and the layering on the
  apply-status restamp interval. Files are content-hashed, so only new and
  changed files load.
- plugin.Host grows Add and Replace for the running state (Register keeps
  its pre-Start rule), and plugin.LoadFile / secret.Registry.LoadFile are
  the single-file load paths the boot loader and the reconciler share.
- Yaegi cannot unload, so a removed file keeps running and the removal is
  reported through apply status against the live version until restart; a
  clean pass clears it.
- A plugin-settings document that changes skills_dir is refused before the
  layering, since skills_dir has no live consumer.
- applystatus.Reporter.AppliedVersion lets the reconciliation report an
  outcome without resetting the version to zero.
This commit is contained in:
sam committed 2026-10-02 10:01:35 +10:00
1 parent e6f90b99e8
commit 9c0ac87ecf
13 files changed
+1162 -53

No files matched your search

+180 -8
View File
@@ -263,17 +263,10 @@ func (h *Host) Register(module Module) error {
h.opMu.Lock()
defer h.opMu.Unlock()
if isNilModule(module) {
return errors.New("plugin module is nil")
}
manifest, err := safeManifest(module)
manifest, err := prepareModule(module)
if err != nil {
return err
}
if err := manifest.Validate(); err != nil {
return err
}
manifest = manifest.clone()
h.mu.Lock()
defer h.mu.Unlock()
@@ -501,3 +494,182 @@ func reverseClone(values []string) []string {
}
return out
}
// Add registers and starts a module on a host that is already running, the
// running-state half of a live plugin load (docs/prds/plugin-settings-live.md).
// The module starts on its own -- every module registered before it is already
// running -- and a failed start removes it again without disturbing them. On a
// host that has not started, Add behaves like Register and the module starts
// with the rest.
func (h *Host) Add(ctx context.Context, module Module) error {
h.opMu.Lock()
defer h.opMu.Unlock()
manifest, err := prepareModule(module)
if err != nil {
return err
}
h.mu.Lock()
h.ensureModulesLocked()
if _, exists := h.modules[manifest.ID]; exists {
h.mu.Unlock()
return fmt.Errorf("plugin module %q is already registered", manifest.ID)
}
h.modules[manifest.ID] = &registeredModule{module: module, manifest: manifest}
h.registration = append(h.registration, manifest.ID)
state := h.state
h.mu.Unlock()
switch state {
case hostIdle:
// Not started yet: Start will pick this module up with the rest.
return nil
case hostRunning:
default:
h.remove(manifest.ID)
return fmt.Errorf("plugin host cannot add a module from state %d", state)
}
// Every registered module is running while the host is running, so a
// dependency that is not registered cannot be satisfied by a later module
// in this pass; refuse and let the next reconciliation retry once it is.
for _, dependency := range manifest.Dependencies {
if !h.registered(dependency) {
h.remove(manifest.ID)
return fmt.Errorf("plugin module %q depends on unregistered module %q", manifest.ID, dependency)
}
}
if err := safeStart(ctx, manifest.ID, module); err != nil {
h.remove(manifest.ID)
return err
}
h.mu.Lock()
h.started = append(h.started, manifest.ID)
h.mu.Unlock()
return nil
}
// Replace swaps the module whose manifest id matches for a new one while the
// host is running. The old module is stopped and the new one started; when
// the new start fails the old one is restarted, so a refused replacement
// leaves the running set as it was. Replacing a module another running module
// depends on is refused rather than swapped, because the dependent would keep
// calling a stopped implementation.
func (h *Host) Replace(ctx context.Context, module Module) error {
h.opMu.Lock()
defer h.opMu.Unlock()
manifest, err := prepareModule(module)
if err != nil {
return err
}
h.mu.Lock()
previous, exists := h.modules[manifest.ID]
if !exists {
h.mu.Unlock()
return fmt.Errorf("plugin module %q is not registered", manifest.ID)
}
if dependent, ok := h.runningDependentLocked(manifest.ID); ok {
h.mu.Unlock()
return fmt.Errorf("plugin module %q is required by running module %q and cannot be replaced", manifest.ID, dependent)
}
wasStarted := slices.Contains(h.started, manifest.ID)
h.mu.Unlock()
if !wasStarted {
// Not running: swap the registration only, so a later Start uses the
// replacement.
h.mu.Lock()
h.modules[manifest.ID] = &registeredModule{module: module, manifest: manifest}
h.mu.Unlock()
return nil
}
if err := safeStop(ctx, manifest.ID, previous.module); err != nil {
return err
}
if err := safeStart(ctx, manifest.ID, module); err != nil {
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
restartErr := safeStart(rollbackCtx, manifest.ID, previous.module)
cancel()
return errors.Join(err, restartErr)
}
h.mu.Lock()
h.modules[manifest.ID] = &registeredModule{module: module, manifest: manifest}
h.mu.Unlock()
return nil
}
// Has reports whether a module with id is registered, running or not.
func (h *Host) Has(id string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
_, ok := h.modules[id]
return ok
}
// Manifests returns the registered modules' manifests sorted by id. It is the
// read side of the running set: a live load reports what is loaded from here.
func (h *Host) Manifests() []Manifest {
h.mu.RLock()
defer h.mu.RUnlock()
out := make([]Manifest, 0, len(h.modules))
for _, entry := range h.modules {
out = append(out, entry.manifest.clone())
}
slices.SortFunc(out, func(a, b Manifest) int { return strings.Compare(a.ID, b.ID) })
return out
}
// prepareModule validates a module and returns its cloned manifest, the
// validation Register, Add and Replace all share.
func prepareModule(module Module) (Manifest, error) {
if isNilModule(module) {
return Manifest{}, errors.New("plugin module is nil")
}
manifest, err := safeManifest(module)
if err != nil {
return Manifest{}, err
}
if err := manifest.Validate(); err != nil {
return Manifest{}, err
}
return manifest.clone(), nil
}
// registered reports whether id is registered. The caller holds no lock.
func (h *Host) registered(id string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
_, ok := h.modules[id]
return ok
}
// runningDependentLocked returns a started module other than id that depends
// on id, which is what makes replacing id unsafe. The caller holds h.mu.
func (h *Host) runningDependentLocked(id string) (string, bool) {
for _, startedID := range h.started {
if startedID == id {
continue
}
entry, ok := h.modules[startedID]
if !ok {
continue
}
if slices.Contains(entry.manifest.Dependencies, id) {
return startedID, true
}
}
return "", false
}
// remove unregisters id, the rollback of a refused Add.
func (h *Host) remove(id string) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.modules, id)
h.registration = slices.DeleteFunc(h.registration, func(v string) bool { return v == id })
}
+200
View File
@@ -0,0 +1,200 @@
package plugin_test
import (
"context"
"errors"
"slices"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/plugin"
)
// The running-state operations a live plugin load needs: Add puts one new
// module beside the running set, Replace swaps one module's implementation,
// and neither disturbs a module it is not touching.
// docs/prds/plugin-settings-live.md ("The three registries").
func TestHostAddStartsANewModuleWhileRunning(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
base := &fakeModule{manifest: validManifest("base"), events: events}
if err := host.Register(base); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
added := &fakeModule{manifest: validManifest("late", "base"), events: events}
if err := host.Add(context.Background(), added); err != nil {
t.Fatalf("Add() error = %v", err)
}
if !host.Has("late") {
t.Fatal("Add() did not register the module")
}
if got, want := events.snapshot(), []string{"start:base", "start:late"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
// The already-running set is stopped after the added module, since the
// added module came later.
if err := host.Stop(context.Background()); err != nil {
t.Fatal(err)
}
if got, want := events.snapshot(), []string{"start:base", "start:late", "stop:late", "stop:base"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
}
func TestHostAddRefusesDuplicateAndUnknownDependency(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base")}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("base")}); err == nil {
t.Fatal("Add() of a duplicate id succeeded")
}
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("dependent", "missing")}); err == nil {
t.Fatal("Add() with an unregistered dependency succeeded")
}
if host.Has("dependent") {
t.Error("a refused Add() left the module registered")
}
}
func TestHostAddRollsBackItsOwnStartFailure(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
broken := &fakeModule{manifest: validManifest("late"), events: events, startErr: errors.New("boom")}
if err := host.Add(context.Background(), broken); err == nil {
t.Fatal("Add() of a module whose Start fails succeeded")
}
if host.Has("late") {
t.Error("Add() left a module whose Start failed registered")
}
if got, want := events.snapshot(), []string{"start:base", "start:late"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the base module untouched by the failed add: %v", got, want)
}
}
func TestHostReplaceStopsTheOldAndStartsTheNew(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
oldManifest := validManifest("module")
oldManifest.Version = "1.0.0"
if err := host.Register(&fakeModule{manifest: oldManifest, events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
newManifest := validManifest("module")
newManifest.Version = "2.0.0"
if err := host.Replace(context.Background(), &fakeModule{manifest: newManifest, events: events}); err != nil {
t.Fatalf("Replace() error = %v", err)
}
if got, want := events.snapshot(), []string{"start:module", "stop:module", "start:module"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
manifests := host.Manifests()
if len(manifests) != 1 || manifests[0].Version != "2.0.0" {
t.Fatalf("manifests after replace = %+v, want the new 2.0.0", manifests)
}
}
func TestHostReplaceRestartsTheOldWhenTheNewStartFails(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("module"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
broken := &fakeModule{manifest: validManifest("module"), events: events, startErr: errors.New("boom")}
err := host.Replace(context.Background(), broken)
if err == nil {
t.Fatal("Replace() with a failing new module succeeded")
}
if got, want := events.snapshot(), []string{"start:module", "stop:module", "start:module", "start:module"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the old module restarted after the failed start: %v", got, want)
}
if !host.Has("module") {
t.Error("a refused Replace() unregistered the module")
}
}
func TestHostReplaceRefusesAModuleARunningDependentNeeds(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Register(&fakeModule{manifest: validManifest("dependent", "base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
err := host.Replace(context.Background(), &fakeModule{manifest: validManifest("base"), events: events})
if err == nil || !strings.Contains(err.Error(), "dependent") {
t.Fatalf("Replace() of a depended-on module = %v, want a refusal naming the dependent", err)
}
if got, want := events.snapshot(), []string{"start:base", "start:dependent"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the dependent left running: %v", got, want)
}
}
func TestHostReplaceRefusesAnUnregisteredModule(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Replace(context.Background(), &fakeModule{manifest: validManifest("absent")}); err == nil {
t.Fatal("Replace() of an unregistered module succeeded")
}
}
func TestHostAddBeforeStartBehavesLikeRegister(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("early"), events: events}); err != nil {
t.Fatalf("Add() before Start error = %v", err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if got, want := events.snapshot(), []string{"start:early"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the module started by Start(): %v", got, want)
}
}
+22 -15
View File
@@ -56,25 +56,32 @@ func LoadDir(dir string, extraSymbols ...map[string]map[string]reflect.Value) ([
plugins := make([]Plugin, 0)
for _, name := range names {
path := filepath.Join(dir, name)
src, err := os.ReadFile(path)
p, err := LoadFile(filepath.Join(dir, name), extraSymbols...)
if err != nil {
slog.Default().Warn("skipping unreadable daemon plugin", "file", name, "err", err)
continue
}
// Each plugin file is package main -- must use a fresh interpreter
// to avoid symbol collisions between files.
i, err := yaegiutil.New(interp.Options{}, extraSymbols...)
if err != nil {
slog.Default().Warn("skipping plugin -- interpreter setup failed", "file", name, "err", err)
continue
}
p, err := yaegiutil.Resolve[Plugin](i, string(src), "main.Plugin")
if err != nil {
slog.Default().Warn("skipping plugin", "file", name, "err", err)
slog.Default().Warn("skipping daemon plugin", "file", name, "err", err)
continue
}
plugins = append(plugins, p)
}
return plugins, nil
}
// LoadFile evaluates one plugin file. Each file is package main and needs a
// fresh interpreter to avoid symbol collisions with the other files, so the
// boot load (LoadDir) and a live directory reconciliation both load through
// here rather than through two copies of the interpreter setup.
func LoadFile(path string, extraSymbols ...map[string]map[string]reflect.Value) (Plugin, error) {
src, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read plugin %s: %w", path, err)
}
i, err := yaegiutil.New(interp.Options{}, extraSymbols...)
if err != nil {
return nil, fmt.Errorf("plugin %s: interpreter setup: %w", path, err)
}
p, err := yaegiutil.Resolve[Plugin](i, string(src), "main.Plugin")
if err != nil {
return nil, fmt.Errorf("plugin %s: %w", path, err)
}
return p, nil
}