@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 168 lines 6.04 KB
Raw
1 import * as billingbudgets from "@distilled.cloud/gcp/billingbudgets_v1";
2 import * as cloudbilling from "@distilled.cloud/gcp/cloudbilling_v1";
3 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { GcpEnvironment } from "../Environment.ts";
9
10 export const MAX_DISPLAY_NAME_LENGTH = 60;
11
12 export class BillingAccountNotResolved extends Data.TaggedError(
13 "GCP.BillingBudgets.BillingAccountNotResolved",
14 )<{
15 project: string;
16 }> {}
17
18 export const lastSegment = (value: string) => {
19 const trimmed = value.replace(/\/+$/, "");
20 const parts = trimmed.split("/");
21 return parts[parts.length - 1] || trimmed;
22 };
23
24 export const billingAccountIdOf = (value: string) => lastSegment(value);
25
26 export const billingAccountParent = (billingAccountId: string) =>
27 billingAccountId.startsWith("billingAccounts/")
28 ? billingAccountId
29 : `billingAccounts/${billingAccountId}`;
30
31 export const budgetNameOf = (billingAccountId: string, budgetId: string) =>
32 `${billingAccountParent(billingAccountId)}/budgets/${budgetId}`;
33
34 export const parseBudgetName = (
35 name: string,
36 fallbackAccount = "",
37 ): { billingAccountId: string; budgetId: string } => {
38 const parts = name.split("/").filter((part) => part.length > 0);
39 const accountsAt = parts.indexOf("billingAccounts");
40 const budgetsAt = parts.indexOf("budgets");
41 return {
42 billingAccountId:
43 accountsAt >= 0 && parts[accountsAt + 1] ? parts[accountsAt + 1]! : fallbackAccount,
44 budgetId: budgetsAt >= 0 && parts[budgetsAt + 1] ? parts[budgetsAt + 1]! : lastSegment(name),
45 };
46 };
47
48 /** The display name Alchemy generates for a logical id when none is given. */
49 export const generatedDisplayName = (id: string) =>
50 createPhysicalName({
51 id,
52 maxLength: 20,
53 lowercase: true,
54 });
55
56 export const lookupProjectBillingAccountId = (project: string) =>
57 cloudbilling.getBillingInfoProjects({ name: `projects/${project}` }).pipe(
58 Effect.map((info) =>
59 info.billingAccountName ? billingAccountIdOf(info.billingAccountName) : undefined,
60 ),
61 Effect.catchTag("NotFound", () => Effect.undefined),
62 );
63
64 export const resolveBillingAccountId = (
65 explicit: string | undefined,
66 existing: string | undefined,
67 ) =>
68 Effect.gen(function* () {
69 if (explicit !== undefined && explicit.length > 0) {
70 return billingAccountIdOf(explicit);
71 }
72 if (existing !== undefined && existing.length > 0) {
73 return billingAccountIdOf(existing);
74 }
75 const env = yield* GcpEnvironment.current;
76 const resolved = yield* lookupProjectBillingAccountId(env.project);
77 if (resolved === undefined) {
78 return yield* new BillingAccountNotResolved({ project: env.project });
79 }
80 return resolved;
81 });
82
83 export const jsonEqual = (left: unknown, right: unknown) =>
84 JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right));
85
86 const canonicalize = (value: unknown): unknown => {
87 if (Array.isArray(value)) return value.map(canonicalize);
88 if (value !== null && typeof value === "object") {
89 return Object.fromEntries(
90 Object.entries(value as Record<string, unknown>)
91 .filter(([, item]) => item !== undefined)
92 .sort(([left], [right]) => left.localeCompare(right))
93 .map(([key, item]) => [key, canonicalize(item)]),
94 );
95 }
96 return value;
97 };
98
99 export const sortedStrings = (values: readonly string[] | undefined) =>
100 [...(values ?? [])].slice().sort();
101
102 export const toProjectNumberRef = (value: string) => {
103 const id = lastSegment(value);
104 if (/^\d+$/.test(id)) return Effect.succeed(`projects/${id}`);
105 return resourcemanager.getProjects({ name: `projects/${id}` }).pipe(
106 Effect.map((project) => project.name ?? `projects/${id}`),
107 Effect.catchTag("NotFound", () => Effect.succeed(`projects/${id}`)),
108 );
109 };
110
111 export const resolveProjectRefs = (projects: readonly string[] | undefined) =>
112 projects === undefined
113 ? Effect.succeed(undefined as string[] | undefined)
114 : Effect.forEach(projects, toProjectNumberRef);
115
116 export const filterChanged = (
117 observed: Record<string, unknown> | undefined,
118 desired: Record<string, unknown> | undefined,
119 ) => {
120 if (desired === undefined) return false;
121 const left = observed ?? {};
122 for (const [key, value] of Object.entries(desired)) {
123 if (value === undefined) continue;
124 if (!jsonEqual(left[key], value)) return true;
125 }
126 return false;
127 };
128
129 export const compact = <T extends Record<string, unknown>>(value: T): T =>
130 Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
131
132 export const projectScope = (project: string) =>
133 project.startsWith("projects/") ? project : `projects/${project}`;
134
135 export const getBudget = (name: string) =>
136 name.length === 0
137 ? Effect.undefined
138 : billingbudgets.getBillingAccountsBudgets({ name }).pipe(
139 // Missing budgets return 403 "The caller does not have permission"
140 // rather than 404 (typed as BudgetNotFound).
141 Effect.catchTag(["NotFound", "BudgetNotFound"], () => Effect.undefined),
142 );
143
144 export const listBudgets = (parent: string, scope?: string) =>
145 parent.length === 0
146 ? Effect.succeed([] as billingbudgets.GoogleCloudBillingBudgetsV1Budget[])
147 : billingbudgets.listBillingAccountsBudgets
148 .pages({
149 parent,
150 pageSize: 100,
151 scope,
152 })
153 .pipe(
154 Stream.take(10),
155 Stream.flatMap((page) => Stream.fromIterable(page.budgets ?? [])),
156 Stream.runCollect,
157 Effect.map((chunk) => Array.from(chunk)),
158 Effect.catchTag("NotFound", () =>
159 Effect.succeed([] as billingbudgets.GoogleCloudBillingBudgetsV1Budget[]),
160 ),
161 );
162
163 export const findBudgetByDisplayName = (parent: string, displayName: string) =>
164 Effect.gen(function* () {
165 const env = yield* GcpEnvironment.current;
166 const budgets = yield* listBudgets(parent, projectScope(env.project));
167 return budgets.find((budget) => budget.displayName === displayName);
168 });