diff --git a/internal/provider/client_shapes_test.go b/internal/provider/client_shapes_test.go index d8ff47dfa..bb974747e 100644 --- a/internal/provider/client_shapes_test.go +++ b/internal/provider/client_shapes_test.go @@ -42,3 +42,30 @@ func TestClientShapeWrittenOnceForTwoWindows(t *testing.T) { t.Fatalf("a new Codex version's User-Agent was not kept: %q", got) } } + +// /api/providers asks the shape of every relay it lists: the file is +// parsed once until it changes, and what a caller does to its copy is +// not what the next one gets. +func TestClientShapeParsedOnceUntilWritten(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clientShapes.Lock() + clientShapes.written = nil + clientShapes.Unlock() + SawClient(ClientClaudeCode, http.Header{"User-Agent": {"claude-cli/2.1.0 (external, cli)"}}) + clientShape(ClientClaudeCode) + parses := shapeParses.Load() + for range 30 { + h := clientShape(ClientClaudeCode) + if h.Get("User-Agent") != "claude-cli/2.1.0 (external, cli)" { + t.Fatalf("shape read back as %v", h) + } + h.Set("User-Agent", "changed") + } + if n := shapeParses.Load() - parses; n != 0 { + t.Fatalf("30 asks parsed the file %d times, want 0", n) + } + SawClient(ClientClaudeCode, http.Header{"User-Agent": {"claude-cli/2.2.0 (external, cli)"}}) + if got := clientShape(ClientClaudeCode).Get("User-Agent"); got != "claude-cli/2.2.0 (external, cli)" { + t.Fatalf("after a write: %q", got) + } +} diff --git a/internal/provider/hold.go b/internal/provider/hold.go index 543b818b6..1c02bc036 100644 --- a/internal/provider/hold.go +++ b/internal/provider/hold.go @@ -32,6 +32,10 @@ var held struct { fgen uint64 // roots is the providers' and the settings' files as last looked at roots [2]rootStamp + // stamp is StampNow's files as a request holding the catalog last + // looked at them, at stampAt (stampNowFiles) + stamp [3]rootStamp + stampAt time.Time } // rootStamp is a file's time and size, or that it wasn't there. @@ -119,6 +123,8 @@ func Hold() (release func()) { held.built, held.env = nil, env } heldFreshLocked(true) + // a request's first StampNow looks at the files again + held.stampAt = time.Time{} } held.holds++ held.Unlock() @@ -175,8 +181,34 @@ func StampNow() Stamp { held.Lock() gen := held.gen held.Unlock() - return Stamp{gen: gen, fgen: filememo.Gen(), env: environSum(), - roots: [3]rootStamp{stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath())}} + return Stamp{gen: gen, fgen: filememo.Gen(), env: environSum(), roots: stampNowFiles()} +} + +// stampLooks counts StampNow's looks at its files, for a test. +var stampLooks atomic.Int64 + +// stampNowFiles is the files' part of StampNow: looked at once by a +// request holding the catalog and its overlapping ones, for heldFor at +// most, as what is held is. KeptListing takes a stamp for every +// provider, and its three stats a provider were most of what a +// Providers page poll spent (~600 of them a poll with 200 providers). +// Another process's write is seen by the next request, as Hold's look +// sees it. +func stampNowFiles() [3]rootStamp { + held.Lock() + roots, fresh := held.stamp, held.holds > 0 && !held.stampAt.IsZero() && time.Since(held.stampAt) < heldFor + held.Unlock() + if fresh { + return roots + } + stampLooks.Add(1) + roots = [3]rootStamp{stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath())} + held.Lock() + if held.holds > 0 { + held.stamp, held.stampAt = roots, time.Now() + } + held.Unlock() + return roots } // Held is what build gives, built once while a request holds it (Hold), diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 31d6409bf..79f1ded63 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -946,8 +946,19 @@ func (p Provider) SignedOut() bool { } // Logins lists the remembered accounts of an agent ("" for every one), -// the active one flagged. +// the active one flagged. A request lists an agent's once: /api/providers +// asks it of every provider, twice with its account models, and each +// took logins.json's lock, a file opened across magpies (a seventh of +// the list's CPU). The caller gets its own copy. func Logins(agent string) []Login { + return slices.Clone(heldOf("logins\x00"+agent, func() []Login { return loginsNow(agent) })) +} + +// loginsRuns counts the lists Logins made (a test reads it). +var loginsRuns atomic.Int64 + +func loginsNow(agent string) []Login { + loginsRuns.Add(1) if settings.AccountDiscoveryOff() { return nil } diff --git a/internal/provider/logins_held_test.go b/internal/provider/logins_held_test.go new file mode 100644 index 000000000..666872fb1 --- /dev/null +++ b/internal/provider/logins_held_test.go @@ -0,0 +1,48 @@ +package provider + +import ( + "testing" + "time" +) + +// TestLoginsListedOnceARequest: /api/providers asks an agent's accounts +// of every provider, and each list took logins.json's lock; a request +// lists an agent's once, a copy each, and a write in it lists anew. +func TestLoginsListedOnceARequest(t *testing.T) { + signIn(t) + loginsSeenAt.Store(0) // another test's look within 30s would skip this HOME's + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Hour // a loaded machine's pause isn't the bound + release := Hold() + defer func() { release() }() + Logins("codex") // the first list notes the sign-in in logins.json + first := Logins("codex") + if len(first) != 1 || first[0].User != "me@example.com" { + t.Fatalf("codex accounts: %+v", first) + } + runs := loginsRuns.Load() + for range 20 { + ls := Logins("codex") + if len(ls) != 1 || ls[0].User != "me@example.com" { + t.Fatalf("listed again as %+v", ls) + } + ls[0].User = "changed" + } + if n := loginsRuns.Load() - runs; n != 0 { + t.Fatalf("20 lists in one request listed %d times, want 0", n) + } + if err := writeLogins(readLogins()); err != nil { + t.Fatal(err) + } + Logins("codex") + if n := loginsRuns.Load() - runs; n != 1 { + t.Fatalf("after a write: listed %d times, want 1", n) + } + release() + release = func() {} + Logins("codex") + Logins("codex") + if n := loginsRuns.Load() - runs; n != 3 { + t.Fatalf("outside a request: listed %d times, want 3", n) + } +} diff --git a/internal/provider/logins_shared_test.go b/internal/provider/logins_shared_test.go index e4ee957cc..0c136b8e7 100644 --- a/internal/provider/logins_shared_test.go +++ b/internal/provider/logins_shared_test.go @@ -16,7 +16,7 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) { pp := plugin.Provider{ID: "fakeco", Accounts: []plugin.Account{{Key: "k1", AccountID: "one"}}} sideLogins("google", "a@example.com", all) // its own sign-in: written pluginLogins(pp) // its account: written - before := loginsCopied.Load() + before, locks := loginsCopied.Load(), pluginLoginLocks.Load() for range 20 { sideLogins("google", "a@example.com", all) if got := pluginLogins(pp); len(got) != 1 || got[0].User != "one" { @@ -26,6 +26,11 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) { if n := loginsCopied.Load() - before; n != 0 { t.Fatalf("20 lists with nothing to change copied the accounts %d times", n) } + // nor took logins.json's lock, a file opened across magpies + if n := pluginLoginLocks.Load() - locks; n != 0 { + t.Fatalf("20 plugin lists with nothing to change took the lock %d times", n) + } + locks = pluginLoginLocks.Load() pp.Accounts = append(pp.Accounts, plugin.Account{Key: "k2", AccountID: "two"}) if got := pluginLogins(pp); len(got) != 2 { @@ -35,6 +40,9 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) { if got := pluginLogins(pp); len(got) != 1 || got[0].User != "two" { t.Fatalf("a signed-out account is still listed: %+v", got) } + if n := pluginLoginLocks.Load() - locks; n != 2 { + t.Fatalf("two changes took the lock %d times, want 2", n) + } n := 0 for _, l := range readLogins() { if l.Agent == "plugin:fakeco" { diff --git a/internal/provider/models.go b/internal/provider/models.go index 800313eee..e9c8b2ec2 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -136,7 +136,13 @@ func (p Provider) Fetched() (time.Time, bool) { // for a built-in, listed by its plugin for a plugin's. func (p Provider) Listed() (time.Time, bool) { if p.IsPlugin() { - return plugin.ListedAt() + // one look at the plugins' list a request, not one a provider + type listed struct { + at time.Time + ok bool + } + l := heldOf("plugin-listed", func() listed { at, ok := plugin.ListedAt(); return listed{at, ok} }) + return l.at, l.ok } return p.Fetched() } diff --git a/internal/provider/plugin_accounts.go b/internal/provider/plugin_accounts.go index 8eccf7350..2065b21ad 100644 --- a/internal/provider/plugin_accounts.go +++ b/internal/provider/plugin_accounts.go @@ -7,6 +7,7 @@ import ( "net/http" "slices" "strings" + "sync/atomic" "time" "github.com/yetone/magpie/internal/plugin" @@ -202,6 +203,10 @@ var pluginOwnUser = func(id string) string { return "" } +// pluginLoginLocks counts the times pluginLogins took loginsMu (a test +// reads it). +var pluginLoginLocks atomic.Int64 + // pluginLogins are the provider's accounts, the first in use first. What // plugin-auth.json keeps is the truth: logins.json follows it. The agent's // own account is named as the agent is signed in now; removed in magpie, @@ -224,53 +229,61 @@ func pluginLogins(pp plugin.Provider) []pluginLogin { mark = ownMark(pp.ID) } labels := pluginLabels(pp, named) - loginsMu.Lock() // looked at as kept, and copied only at the first change: nearly // every list changes nothing, and a page's state lists each plugin's - ls := sharedLogins() - changed := false - have := map[string]bool{} - var keep []savedLogin - for i, l := range ls { - drop, edit := false, false - if l.Agent == agent { - if _, ok := byKey[l.Home]; !ok || have[l.Home] { - drop = true // signed out, or listed twice - } else { - have[l.Home] = true - renamed := l.User != labels[l.Home] - if renamed { - l.User, edit = labels[l.Home], true - } - // the agent's own, hidden, shows again once the agent signs - // in anew: told by its sign-in's mark, else by another account - if l.Hidden != "" && own[l.Home] && (mark != "" && mark != l.Hidden || mark == "" && l.Hidden == hiddenNoMark && renamed) { - l.Hidden, edit = "", true + settle := func(ls []savedLogin) ([]savedLogin, bool) { + changed := false + have := map[string]bool{} + var keep []savedLogin + for i, l := range ls { + drop, edit := false, false + if l.Agent == agent { + if _, ok := byKey[l.Home]; !ok || have[l.Home] { + drop = true // signed out, or listed twice + } else { + have[l.Home] = true + renamed := l.User != labels[l.Home] + if renamed { + l.User, edit = labels[l.Home], true + } + // the agent's own, hidden, shows again once the agent signs + // in anew: told by its sign-in's mark, else by another account + if l.Hidden != "" && own[l.Home] && (mark != "" && mark != l.Hidden || mark == "" && l.Hidden == hiddenNoMark && renamed) { + l.Hidden, edit = "", true + } } } - } - if (drop || edit) && !changed { - keep, changed = slices.Clone(ls[:i:i]), true - } - if changed && !drop { - keep = append(keep, l) - } - } - if changed { - ls = keep - } - for _, a := range pp.Accounts { - if !have[a.Key] { - if !changed { - ls, changed = slices.Clone(ls), true + if (drop || edit) && !changed { + keep, changed = slices.Clone(ls[:i:i]), true + } + if changed && !drop { + keep = append(keep, l) } - ls = append(ls, savedLogin{Agent: agent, User: labels[a.Key], Home: a.Key, On: true, Seen: time.Now().UTC().Truncate(time.Second)}) } + if changed { + ls = keep + } + for _, a := range pp.Accounts { + if !have[a.Key] { + if !changed { + ls, changed = slices.Clone(ls), true + } + ls = append(ls, savedLogin{Agent: agent, User: labels[a.Key], Home: a.Key, On: true, Seen: time.Now().UTC().Truncate(time.Second)}) + } + } + return ls, changed } - if changed { - _ = writeLogins(ls) + // what nothing changes takes no lock: taken, it opens logins.json's + // lock file, across magpies, and /api/providers lists every plugin + // (a fifth of its CPU). A change is made from a read under it. + if _, changed := settle(sharedLogins()); changed { + pluginLoginLocks.Add(1) + loginsMu.Lock() + if ls, changed := settle(sharedLogins()); changed { + _ = writeLogins(ls) + } + loginsMu.Unlock() } - loginsMu.Unlock() var out []pluginLogin for _, l := range sideLogins(agent, "", func(l savedLogin) bool { _, ok := byKey[l.Home]; return ok && l.Hidden == "" }) { l.Lapsed = l.saved.Lapsed // a refused sign-in shows on the account diff --git a/internal/provider/stamp_once_test.go b/internal/provider/stamp_once_test.go new file mode 100644 index 000000000..0643ba1fc --- /dev/null +++ b/internal/provider/stamp_once_test.go @@ -0,0 +1,50 @@ +package provider + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// TestStampLooksOnceARequest: a request holding the catalog looks at +// StampNow's files once, not once for each provider it lists, and the +// next request sees a file another process wrote between them. +func TestStampLooksOnceARequest(t *testing.T) { + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Hour // a loaded machine's pause isn't the bound + if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + release := Hold() + looks := stampLooks.Load() + first := StampNow() + for range 50 { + if StampNow() != first { + t.Fatal("the stamp moved within a request") + } + } + if n := stampLooks.Load() - looks; n != 1 { + t.Fatalf("51 stamps in one request looked %d times, want 1", n) + } + release() + + // another process rewrites the providers' file: a size of its own + b, err := os.ReadFile(Path()) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(Path(), append(b, '\n', '\n'), 0o600); err != nil { + t.Fatal(err) + } + defer Hold()() + if StampNow() == first { + t.Fatal("the next request's stamp missed another process's write") + } +} diff --git a/internal/provider/test_as.go b/internal/provider/test_as.go index f5ead83e1..2a17d253e 100644 --- a/internal/provider/test_as.go +++ b/internal/provider/test_as.go @@ -10,6 +10,9 @@ import ( "slices" "strings" "sync" + "sync/atomic" + + "github.com/yetone/magpie/internal/filememo" ) // A relay can serve only the agents its plan is sold for, and tell them by @@ -180,12 +183,25 @@ func equalHeaders(a, b http.Header) bool { return a != nil && maps.EqualFunc(map[string][]string(a), map[string][]string(b), slices.Equal[[]string]) } +// shapeParses counts client-shapes.json's parses (a test reads it). +var shapeParses atomic.Int64 + // clientShape is the headers last seen from client, nil when it hasn't -// come through. +// come through. The file is parsed once until it changes: /api/providers +// asks it of every relay a list shows, and read anew each time it was a +// sixth of the list's CPU. A copy goes out, as a request's headers take +// it. func clientShape(client string) http.Header { - clientShapes.Lock() - defer clientShapes.Unlock() - return readClientShapes(clientShapesPath())[client] + m, err := filememo.Read("client-shapes", clientShapesPath(), func(b []byte) (map[string]http.Header, error) { + shapeParses.Add(1) + m := map[string]http.Header{} + json.Unmarshal(b, &m) + return m, nil + }) + if err != nil { + return nil + } + return m[client].Clone() } // clientHeaders puts client's headers on a test request: those last seen