@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 330 lines 11.4 KB
Raw
1 import * as cloudbilling from "@distilled.cloud/gcp/cloudbilling_v1";
2 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
3 import * as logging from "@distilled.cloud/gcp/logging_v2";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9
10 export const MAX_NAME_LENGTH = 100;
11 export const DEFAULT_LOCATION = "global";
12 export const DEFAULT_RETENTION_DAYS = 30;
13 export const DEFAULT_BUCKET_ID = "_Default";
14
15 export const lastSegment = (value: string) => {
16 const trimmed = value.replace(/\/+$/, "");
17 const parts = trimmed.split("/");
18 return parts[parts.length - 1] || trimmed;
19 };
20
21 export const encodeDescription = (
22 labels: Record<string, string>,
23 description: string | undefined,
24 ): string => {
25 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
26 return description ? `${marker}\n${description}` : marker;
27 };
28
29 export const parseDescription = (
30 description: string | undefined,
31 ): {
32 labels: Record<string, string>;
33 description: string | undefined;
34 } => {
35 if (!description?.startsWith("[alchemy ")) {
36 return { labels: {}, description };
37 }
38 const end = description.indexOf("]");
39 if (end < 0) return { labels: {}, description };
40 const labels: Record<string, string> = {};
41 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
42 const eq = part.indexOf("=");
43 if (eq > 0) {
44 labels[part.slice(0, eq)] = part.slice(eq + 1);
45 }
46 }
47 const rest = description.slice(end + 1).replace(/^\n/, "");
48 return { labels, description: rest.length > 0 ? rest : undefined };
49 };
50
51 export const hasOwnershipMarker = (description: string | undefined) =>
52 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
53
54 export const toPhysicalId = (
55 id: string,
56 explicit: string | undefined,
57 existing: string | undefined,
58 prefix: string,
59 options?: { delimiter?: string; underscores?: boolean },
60 ) =>
61 Effect.gen(function* () {
62 if (explicit !== undefined) return explicit;
63 if (existing !== undefined) return existing;
64 const generated = yield* createPhysicalName({
65 id,
66 maxLength: MAX_NAME_LENGTH,
67 lowercase: true,
68 delimiter: options?.delimiter,
69 });
70 let next =
71 options?.underscores === true
72 ? generated.replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_")
73 : generated;
74 if (!/^[a-z0-9]/.test(next)) {
75 next = `${prefix}${next}`;
76 }
77 return next.slice(0, MAX_NAME_LENGTH);
78 });
79
80 export const toLinkId = (id: string, explicit: string | undefined, existing: string | undefined) =>
81 Effect.gen(function* () {
82 if (explicit !== undefined) return explicit;
83 if (existing !== undefined) return existing;
84 const generated = yield* createPhysicalName({
85 id,
86 maxLength: MAX_NAME_LENGTH,
87 lowercase: true,
88 });
89 let next = generated.replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_");
90 if (!/^[a-z]/.test(next)) next = `l${next}`;
91 return next.replace(/_+$/g, "").slice(0, MAX_NAME_LENGTH) || "link";
92 });
93
94 export const scopeParent = (project: string, folderId: string | undefined) =>
95 folderId !== undefined && folderId.length > 0
96 ? `folders/${lastSegment(folderId)}`
97 : `projects/${project}`;
98
99 export const locationParent = (parent: string, location: string) =>
100 `${parent}/locations/${location}`;
101
102 export const jsonEqual = (left: unknown, right: unknown) =>
103 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
104
105 export const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort();
106
107 export const createOwnership = (id: string) => createInternalLabels(id);
108
109 export const ownedBy = (id: string, labels: Record<string, string>) => hasAlchemyLabels(id, labels);
110
111 export type ParsedLoggingName = {
112 parent: string;
113 location: string | undefined;
114 bucketId: string | undefined;
115 viewId: string | undefined;
116 linkId: string | undefined;
117 logScopeId: string | undefined;
118 savedQueryId: string | undefined;
119 sinkId: string | undefined;
120 };
121
122 export const parseLoggingName = (name: string): ParsedLoggingName => {
123 const parts = name.split("/").filter((part) => part.length > 0);
124 const get = (key: string) => {
125 const index = parts.indexOf(key);
126 return index >= 0 ? parts[index + 1] : undefined;
127 };
128 const folder = get("folders");
129 const organization = get("organizations");
130 const billingAccount = get("billingAccounts");
131 const project = get("projects");
132 const parent =
133 folder !== undefined
134 ? `folders/${folder}`
135 : organization !== undefined
136 ? `organizations/${organization}`
137 : billingAccount !== undefined
138 ? `billingAccounts/${billingAccount}`
139 : project !== undefined
140 ? `projects/${project}`
141 : parts.slice(0, 2).join("/");
142 return {
143 parent,
144 location: get("locations"),
145 bucketId: get("buckets"),
146 viewId: get("views"),
147 linkId: get("links"),
148 logScopeId: get("logScopes"),
149 savedQueryId: get("savedQueries"),
150 sinkId: get("sinks"),
151 };
152 };
153
154 export const isDeletedBucket = (bucket: logging.LogBucket | undefined): bucket is undefined =>
155 bucket === undefined || bucket.lifecycleState === "DELETE_REQUESTED";
156
157 export const isPendingBucket = (state: string | undefined) =>
158 state === "CREATING" || state === "UPDATING";
159
160 export const canonRestricted = (fields: readonly string[] | undefined) =>
161 [...(fields ?? [])].slice().sort();
162
163 export type LogBucketIndexConfig = {
164 fieldPath: string;
165 type: "INDEX_TYPE_STRING" | "INDEX_TYPE_INTEGER";
166 };
167
168 export const canonIndexConfigs = (
169 configs: readonly logging.IndexConfig[] | readonly LogBucketIndexConfig[] | undefined,
170 ): LogBucketIndexConfig[] =>
171 [...(configs ?? [])]
172 .flatMap((config) =>
173 config.fieldPath
174 ? [
175 {
176 fieldPath: config.fieldPath,
177 type: (config.type ?? "INDEX_TYPE_STRING") as LogBucketIndexConfig["type"],
178 },
179 ]
180 : [],
181 )
182 .sort((left, right) => left.fieldPath.localeCompare(right.fieldPath));
183
184 export type SinkExclusion = {
185 name: string;
186 filter: string;
187 description?: string;
188 disabled?: boolean;
189 };
190
191 export const exclusionsOf = (
192 list: readonly logging.LogExclusion[] | readonly SinkExclusion[] | undefined,
193 ): SinkExclusion[] =>
194 (list ?? [])
195 .map((exclusion) => ({
196 name: exclusion.name ?? "",
197 filter: exclusion.filter ?? "",
198 description: exclusion.description,
199 disabled: exclusion.disabled === true,
200 }))
201 .sort((left, right) => left.name.localeCompare(right.name));
202
203 export const sameExclusions = (
204 left: readonly logging.LogExclusion[] | readonly SinkExclusion[] | undefined,
205 right: readonly logging.LogExclusion[] | readonly SinkExclusion[] | undefined,
206 ) => jsonEqual(exclusionsOf(left), exclusionsOf(right));
207
208 export const toExclusionsBody = (
209 list: readonly SinkExclusion[] | undefined,
210 ): logging.LogExclusion[] | undefined => {
211 if (list === undefined) return undefined;
212 return list.map((exclusion) => ({
213 name: exclusion.name,
214 filter: exclusion.filter,
215 description: exclusion.description,
216 disabled: exclusion.disabled === true ? true : undefined,
217 }));
218 };
219
220 export class BillingAccountNotResolved extends Data.TaggedError(
221 "GCP.Logging.BillingAccountNotResolved",
222 )<{
223 project: string;
224 }> {}
225
226 export class FolderNotResolved extends Data.TaggedError("GCP.Logging.FolderNotResolved")<{
227 project: string;
228 }> {}
229
230 export class OrganizationNotResolved extends Data.TaggedError(
231 "GCP.Logging.OrganizationNotResolved",
232 )<{
233 project: string;
234 }> {}
235
236 export const billingAccountIdOf = (value: string) => lastSegment(value);
237
238 export const billingAccountParent = (billingAccountId: string) =>
239 billingAccountId.startsWith("billingAccounts/")
240 ? billingAccountId
241 : `billingAccounts/${billingAccountId}`;
242
243 export const folderParent = (folderId: string) =>
244 folderId.startsWith("folders/") ? folderId : `folders/${folderId}`;
245
246 export const organizationIdOf = (value: string) => lastSegment(value);
247
248 export const organizationParent = (value: string) =>
249 value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`;
250
251 export const lookupProjectBillingAccountId = (project: string) =>
252 cloudbilling.getBillingInfoProjects({ name: `projects/${project}` }).pipe(
253 Effect.map((info) =>
254 info.billingAccountName ? billingAccountIdOf(info.billingAccountName) : undefined,
255 ),
256 Effect.catchTag("NotFound", () => Effect.undefined),
257 );
258
259 export const resolveBillingAccountId = (
260 explicit: string | undefined,
261 existing: string | undefined,
262 ) =>
263 Effect.gen(function* () {
264 if (explicit !== undefined) return billingAccountIdOf(explicit);
265 if (existing !== undefined) return billingAccountIdOf(existing);
266 const env = yield* GcpEnvironment.current;
267 const resolved = yield* lookupProjectBillingAccountId(env.project);
268 if (resolved === undefined) {
269 return yield* new BillingAccountNotResolved({ project: env.project });
270 }
271 return resolved;
272 });
273
274 export const lookupProjectFolderId = (project: string) =>
275 resourcemanager.getProjects({ name: `projects/${project}` }).pipe(
276 Effect.map((resource) => {
277 const parent = resource.parent ?? "";
278 return parent.startsWith("folders/") ? lastSegment(parent) : undefined;
279 }),
280 Effect.catchTag("NotFound", () => Effect.undefined),
281 );
282
283 export const resolveFolderId = (explicit: string | undefined, existing: string | undefined) =>
284 Effect.gen(function* () {
285 if (explicit !== undefined) return lastSegment(explicit);
286 if (existing !== undefined) return lastSegment(existing);
287 const env = yield* GcpEnvironment.current;
288 const resolved = yield* lookupProjectFolderId(env.project);
289 if (resolved === undefined) {
290 return yield* new FolderNotResolved({ project: env.project });
291 }
292 return resolved;
293 });
294
295 const parentOf = (name: string) =>
296 name.startsWith("projects/")
297 ? resourcemanager.getProjects({ name }).pipe(
298 Effect.map((resource) => resource.parent),
299 Effect.catchTag("NotFound", () => Effect.undefined),
300 )
301 : name.startsWith("folders/")
302 ? resourcemanager.getFolders({ name }).pipe(
303 Effect.map((folder) => folder.parent),
304 Effect.catchTag("NotFound", () => Effect.undefined),
305 )
306 : Effect.undefined;
307
308 export const tryResolveOrganization = () =>
309 Effect.gen(function* () {
310 const env = yield* GcpEnvironment.current;
311 let current: string | undefined = `projects/${env.project}`;
312 for (let i = 0; i < 8; i++) {
313 if (current === undefined) return undefined;
314 if (current.startsWith("organizations/")) return current;
315 current = yield* parentOf(current);
316 }
317 return undefined;
318 });
319
320 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
321 Effect.gen(function* () {
322 if (explicit !== undefined) return organizationParent(explicit);
323 if (existing !== undefined) return organizationParent(existing);
324 const resolved = yield* tryResolveOrganization();
325 if (resolved === undefined) {
326 const env = yield* GcpEnvironment.current;
327 return yield* new OrganizationNotResolved({ project: env.project });
328 }
329 return resolved;
330 });