Open History to see the last commit
1import type {
2 EnvironmentId,
3 ServerSettingsPatch,
4 UsageModelPriceOverride,
5} from "@t3tools/contracts";
6
7export interface UsagePriceTarget {
8 readonly environmentId: EnvironmentId;
9 readonly label: string;
10 readonly prices: Readonly<Record<string, UsageModelPriceOverride>> | null;
11 readonly aliases: Readonly<Record<string, string>> | null;
12 readonly unavailable: string | null;
13}
14
15/** `null` removes the model's custom price or mapping. */
16export type UsagePriceChange =
17 | { readonly model: string; readonly price: UsageModelPriceOverride | null }
18 | { readonly model: string; readonly alias: string | null };
19
20export type UsagePriceWriteResult =
21 | { readonly status: "saved" }
22 | { readonly status: "failed"; readonly error: string };
23
24/** Destinations settle independently; retries pass only failures. */
25export async function writeUsagePrices(input: {
26 readonly targets: readonly UsagePriceTarget[];
27 readonly changes: ReadonlyMap<EnvironmentId, readonly UsagePriceChange[]>;
28 readonly write: (input: {
29 environmentId: EnvironmentId;
30 input: { patch: ServerSettingsPatch };
31 }) => Promise<{ readonly _tag: "Success" | "Failure" }>;
32 readonly onResult: (environmentId: EnvironmentId, result: UsagePriceWriteResult) => void;
33}) {
34 await Promise.all(
35 input.targets.map(async (target) => {
36 let result: UsagePriceWriteResult;
37 const changes = input.changes.get(target.environmentId) ?? [];
38 const prices = changes.flatMap((change) =>
39 "price" in change ? [[change.model, change.price] as const] : [],
40 );
41 const aliases = changes.flatMap((change) =>
42 "alias" in change ? [[change.model, change.alias] as const] : [],
43 );
44 if (target.unavailable !== null) {
45 result = { status: "failed", error: target.unavailable };
46 } else if (aliases.length > 0 && target.aliases === null) {
47 result = { status: "failed", error: "Update server to map models" };
48 } else {
49 try {
50 const saved =
51 changes.length === 0
52 ? { _tag: "Success" as const }
53 : await input.write({
54 environmentId: target.environmentId,
55 input: {
56 patch: {
57 ...(prices.length > 0
58 ? { usagePriceOverrides: Object.fromEntries(prices) }
59 : {}),
60 ...(aliases.length > 0
61 ? { usageModelAliases: Object.fromEntries(aliases) }
62 : {}),
63 },
64 },
65 });
66 result =
67 saved._tag === "Success"
68 ? { status: "saved" }
69 : { status: "failed", error: "Could not save. Try again." };
70 } catch {
71 result = { status: "failed", error: "Could not save. Try again." };
72 }
73 }
74 input.onResult(target.environmentId, result);
75 }),
76 );
77}