@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, 04:45 UTC

main
ts 509 lines 17.5 KB
Raw
1 import * as networkmanagement from "@distilled.cloud/gcp/networkmanagement_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_GLOBAL,
14 MAX_CONNECTIVITY_TEST_ID_LENGTH,
15 changedFields,
16 collectPages,
17 hasAlchemyLabelKeys,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 resourceName as qualifiedName,
22 rfc1035,
23 sameJson,
24 sameStringList,
25 toNetworkResource,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilGone,
30 waitUntilPresent,
31 } from "./internal.ts";
32
33 const COLLECTION = "connectivityTests";
34 const DEFAULT_PROTOCOL = "TCP";
35
36 export type ConnectivityTestNetworkType = networkmanagement.EndpointNetworkTypeEnum | (string & {});
37
38 export type ConnectivityTestEndpoint = {
39 /** IP address of the endpoint (internal or external). */
40 ipAddress?: string;
41 /** TCP or UDP port. Ignored for other protocols. */
42 port?: number;
43 /** Compute Engine instance URI. */
44 instance?: string;
45 /**
46 * Forwarding rule URI. Destination only. Format
47 * `projects/{project}/global/forwardingRules/{id}` or
48 * `projects/{project}/regions/{region}/forwardingRules/{id}`.
49 */
50 forwardingRule?: string;
51 /** GKE control-plane cluster URI. */
52 gkeMasterCluster?: string;
53 /**
54 * GKE control-plane DNS endpoint. Requires `gkeMasterCluster`.
55 * Destination only; cannot be combined with `ipAddress` or `network`.
56 */
57 fqdn?: string;
58 /** Cloud SQL instance URI. */
59 cloudSqlInstance?: string;
60 /** Memorystore Redis instance URI. Destination only. */
61 redisInstance?: string;
62 /** Memorystore Redis cluster URI. Destination only. */
63 redisCluster?: string;
64 /** GKE Pod URI. */
65 gkePod?: string;
66 /**
67 * Database Migration Service private connection. Format
68 * `projects/{project}/locations/{location}/privateConnections/{privateConnection}`.
69 */
70 dmsPrivateConnection?: string;
71 /** Cloud Function. Source only. */
72 cloudFunction?: { uri?: string };
73 /** App Engine service version. Source only. */
74 appEngineVersion?: { uri?: string };
75 /** Cloud Run revision. Source only. */
76 cloudRunRevision?: { uri?: string };
77 /**
78 * Cloud Run job URI. Source only. Format
79 * `projects/{project}/locations/{location}/jobs/{job}`.
80 */
81 cloudRunJob?: string;
82 /**
83 * VPC network URI. For sources, used with `networkType`. For
84 * destinations, used when the source is external and the destination
85 * is internal.
86 */
87 network?: string;
88 /** Type of network where the source endpoint lives. Source only. */
89 networkType?: ConnectivityTestNetworkType;
90 /** Source endpoint project id. Source only. */
91 projectId?: string;
92 };
93
94 export type ConnectivityTestProps = {
95 /**
96 * Test id (the `{test}` segment of
97 * `projects/{project}/locations/global/connectivityTests/{test}`). If
98 * omitted, a unique RFC1035 name is generated. Must be 1-40 characters,
99 * start with a letter, and end with a letter or number. Immutable —
100 * changing it replaces the test.
101 */
102 testId?: string;
103 /**
104 * Location. Must be `global`. Immutable — changing it replaces the
105 * test.
106 * @default "global"
107 */
108 location?: string;
109 /**
110 * Human-readable description (max 512 characters).
111 */
112 description?: string;
113 /**
114 * Source endpoint. Combine IP, URI, project, and VPC network to
115 * identify the origin.
116 */
117 source: ConnectivityTestEndpoint;
118 /**
119 * Destination endpoint. Combine IP, URI, project, and VPC network to
120 * identify the target.
121 */
122 destination: ConnectivityTestEndpoint;
123 /**
124 * IP protocol. When omitted, `TCP` is assumed.
125 * @default "TCP"
126 */
127 protocol?: string;
128 /**
129 * Other projects that may be relevant for reachability analysis when
130 * the path crosses project boundaries.
131 */
132 relatedProjects?: string[];
133 /**
134 * Also analyze the return path from destination to source.
135 * @default false
136 */
137 roundTrip?: boolean;
138 /**
139 * Skip firewall checking during analysis.
140 * @default false
141 */
142 bypassFirewallChecks?: boolean;
143 /**
144 * User labels. Alchemy ownership labels are merged in automatically.
145 */
146 labels?: Record<string, string>;
147 };
148
149 export type ConnectivityTest = Resource<
150 "GCP.NetworkManagement.ConnectivityTest",
151 ConnectivityTestProps,
152 {
153 /** Full resource name `projects/{project}/locations/global/connectivityTests/{test}`. */
154 name: string;
155 /** Test id (last path segment). */
156 testId: string;
157 /** Project id. */
158 project: string;
159 /** Location id (`global`). */
160 location: string;
161 /** User-provided description. */
162 description: string | undefined;
163 /** Source endpoint as stored by the API. */
164 source: ConnectivityTestEndpoint | undefined;
165 /** Destination endpoint as stored by the API. */
166 destination: ConnectivityTestEndpoint | undefined;
167 /** IP protocol. */
168 protocol: string | undefined;
169 /** Related projects considered during analysis. */
170 relatedProjects: string[];
171 /** Server-generated display name. */
172 displayName: string | undefined;
173 /** Whether return-path analysis is enabled. */
174 roundTrip: boolean;
175 /** Whether firewall checking is skipped. */
176 bypassFirewallChecks: boolean;
177 /** Latest forward-path reachability result. */
178 reachabilityResult: string | undefined;
179 /** Latest return-path reachability result. */
180 returnReachabilityResult: string | undefined;
181 /** Latest probing result, when probing applied. */
182 probingResult: string | undefined;
183 /** User labels (Alchemy ownership labels stripped). */
184 labels: Record<string, string>;
185 /** RFC3339 creation timestamp. */
186 createTime: string | undefined;
187 /** RFC3339 last-update timestamp. */
188 updateTime: string | undefined;
189 },
190 never,
191 Providers
192 >;
193
194 /**
195 * A Network Management Connectivity Test (reachability analysis).
196 *
197 * Changing `testId` or `location` replaces the test. Endpoints,
198 * protocol, related projects, round-trip, firewall bypass, description,
199 * and labels update in place. Create runs analysis as part of the
200 * long-running operation.
201 *
202 * ### Creating a ConnectivityTest
203 * **Example:** IP-to-IP TCP test
204 * ```typescript
205 * const test = yield* GCP.NetworkManagement.ConnectivityTest("DnsPath", {
206 * source: {
207 * ipAddress: "10.0.0.1",
208 * networkType: "GCP_NETWORK",
209 * network: "projects/my-project/global/networks/app-vpc",
210 * },
211 * destination: { ipAddress: "10.0.0.2", port: 443 },
212 * protocol: "TCP",
213 * labels: { env: "prod" },
214 * });
215 * ```
216 *
217 * **Example:** Named test with round trip
218 * ```typescript
219 * const test = yield* GCP.NetworkManagement.ConnectivityTest("DnsPath", {
220 * testId: "app-dns-path",
221 * source: { ipAddress: "8.8.8.8", networkType: "NON_GCP_NETWORK" },
222 * destination: { ipAddress: "1.1.1.1", port: 443 },
223 * protocol: "TCP",
224 * roundTrip: true,
225 * description: "public dns path",
226 * });
227 * ```
228 *
229 * @resource
230 * @category NetworkManagement
231 */
232 export const ConnectivityTest = Resource<ConnectivityTest>(
233 "GCP.NetworkManagement.ConnectivityTest",
234 );
235
236 const resourceName = (project: string, location: string, testId: string) =>
237 qualifiedName(project, location, COLLECTION, testId);
238
239 const toEndpoint = (
240 endpoint: ConnectivityTestEndpoint | networkmanagement.Endpoint | undefined,
241 project?: string,
242 ): ConnectivityTestEndpoint | undefined => {
243 if (endpoint === undefined) return undefined;
244 const next: ConnectivityTestEndpoint = {
245 ipAddress: endpoint.ipAddress,
246 port: endpoint.port,
247 instance: endpoint.instance,
248 forwardingRule: endpoint.forwardingRule,
249 gkeMasterCluster: endpoint.gkeMasterCluster,
250 fqdn: endpoint.fqdn,
251 cloudSqlInstance: endpoint.cloudSqlInstance,
252 redisInstance: endpoint.redisInstance,
253 redisCluster: endpoint.redisCluster,
254 gkePod: endpoint.gkePod,
255 dmsPrivateConnection: endpoint.dmsPrivateConnection,
256 cloudFunction: endpoint.cloudFunction ? { uri: endpoint.cloudFunction.uri } : undefined,
257 appEngineVersion: endpoint.appEngineVersion
258 ? { uri: endpoint.appEngineVersion.uri }
259 : undefined,
260 cloudRunRevision: endpoint.cloudRunRevision
261 ? { uri: endpoint.cloudRunRevision.uri }
262 : undefined,
263 cloudRunJob: endpoint.cloudRunJob,
264 network:
265 endpoint.network !== undefined && project !== undefined
266 ? toNetworkResource(project, endpoint.network)
267 : endpoint.network,
268 networkType: endpoint.networkType,
269 projectId: endpoint.projectId,
270 };
271 return next;
272 };
273
274 const endpointKey = (endpoint: ConnectivityTestEndpoint | undefined): unknown => {
275 if (endpoint === undefined) return undefined;
276 return {
277 ipAddress: endpoint.ipAddress ?? "",
278 port: endpoint.port ?? 0,
279 instance: endpoint.instance ?? "",
280 forwardingRule: endpoint.forwardingRule ?? "",
281 gkeMasterCluster: endpoint.gkeMasterCluster ?? "",
282 fqdn: endpoint.fqdn ?? "",
283 cloudSqlInstance: endpoint.cloudSqlInstance ?? "",
284 redisInstance: endpoint.redisInstance ?? "",
285 redisCluster: endpoint.redisCluster ?? "",
286 gkePod: endpoint.gkePod ?? "",
287 dmsPrivateConnection: endpoint.dmsPrivateConnection ?? "",
288 cloudFunction: endpoint.cloudFunction?.uri ?? "",
289 appEngineVersion: endpoint.appEngineVersion?.uri ?? "",
290 cloudRunRevision: endpoint.cloudRunRevision?.uri ?? "",
291 cloudRunJob: endpoint.cloudRunJob ?? "",
292 network: endpoint.network ?? "",
293 networkType: (endpoint.networkType ?? "").toUpperCase(),
294 projectId: endpoint.projectId ?? "",
295 };
296 };
297
298 const toAttrs = (test: networkmanagement.ConnectivityTest, project: string) => {
299 const name = test.name ?? "";
300 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
301 return {
302 name,
303 testId: parsed.id,
304 project: parsed.project || project,
305 location: parsed.location || DEFAULT_GLOBAL,
306 description: test.description,
307 source: toEndpoint(test.source, parsed.project || project),
308 destination: toEndpoint(test.destination, parsed.project || project),
309 protocol: test.protocol,
310 relatedProjects: test.relatedProjects ?? [],
311 displayName: test.displayName,
312 roundTrip: test.roundTrip === true,
313 bypassFirewallChecks: test.bypassFirewallChecks === true,
314 reachabilityResult: test.reachabilityDetails?.result,
315 returnReachabilityResult: test.returnReachabilityDetails?.result,
316 probingResult: test.probingDetails?.result,
317 labels: userLabels(test.labels),
318 createTime: test.createTime,
319 updateTime: test.updateTime,
320 };
321 };
322
323 const getByName = (name: string) =>
324 networkmanagement
325 .getProjectsLocationsGlobalConnectivityTests({ name })
326 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
327
328 export const ConnectivityTestProvider = () =>
329 Provider.succeed(ConnectivityTest, {
330 stables: ["name", "testId", "project", "location", "createTime"],
331
332 diff: Effect.fn(function* ({ news, olds, output }) {
333 if (!isResolved(news)) return undefined;
334 const previousId = olds?.testId ?? output?.testId;
335 const nextId = news.testId
336 ? rfc1035(news.testId, "connectivity-test", MAX_CONNECTIVITY_TEST_ID_LENGTH)
337 : previousId;
338 const previousLocation = normalizeLocation(
339 olds?.location ?? output?.location,
340 DEFAULT_GLOBAL,
341 );
342 const nextLocation = normalizeLocation(
343 news.location ?? olds?.location ?? output?.location,
344 DEFAULT_GLOBAL,
345 );
346 if (
347 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
348 previousLocation !== nextLocation
349 ) {
350 return { action: "replace" as const };
351 }
352 return undefined;
353 }),
354
355 read: Effect.fn(function* ({ id, olds, output }) {
356 const env = yield* GcpEnvironment.current;
357 const testId = yield* toPhysicalId(
358 id,
359 olds?.testId,
360 output?.testId,
361 "connectivity-test",
362 MAX_CONNECTIVITY_TEST_ID_LENGTH,
363 );
364 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
365 const name = output?.name ?? resourceName(env.project, location, testId);
366 const existing = yield* getByName(name);
367 if (existing === undefined) return undefined;
368 const attrs = toAttrs(existing, env.project);
369 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
370 }),
371
372 list: () =>
373 Effect.gen(function* () {
374 const env = yield* GcpEnvironment.current;
375 const items = yield* collectPages(
376 networkmanagement.listProjectsLocationsGlobalConnectivityTests.pages({
377 parent: parentOf(env.project, DEFAULT_GLOBAL),
378 pageSize: 1000,
379 }),
380 (page) => page.resources,
381 );
382 return items
383 .filter((item) => hasAlchemyLabelKeys(item.labels))
384 .map((item) => toAttrs(item, env.project));
385 }),
386
387 reconcile: Effect.fn(function* ({ id, news, output }) {
388 const env = yield* GcpEnvironment.current;
389 const testId = yield* toPhysicalId(
390 id,
391 news.testId,
392 output?.testId,
393 "connectivity-test",
394 MAX_CONNECTIVITY_TEST_ID_LENGTH,
395 );
396 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
397 const name = resourceName(env.project, location, testId);
398 const desiredLabels = {
399 ...toLabels(news.labels),
400 ...(yield* createInternalLabels(id)),
401 };
402 const source = toEndpoint(news.source, env.project);
403 const destination = toEndpoint(news.destination, env.project);
404 const protocol = news.protocol ?? DEFAULT_PROTOCOL;
405 const relatedProjects = news.relatedProjects ?? [];
406 const roundTrip = news.roundTrip === true;
407 const bypassFirewallChecks = news.bypassFirewallChecks === true;
408
409 let current = yield* getByName(name);
410
411 if (current === undefined) {
412 const created = yield* networkmanagement
413 .createProjectsLocationsGlobalConnectivityTests({
414 parent: parentOf(env.project, location),
415 testId,
416 body: {
417 description: news.description,
418 labels: desiredLabels,
419 source,
420 destination,
421 protocol,
422 relatedProjects: relatedProjects.length > 0 ? relatedProjects : undefined,
423 roundTrip,
424 bypassFirewallChecks,
425 },
426 })
427 .pipe(
428 Effect.retry({
429 while: (error) => error._tag === "Conflict",
430 times: 5,
431 schedule: Schedule.spaced("2 seconds"),
432 }),
433 Effect.catchTag("Conflict", () => Effect.undefined),
434 );
435 if (created !== undefined) {
436 yield* waitForOperation(created);
437 }
438 current = yield* waitUntilPresent(getByName(name), name);
439 }
440
441 const observedLabels = tagRecord(current.labels);
442 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
443 const labelsChanged = upsert.length > 0 || removed.length > 0;
444 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
445 const sourceChanged = !sameJson(
446 endpointKey(toEndpoint(current.source, env.project)),
447 endpointKey(source),
448 );
449 const destinationChanged = !sameJson(
450 endpointKey(toEndpoint(current.destination, env.project)),
451 endpointKey(destination),
452 );
453 const protocolChanged =
454 (current.protocol ?? DEFAULT_PROTOCOL).toUpperCase() !== protocol.toUpperCase();
455 const relatedChanged = !sameStringList(current.relatedProjects, relatedProjects);
456 const roundTripChanged = (current.roundTrip === true) !== roundTrip;
457 const bypassChanged = (current.bypassFirewallChecks === true) !== bypassFirewallChecks;
458
459 const updateMask = changedFields([
460 ["labels", labelsChanged],
461 ["description", descriptionChanged],
462 ["source", sourceChanged],
463 ["destination", destinationChanged],
464 ["protocol", protocolChanged],
465 ["relatedProjects", relatedChanged],
466 ["roundTrip", roundTripChanged],
467 ["bypassFirewallChecks", bypassChanged],
468 ]);
469
470 if (updateMask.length > 0) {
471 const operation = yield* networkmanagement.patchProjectsLocationsGlobalConnectivityTests({
472 name: current.name ?? name,
473 updateMask: updateMask.join(","),
474 body: {
475 name: current.name ?? name,
476 labels: desiredLabels,
477 description: news.description,
478 source,
479 destination,
480 protocol,
481 relatedProjects,
482 roundTrip,
483 bypassFirewallChecks,
484 },
485 });
486 yield* waitForOperation(operation);
487 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
488 }
489
490 return toAttrs(current, env.project);
491 }),
492
493 delete: Effect.fn(function* ({ output }) {
494 const operation = yield* networkmanagement
495 .deleteProjectsLocationsGlobalConnectivityTests({ name: output.name })
496 .pipe(
497 Effect.retry({
498 while: (error) => error._tag === "Conflict",
499 times: 8,
500 schedule: Schedule.spaced("2 seconds"),
501 }),
502 Effect.catchTag("NotFound", () => Effect.undefined),
503 );
504 if (operation !== undefined) {
505 yield* waitForOperation(operation, { notFoundOk: true });
506 }
507 yield* waitUntilGone(getByName(output.name), output.name);
508 }),
509 });