diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 55e274e12..8a3507eda 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -682,7 +682,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations and /v1beta/models/*") }) - return s.counted(corsGuard(callerGuard(withCaller(keyLimited(mux))))) + return s.counted(holdCatalog(corsGuard(callerGuard(withCaller(keyLimited(mux)))))) } // responsesOverHTTP answers a GET on /v1/responses, which is how a client diff --git a/internal/gateway/holdcatalog.go b/internal/gateway/holdcatalog.go new file mode 100644 index 000000000..50baf4865 --- /dev/null +++ b/internal/gateway/holdcatalog.go @@ -0,0 +1,24 @@ +package gateway + +import ( + "net/http" + + "github.com/yetone/magpie/internal/filememo" + "github.com/yetone/magpie/internal/provider" +) + +// holdCatalog has a request hold the catalog it built first, and the files it +// read, for every look-up it makes (provider.Hold, as the GUI's /api +// does): without it each Resolve built the providers anew, reading every +// agent's sign-in, every plugin's sign-ins and the settings again, three +// builds a request, and seven agents at once kept magpie at 100–350% CPU +// (#2502). Requests at once share one build a second at most; a write +// magpie makes drops it at once (provider.Changed, plugin.OnChangeNow), +// and a file another program writes is seen within the second. +func holdCatalog(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer provider.Hold()() + defer filememo.Hold()() + h.ServeHTTP(w, r) + }) +} diff --git a/internal/gateway/request_builds_once_test.go b/internal/gateway/request_builds_once_test.go new file mode 100644 index 000000000..290cd75d1 --- /dev/null +++ b/internal/gateway/request_builds_once_test.go @@ -0,0 +1,28 @@ +package gateway + +import ( + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// A request builds the providers once, however many times it looks a +// model up on its way: each build reads every agent's sign-in, every +// plugin's and the settings, and three builds a request kept magpie at +// 100–350% CPU under seven agents at once (#2502). The next request, +// nothing held between them, builds afresh. +func TestRequestBuildsProvidersOnce(t *testing.T) { + plugin.UseCached(nil) + setup(t, provider.Chat, &fake{t: t, reply: sse(`{"choices":[{"delta":{"content":"hi"}}]}`, "[DONE]")}) + for i := range 2 { + n := provider.AllBuilt.Load() + code, body := post(t, "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 { + t.Fatalf("%d %s", code, body) + } + if got := provider.AllBuilt.Load() - n; got != 1 { + t.Fatalf("request %d built the providers %d times, want 1", i+1, got) + } + } +} diff --git a/internal/plugin/auth_parsed_once_test.go b/internal/plugin/auth_parsed_once_test.go new file mode 100644 index 000000000..98481a64d --- /dev/null +++ b/internal/plugin/auth_parsed_once_test.go @@ -0,0 +1,59 @@ +package plugin + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/lastgood" +) + +// plugin-auth.json is parsed once for each version of the file, however +// many times the sign-ins are asked for: every build of the providers +// asked once for each plugin, and parsed the whole file twice each time +// (#2502). A new version is read at once; one that doesn't parse is its +// last good generation, still unknown rather than none (#1505). +func TestAuthParsedOncePerVersion(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + os.MkdirAll(filepath.Dir(AuthPath()), 0o700) + write := func(s string) { + t.Helper() + if err := os.WriteFile(AuthPath(), []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + write(`{"fakeco":{"type":"api","key":"one"},"other#2":{"type":"oauth","accountId":"b@x"}}`) + if a := Auths("fakeco"); a["fakeco"]["key"] != "one" || len(a) != 1 { + t.Fatalf("Auths = %v", a) + } + SignedIn("other") + n := authParses.Load() + for range 100 { + Auths("fakeco") + Auths("other") + SignedIn("other") + listingProxies() + } + if got := authParses.Load() - n; got != 0 { + t.Fatalf("an unchanged plugin-auth.json was parsed %d more times", got) + } + // what a caller is given is its own + Auths("fakeco")["fakeco"]["key"] = "changed" + if a := Auths("fakeco"); a["fakeco"]["key"] != "one" { + t.Fatalf("a caller's change reached the next: %v", a) + } + // rewritten at once, the same size: read again + write(`{"fakeco":{"type":"api","key":"two"},"other#2":{"type":"oauth","accountId":"b@x"}}`) + if a := Auths("fakeco"); a["fakeco"]["key"] != "two" { + t.Fatalf("after a rewrite Auths = %v", a) + } + // zeroed by a crash: the last good generation + os.WriteFile(lastgood.Bak(AuthPath()), []byte(`{"fakeco":{"type":"api","key":"kept"}}`), 0o600) + write("\x00\x00\x00\x00") + if a := Auths("fakeco"); a["fakeco"]["key"] != "kept" { + t.Fatalf("a zeroed file read as %v, want its last good generation", a) + } + if !SignedIn("fakeco") { + t.Fatal("a zeroed file's sign-ins read as none") + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 761e4666e..09ccda7c1 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -23,6 +23,7 @@ import ( "time" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/settings" @@ -641,6 +642,9 @@ func changed() { } func changedNow() { + // the sign-ins are read again, even by a request holding the files it + // read (filememo.Hold): a sign-in just saved is in what comes next + filememo.Look(AuthPath()) onChangeMu.Lock() fs := append([]func(){}, onChangeNow...) onChangeMu.Unlock() diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 5ff373dcd..56b603a91 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -12,8 +12,10 @@ import ( "slices" "strings" "sync" + "sync/atomic" "time" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/steady" @@ -390,11 +392,7 @@ func listingProxies() map[string]map[string]string { if ProxyFor == nil { return out } - var m map[string]json.RawMessage - if b, err := readAuthFile(); err == nil { - _ = json.Unmarshal(b, &m) - } - for k := range m { + for k := range authRaw() { id := ProviderOf(k) if out[id] == nil { out[id] = map[string]string{"": forHost(ProxyFor(id, ""))} @@ -705,14 +703,51 @@ func firstNonEmpty(ss ...string) string { return "" } +// readAuth is plugin-auth.json's sign-ins as storedAuth, by key. What it +// returns is shared: the caller must not change it. func readAuth() map[string]storedAuth { - var m map[string]storedAuth - if b, err := readAuthFile(); err == nil { - _ = json.Unmarshal(b, &m) - } + m, _ := filememo.Read("plugin-auth:stored", AuthPath(), func(b []byte) (map[string]storedAuth, error) { + raw, err := parseAuth(b) + out := make(map[string]storedAuth, len(raw)) + for k, v := range raw { + var a storedAuth + _ = json.Unmarshal(v, &a) + out[k] = a + } + return out, err + }) return m } +// authRaw is plugin-auth.json's sign-ins by key, each as it is written. +// What it returns is shared: the caller must not change it. +func authRaw() map[string]json.RawMessage { + m, _ := filememo.Read("plugin-auth", AuthPath(), parseAuth) + return m +} + +// authParses counts plugin-auth.json's parses, for tests. +var authParses atomic.Int64 + +// parseAuth is plugin-auth.json's contents b, or its last good generation +// when b doesn't read (#1505). It is parsed once for each version of the +// file (filememo): the providers' every build read it whole, and parsed +// it twice over, for each plugin signed in to, on every request the +// gateway served (#2502). +func parseAuth(b []byte) (map[string]json.RawMessage, error) { + authParses.Add(1) + var m map[string]json.RawMessage + if json.Unmarshal(b, &m) != nil { + bak, err := lastgood.Fallback(AuthPath(), b, validAuth) + if err != nil { + return nil, err + } + m = nil + _ = json.Unmarshal(bak, &m) + } + return m, nil +} + // validAuth is plugin-auth.json's contents: one object of sign-ins. func validAuth(b []byte) bool { var m map[string]json.RawMessage @@ -965,15 +1000,15 @@ func Check(ctx context.Context, provider, account string) (Checked, error) { // Auths are provider's sign-ins as plugin-auth.json keeps them, by key. func Auths(provider string) map[string]map[string]any { - var m map[string]map[string]any - if b, err := readAuthFile(); err == nil { - _ = json.Unmarshal(b, &m) - } out := map[string]map[string]any{} - for k, v := range m { - if ProviderOf(k) == provider { - out[k] = v + for k, v := range authRaw() { + if ProviderOf(k) != provider { + continue } + // the caller's own: decoded afresh from what is shared + var a map[string]any + _ = json.Unmarshal(v, &a) + out[k] = a } return out } diff --git a/internal/settings/accounts.go b/internal/settings/accounts.go index c393a6c63..27dd0e768 100644 --- a/internal/settings/accounts.go +++ b/internal/settings/accounts.go @@ -3,6 +3,8 @@ package settings import ( "os" "strings" + + "github.com/yetone/magpie/internal/filememo" ) // AccountDiscoveryOff is whether magpie leaves agents' sign-ins unread @@ -10,7 +12,22 @@ import ( // but "", "0" or "false" for this process alone. The variable only ever // turns discovery off; it never turns on what the user saved off. func AccountDiscoveryOff() bool { - return noAccountsEnv() || Load().NoAccountDiscovery + if noAccountsEnv() { + return true + } + fileMu.RLock() + defer fileMu.RUnlock() + // the one setting, parsed once for each version of the file: it is + // asked for each agent and each plugin every time the providers are + // built, a whole parse of settings.json each (#2502) + off, err := filememo.Read("settings:no-accounts", Path(), func(b []byte) (bool, error) { + s, err := parse(b) + return s.NoAccountDiscovery, err + }) + if err != nil { + return load().NoAccountDiscovery + } + return off } // AccountDiscoveryOffIn is AccountDiscoveryOff with the settings already diff --git a/internal/settings/accounts_parsed_once_test.go b/internal/settings/accounts_parsed_once_test.go new file mode 100644 index 000000000..09cd48427 --- /dev/null +++ b/internal/settings/accounts_parsed_once_test.go @@ -0,0 +1,37 @@ +package settings + +import ( + "testing" +) + +// AccountDiscoveryOff parses settings.json once for each version of the +// file: it is asked for each agent and each plugin every time the +// providers are built, and parsed the whole file each time (#2502). A +// change saved is seen on the next ask. +func TestAccountDiscoveryOffParsedOnce(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("MAGPIE_NO_ACCOUNTS", "") + s := Load() + s.NoAccountDiscovery = true + if err := Save(s); err != nil { + t.Fatal(err) + } + if !AccountDiscoveryOff() { + t.Fatal("saved off, read on") + } + n := Parses() + for range 100 { + AccountDiscoveryOff() + } + if got := Parses() - n; got != 0 { + t.Fatalf("an unchanged settings.json was parsed %d more times", got) + } + s = Load() + s.NoAccountDiscovery = false + if err := Save(s); err != nil { + t.Fatal(err) + } + if AccountDiscoveryOff() { + t.Fatal("saved on, still read off") + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index a8bf19987..312dc5922 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -1039,6 +1039,14 @@ func loadChecked() (Settings, error) { } // parsed on every call: a caller that asks many times in one look holds // what it read (provider.Hold's heldSettings) rather than asking again + return parse(b) +} + +// parse is settings.json's contents b read as Settings, from its last good +// generation when b doesn't parse. +func parse(b []byte) (Settings, error) { + var s Settings + var err error parses.Add(1) if perr := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s); perr != nil { // one left all zero by a crash (#1505) is its last good generation