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,3 +1,6 @@
import { PROVIDER_LABELS } from "./provider-usage.shared.js";
import type { ProviderUsageSnapshot, UsageProviderId } from "./provider-usage.types.js";
export async function fetchJson(
url: string,
init: RequestInit,
@@ -12,3 +15,33 @@ export async function fetchJson(
clearTimeout(timer);
}
}
type BuildUsageHttpErrorSnapshotOptions = {
provider: UsageProviderId;
status: number;
message?: string;
tokenExpiredStatuses?: readonly number[];
};
export function buildUsageErrorSnapshot(
provider: UsageProviderId,
error: string,
): ProviderUsageSnapshot {
return {
provider,
displayName: PROVIDER_LABELS[provider],
windows: [],
error,
};
}
export function buildUsageHttpErrorSnapshot(
options: BuildUsageHttpErrorSnapshotOptions,
): ProviderUsageSnapshot {
const tokenExpiredStatuses = options.tokenExpiredStatuses ?? [];
if (tokenExpiredStatuses.includes(options.status)) {
return buildUsageErrorSnapshot(options.provider, "Token expired");
}
const suffix = options.message?.trim() ? `: ${options.message.trim()}` : "";
return buildUsageErrorSnapshot(options.provider, `HTTP ${options.status}${suffix}`);
}