Files
magpie/internal/provider/quota_refresh.go
T
yetone 8c71cd27f9 quotas: a computer using another's magpie (remote-magpie) shows that magpie's quota cards (莫 on Discord: the second computer had the models and groups but /v1/magpie/quotas was empty, so Usage, the menu bar and magpie quota showed nothing) — each named with the remote ("Codex · Office", id office/codex, from: Office) and kept in its kind (subscription, plan, balance), on the Usage page, the tray, the TUI and magpie quota (which matches by the remote's id or name); their history comes with the local one. Only the computer holding the sign-ins asks vendors: it answers the new GET /v1/magpie/quotas/cards from what it has kept (CachedCards, never a read, whatever the age), asked here at most once in 30s; a card's refresh here POSTs /v1/magpie/quotas/refresh (that card, or every card from the remote's own card), which the remote does at most once in 30s per card. A remote keeps showing its last cards when it can't be reached; with none its one card says why (nothing read there yet, or a magpie too old to share — "update magpie there", zh/ja/de added). Cards from a third magpie aren't passed on, and the refresh path refuses them (400); a Codex reset or check-in isn't offered on a remote card. Same auth as /v1/magpie/quotas (loopback, or LAN with the key).
Verified: provider tests (fake remote: names/kinds, buttons stripped, third-magpie cards dropped, one ask per 30s, refresh paths, unreachable keeps last cards, 404 → update card, cache-only CachedCards, histories) and the gateway test (an in-process gateway with a fake balance vendor counting hits, asked through a remote-magpie provider: nothing read until a refresh, 5 card asks read nothing, two refreshes of a card read once, a remote card's refresh 400, another machine without the key refused) pass with -race -count=20; go test provider/gateway/gui/tui/root, vet, linux and windows builds pass. Two sandbox gateways (3481 with a fake balance vendor, 3482 with it as remote-magpie): magpie quota on the second showed the "nothing read" card with 0 vendor hits, then office/bal "Bal · Office" $12.00 after one refresh (1 hit), 10 more asks 0 hits, two card refreshes 1 hit. usage-remote-cards (names, translated remote errors, refresh ids) passes in Chromium and WebKit, en/zh/ja/de and fails without the app.js change; i18n-keys, gui-ja, gui-de, usage-card-refresh, usage-refresh, quota-reading-again pass. Not tried with a real second computer.
2026-10-06 12:38:52 +08:00

163 lines
4.7 KiB
Go

package provider
import (
"context"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
)
// A card read again on its own, from its refresh button on the Usage page
// (Hu9956, #840: 只刷新单个套餐的用量): the provider's, and of the one
// account user when it has several ("" for every one). Only that card is
// asked for; the others stay as they were last read.
type cardRefresh struct{ provider, user string }
type cardRefreshKey struct{}
type quotaReadKey struct{}
var quotaReadSequence atomic.Uint64
// quotaReading orders reads when they start, not when the vendor answers.
// A card refresh shares its order across the three kinds of usage.
func quotaReading(ctx context.Context) (context.Context, uint64) {
if seq, ok := ctx.Value(quotaReadKey{}).(uint64); ok {
return ctx, seq
}
seq := quotaReadSequence.Add(1)
return context.WithValue(ctx, quotaReadKey{}, seq), seq
}
// keepReading also orders the last good reading on disk: a late response
// must not become the fallback for the next failed request.
func keepReading(ctx context.Context, q SubscriptionQuota, user string) SubscriptionQuota {
q.readSeq, _ = ctx.Value(quotaReadKey{}).(uint64)
return keepLast(q, user)
}
// refreshing is the card a read is for, when it is for one card alone.
func refreshing(ctx context.Context) (cardRefresh, bool) {
r, ok := ctx.Value(cardRefreshKey{}).(cardRefresh)
return r, ok
}
// wantsCard reports whether a read asks for the card of provider and
// account user: every card, unless it reads one again on its own.
func wantsCard(ctx context.Context, provider, user string) bool {
r, ok := refreshing(ctx)
return !ok || r.wants(provider, user)
}
func (r cardRefresh) wants(provider, user string) bool {
return provider == r.provider && (r.user == "" || strings.EqualFold(user, r.user))
}
// refreshLogins is the accounts of ls a read asks for, each read afresh
// rather than from the minute's cache when it reads one card again.
func refreshLogins(ctx context.Context, ls []Login) []Login {
r, ok := refreshing(ctx)
if !ok {
return ls
}
var out []Login
for _, l := range ls {
if r.user != "" && !strings.EqualFold(l.User, r.user) {
continue
}
forgetLoginReading(l)
out = append(out, l)
}
return out
}
// forgetLoginReading has l's next reading asked for, keeping what it was
// for a hiccup (as AskUsage does for every account).
func forgetLoginReading(l Login) {
key := l.Agent + "/" + strings.ToLower(l.User)
c := &loginUsageCache
c.Lock()
if e, ok := c.m[key]; ok {
e.at = time.Time{}
c.m[key] = e
}
c.Unlock()
}
// RefreshUsage reads the card of provider (of account user, "" for every
// account it has) again, whether a subscription's, a plan's or a key's
// balance, and keeps it with the others, which aren't asked. The next
// Quotas has it.
func RefreshUsage(ctx context.Context, provider, user string) {
// a remote magpie's card is read again there (remote_quotas.go)
if p, card, ok := remoteOf(provider); ok {
refreshRemote(ctx, p, card, user)
return
}
r := cardRefresh{provider, user}
ctx = context.WithValue(ctx, cardRefreshKey{}, r)
ctx, seq := quotaReading(ctx)
if provider == "claude" {
// Claude Code's /usage, run when the user asks (claudeWindows)
claudeAsked.Store(time.Now().UnixNano())
}
var wg sync.WaitGroup
wg.Add(3)
go func() { defer wg.Done(); PlanQuotas(ctx) }()
go func() { defer wg.Done(); KeyBalances(ctx) }()
go func() {
defer wg.Done()
out := fetchSubscriptionUsage(ctx)
now := time.Now()
noteDailyCredits(out, now)
noteQuotaHistory(out, now)
c := &subscriptionUsageCache
c.Lock()
c.data = cacheCards(c.data, out, seq, true)
c.Unlock()
}()
wg.Wait()
}
// cacheCards commits a batch without overwriting cards read by a newer
// batch. A whole-page read still replaces the other cards (and drops ones
// no longer present); a partial read keeps the rest as they were.
func cacheCards(kept, got []SubscriptionQuota, seq uint64, partial bool) []SubscriptionQuota {
out := slices.Clone(got)
for i := range out {
out[i].readSeq = seq
}
if partial {
return mergeCards(kept, out)
}
for _, q := range kept {
if q.readSeq > seq {
out = mergeCards(out, []SubscriptionQuota{q})
}
}
return out
}
// mergeCards is the cards of kept with each of got in place of the one of
// its provider and account, or after them when it is new. Nothing kept,
// nothing is: the next read reads every card.
func mergeCards(kept, got []SubscriptionQuota) []SubscriptionQuota {
if kept == nil {
return nil
}
out := slices.Clone(kept)
for _, g := range got {
i := slices.IndexFunc(out, func(q SubscriptionQuota) bool {
return q.Provider == g.Provider && strings.EqualFold(q.User, g.User)
})
if i < 0 {
out = append(out, g)
} else if g.readSeq >= out[i].readSeq {
out[i] = g
}
}
return out
}