provider: a Command Code plan key's Credits window renews at the plan's period end (#2454)

#2451 drew a plan key's month of credits as a Credits meter beside the
5-hour and weekly windows. Those two say when they start again; the
Credits one said nothing, though cmdKeyPlanID already asks
billing/subscriptions for the plan id and threw its currentPeriodEnd
away. cmdKeyPlanID now keeps the period end beside the plan id (cached
the same ten minutes, and the pair read before kept while the endpoint
can't be read), and cmdQuotaOf puts it on the Credits window's
ResetsAt. No new request. The signed-in subscription's card is the
plugin's since be62bcf79; the plugin sets the same reset from
commandcode-auth 0.1.13.

Patch by ggbdpq (Discord gua2100), as rebased in #2454. Added in
review: a period end already past is dropped, so a pair kept while the
endpoint fails, or a renewal its reply doesn't show yet, never puts a
reset in the past on the card; the test has a case for it.

Run (sandbox HOME, at origin/main 85b45b4d7 plus this):
- go test -tags nogui -run 'CommandCode|KeyQuotas' ./internal/provider/: ok
- Broken by hand: ResetsAt: until taken out -> "the key card's credits
  have no reset" (ResetsAt nil); the past-end guard taken out -> "the
  key card's credits reset in the past". Each restored: ok.
- go test -tags nogui ./internal/provider/: two known reds on main,
  both filed and both red at 85b45b4d7 without this change:
  TestUnreadLoginsWriteErrorsKeepCredentials crashes the binary (#3632),
  and with it skipped the rest pass except TestFetchAsksASharedBaseOnce
  and two siblings (#3854).
- gofmt -l internal/provider: clean. go vet ./internal/provider/ on
  darwin, GOOS=windows, GOOS=linux: ok.
Not tried: a real Command Code plan key (none here), the GUI card, a
period that renews while the card is open; go test ./... (one suite per
machine). The key card only learns the period end when billing/credits
leaves the plan id out, which is what it does today; if it starts
sending the plan id, the reset is not read.
This commit is contained in:
ggbdpq
2026-10-28 00:58:06 +08:00
committed by yetone
parent 85b45b4d71
commit ff7048dece
4 changed files with 78 additions and 15 deletions
+1 -1
View File
@@ -55,7 +55,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.go) |
| A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) |
| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; a key whose plan was never read has its two windows alone. Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
@@ -4,8 +4,10 @@ import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"sync/atomic"
"testing"
"time"
)
// #2451 (tianxia3111): a Command Code plan's key, on the keyed preset,
@@ -78,3 +80,50 @@ func TestCommandCodeKeyCardHasCredits(t *testing.T) {
t.Errorf("plan never read: %v %q %+v", err, plan, ws)
}
}
// The Credits window #2451 added renews when the plan's period does: the
// end is in the same billing/subscriptions reply the plan id is read
// from, and the card's other two windows each say when they start again.
func TestCommandCodeKeyCreditsRenewAtPeriodEnd(t *testing.T) {
const end = int64(4102444800000) // 2100-01-01, in ms as cmdTime reads it
periodEnd := end
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Header.Get("X-Host") + r.URL.Path {
case "api.commandcode.ai/alpha/billing/credits":
w.Write([]byte(`{"credits":{"monthlyCredits":5.22,"purchasedCredits":0,"freeCredits":0},
"windowLimits":{"limited":true,
"fiveHour":{"used":1,"cap":14,"resetAt":4102444800000},
"weekly":{"used":2,"cap":35,"resetAt":4102444800000}}}`))
case "api.commandcode.ai/alpha/billing/subscriptions":
w.Write([]byte(`{"success":true,"data":{"planId":"individual-go-monthly","status":"active","currentPeriodEnd":` + strconv.FormatInt(periodEnd, 10) + `}}`))
default:
t.Errorf("asked %s%s", r.Header.Get("X-Host"), r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
t.Cleanup(func() { http.DefaultClient.Transport = old })
p := Provider{ID: "commandcode", Key: "cmd-reset", Chat: "https://api.commandcode.ai/provider/v1"}
src, _ := planQuotaSourceOf(p)
_, ws, _, err := planKeyWindows(context.Background(), p, src, p.Key)
if err != nil || len(ws) != 3 {
t.Fatalf("%v %+v", err, ws)
}
if c := ws[2]; c.Name != "Credits" || c.ResetsAt == nil || c.ResetsAt.UnixMilli() != end {
t.Errorf("the key card's credits have no reset: %+v", c)
}
// a period end already past says nothing about when they come back
periodEnd = time.Now().Add(-time.Hour).UnixMilli()
p.Key = "cmd-reset-past"
_, ws, _, err = planKeyWindows(context.Background(), p, src, p.Key)
if err != nil || len(ws) != 3 {
t.Fatalf("%v %+v", err, ws)
}
if c := ws[2]; c.Name != "Credits" || c.ResetsAt != nil {
t.Errorf("the key card's credits reset in the past: %+v", c)
}
}
+26 -12
View File
@@ -114,7 +114,10 @@ func cmdLogins() []cmdLogin {
type cmdSeen struct {
plan string
at time.Time
// until is, on a key's plan (cmdKeyPlanID), when the plan's period
// ends: the month's credits come back then, on the Credits window.
until *time.Time
at time.Time
}
// ---- allowance ----------------------------------------------------------------
@@ -241,14 +244,15 @@ func cmdLeft(c cmdCredits) (monthly, left float64, ok bool) {
}
// cmdQuotaOf makes the credits reply into the plan's windows: the 5-hour
// and weekly limits, and the month's credits as one more. A card's
// and weekly limits, and the month's credits as one more, renewing at
// until, the plan's period's end (nil when that isn't known). A card's
// Balance is shown instead of its windows — it is a key's money, not an
// allowance — so, set beside them, it hid both limits on the Usage page,
// the panel and the TUI. The dollars are a window when the plan is known,
// used of the CLI's pool (the plan's month of credits, or what is left of
// it if more, and the bought and free ones) as its /usage bar is; a reply
// with neither windows nor a plan is a Balance still.
func cmdQuotaOf(q SubscriptionQuota, c cmdCredits) SubscriptionQuota {
func cmdQuotaOf(q SubscriptionQuota, c cmdCredits, until *time.Time) SubscriptionQuota {
name, planMonthly := cmdPlanOf(c.Credits.PlanID)
if name != "" {
q.Plan = name
@@ -260,7 +264,7 @@ func cmdQuotaOf(q SubscriptionQuota, c cmdCredits) SubscriptionQuota {
case planMonthly > 0:
pool := max(planMonthly, monthly) + left - monthly
q.Windows = append(q.Windows, QuotaWindow{Name: "Credits", Used: min(100, 100*(pool-left)/pool),
Display: money("$", pool-left) + " / " + money("$", pool)})
Display: money("$", pool-left) + " / " + money("$", pool), ResetsAt: until})
case len(q.Windows) == 0:
q.Balance = money("$", left)
}
@@ -315,10 +319,17 @@ func cmdKeyWindows(ctx context.Context, src planQuotaSource, key string) (string
if len(cmdWindows(c)) == 0 {
return cmdPlanName(c.Credits.PlanID), []QuotaWindow{}, nil
}
var until *time.Time
if c.Credits.PlanID == "" {
c.Credits.PlanID = cmdKeyPlanID(ctx, key)
c.Credits.PlanID, until = cmdKeyPlanID(ctx, key)
}
q := cmdQuotaOf(SubscriptionQuota{}, c)
if until != nil && !until.After(time.Now()) {
// a period end already past (the pair kept while the endpoint
// can't be read, or a renewal not yet in its reply) says nothing
// about when the credits come back
until = nil
}
q := cmdQuotaOf(SubscriptionQuota{}, c, until)
return q.Plan, q.Windows, nil
}
@@ -327,21 +338,24 @@ var cmdKeyPlans = struct {
m map[string]cmdSeen // plan is the subscription's id here
}{m: map[string]cmdSeen{}}
func cmdKeyPlanID(ctx context.Context, key string) string {
// cmdKeyPlanID is the key's subscription's plan id, and the end of its
// period, for the Credits window's reset: asked at most every ten minutes,
// and the pair read before kept while it can't be read.
func cmdKeyPlanID(ctx context.Context, key string) (string, *time.Time) {
cmdKeyPlans.Lock()
seen, had := cmdKeyPlans.m[key]
cmdKeyPlans.Unlock()
if had && time.Since(seen.at) < 10*time.Minute {
return seen.plan
return seen.plan, seen.until
}
id, _, _, _, ok := cmdSubscription(ctx, cmdAuth{APIKey: key})
id, _, until, _, ok := cmdSubscription(ctx, cmdAuth{APIKey: key})
if !ok {
return seen.plan
return seen.plan, seen.until
}
cmdKeyPlans.Lock()
cmdKeyPlans.m[key] = cmdSeen{id, time.Now()}
cmdKeyPlans.m[key] = cmdSeen{plan: id, until: until, at: time.Now()}
cmdKeyPlans.Unlock()
return id
return id, until
}
// ---- signing in ---------------------------------------------------------------
+2 -2
View File
@@ -112,7 +112,7 @@ func TestCommandCodeQuotaShowsWindows(t *testing.T) {
if err := json.Unmarshal([]byte(cmdCreditsReply), &c); err != nil {
t.Fatal(err)
}
q := cmdQuotaOf(SubscriptionQuota{}, c)
q := cmdQuotaOf(SubscriptionQuota{}, c, nil)
if q.Balance != "" || q.Plan != "GOAT" || len(q.Windows) != 3 {
t.Fatalf("%+v", q)
}
@@ -124,7 +124,7 @@ func TestCommandCodeQuotaShowsWindows(t *testing.T) {
// no plan and no windows: what is left is all there is to show
var none cmdCredits
_ = json.Unmarshal([]byte(`{"credits":{"purchasedCredits":"20","freeCredits":1}}`), &none)
if q := cmdQuotaOf(SubscriptionQuota{}, none); q.Balance != "$21.00" || len(q.Windows) != 0 {
if q := cmdQuotaOf(SubscriptionQuota{}, none, nil); q.Balance != "$21.00" || len(q.Windows) != 0 {
t.Errorf("no plan: %+v", q)
}
}