Files
plugins/packages/page-usage-tree/lib/server.mjs
T
CHENZUDE 1e060e6163 page-usage-tree 0.1.1: refresh warning only on a real failure, hit rate and model-detail fixes (#960)
page-usage-tree 0.1.1 (CHENZUDE):

- A failed refresh is kept on the cache entry the page reads, so
  "Refresh failed; showing the previous data" shows when a refresh threw
  (on 0.1.0 it was written to an entry already replaced and never shown).
  Only a loader that threw counts: an older disk cache marked stale does
  not, and a retry from a failed entry stays failed until a loader succeeds.
  The page takes the server's X-Usage-Tree-Refresh on every answer, quiet
  follow-ups included, so the warning clears once the gateway recovers.
- Hit rate uses magpie's hitPct rounding (0.9996 shows 99.96%, not 100%).
- A failed per-account model-detail read keeps the account totals and says
  model details are incomplete (zh, en). Disk cache v8.
- Not in the PR body: a /bridge.js shim served by the service (talks only to
  parent: hello, options.get/set, theme and visibility), request timeout
  10s -> 30s, narrow breakpoint 620px -> 700px, model split on narrow
  screens, "permissions": [] added (same as absent), zh warnings joined
  with ";".

Run at the reviewed head 74363201570d9f69866ac0e4afff7a2b898e6dab:
- WSL (magpie-desktop), fresh HOME: bun test packages/page-usage-tree
  62 pass 1 skip (parity needs a live magpie); node --test 68 pass 1 skip;
  bun scripts/check.mjs ok.
- Windows (xiaomi-gpu), fresh HOME and USERPROFILE: bun test
  packages/page-usage-tree exit 0; bun scripts/check.mjs ok. CI green.
- Playwright 1.62 Chromium and WebKit on WSL, sandbox server with fake
  data, 1280 and 420px, en and zh: a first open from a stale disk cache
  never shows the refresh warning; a failed manual refresh shows it, it
  stays while the gateway is down, and clears on the quiet follow-ups after
  recovery while the model-detail warning stays; no page errors, no
  horizontal scroll. The same probe on e3da32bed fails 3 checks (false
  warning on open, warning never clears, zh joined by a space).
- Broken by hand: counting data.stale as failed, a retry entry forgetting
  the failure, and a quiet load never clearing each turn a test red.
  Not covered by a test: dropping warningStateChanged (render also runs
  renderWarnings) and the zh join between two data warnings.
- Host/Origin/token handling on /api/tree unchanged from main; /bridge.js
  is static and behind the Host check. dist had only 0.1.0.
2026-11-11 15:18:33 +08:00

606 lines
21 KiB
JavaScript

import { createServer } from "node:http";
import { createHash, randomBytes } from "node:crypto";
import { readFile } from "node:fs/promises";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { displaySettings, loadUsageData } from "./data.mjs";
import { PERIODS } from "./usage.mjs";
const UI_DIR = fileURLToPath(new URL("../ui/", import.meta.url));
const CACHE_MS = 25_000;
export const PLUGIN_NAME = "magpie-usage-tree";
// The service page runs inside Magpie's plugin frame. Its own bridge lives
// in the launcher document; this small registered bridge serves subsequent
// plugin-option and visibility calls from the same parent window.
const BRIDGE_SHIM = `(() => {
const waiting = new Map();
let next = 0;
const themed = [];
const watched = [];
function call(method, params) {
// Opening the service directly has no Magpie parent to answer. Leave the
// optional bridge inert instead of posting a request to the page itself.
if (parent === window) return Promise.resolve(undefined);
const id = ++next;
return new Promise((resolve, reject) => {
waiting.set(id, { resolve, reject });
parent.postMessage({ magpie: 1, id, method, params }, "*");
});
}
function paint(theme) {
if (!theme) return;
const root = document.documentElement;
root.dataset.theme = theme.dark ? "dark" : "light";
root.style.colorScheme = theme.dark ? "dark" : "light";
if (theme.lang) root.lang = theme.lang;
for (const [key, value] of Object.entries(theme.tokens || {})) {
if (typeof value === "string") root.style.setProperty("--magpie-" + key, value);
}
}
addEventListener("message", (event) => {
const message = event.data;
if (!message || message.magpie !== 1 || event.source !== parent) return;
if (message.event === "theme") {
api.theme = message.data;
paint(message.data);
for (const fn of themed) {
try { fn(message.data); } catch { /* a page listener cannot break the bridge */ }
}
return;
}
if (message.event === "visibility") {
for (const fn of watched) fn(!!message.data?.visible);
return;
}
const wait = waiting.get(message.id);
if (!wait) return;
waiting.delete(message.id);
if (message.error) wait.reject(new Error(message.error));
else wait.resolve(message.result);
});
const api = {
theme: null,
context: {},
service: "",
onTheme(fn) { themed.push(fn); },
options: {
get: () => call("options.get"),
set: (options) => call("options.set", { options }),
},
onVisibility(fn) { watched.push(fn); },
};
api.ready = call("hello").then((hello = {}) => {
const { context, service, ...theme } = hello;
api.theme = theme;
api.context = context || {};
api.service = "";
if (service) {
try { api.service = new URL(service, location.href).href; } catch { /* none */ }
}
paint(theme);
return theme;
});
window.magpie = api;
})();`;
// The build's own version, so an older service on the port is told apart
// from this one.
export function version() {
try {
const raw = JSON.parse(
readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"),
);
return typeof raw.version === "string" ? raw.version : "0";
} catch {
return "0";
}
}
let cachedBuild = "";
export const BUILD_FILES = Object.freeze([
"server.mjs",
"data.mjs",
"gateway.mjs",
"usage.mjs",
"../index.mjs",
"../serve.mjs",
"../package.json",
"../page/index.html",
"../page/boot.js",
"../page/icon.svg",
"../ui/app.html",
"../ui/app.js",
"../ui/view.js",
"../ui/i18n.js",
"../ui/style.css",
]);
// A version alone cannot tell a rebuilt local plugin from the code already
// loaded in the host. Hash every runtime asset as well, so a same-version
// but changed build is never mistaken for the running one.
export function buildId() {
if (cachedBuild) return cachedBuild;
try {
const base = new URL("./", import.meta.url);
const hash = createHash("sha256");
for (const name of BUILD_FILES) {
hash.update(name);
hash.update("\0");
hash.update(readFileSync(fileURLToPath(new URL(name, base))));
}
cachedBuild = hash.digest("hex").slice(0, 16);
} catch {
cachedBuild = `version:${version()}`;
}
return cachedBuild;
}
const STATIC = new Map([
["/app.js", ["app.js", "text/javascript; charset=utf-8"]],
["/view.js", ["view.js", "text/javascript; charset=utf-8"]],
["/i18n.js", ["i18n.js", "text/javascript; charset=utf-8"]],
["/style.css", ["style.css", "text/css; charset=utf-8"]],
// The page's own icon lives beside the launcher, not in ui/.
["/icon.svg", ["../page/icon.svg", "image/svg+xml"]],
]);
function json(res, status, value) {
const body = JSON.stringify(value);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
res.end(body);
}
function allowedOrigin(origin, port) {
if (!origin || origin === "null") return true;
return (
origin === `http://127.0.0.1:${port}` ||
origin === `http://localhost:${port}` ||
origin === `http://[::1]:${port}`
);
}
// A plugin page is a sandboxed frame, so it reaches this service with an
// opaque origin ("null"). Its own token still guards the data; these
// headers only let that frame read the answer it asked for.
function allowNullOrigin(req, res) {
if (req.headers.origin === "null") {
res.setHeader("Access-Control-Allow-Origin", "null");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "x-usage-tree-token");
res.setHeader("Access-Control-Expose-Headers", "x-usage-tree-cache, x-usage-tree-refresh");
res.setHeader("Vary", "Origin");
}
}
function allowedHost(host, port) {
const value = String(host || "").toLowerCase();
return (
value === `127.0.0.1:${port}` ||
value === `localhost:${port}` ||
value === `[::1]:${port}`
);
}
function escHTML(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function parseTokens(raw) {
if (!raw) return {};
try {
const value = JSON.parse(Buffer.from(String(raw), "base64").toString("utf8"));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const out = {};
for (const [key, item] of Object.entries(value)) {
if (/^[a-z0-9-]{1,40}$/i.test(key) && typeof item === "string" && item.length <= 160) {
out[key] = item;
}
}
return out;
} catch {
return {};
}
}
// probeService asks an already running copy of this page's service whether
// it is up, and the token its page was given. Both the app's plugin host and
// the host a `magpie plugin` command starts load this plugin, so one of them
// wins the port; the other must treat that as success, not a failure.
async function probeService(port) {
try {
const res = await fetch(`http://127.0.0.1:${port}/healthz`, {
signal: AbortSignal.timeout(1200),
});
if (!res.ok) {
await res.body?.cancel().catch(() => {});
return null;
}
const body = await res.json();
if (!body || body.name !== PLUGIN_NAME) return null;
// The token stays with the copy that owns the port; a page is always
// served by that copy, so the second host needs nothing from it.
return {
reused: true,
version: body.version || "",
build: body.build || "",
};
} catch {
return null;
}
}
export async function startServer(options = {}) {
const port = Number(options.port);
const requestedPort = Number.isInteger(port) && port >= 0 && port <= 65535 ? port : 3494;
// A restarting host normally frees the port within a fraction of a second.
// Sixteen 100 ms retries bound the worst-case start delay to 1.6 s; waiting
// longer would make the plugin host look hung when another build is live.
const retryAttempts =
Number.isInteger(options.retryAttempts) && options.retryAttempts > 0
? options.retryAttempts
: 16;
const retryDelayMs =
Number.isInteger(options.retryDelayMs) && options.retryDelayMs >= 0
? options.retryDelayMs
: 100;
const token = randomBytes(24).toString("base64url");
const loader = options.load || loadUsageData;
const cache = new Map();
let boundPort = requestedPort;
function refreshFailedFor(period) {
// A stale answer can simply be an older disk cache. Only a loader that
// actually threw makes this a failed refresh.
return cache.get(period)?.refreshFailed === true;
}
async function dataFor(period, options = {}) {
const wanted = PERIODS.has(period) ? period : "7d";
const hit = cache.get(wanted);
const now = Date.now();
// What was read last is shown at once, whatever its age; a new read
// never stands between the reader and the numbers they had a moment
// ago. Only a first read waits, as there is nothing to show yet.
if (!options.fresh && hit?.data) {
const stale = hit.data.stale === true || now - hit.at >= (hit.ttl ?? CACHE_MS);
if (stale) void refreshInBackground(wanted, { fresh: true });
return {
data: { ...hit.data, stale },
cache: stale ? "stale" : "fresh",
refreshFailed: refreshFailedFor(wanted),
};
}
// A read is already running behind the page: what was read last is
// still the best answer to give now.
if (hit?.pending) {
if (hit.data && !options.fresh) {
return {
data: { ...hit.data, stale: true },
cache: "stale",
refreshFailed: refreshFailedFor(wanted),
};
}
return { data: await hit.pending, cache: "shared", refreshFailed: refreshFailedFor(wanted) };
}
const loaded = await refreshInBackground(wanted, { wait: true, fresh: options.fresh });
return {
data: loaded,
cache: loaded?.stale ? "stale" : "miss",
refreshFailed: refreshFailedFor(wanted),
};
}
function refreshInBackground(wanted, options = {}) {
const hit = cache.get(wanted);
if (hit?.pending) {
return options.wait ? hit.pending : Promise.resolve(hit.data);
}
// A retry started from a failed entry must keep that failure visible
// until a loader actually succeeds; otherwise a quiet read would report
// success while another failed refresh is still in flight.
const entry = {
at: hit?.at || 0,
data: hit?.data,
pending: null,
refreshFailed: hit?.refreshFailed === true,
};
const pending = loader(wanted, { fresh: Boolean(options.fresh) })
.then((data) => {
cache.set(wanted, {
at: Date.now(),
data,
ttl: CACHE_MS,
refreshFailed: false,
});
return data;
})
.catch((error) => {
if (entry.data) {
entry.refreshFailed = true;
entry.error = error;
// Keep the last good answer, but never let the page mistake it for
// a successful fresh read. Marking it stale also keeps the next
// request retrying instead of accepting the cache as current.
entry.data = { ...entry.data, stale: true };
if (cache.get(wanted) === entry) cache.set(wanted, entry);
return entry.data;
}
throw error;
})
.finally(() => {
const current = cache.get(wanted);
if (current?.pending === pending) current.pending = null;
});
entry.pending = pending;
cache.set(wanted, entry);
if (!options.wait) {
void pending.catch(() => {});
return Promise.resolve(entry.data);
}
return pending;
}
const handler = async (req, res) => {
try {
const host = req.headers.host || "";
if (!allowedHost(host, boundPort)) {
json(res, 403, { error: "invalid host" });
return;
}
const url = new URL(req.url || "/", `http://${host}`);
if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "OPTIONS") {
json(res, 405, { error: "method not allowed" });
return;
}
if (url.pathname === "/healthz") {
json(res, 200, {
ok: true,
name: PLUGIN_NAME,
version: version(),
build: buildId(),
});
return;
}
if (
req.method === "OPTIONS" &&
(url.pathname === "/api/tree" || url.pathname === "/api/settings")
) {
allowNullOrigin(req, res);
res.writeHead(204, {
"Access-Control-Expose-Headers": "x-usage-tree-cache, x-usage-tree-refresh",
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
res.end();
return;
}
if (url.pathname === "/") {
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
const template = await readFile(join(UI_DIR, "app.html"), "utf8");
const hasUnits = url.searchParams.has("chineseUnits");
const boot = {
tokens: parseTokens(url.searchParams.get("tokens")),
...displaySettings({
theme: url.searchParams.get("theme") === "dark" ? "dark" : "light",
lang: url.searchParams.get("lang") || "",
currency: url.searchParams.get("currency") || options.currency || "",
chineseUnits: hasUnits
? url.searchParams.get("chineseUnits") === "1"
: options.chineseUnits === true,
usdCny: url.searchParams.get("usdCny") || options.usdCny || 0,
}),
};
const lang = String(url.searchParams.get("lang") || boot.lang).slice(0, 12);
const html = template
.replaceAll("__USAGE_TREE_TOKEN__", escHTML(token))
.replaceAll("__USAGE_TREE_THEME__", escHTML(boot.theme))
.replaceAll("__USAGE_TREE_LANG__", escHTML(lang))
.replaceAll("__USAGE_TREE_TOKENS__", escHTML(JSON.stringify(boot.tokens)))
.replaceAll("__USAGE_TREE_CURRENCY__", escHTML(boot.currency))
.replaceAll("__USAGE_TREE_USD_CNY__", escHTML(String(boot.usdCny)))
.replaceAll("__USAGE_TREE_CHINESE_UNITS__", String(boot.chineseUnits))
.replaceAll("__USAGE_TREE_SETTINGS__", url.searchParams.get("settings") === "1" ? "1" : "0")
.replaceAll(
"__USAGE_TREE_TITLE__",
escHTML(lang.toLowerCase().startsWith("zh") ? "账号用量" : "Account usage"),
);
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy":
`default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http://127.0.0.1:${boundPort} http://localhost:${boundPort}; base-uri 'none'; form-action 'none'`,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
});
res.end(req.method === "HEAD" ? undefined : html);
return;
}
// A small same-page bridge keeps plugin-option and visibility messages
// working after the launcher navigates to the service.
if (url.pathname === "/bridge.js") {
res.writeHead(200, {
"Content-Type": "text/javascript; charset=utf-8",
"Cache-Control": "no-cache",
"X-Content-Type-Options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : BRIDGE_SHIM);
return;
}
if (url.pathname === "/api/tree") {
allowNullOrigin(req, res);
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
if (req.headers["x-usage-tree-token"] !== token) {
json(res, 401, { error: "missing or invalid token" });
return;
}
const period = url.searchParams.get("period") || "7d";
if (!PERIODS.has(period)) {
json(res, 400, { error: "period must be today, 7d, 30d or all" });
return;
}
const loaded = await dataFor(period, { fresh: url.searchParams.get("fresh") === "1" });
res.setHeader("X-Usage-Tree-Cache", loaded.cache);
res.setHeader("X-Usage-Tree-Refresh", loaded.refreshFailed ? "failed" : "ok");
json(res, 200, loaded.data);
return;
}
if (url.pathname === "/api/settings") {
// The page no longer polls settings. Keep the endpoint for callers
// that still use it, and answer its preflight above.
allowNullOrigin(req, res);
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
if (req.headers["x-usage-tree-token"] !== token) {
json(res, 401, { error: "missing or invalid token" });
return;
}
json(res, 200, displaySettings(options));
return;
}
const item = STATIC.get(url.pathname);
if (item) {
const body = await readFile(join(UI_DIR, item[0]));
res.writeHead(200, {
"Content-Type": item[1],
"Content-Length": body.length,
"Cache-Control": "no-cache",
"X-Content-Type-Options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : body);
return;
}
json(res, 404, { error: "not found" });
} catch (error) {
json(res, 500, { error: error?.message || "usage tree failed" });
}
};
// A restarted plugin host can overlap the one it replaces for a moment.
// Bind first, and only after the port stays busy for a while accept that
// another live host already serves this plugin; a dying host releases the
// port and the retry then takes it.
let server = null;
const bind = () =>
new Promise((resolve, reject) => {
const instance = createServer(handler);
const onError = (error) => {
instance.off("listening", onListening);
reject(error);
};
const onListening = () => {
instance.off("error", onError);
resolve(instance);
};
instance.once("error", onError);
instance.once("listening", onListening);
instance.listen(requestedPort, "127.0.0.1");
});
if (requestedPort === 0) {
server = await bind();
} else {
let bound = false;
// A host that is on its way out keeps the port for a moment: the new
// build waits for it, and takes the port when it is free. A live service
// of another build is never killed: it may be the same plugin host that
// serves every other plugin.
for (let attempt = 0; attempt < retryAttempts; attempt += 1) {
try {
server = await bind();
bound = true;
break;
} catch (error) {
if (error?.code !== "EADDRINUSE") throw error;
const running = await probeService(requestedPort);
if (running && running.version === version() && running.build === buildId()) {
return {
port: requestedPort,
token: "",
server: null,
reused: true,
close: async () => {},
};
}
if (retryDelayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
}
}
if (!bound) {
const running = await probeService(requestedPort);
if (running && running.version === version() && running.build === buildId()) {
return {
port: requestedPort,
token: "",
server: null,
reused: true,
close: async () => {},
};
}
throw new Error(
running
? `port ${requestedPort} is held by another build of this plugin (${running.version || "unknown"})`
: `port ${requestedPort} is in use and not by this plugin`,
);
}
}
boundPort = server.address().port;
// Warm only when there is a real loader behind the service. A test loader
// is cheap, but a pending warm read can outlive the server's close.
if (!options.load) void dataFor("today").catch(() => {});
return {
port: boundPort,
token,
server,
close: () =>
new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
// Fetch may still be retiring a reused connection when close()
// reports done on Windows. One turn is enough for that to settle.
setTimeout(resolve, 25);
};
server.close(finish);
// Fetch keeps idle sockets alive. Release them so a stopped plugin
// host does not wait for the client's connection timeout.
server.closeIdleConnections?.();
}),
};
}