@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 252 lines 8.21 KB
Raw
1 import * as networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import { tagRecord } from "alchemy/Tags";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Stream from "effect/Stream";
8 import { stripInternalLabels } from "../Labels.ts";
9 import { waitForOperation as waitForLongRunning } from "../Operation.ts";
10
11 export const DEFAULT_GLOBAL = "global";
12 export const MAX_NAME_LENGTH = 63;
13
14 export class NetworkConnectivityNotResolved extends Data.TaggedError(
15 "GCP.NetworkConnectivity.NotResolved",
16 )<{
17 resourceName: string;
18 }> {}
19
20 export class NetworkConnectivityStillExists extends Data.TaggedError(
21 "GCP.NetworkConnectivity.StillExists",
22 )<{
23 resourceName: string;
24 }> {}
25
26 export class NetworkConnectivityFailed extends Data.TaggedError("GCP.NetworkConnectivity.Failed")<{
27 resourceName: string;
28 state: string | undefined;
29 }> {}
30
31 export const lastSegment = (value: string) => {
32 const trimmed = value.replace(/\/+$/, "");
33 const parts = trimmed.split("/");
34 return parts[parts.length - 1] || trimmed;
35 };
36
37 export const rfc1035 = (
38 name: string,
39 fallback = "resource",
40 maxLength = MAX_NAME_LENGTH,
41 ): string => {
42 let next = name
43 .toLowerCase()
44 .replace(/[^a-z0-9-]/g, "-")
45 .replace(/-+/g, "-")
46 .replace(/^-+/, "")
47 .replace(/-+$/, "");
48 if (!/^[a-z]/.test(next)) {
49 next = `n${next}`;
50 }
51 next = next.slice(0, maxLength).replace(/-+$/, "");
52 return next.length > 0 ? next : fallback;
53 };
54
55 export const normalizeLocation = (location: string | undefined, fallback: string) =>
56 lastSegment(location ?? fallback).toLowerCase();
57
58 export const parentOf = (project: string, location: string) =>
59 `projects/${project}/locations/${location}`;
60
61 export const parentOfName = (name: string, collection: string) => {
62 const parts = name.split("/").filter((part) => part.length > 0);
63 const at = parts.lastIndexOf(collection);
64 if (at <= 0) return name;
65 return parts.slice(0, at).join("/");
66 };
67
68 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
69 const parts = name.split("/").filter((part) => part.length > 0);
70 const collectionAt = parts.lastIndexOf(collection);
71 const locationsAt = parts.lastIndexOf("locations");
72 const projectsAt = parts.lastIndexOf("projects");
73 return {
74 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
75 location:
76 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
77 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
78 };
79 };
80
81 export const toPhysicalId = (
82 id: string,
83 explicit: string | undefined,
84 existing: string | undefined,
85 fallback = "resource",
86 maxLength = MAX_NAME_LENGTH,
87 ) =>
88 Effect.gen(function* () {
89 if (explicit !== undefined) return explicit;
90 if (existing !== undefined) return existing;
91 return rfc1035(
92 yield* createPhysicalName({
93 id,
94 maxLength,
95 lowercase: true,
96 }),
97 fallback,
98 maxLength,
99 );
100 });
101
102 export const userLabels = (
103 labels: Record<string, string | undefined> | null | undefined,
104 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
105
106 export const hasAlchemyLabelKeys = (
107 labels: Record<string, string | undefined> | null | undefined,
108 ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
109
110 export const sameJson = (left: unknown, right: unknown) =>
111 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
112
113 export const sameStringList = (
114 left: readonly string[] | undefined,
115 right: readonly string[] | undefined,
116 ) =>
117 JSON.stringify([...(left ?? [])].map(canonicalizeLink).sort()) ===
118 JSON.stringify([...(right ?? [])].map(canonicalizeLink).sort());
119
120 export const canonicalizeLink = (value: string | undefined) => {
121 if (value === undefined || value.length === 0) return "";
122 return value
123 .replace(/^https?:\/\/[^/]+\//, "")
124 .replace(/^compute\/v1\//, "")
125 .replace(/\/+$/, "");
126 };
127
128 export const toNetworkResource = (project: string, network: string) => {
129 const trimmed = canonicalizeLink(network);
130 if (trimmed.includes("/")) return trimmed;
131 return `projects/${project}/global/networks/${trimmed}`;
132 };
133
134 export const toSubnetworkResource = (project: string, region: string, subnetwork: string) => {
135 const trimmed = canonicalizeLink(subnetwork);
136 if (trimmed.includes("/")) return trimmed;
137 return `projects/${project}/regions/${region}/subnetworks/${trimmed}`;
138 };
139
140 export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) =>
141 pairs.filter(([, changed]) => changed).map(([field]) => field);
142
143 /**
144 * Wait for a Network Connectivity Center long-running operation. Transports,
145 * gateway spokes and internal ranges can take tens of minutes.
146 * `ALREADY_EXISTS` (a concurrent create won) always succeeds;
147 * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has
148 * already been garbage-collected (deletes).
149 */
150 export const waitForOperation = (
151 operation: networkconnectivity.GoogleLongrunningOperation,
152 options?: { notFoundOk?: boolean },
153 ) =>
154 waitForLongRunning(
155 operation,
156 (name) => networkconnectivity.getProjectsLocationsOperations({ name }),
157 { budget: "30 minutes" },
158 ).pipe(
159 Effect.catchIf(
160 (error) =>
161 error._tag === "GCP.OperationFailed" &&
162 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
163 () => Effect.void,
164 ),
165 Effect.catchIf(
166 (error) => options?.notFoundOk === true && error._tag === "NotFound",
167 () => Effect.void,
168 ),
169 );
170
171 export const waitUntilPresent = <A, E, R>(
172 get: Effect.Effect<A | undefined, E, R>,
173 name: string,
174 ): Effect.Effect<A, E | NetworkConnectivityNotResolved, R> =>
175 get.pipe(
176 Effect.filterOrFail(
177 (value): value is A => value !== undefined,
178 () => new NetworkConnectivityNotResolved({ resourceName: name }),
179 ),
180 Effect.retry({
181 while: (error) => error instanceof NetworkConnectivityNotResolved,
182 times: 8,
183 schedule: Schedule.spaced("1 second"),
184 }),
185 );
186
187 export const waitUntilGone = <A, E, R>(
188 get: Effect.Effect<A | undefined, E, R>,
189 name: string,
190 ): Effect.Effect<void, E | NetworkConnectivityStillExists, R> =>
191 get.pipe(
192 Effect.filterOrFail(
193 (value) => value === undefined,
194 () => new NetworkConnectivityStillExists({ resourceName: name }),
195 ),
196 Effect.retry({
197 while: (error) => error instanceof NetworkConnectivityStillExists,
198 times: 10,
199 schedule: Schedule.spaced("2 seconds"),
200 }),
201 Effect.asVoid,
202 );
203
204 const PENDING_STATES = new Set([
205 "STATE_UNSPECIFIED",
206 "CREATING",
207 "UPDATING",
208 "DELETING",
209 "ACCEPTING",
210 "REJECTING",
211 ]);
212
213 const FAILED_STATES = new Set(["FAILED", "DELETE_FAILED", "OBSOLETE", "FAILED_DEPROGRAMMING"]);
214
215 export const waitUntilReady = <A extends { state?: string }, E, R>(
216 get: Effect.Effect<A | undefined, E, R>,
217 name: string,
218 ): Effect.Effect<A, E | NetworkConnectivityNotResolved | NetworkConnectivityFailed, R> =>
219 get.pipe(
220 Effect.filterOrFail(
221 (value): value is A => value !== undefined,
222 () => new NetworkConnectivityNotResolved({ resourceName: name }),
223 ),
224 Effect.filterOrFail(
225 (value) => !FAILED_STATES.has(value.state ?? ""),
226 (value) => new NetworkConnectivityFailed({ resourceName: name, state: value.state }),
227 ),
228 Effect.filterOrFail(
229 (value) => !PENDING_STATES.has(value.state ?? ""),
230 () => new NetworkConnectivityNotResolved({ resourceName: name }),
231 ),
232 Effect.retry({
233 while: (error) => error instanceof NetworkConnectivityNotResolved,
234 times: 10,
235 schedule: Schedule.spaced("4 seconds"),
236 }),
237 );
238
239 /** Collect every page; a missing parent (`NotFound`) lists as empty. */
240 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
241 stream: Stream.Stream<Page, E, R>,
242 pick: (page: Page) => readonly Item[] | undefined,
243 ) =>
244 stream.pipe(
245 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
246 Stream.runCollect,
247 Effect.map((chunk): Item[] => Array.from(chunk)),
248 Effect.catchIf(
249 (error) => error._tag === "NotFound",
250 () => Effect.succeed<Item[]>([]),
251 ),
252 );