diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 401fe791c..d21912cb1 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -62,12 +62,21 @@ func appliedSave(m map[string]applied) { b, _ := json.MarshalIndent(m, "", " ") os.MkdirAll(filepath.Dir(appliedPath()), 0o755) os.WriteFile(appliedPath(), b, 0o600) + filememo.Look(appliedPath()) } +// appliedOf is what magpie set on agent id. Every look at an agent's +// drift asks it, for every agent a poll lists, so the file is parsed once +// a change and the map is shared: callers only read it. func appliedOf(id string) applied { appliedMu.Lock() defer appliedMu.Unlock() - return appliedLoad()[id] + m, _ := filememo.Read("applied", appliedPath(), func(b []byte) (map[string]applied, error) { + out := map[string]applied{} + json.Unmarshal(b, &out) + return out, nil + }) + return m[id] } // record keeps what a field reads after magpie set it; a field put back to diff --git a/internal/agent/applied_memo_test.go b/internal/agent/applied_memo_test.go new file mode 100644 index 000000000..51169eb2c --- /dev/null +++ b/internal/agent/applied_memo_test.go @@ -0,0 +1,41 @@ +package agent + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/filememo" +) + +// appliedOf is asked for every agent on every drift poll: an unchanged +// applied.json is parsed once, and magpie's own record is read at once. +func TestAppliedOfParsesAnUnchangedFileOnce(t *testing.T) { + stashHome(t) + p := appliedPath() + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(`{"codex":{"fields":{"model":"magpie/a"}}}`), 0o600); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-time.Minute) + os.Chtimes(p, old, old) + if got := appliedOf("codex").Fields["model"]; got != "magpie/a" { + t.Fatalf("model = %q", got) + } + release := filememo.Hold() + defer release() + appliedOf("codex") + if n := testing.AllocsPerRun(20, func() { appliedOf("codex") }); n > 2 { + t.Fatalf("%v allocations for an unchanged file", n) + } + record("codex", "model", "magpie/b") + if got := appliedOf("codex").Fields["model"]; got != "magpie/b" { + t.Fatalf("after record, model = %q", got) + } + os.Remove(p) + filememo.Look(p) + if got := appliedOf("codex"); got.Fields != nil { + t.Fatalf("gone file: %+v", got) + } +}