Files
plugins/packages/page-usage-tree/lib/gateway.mjs
T
CHENZUDE 808f7a184d page-usage-tree 0.1.0: usage as provider → account → model (CHENZUDE, #575)
New page plugin @magpie-community/page-usage-tree 0.1.0 by CHENZUDE: magpie's usage as a provider -> account -> model tree, served by a small server that reads the gateway's /v1/magpie/usage and /usage/requests.

The last round (f9e0907) gives the model row's calls cell the calls-cell class, so CALLS values sit under their right-aligned header, adds a test for it, and comments why the server's retry budget is 16 x 100ms.

What was run at f9e09079 (mote, macOS, sandbox HOME):
- In the package: node --test 50 pass; bun test 47 tests, 0 fail.
- f9e09079 merged onto main 8765cf8f: bun scripts/check.mjs ok; whole-repo bun test 6149 pass, 20 skip, 0 fail.
- Playwright against a fake gateway: CALLS header and value right edges 616/616 (1280px), 423/423 (900), 341/341 (760, 621) in Chromium and WebKit. Chromium 1280-620px, WebKit 900/760, both engines at 420px in en and zh: no clipped cell, no sideways scroll, no <select>, no page errors.
- Broken by hand: the old `model.errors ? "bad" : ""` puts values at 544 and 273 and turns "model calls sit under the right-aligned calls header" red (27 pass, 1 fail).

Not tried: a real magpie with real accounts, the desktop app, Windows and Linux.
2026-11-05 17:11:25 +08:00

149 lines
4.7 KiB
JavaScript

// The gateway answers this page's data through magpie's own usage API.
// Nothing here reads magpie's files: MAGPIE_ADDR is what the plugin host
// gives its plugins, and the gateway is the service that counted the calls.
import http from "node:http";
import https from "node:https";
const DEFAULT_GATEWAY = "http://127.0.0.1:3425";
function normalizeGateway(value) {
const text = String(value || "").trim().replace(/\/+$/, "");
return /^https?:\/\//i.test(text) ? text : "";
}
export function gatewayCandidates(options = {}) {
const out = [];
const push = (value) => {
const text = normalizeGateway(value);
if (text && !out.includes(text)) out.push(text);
};
push(options.gateway);
push(process.env.MAGPIE_USAGE_TREE_GATEWAY);
push(process.env.MAGPIE_GATEWAY);
const addr = process.env.MAGPIE_ADDR;
if (addr) {
const loopback = String(addr).replace(/^(0\.0\.0\.0|\[::\]):/, "127.0.0.1:");
if (/^[\w.-]+:\d+$/.test(loopback)) push(`http://${loopback}`);
}
push(DEFAULT_GATEWAY);
return out;
}
let picked = { at: 0, url: "" };
export function resetGatewayCache() {
picked = { at: 0, url: "" };
}
function gatewayHeaders() {
const key = String(process.env.MAGPIE_API_KEY || process.env.MAGPIE_GATEWAY_KEY || "").trim();
return key ? { Authorization: `Bearer ${key}` } : {};
}
export async function resolveGateway(options = {}) {
// An explicit gateway belongs to the caller and is never replaced by a
// remembered one. Tests use this, and so does a manual serve.mjs run.
if (options.gateway) {
const explicit = normalizeGateway(options.gateway);
if (!explicit) throw new Error("invalid Magpie gateway URL");
return explicit;
}
if (picked.url && Date.now() - picked.at < 60_000) return picked.url;
for (const url of gatewayCandidates(options)) {
try {
const res = await fetch(`${url}/v1/magpie/usage?period=today`, {
headers: gatewayHeaders(),
signal: AbortSignal.timeout(2500),
});
if (res.ok) {
await res.body?.cancel().catch(() => {});
picked = { at: Date.now(), url };
return url;
}
await res.body?.cancel().catch(() => {});
} catch {
// Try the next candidate.
}
}
return gatewayCandidates(options)[0] || DEFAULT_GATEWAY;
}
function getJSON(url, timeout = 10_000) {
return new Promise((resolve, reject) => {
let request;
try {
const target = new URL(url);
const client = target.protocol === "https:" ? https : http;
request = client.get(
target,
{
agent: false,
headers: {
...gatewayHeaders(),
Accept: "application/json",
"Accept-Encoding": "identity",
Connection: "close",
},
},
(res) => {
const chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("error", reject);
res.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
let body = null;
try {
body = JSON.parse(raw);
} catch {
// Keep body null so a failed response still reports its HTTP status.
}
const status = Number(res.statusCode) || 0;
if (status < 200 || status >= 300) {
reject(new Error(body?.error || `Magpie gateway returned HTTP ${status}`));
return;
}
if (!body || typeof body !== "object" || Array.isArray(body)) {
reject(new Error("Magpie gateway returned an invalid JSON object"));
return;
}
resolve(body);
});
},
);
request.setTimeout(timeout, () => {
request.destroy(new Error("Magpie gateway request timed out"));
});
request.on("error", reject);
} catch (error) {
reject(error);
}
});
}
function query(params) {
const out = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value != null && value !== "") out.set(key, String(value));
}
return out.toString();
}
export async function gatewayUsage(period, options = {}) {
const base = await resolveGateway(options);
return getJSON(`${base}/v1/magpie/usage?${query({ period })}`, options.timeout);
}
export async function gatewayRequests(period, options = {}) {
const base = await resolveGateway(options);
return getJSON(`${base}/v1/magpie/usage/requests?${query({ period })}`, options.timeout);
}
export async function gatewayAccountRequests(period, account, provider = "", options = {}) {
const base = await resolveGateway(options);
return getJSON(
`${base}/v1/magpie/usage/requests?${query({ period, account, provider })}`,
options.timeout,
);
}