provider: a balance field sums, maxes or counts a list's items, and one amount it can't read is "—" (#1993, RicardoWYP)

A relay's /api/subscription/self tells usage per subscription, a list.
A balance path could only name one index (subscriptions.0), so several
active subscriptions read as the first, ".0 + .1" failed whole when only
one existed, and a weekly cap of 0 ("divides by 0") hid every amount of
the field.

Now a path goes through a list's items with "*" (a.*.used), or those
that match with "[key=value]" / "[key!=value]" (a[status=active].used,
also on an object: a.*.subscription[status=active].used). Such a path is
several values, made one by sum(), max(), min() or count(); arithmetic
between two of them goes item by item, so max(a.*.used / a.*.cap) is the
fullest window. Several values left outside a function are an error
naming the functions, not a guessed sum. Within a list an item without
the path, or divided by 0, is left out; max/min of nothing is an error.

In a field of several ";" amounts, one that can't be read shows "—"
(BalancePart.Error says why, as the card's hover on the Usage page and
in the panel) and the others still show; the read fails only when none
can be read. A single amount alone still fails as before.

The GUI hint (zh, zh-TW, ja, de) and `magpie provider` help say the new
syntax.

Run:
- TestBalancePathLists, with the reporter's literal JSON: against the
  old balance.go it fails ("nothing at \"sum\" in the reply", and the
  "—" cases error); passes now. TestReadBalancePath's one case that
  expected a whole-field failure with one bad amount now expects it
  only when every amount fails.
- go test -tags nogui ./internal/provider ./internal/cli ./internal/gui
  under a temp HOME: ok.
- balance-parts, gui-de, gui-ja, gui-zh-tw, i18n-keys in Chromium and
  WebKit: 14 pass. With the title lines removed, balance-parts fails on
  the missing hover text.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  provider and cli.
Not tried against the reporter's real relay.
This commit is contained in:
yetone
2026-10-14 04:37:43 +08:00
parent 9bfbd6e45e
commit 80211e7075
6 changed files with 517 additions and 88 deletions
+4 -1
View File
@@ -105,7 +105,10 @@ const providerUsage = `usage:
(a new-api relay's whole account: its access token and user id, from its personal settings)
(balance.path: where the amount is in the reply, or a sum of those with + - * / and
brackets; $ or ¥ in front adds the sign, % after it shows a percent of 1;
several go apart by ; each with a label: '5h: a.used / a.cap %; $credits.left')
several go apart by ; each with a label: '5h: a.used / a.cap %; $credits.left';
a list's items are a.*.used, or a[status=active].used for those that match,
in sum() max() min() count(): 'sum(a.*.used) / sum(a.*.cap) %'; one the reply
hasn't shows — and the others still show)
magpie provider set my-relay context=272k context.gpt-6=1m
(context: how long a request agents are told the models take, over what the
vendor or models.dev says; context.<model> for one of them; empty clears)
+13 -8
View File
@@ -9066,7 +9066,7 @@ function drawEditor(p, presetID) {
balPair.append(res);
balPair.classList.add("wrap");
}
inner.append(...field(t("Balance field"), balPair, t("Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left")));
inner.append(...field(t("Balance field"), balPair, t("Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left; a list's items are a.*.used, or a[status=active].used for those that match, put in sum(), max(), min() or count(); an amount the reply hasn't shows \"—\" and the others still show")));
more.append(inner);
ed.append(more);
}
@@ -15876,16 +15876,19 @@ function panelBalances(bals) {
// the others each a quiet line, a percent a meter (#420)
const parts = q.balanceParts?.length ? q.balanceParts : [{ text: q.balance }];
for (const [i, p] of parts.entries()) {
if (!i && !p.label) card.append(el("b", "pq-amt", p.text));
let amount;
if (!i && !p.label) card.append(amount = el("b", "pq-amt", p.text));
else if (!i) {
const lead = el("span", "pq-lead");
lead.append(el("b", "pq-amt", p.text), el("span", "", p.label));
card.append(lead);
amount = el("span", "pq-lead");
amount.append(el("b", "pq-amt", p.text), el("span", "", p.label));
card.append(amount);
} else {
const line = el("span", "pq-sub pq-bp");
line.append(el("span", "", p.label || ""), el("b", "", p.text));
card.append(line);
amount = el("span", "pq-sub pq-bp");
amount.append(el("span", "", p.label || ""), el("b", "", p.text));
card.append(amount);
}
// an amount the reply hadn't, "—": why, on hover (#1993)
if (p.error) amount.title = p.error;
if (p.percent != null) card.append(balanceMeter(p.percent));
}
// standing in for a reading that failed just now: as of when
@@ -16585,6 +16588,8 @@ function balanceRow(sub, why, when = true) {
for (const [i, p] of (parts || []).entries()) {
const row = el("div", "bal-part" + (i ? "" : " lead"));
row.append(el("span", "", p.label || (i ? "" : t("Balance"))), el("b", "", p.text));
// an amount the reply hadn't, "—": why, on hover (#1993)
if (p.error) row.title = p.error;
if (p.percent != null) row.append(balanceMeter(p.percent));
b.append(row);
}
+4 -4
View File
@@ -1759,7 +1759,7 @@ const I18N = {
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供应商的模型列表接口,不在基础地址下时填写;请求时会带上 Key",
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "查询 Key 余额的接口,像对话请求一样带 Key 请求;地址或请求头中的 {key} 替换为各 Key 自身的值,用于 Key 放在 URL 中的接口(…?key={key});结果显示在用量页",
"Balance field": "余额字段",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left": "金额在返回 JSON 中的位置,例如 data.balance;可用 + - * / 和括号计算,例如 data.total / 500000 或 (1 - credits.used / 70) %;前加 \"$\" 显示币种符号,后加 \"%\" 显示为百分比和进度条;多个金额用 \";\" 分隔,可各加标签,例如 5h: a.used / a.cap %; $credits.left",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left; a list's items are a.*.used, or a[status=active].used for those that match, put in sum(), max(), min() or count(); an amount the reply hasn't shows \"—\" and the others still show": "金额在返回 JSON 中的位置,例如 data.balance;可用 + - * / 和括号计算,例如 data.total / 500000 或 (1 - credits.used / 70) %;前加 \"$\" 显示币种符号,后加 \"%\" 显示为百分比和进度条;多个金额用 \";\" 分隔,可各加标签,例如 5h: a.used / a.cap %; $credits.left;数组的每一项写作 a.*.used,只取符合条件的写作 a[status=active].used,放进 sum()、max()、min() 或 count() 汇总;某个金额在返回中取不到时显示 \"—\",其他金额照常显示",
"Balance": "余额",
"Balances": "余额",
"Updated {when}": "{when}更新",
@@ -6480,7 +6480,7 @@ const I18N = {
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供應商的模型列表介面,不在基礎位址下時填寫;請求時會帶上 Key",
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "查詢 Key 餘額的介面,像對話請求一樣帶 Key 請求;位址或請求頭中的 {key} 替換為各 Key 自身的值,用於 Key 放在 URL 中的介面(…?key={key});結果顯示在用量頁",
"Balance field": "餘額欄位",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left": "金額在返回 JSON 中的位置,例如 data.balance;可用 + - * / 和括號計算,例如 data.total / 500000 或 (1 - credits.used / 70) %;前加 \"$\" 顯示幣種符號,後加 \"%\" 顯示為百分比和進度條;多個金額用 \";\" 分隔,可各加標籤,例如 5h: a.used / a.cap %; $credits.left",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left; a list's items are a.*.used, or a[status=active].used for those that match, put in sum(), max(), min() or count(); an amount the reply hasn't shows \"—\" and the others still show": "金額在返回 JSON 中的位置,例如 data.balance;可用 + - * / 和括號計算,例如 data.total / 500000 或 (1 - credits.used / 70) %;前加 \"$\" 顯示幣種符號,後加 \"%\" 顯示為百分比和進度條;多個金額用 \";\" 分隔,可各加標籤,例如 5h: a.used / a.cap %; $credits.left;陣列的每一項寫作 a.*.used,只取符合條件的寫作 a[status=active].used,放進 sum()、max()、min() 或 count() 匯總;某個金額在返回中取不到時顯示 \"—\",其他金額照常顯示",
"Balance": "餘額",
"Balances": "餘額",
"Updated {when}": "{when}更新",
@@ -11175,7 +11175,7 @@ const I18N = {
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "ベース URL の下にない場合の、ベンダーがモデル一覧を返す場所。キー付きで問い合わせます",
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "ベンダーがキーの残量を返す場所。チャットリクエストと同様にキー付きで問い合わせます。URL やヘッダー内の {key} は各キー自身の値になります(キーを URL に含めるベンダー向け:…?key={key})。使用量ページに表示されます",
"Balance field": "残高フィールド",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left": "応答内で金額がある場所(例:data.balance)。+ - * / と括弧で計算でき(例:data.total / 500000 や (1 - credits.used / 70) %)、前に \"$\" を付けると通貨記号、後ろに \"%\" を付けるとバー付きのパーセント表示になります。複数はそれぞれラベルを付けて \";\" で区切ります(例:5h: a.used / a.cap %; $credits.left)",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left; a list's items are a.*.used, or a[status=active].used for those that match, put in sum(), max(), min() or count(); an amount the reply hasn't shows \"—\" and the others still show": "応答内で金額がある場所(例:data.balance)。+ - * / と括弧で計算でき(例:data.total / 500000 や (1 - credits.used / 70) %)、前に \"$\" を付けると通貨記号、後ろに \"%\" を付けるとバー付きのパーセント表示になります。複数はそれぞれラベルを付けて \";\" で区切ります(例:5h: a.used / a.cap %; $credits.left)。配列の各項目は a.*.used、条件に合うものだけなら a[status=active].used と書き、sum()・max()・min()・count() で集計します。応答にない金額は \"—\" と表示され、ほかの金額はそのまま表示されます",
"Balance": "残高",
"Balances": "残高",
"Updated {when}": "{when}に更新",
@@ -15890,7 +15890,7 @@ const I18N = {
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "Wo der Anbieter seine Modelle auflistet, falls nicht unter der Basis-URL; wird mit dem Schlüssel abgefragt",
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "Wo der Anbieter das Restguthaben des Schlüssels meldet, abgefragt mit dem Schlüssel wie eine Chat-Anfrage; {key} darin oder in einem Header steht für den jeweiligen Schlüssel, für Anbieter, die den Schlüssel in der URL erwarten (…?key={key}); angezeigt auf der Seite Nutzung",
"Balance field": "Guthabenfeld",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left": "Wo der Betrag in der Antwort steht, z. B. data.balance; auch eine Rechnung mit + - * / und Klammern ist möglich, z. B. data.total / 500000 oder (1 - credits.used / 70) %; \"$\" davor ergänzt das Währungszeichen, \"%\" dahinter zeigt einen Prozentwert mit Balken; mehrere, jeweils mit Bezeichnung, durch \";\" trennen, z. B. 5h: a.used / a.cap %; $credits.left",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left; a list's items are a.*.used, or a[status=active].used for those that match, put in sum(), max(), min() or count(); an amount the reply hasn't shows \"—\" and the others still show": "Wo der Betrag in der Antwort steht, z. B. data.balance; auch eine Rechnung mit + - * / und Klammern ist möglich, z. B. data.total / 500000 oder (1 - credits.used / 70) %; \"$\" davor ergänzt das Währungszeichen, \"%\" dahinter zeigt einen Prozentwert mit Balken; mehrere, jeweils mit Bezeichnung, durch \";\" trennen, z. B. 5h: a.used / a.cap %; $credits.left; alle Einträge einer Liste sind a.*.used, nur passende a[status=active].used, zusammengefasst mit sum(), max(), min() oder count(); ein Betrag, der in der Antwort fehlt, zeigt \"—\", die anderen erscheinen trotzdem",
"Balance": "Guthaben",
"Balances": "Guthaben",
"Updated {when}": "Aktualisiert {when}",
+11 -6
View File
@@ -6,7 +6,8 @@
// "Updated 3 minutes ago" — or, standing in for a reading that failed just
// now, "As of … — couldn't be read just now", windows' cards too. The menu
// bar panel's Balances show the same amounts and the "As of". A balance of
// one amount reads as it did. No left-border accent. English and Chinese,
// one amount reads as it did. One the reply hadn't is "—" and says why on
// hover (#1993). No left-border accent. English and Chinese,
// Chromium and WebKit; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
@@ -18,7 +19,7 @@ const assets = path.resolve(__dirname, "../assets");
const ago = (min) => new Date(Date.now() - min * 6e4).toISOString();
const quotas = () => [
{ provider: "relay", name: "My Relay", icon: "generic", windows: [], balance: "$2.00 · Today $2.50 · Used 95%", readAt: ago(3),
balanceParts: [{ text: "$2.00" }, { label: "Today", text: "$2.50" }, { label: "Used", text: "95%", percent: 95 }] },
balanceParts: [{ text: "$2.00" }, { label: "Today", text: "$2.50" }, { label: "Used", text: "95%", percent: 95 }, { label: "Week", text: "—", error: "Week: max() of the balance path has nothing to take it of" }] },
{ provider: "other", name: "Other Relay", icon: "generic", windows: [], balance: "$4.20", readAt: ago(120), asOf: ago(120) },
{ provider: "plain", name: "Plain", icon: "generic", windows: [], balance: "¥9.00", readAt: ago(0) },
{ provider: "kimi", name: "Kimi", icon: "kimi-color", asOf: ago(45), windows: [{ name: "Weekly", used: 30 }] },
@@ -79,8 +80,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const page = await open("usage", "http://magpie.test/?view=usage", { width: 900, height: 700 });
const relay = page.locator(".subscription-card", { hasText: "My Relay" });
await relay.locator(".bal-part").first().waitFor();
assert.deepEqual(await relay.locator(".bal-part > span").allTextContents(), [w.balance, "Today", "Used"]);
assert.deepEqual(await relay.locator(".bal-part > b").allTextContents(), ["$2.00", "$2.50", "95%"]);
assert.deepEqual(await relay.locator(".bal-part > span").allTextContents(), [w.balance, "Today", "Used", "Week"]);
assert.deepEqual(await relay.locator(".bal-part > b").allTextContents(), ["$2.00", "$2.50", "95%", "—"]);
// an amount the reply hadn't is "—", and says why on hover (#1993)
assert.equal(await relay.locator(".bal-part").nth(3).getAttribute("title"), "Week: max() of the balance path has nothing to take it of");
assert.equal(await relay.locator(".bal-part").nth(2).getAttribute("title"), null);
assert.equal(await relay.locator(".bal-part.lead").count(), 1, "the first is the one that counts");
const [lead, rest] = await relay.locator(".bal-part > b").evaluateAll((es) => es.slice(0, 2).map((e) => parseFloat(getComputedStyle(e).fontSize)));
assert(lead > rest, `the first larger: ${lead} ${rest}`);
@@ -114,8 +118,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const card = panel.locator(".pq-card.bal", { hasText: "My Relay" });
await card.locator(".pq-amt").waitFor();
assert.equal(await card.locator(".pq-amt").textContent(), "$2.00");
assert.deepEqual(await card.locator(".pq-bp > span").allTextContents(), ["Today", "Used"]);
assert.deepEqual(await card.locator(".pq-bp > b").allTextContents(), ["$2.50", "95%"]);
assert.deepEqual(await card.locator(".pq-bp > span").allTextContents(), ["Today", "Used", "Week"]);
assert.deepEqual(await card.locator(".pq-bp > b").allTextContents(), ["$2.50", "95%", "—"]);
assert.equal(await card.locator(".pq-bp").nth(2).getAttribute("title"), "Week: max() of the balance path has nothing to take it of");
assert.equal(await width(card.locator(".quota-track.full i")), 95);
const stale = panel.locator(".pq-card.bal", { hasText: "Other Relay" });
assert(await stale.evaluate((e) => e.classList.contains("stale")));
+404 -68
View File
@@ -13,6 +13,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"math"
"net/http"
"net/url"
@@ -436,10 +437,13 @@ func readAiHubMixAccount(b []byte) (string, error) {
// telling what was used of a plan ("(1 - credits.monthlyCredits / 70) %").
// A "$" or "¥" before it is put in front of the amount; a "%" after it
// shows it as a percent of 1 (0.25 is 25%). A path alone that is not a
// number is shown as it is. Several amounts, each with a label if wanted,
// go apart by ";" and are shown together: "5h: windowLimits.fiveHour.used /
// windowLimits.fiveHour.cap %; week: …; $credits.monthlyCredits" is
// "5h 0% · week 3.4% · $70.00".
// number is shown as it is. A path through a list's items ("a.*.used",
// "a[status=active].used") is several values, which sum(), max(), min()
// or count() make one (balanceExpr). Several amounts, each with a label if
// wanted, go apart by ";" and are shown together: "5h: windowLimits.
// fiveHour.used / windowLimits.fiveHour.cap %; week: …; $credits.
// monthlyCredits" is "5h 0% · week 3.4% · $70.00"; one of them the reply
// hasn't is "—" while the others show.
func readBalancePath(b []byte, path string) (string, error) {
parts, err := readBalanceParts(b, path)
if err != nil {
@@ -456,6 +460,8 @@ type BalancePart struct {
Label string `json:"label,omitempty"`
Text string `json:"text"`
Percent *float64 `json:"percent,omitempty"`
// Error is why the amount couldn't be read, its Text then "—".
Error string `json:"error,omitempty"`
}
// joinBalanceParts is the amounts on one line, as Balance tells them:
@@ -482,6 +488,8 @@ func readBalanceParts(b []byte, path string) ([]BalancePart, error) {
return []BalancePart{{Text: v, Percent: pct}}, nil
}
var out []BalancePart
var first error
read := false
for part := range strings.SplitSeq(path, ";") {
if strings.TrimSpace(part) == "" {
continue
@@ -493,16 +501,27 @@ func readBalanceParts(b []byte, path string) ([]BalancePart, error) {
label = strings.TrimSpace(label)
v, pct, err := readBalanceOne(b, expr)
if err != nil {
// one amount the reply hasn't (an index past the list's end, a
// window whose cap is 0) is "—", and the others still show
// (#1993); the whole fails only when none can be read
if label != "" {
err = fmt.Errorf("%s: %w", label, err)
}
return nil, err
if first == nil {
first = err
}
out = append(out, BalancePart{Label: label, Text: "—", Error: err.Error()})
continue
}
read = true
out = append(out, BalancePart{Label: label, Text: v, Percent: pct})
}
if len(out) == 0 {
return nil, errors.New("no balance path: where in the reply the amount is, e.g. data.balance")
}
if !read {
return nil, first
}
return out, nil
}
@@ -543,10 +562,7 @@ func readBalanceOne(b []byte, path string) (string, *float64, error) {
}
return "", nil, fmt.Errorf("%q in the reply is not an amount", path)
}
n, err := e.sum()
if err == nil && e.i < len(e.src) {
err = fmt.Errorf("the balance path has %q it can't read", e.src[e.i:])
}
n, err := e.number()
if err != nil {
return "", nil, err
}
@@ -574,25 +590,92 @@ func balanceAmount(sign string, n float64, percent bool) string {
}
// balanceExpr reads a balance path's sum: paths into the reply, numbers,
// + - * / and brackets.
// + - * / and brackets. A path can go through every item of a list ("*",
// "data.subscriptions.*.used") or those of them that match ("[status=
// active]", "[plan.kind!=free]"), and is then several values, which
// sum(), max(), min() or count() make one (#1993): "sum(a.*.used) /
// sum(a.*.cap)", "max(a.*.used / a.*.cap)". Several values left as they
// are, outside those, are an error rather than a guess at which of them
// was meant. Within them, an item without the path, or one divided by 0,
// is left out.
type balanceExpr struct {
src string
i int
reply any
}
// balanceVal is a number, or several (many) when a path went through a
// list; NaN stands for an item that has none.
type balanceVal struct {
n float64
ns []float64
many bool
// items are a path's own values, for count() to count those that are
// there, numbers or not
items []any
}
// balanceFuncs make a path's several values one.
var balanceFuncs = map[string]func([]float64) (float64, error){
"sum": func(ns []float64) (float64, error) {
s := 0.0
for _, n := range ns {
if !math.IsNaN(n) {
s += n
}
}
return s, nil
},
"count": func(ns []float64) (float64, error) {
c := 0.0
for _, n := range ns {
if !math.IsNaN(n) {
c++
}
}
return c, nil
},
"max": func(ns []float64) (float64, error) { return balanceExtreme(ns, "max", 1) },
"min": func(ns []float64) (float64, error) { return balanceExtreme(ns, "min", -1) },
}
func balanceExtreme(ns []float64, name string, sign float64) (float64, error) {
best, found := 0.0, false
for _, n := range ns {
if !math.IsNaN(n) && (!found || (n-best)*sign > 0) {
best, found = n, true
}
}
if !found {
return 0, fmt.Errorf("%s() of the balance path has nothing to take it of", name)
}
return best, nil
}
func (e *balanceExpr) space() {
for e.i < len(e.src) && e.src[e.i] == ' ' {
e.i++
}
}
// lone is whether the whole is one path.
// lone is whether the whole is one path, to one value.
func (e *balanceExpr) lone() bool {
return !strings.ContainsAny(e.src, "+-*/() ") && e.src != "" && !isDigit(e.src[0])
return !strings.ContainsAny(e.src, "+-*/() [") && e.src != "" && !isDigit(e.src[0])
}
func (e *balanceExpr) sum() (float64, error) {
// number is the whole's one number.
func (e *balanceExpr) number() (float64, error) {
v, err := e.sum()
if err == nil && e.i < len(e.src) {
err = fmt.Errorf("the balance path has %q it can't read", e.src[e.i:])
}
if err == nil && v.many {
err = errors.New("the balance path has several values where one is wanted: put them in sum(), max(), min() or count()")
}
return v.n, err
}
func (e *balanceExpr) sum() (balanceVal, error) {
v, err := e.product()
for err == nil {
e.space()
@@ -601,17 +684,15 @@ func (e *balanceExpr) sum() (float64, error) {
}
op := e.src[e.i]
e.i++
var w float64
if w, err = e.product(); op == '+' {
v += w
} else {
v -= w
var w balanceVal
if w, err = e.product(); err == nil {
v, err = balanceOp(v, w, op)
}
}
return v, err
}
func (e *balanceExpr) product() (float64, error) {
func (e *balanceExpr) product() (balanceVal, error) {
v, err := e.unary()
for err == nil {
e.space()
@@ -620,43 +701,71 @@ func (e *balanceExpr) product() (float64, error) {
}
op := e.src[e.i]
e.i++
var w float64
if w, err = e.unary(); err != nil {
break
}
if op == '*' {
v *= w
} else if w == 0 {
return 0, errors.New("the balance path divides by 0")
} else {
v /= w
var w balanceVal
if w, err = e.unary(); err == nil {
v, err = balanceOp(v, w, op)
}
}
return v, err
}
func (e *balanceExpr) unary() (float64, error) {
// balanceOp is v op w, item by item when either is several values: two
// lists by the same path go together, a number with each of a list's.
func balanceOp(v, w balanceVal, op byte) (balanceVal, error) {
one := func(a, b float64) float64 {
switch op {
case '+':
return a + b
case '-':
return a - b
case '*':
return a * b
}
if b == 0 {
return math.NaN()
}
return a / b
}
if !v.many && !w.many {
if op == '/' && w.n == 0 {
return v, errors.New("the balance path divides by 0")
}
return balanceVal{n: one(v.n, w.n)}, nil
}
if v.many && w.many && len(v.ns) != len(w.ns) {
return v, fmt.Errorf("the balance path puts %d values with %d", len(v.ns), len(w.ns))
}
size := max(len(v.ns), len(w.ns))
out := make([]float64, size)
for i := range out {
a, b := v.n, w.n
if v.many {
a = v.ns[i]
}
if w.many {
b = w.ns[i]
}
out[i] = one(a, b)
}
return balanceVal{ns: out, many: true}, nil
}
func (e *balanceExpr) unary() (balanceVal, error) {
e.space()
if e.i >= len(e.src) {
return 0, errors.New("the balance path ends where a number or a path should be")
return balanceVal{}, errors.New("the balance path ends where a number or a path should be")
}
switch c := e.src[e.i]; {
case c == '-':
e.i++
v, err := e.unary()
return -v, err
if err != nil {
return v, err
}
return balanceOp(balanceVal{n: 0}, v, '-')
case c == '(':
e.i++
v, err := e.sum()
if err != nil {
return 0, err
}
e.space()
if e.i >= len(e.src) || e.src[e.i] != ')' {
return 0, errors.New("the balance path has a ( without its )")
}
e.i++
return v, nil
return e.closed(e.sum())
case isDigit(c) || c == '.':
j := e.i
for j < len(e.src) && (isDigit(e.src[j]) || e.src[j] == '.') {
@@ -664,52 +773,279 @@ func (e *balanceExpr) unary() (float64, error) {
}
n, err := strconv.ParseFloat(e.src[e.i:j], 64)
if err != nil {
return 0, fmt.Errorf("the balance path has %q, not a number", e.src[e.i:j])
return balanceVal{}, fmt.Errorf("the balance path has %q, not a number", e.src[e.i:j])
}
e.i = j
return n, nil
return balanceVal{n: n}, nil
}
j := e.i
for j < len(e.src) && !strings.ContainsRune("+-*/() ", rune(e.src[j])) {
for j < len(e.src) {
c := e.src[j]
if c == '[' {
k := strings.IndexByte(e.src[j:], ']')
if k < 0 {
return balanceVal{}, errors.New("the balance path has a [ without its ]")
}
j += k + 1
continue
}
// "*" right after a dot, or at the start, is every item of a list
if c == '*' && (j == e.i || e.src[j-1] == '.') {
j++
continue
}
if strings.IndexByte("+-*/() ", c) >= 0 {
break
}
j++
}
if j == e.i {
return 0, fmt.Errorf("the balance path has %q where a number or a path should be", e.src[e.i:])
return balanceVal{}, fmt.Errorf("the balance path has %q where a number or a path should be", e.src[e.i:])
}
path := e.src[e.i:j]
e.i = j
v, err := e.at(path)
if f, ok := balanceFuncs[path]; ok && e.i < len(e.src) && e.src[e.i] == '(' {
e.i++
v, err := e.closed(e.sum())
if err != nil {
return v, err
}
ns := v.ns
if !v.many {
ns = []float64{v.n}
}
if path == "count" && v.items != nil {
ns = make([]float64, 0, len(v.items))
for _, x := range v.items {
if x != nil {
ns = append(ns, 1)
}
}
}
n, err := f(ns)
return balanceVal{n: n}, err
}
vs, many, err := e.all(path)
if err != nil {
return 0, err
return balanceVal{}, err
}
n, ok := number(v)
if !ok {
return 0, fmt.Errorf("%q in the reply is not a number", path)
if !many {
n, ok := number(vs[0])
if !ok {
return balanceVal{}, fmt.Errorf("%q in the reply is not a number", path)
}
return balanceVal{n: n}, nil
}
return n, nil
ns := make([]float64, len(vs))
for i, x := range vs {
ns[i] = math.NaN()
if n, ok := number(x); ok {
ns[i] = n
}
}
return balanceVal{ns: ns, many: true, items: vs}, nil
}
// at is what is at a dotted path in the reply.
// closed is a bracket's inside, with the ) after it.
func (e *balanceExpr) closed(v balanceVal, err error) (balanceVal, error) {
if err != nil {
return v, err
}
e.space()
if e.i >= len(e.src) || e.src[e.i] != ')' {
return v, errors.New("the balance path has a ( without its )")
}
e.i++
return v, nil
}
// at is what is at a dotted path in the reply, the path to one value.
func (e *balanceExpr) at(path string) (any, error) {
v := e.reply
for _, k := range strings.Split(path, ".") {
switch x := v.(type) {
case map[string]any:
v = x[k]
case []any:
i, err := strconv.Atoi(k)
if err != nil || i < 0 || i >= len(x) {
return nil, fmt.Errorf("nothing at %q in the reply", path)
vs, many, err := e.all(path)
if err != nil {
return nil, err
}
if many {
return nil, fmt.Errorf("%q is several values: put it in sum(), max(), min() or count()", path)
}
return vs[0], nil
}
// all is what is at a dotted path in the reply: one value, or, when the
// path goes through a list by "*" or "[…]", every item's (many), nil for
// an item without the rest of the path.
func (e *balanceExpr) all(path string) ([]any, bool, error) {
segs, err := balanceSegments(path)
if err != nil {
return nil, false, err
}
vs, many := []any{e.reply}, false
for _, s := range segs {
var next []any
for _, v := range vs {
if v == nil {
next = append(next, nil)
continue
}
v = x[i]
default:
v = nil
next = append(next, s.step(v)...)
}
if v == nil {
return nil, fmt.Errorf("nothing at %q in the reply", path)
many = many || s.spreads()
vs = next
if !many && (len(vs) != 1 || vs[0] == nil) {
return nil, false, fmt.Errorf("nothing at %q in the reply", path)
}
}
return v, nil
return vs, many, nil
}
// balanceSegment is one step of a path: a key, an index or "*", and the
// tests an item must pass, "[status=active]": a list's items that pass,
// or an object when it does.
type balanceSegment struct {
key string
tests []balanceTest
}
type balanceTest struct {
path []string
not bool
want string
}
func (s balanceSegment) spreads() bool { return s.key == "*" || len(s.tests) > 0 }
// step is what one value leads to: one value, or a list's items.
func (s balanceSegment) step(v any) []any {
if s.key == "*" {
v = balanceItems(v)
} else if s.key != "" {
v = balanceChild(v, s.key)
}
if len(s.tests) == 0 {
if s.key == "*" {
return v.([]any)
}
return []any{v}
}
// a list's items that pass, or an object itself when it does
items, ok := v.([]any)
if !ok {
items = []any{v}
}
var out []any
for _, x := range items {
if x != nil && s.passes(x) {
out = append(out, x)
}
}
return out
}
func (s balanceSegment) passes(x any) bool {
for _, t := range s.tests {
v := x
for _, k := range t.path {
if v = balanceChild(v, k); v == nil {
break
}
}
got := ""
switch y := v.(type) {
case string:
got = y
case float64:
got = strconv.FormatFloat(y, 'f', -1, 64)
case bool:
got = strconv.FormatBool(y)
}
if (v != nil && got == t.want) == t.not {
return false
}
}
return true
}
// balanceChild is a key of an object, or an index of a list.
func balanceChild(v any, k string) any {
switch x := v.(type) {
case map[string]any:
return x[k]
case []any:
if i, err := strconv.Atoi(k); err == nil && i >= 0 && i < len(x) {
return x[i]
}
}
return nil
}
// balanceItems is a list's items, or an object's values by key.
func balanceItems(v any) []any {
switch x := v.(type) {
case []any:
return x
case map[string]any:
keys := slices.Sorted(maps.Keys(x))
out := make([]any, len(keys))
for i, k := range keys {
out[i] = x[k]
}
return out
}
return []any{}
}
// balanceSegments splits a path at its dots, a "[…]" test kept whole.
func balanceSegments(path string) ([]balanceSegment, error) {
var out []balanceSegment
for rest := path; ; {
end := 0
for end < len(rest) && rest[end] != '.' {
if rest[end] == '[' {
k := strings.IndexByte(rest[end:], ']')
if k < 0 {
return nil, errors.New("the balance path has a [ without its ]")
}
end += k
}
end++
}
seg, err := balanceSegmentOf(rest[:end], path)
if err != nil {
return nil, err
}
out = append(out, seg)
if end == len(rest) {
return out, nil
}
rest = rest[end+1:]
}
}
func balanceSegmentOf(raw, path string) (balanceSegment, error) {
key, tests, _ := strings.Cut(raw, "[")
s := balanceSegment{key: key}
if key == "" && tests == "" {
return s, fmt.Errorf("nothing at %q in the reply", path)
}
for tests != "" {
body, after, ok := strings.Cut(tests, "]")
if !ok {
return s, errors.New("the balance path has a [ without its ]")
}
t := balanceTest{}
left, want, ok := strings.Cut(body, "=")
if !ok || strings.TrimSpace(left) == "" {
return s, fmt.Errorf("the balance path has [%s], not a test like [status=active]", body)
}
if l, isNot := strings.CutSuffix(left, "!"); isNot {
t.not, left = true, l
}
t.path = strings.Split(strings.TrimSpace(left), ".")
t.want = strings.Trim(strings.TrimSpace(want), `'"`)
s.tests = append(s.tests, t)
tests = strings.TrimPrefix(after, "[")
}
return s, nil
}
// Balance asks the vendor what is left on the provider's key in use. ok is
+81 -1
View File
@@ -71,7 +71,7 @@ func TestReadBalancePath(t *testing.T) {
t.Errorf("%q: %q %v, want %q", path, got, err, want)
}
}
for _, path := range []string{";", "5h: windowLimits.hour.used; $credits.monthlyCredits", "week:"} {
for _, path := range []string{";", "5h: windowLimits.hour.used; week: windowLimits.weekly.used / 0", "week:"} {
if got, err := readBalancePath(cc, path); err == nil {
t.Errorf("%q: read %q, want an error", path, got)
}
@@ -83,6 +83,86 @@ func TestReadBalancePath(t *testing.T) {
}
}
// A relay's subscriptions are a list: a balance path sums, or takes the
// max of, every item's or those that match (#1993, RicardoWYP's
// /api/subscription/self, as pasted), and one amount of several that the
// reply hasn't (a second subscription that isn't there, a weekly cap of 0)
// is "—" while the others still show.
func TestBalancePathLists(t *testing.T) {
one := []byte(`{
"data": {
"subscriptions": [
{ "subscription": { "status": "active", "amount_total": 50000000, "amount_used": 31593277, "weekly_amount_total": 0, "weekly_amount_used": 0 } }
],
"all_subscriptions": [ { "subscription": { "status": "expired", "...": "..." } } ]
}
}`)
two := []byte(`{"data":{"subscriptions":[
{"subscription":{"status":"active","amount_total":50000000,"amount_used":31593277,"weekly_amount_total":0,"weekly_amount_used":0}},
{"subscription":{"status":"active","amount_total":"10000000","amount_used":5000000,"weekly_amount_total":4000000,"weekly_amount_used":1000000}},
{"subscription":{"status":"expired","amount_total":90000000,"amount_used":90000000,"weekly_amount_total":1000000,"weekly_amount_used":1000000}}]}}`)
const (
used = "sum(data.subscriptions[subscription.status=active].subscription.amount_used) / sum(data.subscriptions[subscription.status=active].subscription.amount_total) %"
week = "max(data.subscriptions[subscription.status=active].subscription.weekly_amount_used / data.subscriptions[subscription.status=active].subscription.weekly_amount_total) %"
count = "count(data.subscriptions.*.subscription[status='active'])"
)
for _, c := range []struct {
body []byte
path string
want string
}{
{one, used, "63.2%"},
{two, used, "61%"},
{one, "$ sum(data.subscriptions.*.subscription.amount_used) / 500000", "$63.19"},
{two, "max(data.subscriptions.*.subscription.amount_used)", "90000000.00"},
{two, "min(data.subscriptions.*.subscription.amount_used)", "5000000.00"},
{two, "count(data.subscriptions[subscription.status!=active])", "1.00"},
{one, "sum(data.all_subscriptions.*.subscription.amount_used)", "0.00"},
{two, week, "25%"},
{two, count, "2.00"},
{two, "sum(data.subscriptions.*.subscription[status=active].amount_total) / 1000000", "60.00"},
{two, "max(data.subscriptions.*.subscription.weekly_amount_used / data.subscriptions.*.subscription.weekly_amount_total) %", "100%"},
{two, "sum(data.subscriptions[subscription.status=active].subscription.amount_used) * 2 / 1000000", "73.19"},
// all of a list's items, as they are
{[]byte(`[{"left":1},{"left":2.5}]`), "sum(*.left)", "3.50"},
{[]byte(`{"a":{"x":{"n":1},"y":{"n":4}}}`), "max(a.*.n)", "4.00"},
// one amount the reply hasn't is "—", the others still show
{one, "used: " + used + "; week: " + week, "used 63.2% · week —"},
{one, "first: data.subscriptions.0.subscription.amount_used; second: data.subscriptions.1.subscription.amount_used", "first 31593277.00 · second —"},
{one, "all: data.subscriptions.0.subscription.amount_used + data.subscriptions.1.subscription.amount_used; used: " + used, "all — · used 63.2%"},
} {
if got, err := readBalancePath(c.body, c.path); err != nil || got != c.want {
t.Errorf("%q: %q %v, want %q", c.path, got, err, c.want)
}
}
for _, path := range []string{
// several values where one is wanted: a sum, not a guess
"data.subscriptions.*.subscription.amount_used",
"data.subscriptions[subscription.status=active].subscription.amount_used / 2",
"data.subscriptions.*.subscription.amount_used %",
// a max of nothing, a list beside one of another length
"max(data.all_subscriptions.*.subscription.amount_used)",
// one alone that can't be read still fails, as does every one of several
week,
"week: " + week + "; second: data.subscriptions.1.subscription.amount_used",
"sum(data.subscriptions.*.subscription.amount_used",
"sum(data.subscriptions[status.amount_used)",
"sum(data.subscriptions[status].amount_used)",
} {
if got, err := readBalancePath(one, path); err == nil {
t.Errorf("%q: read %q, want an error", path, got)
}
}
if got, err := readBalancePath(two, "sum(data.subscriptions.*.subscription.amount_used + data.subscriptions[subscription.status=active].subscription.amount_total)"); err == nil {
t.Errorf("lists of 3 and 2 put together: read %q, want an error", got)
}
// the card's amount says why it is "—"
parts, err := readBalanceParts(one, "used: "+used+"; week: "+week)
if err != nil || len(parts) != 2 || parts[1].Text != "—" || !strings.Contains(parts[1].Error, "nothing to take it of") || parts[0].Error != "" {
t.Errorf("parts: %+v %v", parts, err)
}
}
func TestBalanceSourceByHost(t *testing.T) {
for base, want := range map[string]string{
"https://api.deepseek.com/v1": "https://api.deepseek.com/user/balance",