refactor: dedupe provider usage fetch logic and tests

This commit is contained in:
Peter Steinberger
2026-02-19 12:50:55 +00:00
parent 6195660b1a
commit badafdc7b3
16 changed files with 806 additions and 215 deletions

View File

@@ -1,5 +1,5 @@
import { isRecord } from "../utils.js";
import { fetchJson } from "./provider-usage.fetch.shared.js";
import { buildUsageHttpErrorSnapshot, fetchJson } from "./provider-usage.fetch.shared.js";
import { clampPercent, PROVIDER_LABELS } from "./provider-usage.shared.js";
import type { ProviderUsageSnapshot, UsageWindow } from "./provider-usage.types.js";
@@ -224,10 +224,7 @@ function collectUsageCandidates(root: Record<string, unknown>): Record<string, u
let scanned = 0;
while (queue.length && scanned < MAX_SCAN_NODES) {
const next = queue.shift();
if (!next) {
break;
}
const next = queue.shift() as { value: unknown; depth: number };
scanned += 1;
const { value, depth } = next;
@@ -292,10 +289,7 @@ function deriveUsedPercent(payload: Record<string, unknown>): number | null {
if (percentRaw !== undefined) {
const normalized = clampPercent(percentRaw <= 1 ? percentRaw * 100 : percentRaw);
if (fromCounts !== null) {
const inverted = clampPercent(100 - normalized);
if (Math.abs(normalized - fromCounts) <= 1 || Math.abs(inverted - fromCounts) <= 1) {
return fromCounts;
}
// Count-derived usage is more stable across provider percent field variations.
return fromCounts;
}
return normalized;
@@ -324,12 +318,10 @@ export async function fetchMinimaxUsage(
);
if (!res.ok) {
return {
return buildUsageHttpErrorSnapshot({
provider: "minimax",
displayName: PROVIDER_LABELS.minimax,
windows: [],
error: `HTTP ${res.status}`,
};
status: res.status,
});
}
const data = (await res.json().catch(() => null)) as MinimaxUsageResponse;