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/**
25 * Each destination settles independently; retry callers pass only the failed destinations.
26 */
27export async function writeUsagePrices(input: {
28 readonly targets: readonly UsagePriceTarget[];
29 readonly changes: ReadonlyMap<EnvironmentId, readonly UsagePriceChange[]>;
30 readonly write: (input: {
31 environmentId: EnvironmentId;
32 input: { patch: ServerSettingsPatch };
33 }) => Promise<{ readonly _tag: "Success" | "Failure" }>;
34 readonly onResult: (environmentId: EnvironmentId, result: UsagePriceWriteResult) => void;
35}) {
36 await Promise.all(
37 input.targets.map(async (target) => {
38 let result: UsagePriceWriteResult;
39 const changes = input.changes.get(target.environmentId) ?? [];
40 const prices = changes.flatMap((change) =>
41 "price" in change ? [[change.model, change.price] as const] : [],
42 );
43 const aliases = changes.flatMap((change) =>
44 "alias" in change ? [[change.model, change.alias] as const] : [],
45 );
46 if (target.unavailable !== null) {
47 result = { status: "failed", error: target.unavailable };
48 } else if (aliases.length > 0 && target.aliases === null) {
49 result = { status: "failed", error: "Update server to map models" };
50 } else {
51 try {
52 const saved =
53 changes.length === 0
54 ? { _tag: "Success" as const }
55 : await input.write({
56 environmentId: target.environmentId,
57 input: {
58 patch: {
59 ...(prices.length > 0
60 ? { usagePriceOverrides: Object.fromEntries(prices) }
61 : {}),
62 ...(aliases.length > 0
63 ? { usageModelAliases: Object.fromEntries(aliases) }
64 : {}),
65 },
66 },
67 });
68 result =
69 saved._tag === "Success"
70 ? { status: "saved" }
71 : { status: "failed", error: "Could not save. Try again." };
72 } catch {
73 result = { status: "failed", error: "Could not save. Try again." };
74 }
75 }
76 input.onResult(target.environmentId, result);
77 }),
78 );
79}