diff --git a/internal/budget/all_of_test.go b/internal/budget/all_of_test.go new file mode 100644 index 000000000..138793c53 --- /dev/null +++ b/internal/budget/all_of_test.go @@ -0,0 +1,138 @@ +package budget + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/usage" +) + +// a big ledger: perDay calls a day for days days over keys keys, each key +// holding a day, a week and a month limit +func bigLedger(tb testing.TB, days, perDay, keys int) []access.Key { + home := tb.TempDir() + tb.Setenv("HOME", home) + tb.Setenv("USERPROFILE", home) + tb.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + tb.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + Forget() + var ks []access.Key + for i := 0; i < keys; i++ { + name := fmt.Sprintf("k%d", i) + if _, err := access.Update("add-key", access.Change{Name: name}); err != nil { + tb.Fatal(err) + } + } + list, _ := access.List() + for _, k := range list { + for _, p := range []string{"day", "week", "month"} { + if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &access.Limit{Period: p, Tokens: 1 << 40}}); err != nil { + tb.Fatal(err) + } + } + } + list, _ = access.List() + ks = list + now := time.Now() + for d := 0; d < days; d++ { + for i := 0; i < perDay; i++ { + at := now.Add(-time.Duration(d)*24*time.Hour - time.Duration(i)*time.Second*86400/time.Duration(perDay)) + usage.Append(usage.Record{Time: at, Provider: "p", Model: "m", Input: 1000, Output: 100, Status: 200, CallerKeyID: ks[i%len(ks)].ID}) + } + } + return ks +} + +func BenchmarkAll(b *testing.B) { + ks := bigLedger(b, 31, 12000, 8) + All(ks[0], time.Now()) // the log's first parse is the ledger's, not this read's + b.ResetTimer() + for i := 0; i < b.N; i++ { + now := time.Now() + for _, k := range ks { + All(k, now) + } + } +} + +// AllOf counts what read counts for each window of each key, from one pass +// and from what the last call kept: keys with several limits, a scoped +// limit, a key issued under another, the log growing past full blocks +// between calls, and the log rewritten. +func TestAllOfIsWhatEachWindowRead(t *testing.T) { + ks := bigLedger(t, 3, 700, 3) + if _, err := access.Update("limit-key", access.Change{Key: ks[0].ID, Limit: &access.Limit{Period: "day", Tokens: 5000, Models: []string{"p/m"}}}); err != nil { + t.Fatal(err) + } + ks, _ = access.List() + now := time.Now() + same := func(when string) int { + t.Helper() + all := AllOf(ks, now) + if len(all) != len(ks) { + t.Fatalf("%s: %d rows for %d keys", when, len(all), len(ks)) + } + n := 0 + for i, k := range ks { + ls := k.Limits() + if len(all[i]) != len(ls) { + t.Fatalf("%s: key %d: %d statuses for %d limits", when, i, len(all[i]), len(ls)) + } + for j, l := range ls { + start, _ := l.Window(now) + want := read(k.ID, start, l) + got := all[i][j] + if got.Calls != want.calls || got.Tokens != want.tokens(l) || got.Cost != want.cost { + t.Fatalf("%s: key %d limit %d (%s): got %d calls %d tokens, read %d calls %d tokens", when, i, j, l.Period, got.Calls, got.Tokens, want.calls, want.tokens(l)) + } + n += got.Calls + } + } + return n + } + if same("first") == 0 { + t.Fatal("no call was counted at all") + } + same("again") + for round := 0; round < 3; round++ { + for i := 0; i < 400+round*300; i++ { + rec := usage.Record{Time: now.Add(-time.Duration(i) * time.Second), Provider: "p", Model: "m", Input: 10, Status: 200, CallerKeyID: ks[i%len(ks)].ID} + if i%5 == 0 { + rec.CallerKeyID, rec.CallerIssuerID = "child", ks[1].ID + } + Append(rec) + } + same(fmt.Sprintf("grown %d", round)) + } + // rewritten: the log is another file's + if err := os.WriteFile(usage.Path(), nil, 0o600); err != nil { + t.Fatal(err) + } + if n := same("cleared"); n != 0 { + t.Fatalf("a cleared log counted %d calls", n) + } + if one := All(ks[1], now); len(one) != len(ks[1].Limits()) { + t.Fatalf("All: %+v", one) + } +} + +// BenchmarkReadEach is how All answered before AllOf: the ledger read +// again for each window of each key. +func BenchmarkReadEach(b *testing.B) { + ks := bigLedger(b, 31, 12000, 8) + All(ks[0], time.Now()) // the log's first parse is the ledger's, not this read's + b.ResetTimer() + for i := 0; i < b.N; i++ { + now := time.Now() + for _, k := range ks { + for _, l := range k.Limits() { + start, _ := l.Window(now) + read(k.ID, start, l) + } + } + } +} diff --git a/internal/budget/budget.go b/internal/budget/budget.go index f741a953a..681f8e06b 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -203,6 +203,9 @@ func Forget() { defer state.Unlock() state.sums = map[string][]*sums{} state.held = map[window]*held{} + kept.Lock() + clear(kept.of) + kept.Unlock() } // Append writes rec to usage.jsonl and, for a key's call, counts it @@ -301,25 +304,155 @@ func Of(k access.Key, now time.Time) *Status { // order k keeps them; none for a key with no limit. A window two // limits share is read once. func All(k access.Key, now time.Time) []Status { - ls := k.Limits() - var out []Status - read1 := map[window]*sums{} - for _, l := range ls { - start, reset := l.Window(now) - w := window{slot(k.ID), start.Unix(), l.Scope()} - s := read1[w] - if s == nil { - s = read(k.ID, start, l) - read1[w] = s + return AllOf([]access.Key{k}, now)[0] +} + +// AllOf is All for each of keys, in their order, from one pass over the +// ledger, and from what the last pass counted: the Gateway page asked for +// every key's limits and read a month of the log again for each window of +// each key, on every poll, which timed out behind a proxy for a user with +// 12,000 calls a day (aiandcloud on X). A window's full blocks of the log +// are counted once and kept (usage.VisitFrom); each call counts the rows +// after them. The gateway's own count (sumsFor) is the one a limit is +// held by, and still reads the file on its own. +func AllOf(keys []access.Key, now time.Time) [][]Status { + type want struct { + w window + prefix sums // the full blocks' rows + cur usage.Cursor + total *sums // and the rows after them + } + out := make([][]Status, len(keys)) + wants := make([][]*want, len(keys)) + byKey := map[string][]*want{} // by the key a call is recorded under, or issued under + var all []*want + for i, k := range keys { + seen := map[window]*want{} + for _, l := range k.Limits() { + start, _ := l.Window(now) + w := window{slot(k.ID), start.Unix(), l.Scope()} + x := seen[w] + if x == nil { + x = &want{w: w} + x.prefix = sums{start: start, scope: l.Scope()} + if l.Scoped() { + x.prefix.models = scopeModels(l) + } + kept.Lock() + if e, ok := kept.of[w]; ok { + x.prefix, x.cur = e.prefix, e.cur + } + kept.Unlock() + seen[w] = x + byKey[k.ID] = append(byKey[k.ID], x) + all = append(all, x) + } + wants[i] = append(wants[i], x) + } + } + if len(all) > 0 { + cost := usage.NewCoster() + // the windows that stopped at the same place read together + for len(all) > 0 { + cur := all[0].cur + var group, rest []*want + for _, x := range all { + if x.cur == cur { + group = append(group, x) + } else { + rest = append(rest, x) + } + } + all = rest + since := group[0].prefix.start + for _, x := range group { + if x.prefix.start.Before(since) { + since = x.prefix.start + } + } + ofGroup := map[string][]*want{} + for _, x := range group { + for id, ws := range byKey { + if slices.Contains(ws, x) { + ofGroup[id] = append(ofGroup[id], x) + } + } + } + count := func(into func(*want) *sums) func(usage.Record) { + return func(r usage.Record) { + ws := ofGroup[r.CallerKeyID] + if r.CallerIssuerID != "" && r.CallerIssuerID != r.CallerKeyID { + ws = append(slices.Clone(ws), ofGroup[r.CallerIssuerID]...) + } + if len(ws) == 0 || !counts(r) { + return + } + var c float64 + var ok, priced bool + for _, x := range ws { + // a key issued under keyID spends from its limits too + if s := into(x); !r.Time.Before(s.start) && s.counts(r) { + if !priced { + c, ok = cost(r) + priced = true + } + s.add(r, c, ok) + } + } + } + } + next := usage.VisitFrom(since, cur, + func() { + for _, x := range group { + x.prefix = sums{start: x.prefix.start, scope: x.prefix.scope, models: x.prefix.models} + } + }, + count(func(x *want) *sums { return &x.prefix }), + count(func(x *want) *sums { + if x.total == nil { + c := x.prefix + x.total = &c + } + return x.total + })) + for _, x := range group { + x.cur = next + if x.total == nil { + c := x.prefix + x.total = &c + } + kept.Lock() + if len(kept.of) > 1024 { + clear(kept.of) + } + kept.of[x.w] = keptSums{prefix: x.prefix, cur: next} + kept.Unlock() + } + } + } + state.Lock() + defer state.Unlock() + for i, k := range keys { + for j, l := range k.Limits() { + x := wants[i][j] + _, reset := l.Window(now) + out[i] = append(out[i], status(k.ID, l, x.total, state.held[x.w], reset)) } - state.Lock() - h := state.held[w] - out = append(out, status(k.ID, l, s, h, reset)) - state.Unlock() } return out } +// kept is what AllOf counted of each window's full blocks of the log. +var kept = struct { + sync.Mutex + of map[window]keptSums +}{of: map[window]keptSums{}} + +type keptSums struct { + prefix sums + cur usage.Cursor +} + // Binding is the one of a key's statuses that holds it most: of those // spent, the one that resets last, as the key is refused until then; // else the one with the most of a cap used. Nil for none. A limit of diff --git a/internal/gui/api.go b/internal/gui/api.go index 9e24ca63c..e1c7f72db 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -3489,6 +3489,11 @@ func fail(rw http.ResponseWriter, err error) { out["code"], out["bun"], out["bunWhy"] = "bun_unstartable", bun.Bun, bun.Why out["said"] = bunSaid[bun.Why] } + // a proxy's web page inside the text: its title, said in the reader's + // language, never the markup + if what, ok := webPageSaid(out["error"]); ok && out["said"] == "" { + out["error"], out["said"], out["what"] = "A proxy in front of magpie answered, not magpie ("+what+")", "A proxy in front of magpie answered, not magpie ({what})", what + } _ = json.NewEncoder(rw).Encode(out) } diff --git a/internal/gui/caller_keys.go b/internal/gui/caller_keys.go index 2f020771d..17de1a73d 100644 --- a/internal/gui/caller_keys.go +++ b/internal/gui/caller_keys.go @@ -54,8 +54,9 @@ type keyMCPJSON struct { func withLimits(keys []access.Key) []keyRow { now := time.Now() out := make([]keyRow, 0, len(keys)) - for _, k := range keys { - row := keyRow{Key: k, UsedAll: budget.All(k, now)} + all := budget.AllOf(keys, now) + for i, k := range keys { + row := keyRow{Key: k, UsedAll: all[i]} if len(row.UsedAll) > 0 { row.Used = &row.UsedAll[0] } diff --git a/internal/gui/tests/gateway-keys-proxy-page.test.cjs b/internal/gui/tests/gateway-keys-proxy-page.test.cjs new file mode 100644 index 000000000..4fecc53ba --- /dev/null +++ b/internal/gui/tests/gateway-keys-proxy-page.test.cjs @@ -0,0 +1,90 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Gateway page's keys list, read through a proxy that answers with its +// own web page (Cloudflare's 524 when the read outlasted its 100 seconds): +// the section showed " + +