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 unavailable: string | null;
12}
13
14export interface UsagePriceChange {
15 readonly model: string;
16 readonly price: UsageModelPriceOverride | null;
17}
18
19export type UsagePriceWriteResult =
20 | { readonly status: "saved" }
21 | { readonly status: "failed"; readonly error: string };
22
23/** Each destination settles independently; retry callers pass only the failed destinations. */
24export async function writeUsagePrices(input: {
25 readonly targets: readonly UsagePriceTarget[];
26 readonly changes: ReadonlyMap<EnvironmentId, readonly UsagePriceChange[]>;
27 readonly write: (input: {
28 environmentId: EnvironmentId;
29 input: { patch: ServerSettingsPatch };
30 }) => Promise<{ readonly _tag: "Success" | "Failure" }>;
31 readonly onResult: (environmentId: EnvironmentId, result: UsagePriceWriteResult) => void;
32}) {
33 await Promise.all(
34 input.targets.map(async (target) => {
35 let result: UsagePriceWriteResult;
36 if (target.unavailable !== null) {
37 result = { status: "failed", error: target.unavailable };
38 } else {
39 try {
40 const changes = input.changes.get(target.environmentId) ?? [];
41 const saved =
42 changes.length === 0
43 ? { _tag: "Success" as const }
44 : await input.write({
45 environmentId: target.environmentId,
46 input: {
47 patch: {
48 usagePriceOverrides: Object.fromEntries(
49 changes.map((change) => [change.model, change.price]),
50 ),
51 },
52 },
53 });
54 result =
55 saved._tag === "Success"
56 ? { status: "saved" }
57 : { status: "failed", error: "Could not save. Try again." };
58 } catch {
59 result = { status: "failed", error: "Could not save. Try again." };
60 }
61 }
62 input.onResult(target.environmentId, result);
63 }),
64 );
65}