appliedOf is asked for every agent on every drift poll (the GUI asks /api/drift every 15s while visible), and each ask read and decoded the whole applied.json. It now goes through filememo.Read: an unchanged file is parsed once and its map shared (every appliedOf caller only reads it). appliedSave calls filememo.Look so magpie's own record is read at once, even inside a held request. Writers (record, appliedLoad's other callers) still decode a fresh map. Run (mote, at this tree): - go test -count=1 ./internal/agent ./internal/filememo: ok (227s) - go vet ./internal/agent for darwin, linux, windows: clean - TestAppliedOfParsesAnUnchangedFileOnce: green; with appliedOf put back on appliedLoad by hand it is red (25 allocations), restored - Real accounts (sandbox HOME copy), 40 /api/drift calls, paired runs: appliedLoad 2.0/3.1 MB before, gone after; totals 26.1/20.6 MB before, 18.9/18.2 MB after. Not tried: Windows and Linux runs of the package (vet only).
42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
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)
|
|
}
|
|
}
|