quotas: the gateway's whole-page refresh reads saved Claude accounts again too (#5443)
POST /v1/magpie/quotas/refresh with no card named ran ReadAllCards, which only cleared the caches (AskUsage). A saved, inactive Claude account's /usage was never run again, so another magpie's refresh of this one, or an app with a gateway key, kept showing its old numbers. #5380 (814a625a2) fixed the GUI and the TUI and missed this route. - ReadAllCards asks AskEveryClaudeUsage, as the Usage page's Refresh does. The 30s per-account floor and the running holds are unchanged; saved accounts are read side by side by fetchSubscriptionUsage, each bounded by its 20s wait, inside the handler's 30s. - A key told only some cards had them read one after another, each waiting up to 20s, so a few cards outlasted the 30s handler. RefreshEach reads them side by side. - Another magpie's refresh of its remote card waited 8s for the POST (remoteBody's GET wait) and fetched the old cards while the remote was still reading. The refresh POST now waits remoteRefreshWait (25s); kept-card and history GETs keep 8s. Other routes checked: the GUI's asked=1&all=1 and the TUI's r already read every account. The CLI has no whole-page refresh: `magpie quota` and `accounts` open with AskClaudeUsage by design, `quota refresh <provider>` reads per card, `quota wait` waits, `accounts refresh` renews logins. Unchanged. Run at this head (rebased onb4799a6bb), on mote through mote-run: go vet, go test -count=1 ./internal/provider: ok (148.3s) Run atf86dd7910(b4799a6bbsince touched quota history in provider only): go test -count=1 ./internal/provider: ok (131.9s) go test -count=1 -run 'Quota|Remote|LAN|Lan|Cors|ReadOnly|Readonly|Held|Antigravity|Draw' ./internal/gateway: ok (36.3s) go vet of internal/provider and internal/gateway: clean. GOOS=linux and GOOS=windows go vet of both, atd2c29abe7: clean. gofmt -l: clean. Broken by hand, each red, then restored: ReadAllCards back to AskUsage: TestReadAllCardsReadsSavedClaude fails (ran the saved account's /usage 0 times, want once more). The refresh POST back on the 8s wait (remoteWait): TestRemoteMagpieRefreshWaitedFor fails (old Used 0). RefreshEach made serial: TestRefreshEachReadsSideBySide fails (alone). Not tried: the reporter's case end to end with a built magpie in a sandbox HOME (a fake claude binary behind a real gateway); a real Claude account; Windows and Linux runs (vetted for both). The full suite runs after the push, under mote's suite lock. Reported-by: prgrmrwy
This commit is contained in:
+4
-2
@@ -551,8 +551,10 @@ shared magpie's cards named with it (`Codex · office`, id `office/codex`), as
|
||||
that magpie last read them — only the computer holding the sign-ins asks the
|
||||
vendors, and it answers from what it has kept (`GET /v1/magpie/quotas/cards`).
|
||||
A card's refresh here has it read that card once more
|
||||
(`POST /v1/magpie/quotas/refresh`, at most once in 30 seconds a card); until it
|
||||
has read anything, the remote's one card says so. Their history is shown with
|
||||
(`POST /v1/magpie/quotas/refresh`, at most once in 30 seconds a card); the
|
||||
remote's own card has it read every card, each saved Claude account's
|
||||
`/usage` too, as its Usage page's Refresh does, and is waited for up to 25
|
||||
seconds (#5443). Until it has read anything, the remote's one card says so. Their history is shown with
|
||||
its own. A check-in is pressed on that computer, not here. A Codex card's
|
||||
reset can be used from here (#3850): **Use one…** asks first, as for this
|
||||
computer's accounts, and that magpie spends it on its account
|
||||
|
||||
@@ -309,7 +309,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. `savedTokenMu` stops two requests refreshing one saved account at once.
|
||||
- A Claude subscription account is used only for Claude Code, through the genuine Claude Code binary (see [Claude subscription bridge](claude-subscription-bridge.md)).
|
||||
- Claude usage asks are ordered by `claudeAskGeneration`, not wall-clock timestamps. `AskClaudeUsage` and a Claude card's `RefreshUsage` advance it while holding the subscription cache then the login cache lock (`markClaudeUsageAsked`). Each cache captures it under its own lock before launching a read and checks it under that lock when publishing: a newer ask prevents `LoginUsage` from keeping the older reading and leaves `SubscriptionUsage` due to read again. Each `claudeWindows` entry records the generation its run answered. The timestamp's zero sentinel, `tried`/`wait`, the 30-second floor, idle behavior and saved-account scope remain unchanged. [`login_usage.go`](../../internal/provider/login_usage.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go).
|
||||
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked), or when every allowance is refreshed by hand (#5380): the tray panel's and the Usage page's top refresh, Routing's Read allowances and the TUI's `r` ask `usage/quotas?asked=1&all=1` (`AskEveryClaudeUsage`), which marks its generation in `claudeEveryAsked`, and for `claudeEveryFor` (2 minutes) each saved account not read since is read as its card's refresh would, under the same due check and 30-second floor (`TestRefreshEveryReadsSavedClaude`). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page or the Allowances tab opened, `magpie quota` and `magpie accounts` ask every card without `all` and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (`markClaudeRun`, `<dir>.run-<pid>-<n>.lock`), and the switch waits on every one there first (`waitClaudeRuns`, up to `claudeRunWait`, 90s, then `errClaudeRunning` with the sign-in left as it was): before, `magpie accounts switch` didn't wait for the app's run (#4532; `TestClaudeSwitchWaitsForAnotherMagpiesRun`, `TestClaudeSwitchRunHeldAndLeft`). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (`handedOver`, `subscriptionRun.handed`, `TestClaudeHandOverEndsTheAccountsBusyRuns`). After the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run goes through the account's reading as a card refresh's does (`keepingAlive` has `claudeWindows` run it, past the 30-second floor; `loginReading` keeps it beside the account and on disk, `keepCardRead` on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits `keepAliveRetry` (6 hours, `renewWaiting`) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it; `magpie accounts refresh` tries it at once (`TestRenewLoginsKeepsSavedClaudeSignedIn`, `TestRenewLoginsKeepsClaudeReading`, `TestRenewLoginsFailedWaitsItsTurn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
|
||||
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked), or when every allowance is refreshed by hand (#5380): the tray panel's and the Usage page's top refresh, Routing's Read allowances and the TUI's `r` ask `usage/quotas?asked=1&all=1` (`AskEveryClaudeUsage`), and so does the gateway's `POST /v1/magpie/quotas/refresh` with no card named (`ReadAllCards`: another magpie's refresh of its card for this one, or an app with a gateway key, #5443; `TestReadAllCardsReadsSavedClaude`; a key told only some cards has each read again side by side, `RefreshEach`, and the other magpie waits `remoteRefreshWait`, 25s, for the refresh, not the 8s of a kept-cards read), which marks its generation in `claudeEveryAsked`, and for `claudeEveryFor` (2 minutes) each saved account not read since is read as its card's refresh would, under the same due check and 30-second floor (`TestRefreshEveryReadsSavedClaude`). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page or the Allowances tab opened, `magpie quota` and `magpie accounts` ask every card without `all` and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (`markClaudeRun`, `<dir>.run-<pid>-<n>.lock`), and the switch waits on every one there first (`waitClaudeRuns`, up to `claudeRunWait`, 90s, then `errClaudeRunning` with the sign-in left as it was): before, `magpie accounts switch` didn't wait for the app's run (#4532; `TestClaudeSwitchWaitsForAnotherMagpiesRun`, `TestClaudeSwitchRunHeldAndLeft`). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (`handedOver`, `subscriptionRun.handed`, `TestClaudeHandOverEndsTheAccountsBusyRuns`). After the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run goes through the account's reading as a card refresh's does (`keepingAlive` has `claudeWindows` run it, past the 30-second floor; `loginReading` keeps it beside the account and on disk, `keepCardRead` on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits `keepAliveRetry` (6 hours, `renewWaiting`) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it; `magpie accounts refresh` tries it at once (`TestRenewLoginsKeepsSavedClaudeSignedIn`, `TestRenewLoginsKeepsClaudeReading`, `TestRenewLoginsFailedWaitsItsTurn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
|
||||
- Claude Code's `/usage` prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). `claudeResetTime` reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and `claudeResetSlack`: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
|
||||
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
|
||||
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
|
||||
|
||||
@@ -1201,9 +1201,7 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
case id != "":
|
||||
provider.RefreshUsage(ctx, id, user)
|
||||
case scope != nil:
|
||||
for _, q := range scope.cards(provider.CachedCards(time.Now())) {
|
||||
provider.RefreshUsage(ctx, q.Provider, q.User)
|
||||
}
|
||||
provider.RefreshEach(ctx, scope.cards(provider.CachedCards(time.Now())))
|
||||
default:
|
||||
provider.ReadAllCards(ctx)
|
||||
}
|
||||
|
||||
@@ -292,3 +292,158 @@ func TestSavedClaudeUsageSavesRotatedSignIn(t *testing.T) {
|
||||
}
|
||||
t.Fatal("max@x.com isn't saved")
|
||||
}
|
||||
|
||||
// #5443 (prgrmrwy): the gateway's POST /v1/magpie/quotas/refresh with no
|
||||
// card named (another magpie's refresh of this one's card, or an app with
|
||||
// a gateway key) reads every card again (ReadAllCards), and a saved,
|
||||
// inactive Claude account kept the reading it had: ReadAllCards asked
|
||||
// AskUsage alone, which runs no saved account's Claude Code. It is the
|
||||
// user's refresh of every allowance, as the Usage page's Refresh is, so
|
||||
// each saved account's /usage runs too, side by side, and the cards the
|
||||
// gateway answers (CachedCards) carry the new figures. The floor holds.
|
||||
func TestReadAllCardsReadsSavedClaude(t *testing.T) {
|
||||
claudeThree(t)
|
||||
var text atomic.Value
|
||||
text.Store("Current session: 0% used\nCurrent week (all models): 10% used")
|
||||
fakeClaudeUsage(t, &text, nil)
|
||||
var saved []string
|
||||
for _, l := range Logins("claude") {
|
||||
if !l.Active {
|
||||
saved = append(saved, l.User)
|
||||
}
|
||||
}
|
||||
if len(saved) != 2 {
|
||||
t.Fatalf("saved accounts: %v", saved)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
ran := map[string]int{}
|
||||
// while held, a saved account's run waits for the other's to start:
|
||||
// read one after another, the first gives up waiting
|
||||
var held atomic.Bool
|
||||
both := make(chan struct{})
|
||||
var in atomic.Int32
|
||||
var alone atomic.Bool
|
||||
UsageClaudeVia(func(ctx context.Context, dir string) (string, error) {
|
||||
if dir != "" {
|
||||
mu.Lock()
|
||||
ran[dir]++
|
||||
mu.Unlock()
|
||||
if held.Load() {
|
||||
if in.Add(1) == 2 {
|
||||
close(both)
|
||||
}
|
||||
select {
|
||||
case <-both:
|
||||
case <-time.After(5 * time.Second):
|
||||
alone.Store(true)
|
||||
case <-ctx.Done():
|
||||
alone.Store(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
return text.Load().(string), nil
|
||||
})
|
||||
runsIn := func(user string) int {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return ran[claudeAccountDir(user)]
|
||||
}
|
||||
card := func(user string) SubscriptionQuota {
|
||||
for _, q := range CachedCards(time.Now()) {
|
||||
if q.Provider == "claude" && strings.EqualFold(q.User, user) {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return SubscriptionQuota{}
|
||||
}
|
||||
age := func(user string) {
|
||||
claudeUsage.Lock()
|
||||
e := claudeUsage.m[strings.ToLower(user)]
|
||||
e.tried = e.tried.Add(-time.Hour)
|
||||
claudeUsage.m[strings.ToLower(user)] = e
|
||||
claudeUsage.Unlock()
|
||||
}
|
||||
ctx := context.Background()
|
||||
// each saved account read once, by its own card, as the reporter's
|
||||
// had been hours before
|
||||
for _, user := range saved {
|
||||
RefreshUsage(ctx, "claude", user)
|
||||
if q := card(user); q.Error != "" || len(q.Windows) != 2 || q.Windows[1].Used != 10 || runsIn(user) != 1 {
|
||||
t.Fatalf("card refresh of saved %s: %+v, %d runs", user, q, runsIn(user))
|
||||
}
|
||||
age(user)
|
||||
}
|
||||
|
||||
text.Store("Current session: 45% used\nCurrent week (all models): 60% used")
|
||||
held.Store(true)
|
||||
ReadAllCards(ctx)
|
||||
held.Store(false)
|
||||
for _, user := range saved {
|
||||
q := card(user)
|
||||
if runsIn(user) != 2 {
|
||||
t.Fatalf("the gateway's refresh of every card ran saved %s's /usage %d times, want once more", user, runsIn(user)-1)
|
||||
}
|
||||
if q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Used != 45 || q.Windows[1].Used != 60 {
|
||||
t.Fatalf("the gateway's refresh of every card kept saved %s's old reading: %+v", user, q)
|
||||
}
|
||||
}
|
||||
if alone.Load() {
|
||||
t.Fatal("the saved accounts' /usage ran one after another, not side by side")
|
||||
}
|
||||
|
||||
// pressed again at once: the per-account floor holds
|
||||
ReadAllCards(ctx)
|
||||
for _, user := range saved {
|
||||
if n := runsIn(user); n != 2 {
|
||||
t.Fatalf("a second refresh inside the floor ran saved %s again (%d runs)", user, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway key told only some cards has each of them read again on a
|
||||
// refresh of them all (RefreshEach), side by side: one after another, a
|
||||
// few saved Claude accounts' /usage outlasted the gateway's 30 seconds
|
||||
// (#5443).
|
||||
func TestRefreshEachReadsSideBySide(t *testing.T) {
|
||||
claudeThree(t)
|
||||
var text atomic.Value
|
||||
text.Store("Current session: 12% used\nCurrent week (all models): 34% used")
|
||||
fakeClaudeUsage(t, &text, nil)
|
||||
var saved []SubscriptionQuota
|
||||
for _, l := range Logins("claude") {
|
||||
if !l.Active {
|
||||
saved = append(saved, SubscriptionQuota{Provider: "claude", User: l.User})
|
||||
}
|
||||
}
|
||||
if len(saved) != 2 {
|
||||
t.Fatalf("saved accounts: %v", saved)
|
||||
}
|
||||
both := make(chan struct{})
|
||||
var in atomic.Int32
|
||||
var alone atomic.Bool
|
||||
UsageClaudeVia(func(ctx context.Context, dir string) (string, error) {
|
||||
if dir != "" {
|
||||
if in.Add(1) == 2 {
|
||||
close(both)
|
||||
}
|
||||
select {
|
||||
case <-both:
|
||||
case <-time.After(5 * time.Second):
|
||||
alone.Store(true)
|
||||
case <-ctx.Done():
|
||||
alone.Store(true)
|
||||
}
|
||||
}
|
||||
return text.Load().(string), nil
|
||||
})
|
||||
RefreshEach(context.Background(), saved)
|
||||
if alone.Load() || in.Load() != 2 {
|
||||
t.Fatalf("saved accounts read one after another: %d runs, alone %v", in.Load(), alone.Load())
|
||||
}
|
||||
for _, s := range saved {
|
||||
q := LoginUsage(context.Background(), "claude")[s.User]
|
||||
if q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Used != 12 {
|
||||
t.Fatalf("saved %s not read: %+v", s.User, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,26 @@ func RefreshUsage(ctx context.Context, provider, user string) {
|
||||
toldUsage()
|
||||
}
|
||||
|
||||
// RefreshEach is RefreshUsage of each of cards, read side by side: a
|
||||
// gateway key told some cards has every one of them read again on a
|
||||
// Refresh of them all, and one after another, a saved Claude account's
|
||||
// /usage about 5 seconds each, a few of them outlasted the gateway's 30
|
||||
// seconds (#5443). Each read is bounded as RefreshUsage's is.
|
||||
func RefreshEach(ctx context.Context, cards []SubscriptionQuota) {
|
||||
var wg sync.WaitGroup
|
||||
for _, q := range cards {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
refreshCards(ctx, q.Provider, q.User)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if len(cards) > 0 {
|
||||
toldUsage() // the menu bar shows the same cards (#2357), told once
|
||||
}
|
||||
}
|
||||
|
||||
// RefreshReport is RefreshUsage answering the cards it read, as
|
||||
// QuotaReport tells them: magpie quota refresh (#2104), which reads the
|
||||
// card the Usage page's refresh button does and shows only it. A process
|
||||
|
||||
@@ -154,9 +154,16 @@ func CachedCards(now time.Time) []SubscriptionQuota {
|
||||
}
|
||||
|
||||
// ReadAllCards has every card read again, the page's Refresh asked by
|
||||
// another magpie whose card of this one's said nothing was read yet.
|
||||
// another magpie whose card of this one's said nothing was read yet, or
|
||||
// by an app holding a gateway key (POST RemoteRefreshPath with no card
|
||||
// named). It is the user's refresh of every allowance, as the Usage
|
||||
// page's Refresh is (AskEveryClaudeUsage): each saved Claude account's
|
||||
// /usage is run too, under the same 30-second floor and holds (#5443,
|
||||
// prgrmrwy: it asked AskUsage alone, and a saved account kept its old
|
||||
// reading). The accounts are read side by side, each bounded by
|
||||
// subscriptionTimeout, so many of them answer within the gateway's wait.
|
||||
func ReadAllCards(ctx context.Context) {
|
||||
AskUsage()
|
||||
AskEveryClaudeUsage()
|
||||
ForgetBalances()
|
||||
forgetPlanQuotas()
|
||||
Quotas(Asked(ctx))
|
||||
@@ -244,7 +251,7 @@ func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuot
|
||||
c.Unlock()
|
||||
if !ok || fresh || time.Since(r.at) >= remoteCardsFor {
|
||||
asked := time.Now()
|
||||
cards, err := askRemote(ctx, p, http.MethodGet, RemoteCardsPath)
|
||||
cards, err := askRemote(ctx, p, http.MethodGet, RemoteCardsPath, remoteWait)
|
||||
r = keepRemoteCards(id, asked, cards, err)
|
||||
}
|
||||
name := remoteName(p)
|
||||
@@ -329,7 +336,7 @@ func refreshRemote(ctx context.Context, p Provider, card, user string) {
|
||||
path += "?" + q.Encode()
|
||||
}
|
||||
asked := time.Now()
|
||||
if _, err := askRemote(ctx, p, http.MethodPost, path); err != nil {
|
||||
if _, err := askRemote(ctx, p, http.MethodPost, path, remoteRefreshWait); err != nil {
|
||||
keepRemoteCards(remoteCardsID(p), asked, nil, err)
|
||||
}
|
||||
remoteCards(ctx, p, true)
|
||||
@@ -376,7 +383,7 @@ func RemoteQuotaHistories(ctx context.Context, days string) []QuotaHistory {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var hs []QuotaHistory
|
||||
if err := remoteJSON(ctx, p, http.MethodGet, "/v1/magpie/quotas/history?days="+url.QueryEscape(days), &hs); err != nil {
|
||||
if err := remoteJSON(ctx, p, http.MethodGet, "/v1/magpie/quotas/history?days="+url.QueryEscape(days), remoteWait, &hs); err != nil {
|
||||
return
|
||||
}
|
||||
for j := range hs {
|
||||
@@ -389,9 +396,21 @@ func RemoteQuotaHistories(ctx context.Context, days string) []QuotaHistory {
|
||||
return slices.Concat(got...)
|
||||
}
|
||||
|
||||
func askRemote(ctx context.Context, p Provider, method, path string) ([]SubscriptionQuota, error) {
|
||||
// remoteWait is how long a remote magpie is waited for to answer what it
|
||||
// keeps; remoteRefreshWait, to read a card or every card again first,
|
||||
// which asks the vendors there: one saved Claude account's /usage alone
|
||||
// takes about 5 seconds, and a refresh of the remote's every card runs
|
||||
// each saved account's (#5443), within its gateway's 30 seconds. At 8
|
||||
// seconds the refresh was given up on while it still read, and the cards
|
||||
// asked for after it were the ones from before.
|
||||
var (
|
||||
remoteWait = 8 * time.Second
|
||||
remoteRefreshWait = 25 * time.Second
|
||||
)
|
||||
|
||||
func askRemote(ctx context.Context, p Provider, method, path string, wait time.Duration) ([]SubscriptionQuota, error) {
|
||||
var cards []SubscriptionQuota
|
||||
if err := remoteJSON(ctx, p, method, path, &cards); err != nil {
|
||||
if err := remoteJSON(ctx, p, method, path, wait, &cards); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cards, nil
|
||||
@@ -427,8 +446,8 @@ func remoteKey(h http.Header, key string) {
|
||||
}
|
||||
|
||||
// remoteJSON asks p's gateway, with its key, for a {"data": …} list.
|
||||
func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) error {
|
||||
b, err := remoteBody(ctx, p, method, path, 8*time.Second)
|
||||
func remoteJSON(ctx context.Context, p Provider, method, path string, wait time.Duration, dst any) error {
|
||||
b, err := remoteBody(ctx, p, method, path, wait)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -554,3 +554,37 @@ func TestRemoteCodexResetAnswers(t *testing.T) {
|
||||
t.Fatalf("a card not a remote's Codex card asked the remote (%d)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// #5443: a refresh of a remote magpie's every card has it run each saved
|
||||
// Claude account's /usage there, about 5 seconds each, side by side. The
|
||||
// refresh was waited for as long as a read of the kept cards (8s), given
|
||||
// up on while it still read, and the cards asked for after it were the
|
||||
// old ones. It is waited for as long as the remote's gateway may take.
|
||||
func TestRemoteMagpieRefreshWaitedFor(t *testing.T) {
|
||||
peer := &fakePeer{cards: []SubscriptionQuota{{Provider: "claude", Name: "Claude", User: "max@x.com", Windows: []QuotaWindow{{Name: "5h", Used: 0}}}}}
|
||||
slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == RemoteRefreshPath {
|
||||
// reading there, longer than a read of what it keeps may take
|
||||
time.Sleep(time.Second)
|
||||
peer.Lock()
|
||||
peer.cards = []SubscriptionQuota{{Provider: "claude", Name: "Claude", User: "max@x.com", Windows: []QuotaWindow{{Name: "5h", Used: 45}}}}
|
||||
peer.Unlock()
|
||||
}
|
||||
peer.ServeHTTP(w, r)
|
||||
})
|
||||
remoteQuotaHome(t, slow)
|
||||
oldWait, oldRefresh := remoteWait, remoteRefreshWait
|
||||
remoteWait, remoteRefreshWait = 100*time.Millisecond, 20*time.Second
|
||||
t.Cleanup(func() { remoteWait, remoteRefreshWait = oldWait, oldRefresh })
|
||||
ctx := context.Background()
|
||||
RefreshUsage(ctx, "office", "")
|
||||
var got *SubscriptionQuota
|
||||
for _, q := range peerCards(RemoteCards(ctx)) {
|
||||
if q.Provider == "office/claude" {
|
||||
got = &q
|
||||
}
|
||||
}
|
||||
if got == nil || got.Error != "" || len(got.Windows) != 1 || got.Windows[0].Used != 45 {
|
||||
t.Fatalf("after the remote's refresh of every card: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user