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 " + +${title} +

A timeout occurred

`; + +const CASES = [ + { status: 524, title: "magpie.example.com | 524: A timeout occurred", key: "A proxy in front of magpie stopped waiting; magpie may still be finishing, check again in a minute ({what})" }, + { status: 502, title: "magpie.example.com | 502: Bad gateway", key: "A proxy in front of magpie answered, not magpie ({what})" }, + { status: 200, title: "Sign in", key: "A proxy in front of magpie answered, not magpie ({what})" }, +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: the keys list read through a proxy's error page says so, in words`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const c of CASES) { + const page = await (await browser.newContext({ viewport: { width: 420, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const base = fixture(lang, "light", [], { lan: true, web: true }); + await page.route("**/*", (route) => { + if (new URL(route.request().url()).pathname === "/api/caller-keys") { + return route.fulfill({ status: c.status, contentType: "text/html; charset=UTF-8", body: page524(c.title) }); + } + return base(route); + }); + await page.goto("http://magpie.test/?view=gateway"); + const none = page.locator("#gatewayKeys .gw-keys .none"); + await none.waitFor(); + const said = (await none.textContent()).trim(); + assert.equal(said, tr(lang, c.key, { what: c.title }), `${c.status}`); + assert.doesNotMatch(await page.locator("#gatewayKeys").textContent(), / document.documentElement.scrollWidth <= document.documentElement.clientWidth + 1), "fits"); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + } +} + +// the same page inside magpie's own JSON error, as the server says it when +// a request it made to a remote magpie or a vendor came back as a proxy's +// page: the toast of a key action says the title, not the markup +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: a web page inside magpie's error is said by its title`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 420, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const base = fixture(lang, "light", [], { lan: true, web: true }); + const title = "magpie.example.com | 524: A timeout occurred"; + await page.route("**/*", (route) => { + if (new URL(route.request().url()).pathname === "/api/caller-keys" && route.request().method() === "GET") { + return route.fulfill({ status: 400, json: { error: "remote magpie answered 524: " + title, said: "A proxy in front of magpie answered, not magpie ({what})", what: "remote magpie answered 524: " + title } }); + } + return base(route); + }); + await page.goto("http://magpie.test/?view=gateway"); + const none = page.locator("#gatewayKeys .gw-keys .none"); + await none.waitFor(); + const said = (await none.textContent()).trim(); + assert.equal(said, tr(lang, "A proxy in front of magpie answered, not magpie ({what})", { what: "remote magpie answered 524: " + title })); + assert.doesNotMatch(said, /]*>(.*?)`) +) + +// webPageSaid is a proxy's own web page inside an error text of magpie's: +// a request magpie made to a remote magpie or a vendor came back as +// Cloudflare's 524 page, and the Gateway page showed " +// +magpie.example.com | 524: A timeout occurred +

A timeout occurred

` + +// An error with a proxy's page in it reaches the page as the page's title, +// said by a key the GUI translates, and not as markup. +func TestFailSaysAProxyPageByItsTitle(t *testing.T) { + w := httptest.NewRecorder() + fail(w, errors.New("remote magpie answered 524: "+cf524)) + var got map[string]string + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + what := "remote magpie answered 524: magpie.example.com | 524: A timeout occurred" + if got["what"] != what || got["said"] != "A proxy in front of magpie answered, not magpie ({what})" { + t.Fatalf("got %v", got) + } + if strings.Contains(got["error"], "<") { + t.Fatalf("markup in the error: %q", got["error"]) + } + // no page: the text stays as it was + w = httptest.NewRecorder() + fail(w, errors.New("a < b and bold")) + got = nil + _ = json.Unmarshal(w.Body.Bytes(), &got) + if got["error"] != "a < b and bold" || got["said"] != "" { + t.Fatalf("plain text changed: %v", got) + } +} diff --git a/internal/usage/visit_from.go b/internal/usage/visit_from.go new file mode 100644 index 000000000..c61c041fc --- /dev/null +++ b/internal/usage/visit_from.go @@ -0,0 +1,42 @@ +package usage + +import "time" + +// Cursor is where a reader stopped in the log: the full blocks it has +// read, which the log keeps as they are while it only grows. The zero +// Cursor starts at the beginning. +type Cursor struct { + path string + n int + last *rowChunk +} + +// VisitFrom is Visit for a reader that keeps what it counted of the rows +// before cur: settled is called with each record of the full blocks after +// cur, which the reader keeps and the next call starts after; tail is +// called with the rows of the last, partial block, which it counts again +// each call. A cur the log has left behind (rewritten, cleared, another +// file) starts over: reset is called first, and settled gets every record. A +// reader of the Gateway page's key limits read a month of the log, row by +// row, for each poll. +func VisitFrom(since time.Time, cur Cursor, reset func(), settled, tail func(Record)) Cursor { + s := readLogSnapshot() + n := cur.n + full := len(s.blocks) + if full > 0 && s.blocks[full-1].Count < logBlockRows { + full-- + } + if n > full || n > 0 && (cur.path != s.path || s.blocks[n-1] != cur.last) { + n = 0 + reset() + } + visitBlocks(s.blocks[n:full], since, settled) + if full < len(s.blocks) { + visitBlocks(s.blocks[full:], since, tail) + } + next := Cursor{path: s.path, n: full} + if full > 0 { + next.last = s.blocks[full-1] + } + return next +}