@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 209 lines 7.06 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as networksecurity from "@distilled.cloud/gcp/networksecurity_v1";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import { tagRecord } from "alchemy/Tags";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { stripInternalLabels } from "../Labels.ts";
10 import { waitForOperation as waitForLongRunning } from "../Operation.ts";
11
12 export const DEFAULT_LOCATION = "global";
13 export const DEFAULT_ZONE = "us-central1-a";
14 export const MAX_NAME_LENGTH = 63;
15
16 export class ResourceNotResolved extends Data.TaggedError(
17 "GCP.NetworkSecurity.ResourceNotResolved",
18 )<{
19 resourceName: string;
20 }> {}
21
22 export class ResourceStillExists extends Data.TaggedError(
23 "GCP.NetworkSecurity.ResourceStillExists",
24 )<{
25 resourceName: string;
26 }> {}
27
28 export class OrganizationRequired extends Data.TaggedError(
29 "GCP.NetworkSecurity.OrganizationRequired",
30 )<{
31 project: string;
32 }> {}
33
34 export const lastSegment = (value: string) => {
35 const trimmed = value.replace(/\/+$/, "");
36 const parts = trimmed.split("/");
37 return parts[parts.length - 1] || trimmed;
38 };
39
40 export const rfc1035 = (name: string, fallback = "resource"): string => {
41 let next = name
42 .toLowerCase()
43 .replace(/[^a-z0-9-]/g, "-")
44 .replace(/-+/g, "-")
45 .replace(/^-+/, "")
46 .replace(/-+$/, "");
47 if (!/^[a-z]/.test(next)) {
48 next = `${fallback[0] ?? "n"}${next}`;
49 }
50 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
51 return next.length > 0 ? next : fallback;
52 };
53
54 export const normalizeLocation = (location: string | undefined, fallback = DEFAULT_LOCATION) =>
55 lastSegment(location ?? fallback).toLowerCase();
56
57 export const normalizeZone = (location: string | undefined, fallback = DEFAULT_ZONE) =>
58 lastSegment(location ?? fallback).toLowerCase();
59
60 export const projectParent = (project: string, location: string) =>
61 `projects/${project}/locations/${location}`;
62
63 export const organizationParent = (organization: string, location: string) =>
64 `organizations/${lastSegment(organization)}/locations/${location}`;
65
66 export const parseResourceName = (name: string) => {
67 const parts = name.split("/").filter((part) => part.length > 0);
68 const locationsAt = parts.lastIndexOf("locations");
69 const projectsAt = parts.lastIndexOf("projects");
70 const organizationsAt = parts.lastIndexOf("organizations");
71 const parentAt = organizationsAt >= 0 ? organizationsAt : projectsAt;
72 return {
73 parentId: parentAt >= 0 && parts[parentAt + 1] ? parts[parentAt + 1]! : "",
74 location:
75 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
76 id: lastSegment(name),
77 };
78 };
79
80 export const toPhysicalId = (
81 id: string,
82 explicit: string | undefined,
83 existing: string | undefined,
84 fallback = "resource",
85 ) =>
86 Effect.gen(function* () {
87 if (explicit !== undefined) return explicit;
88 if (existing !== undefined) return existing;
89 return rfc1035(
90 yield* createPhysicalName({
91 id,
92 maxLength: MAX_NAME_LENGTH,
93 lowercase: true,
94 }),
95 fallback,
96 );
97 });
98
99 export const userLabels = (
100 labels: Record<string, string | undefined> | null | undefined,
101 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
102
103 export const sameJson = (left: unknown, right: unknown) =>
104 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
105
106 export const sortedStrings = (values: ReadonlyArray<string> | undefined) =>
107 [...(values ?? [])].map((value) => value).sort();
108
109 export const sameStringList = (
110 left: readonly string[] | undefined,
111 right: readonly string[] | undefined,
112 ) => JSON.stringify(sortedStrings(left)) === JSON.stringify(sortedStrings(right));
113
114 /**
115 * Wait for a Network Security long-running operation. Cloud NGFW firewall
116 * endpoints take ~20 minutes to provision; intercept and mirroring
117 * deployments take several minutes.
118 * `ALREADY_EXISTS` (a concurrent create won) always succeeds;
119 * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has
120 * already been garbage-collected (deletes).
121 */
122 export const waitForOperation = (
123 operation: networksecurity.Operation,
124 options?: { notFoundOk?: boolean },
125 ) =>
126 waitForLongRunning(
127 operation,
128 (name) => networksecurity.getProjectsLocationsOperations({ name }),
129 { budget: "30 minutes" },
130 ).pipe(
131 Effect.catchIf(
132 (error) =>
133 error._tag === "GCP.OperationFailed" &&
134 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
135 () => Effect.void,
136 ),
137 Effect.catchIf(
138 (error) => options?.notFoundOk === true && error._tag === "NotFound",
139 () => Effect.void,
140 ),
141 );
142
143 export const waitUntilExists = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
144 get.pipe(
145 Effect.flatMap((value) =>
146 value ? Effect.succeed(value) : Effect.fail(new ResourceNotResolved({ resourceName: name })),
147 ),
148 Effect.retry({
149 while: (error) => error instanceof ResourceNotResolved,
150 times: 8,
151 schedule: Schedule.spaced("1 second"),
152 }),
153 );
154
155 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
156 get.pipe(
157 Effect.flatMap((value) =>
158 value === undefined
159 ? Effect.void
160 : Effect.fail(new ResourceStillExists({ resourceName: name })),
161 ),
162 Effect.retry({
163 while: (error) => error instanceof ResourceStillExists,
164 times: 10,
165 schedule: Schedule.spaced("2 seconds"),
166 }),
167 );
168
169 const parentOf = (name: string) =>
170 name.startsWith("projects/")
171 ? resourcemanager.getProjects({ name }).pipe(
172 Effect.map((resource) => resource.parent),
173 Effect.catchTag("NotFound", () => Effect.undefined),
174 )
175 : name.startsWith("folders/")
176 ? resourcemanager.getFolders({ name }).pipe(
177 Effect.map((folder) => folder.parent),
178 Effect.catchTag("NotFound", () => Effect.undefined),
179 )
180 : Effect.undefined;
181
182 const tryResolveOrganizationId = (project: string) =>
183 Effect.gen(function* () {
184 let current: string | undefined = `projects/${project}`;
185 for (let i = 0; i < 8; i++) {
186 if (current === undefined) return undefined;
187 if (current.startsWith("organizations/")) return lastSegment(current);
188 current = yield* parentOf(current);
189 }
190 return undefined;
191 });
192
193 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
194 Effect.gen(function* () {
195 if (explicit !== undefined) return lastSegment(explicit);
196 if (existing !== undefined) return lastSegment(existing);
197 const env = yield* GcpEnvironment.current;
198 const resolved = yield* tryResolveOrganizationId(env.project);
199 if (resolved === undefined) {
200 return yield* new OrganizationRequired({ project: env.project });
201 }
202 return resolved;
203 });
204
205 export const listOrganizations = (project: string) =>
206 Effect.gen(function* () {
207 const resolved = yield* tryResolveOrganizationId(project);
208 return resolved === undefined ? [] : [resolved];
209 });