@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 558 lines 19.4 KB
Raw
1 import * as gkeonprem from "@distilled.cloud/gcp/gkeonprem_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 { hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 ResourceNotResolved,
14 VMWARE_NAME_LENGTH,
15 collectPages,
16 createInternalLabels,
17 desiredAnnotations,
18 differs,
19 encodeOwnership,
20 fieldMask,
21 isOwned,
22 listAtLocation,
23 membershipName,
24 normalizeLocation,
25 parentOf,
26 parseName,
27 parseOwnership,
28 replaceOnIdentity,
29 rfc1035,
30 sameText,
31 textState,
32 toPhysicalId,
33 userLabels,
34 waitForOperation,
35 waitUntilExists,
36 waitUntilGone,
37 } from "./internal.ts";
38 import type {
39 Authorization,
40 BinaryAuthorization,
41 Fleet,
42 VmwareAAGConfig,
43 VmwareAutoRepairConfig,
44 VmwareClusterUpgradePolicy,
45 VmwareControlPlaneNodeConfig,
46 VmwareDataplaneV2Config,
47 VmwareLoadBalancerConfig,
48 VmwareNetworkConfig,
49 VmwareStorageConfig,
50 VmwareVCenterConfig,
51 } from "./types.ts";
52
53 const COLLECTION = "vmwareClusters";
54
55 export type VmwareClusterProps = {
56 /**
57 * Cluster id (the `{vmwareCluster}` segment). If omitted, a unique
58 * RFC1123 name is generated. Max 40 characters. Immutable — changing
59 * it replaces the cluster.
60 */
61 vmwareClusterId?: string;
62 /**
63 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
64 * replaces the cluster. `US-CENTRAL1` is accepted and normalized.
65 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
66 */
67 location?: string;
68 /**
69 * Admin cluster Hub membership this user cluster belongs to. Full name
70 * `projects/{project}/locations/global/memberships/{membership}` or a
71 * membership id. Immutable — changing it replaces the cluster.
72 */
73 adminClusterMembership: string;
74 /**
75 * Anthos clusters on VMware version for the user cluster.
76 */
77 onPremVersion: string;
78 /**
79 * Control plane node configuration (CPU, memory, replica count).
80 */
81 controlPlaneNode?: VmwareControlPlaneNodeConfig;
82 /**
83 * Cluster network configuration (pod/service CIDRs, DHCP or static IP).
84 */
85 networkConfig?: VmwareNetworkConfig;
86 /**
87 * Load balancer configuration (MetalLB, F5, Seesaw, or manual).
88 */
89 loadBalancer?: VmwareLoadBalancerConfig;
90 /**
91 * vSphere CSI storage configuration.
92 */
93 storage?: VmwareStorageConfig;
94 /**
95 * vCenter settings. Inherited from the admin cluster when omitted.
96 */
97 vcenter?: VmwareVCenterConfig;
98 /**
99 * Dataplane V2 configuration.
100 */
101 dataplaneV2?: VmwareDataplaneV2Config;
102 /**
103 * Anti-affinity group (spread nodes across three hosts).
104 */
105 antiAffinityGroups?: VmwareAAGConfig;
106 /**
107 * Bootstrap RBAC users granted cluster-admin.
108 */
109 authorization?: Authorization;
110 /**
111 * Auto-repair configuration.
112 */
113 autoRepairConfig?: VmwareAutoRepairConfig;
114 /**
115 * Cluster upgrade policy.
116 */
117 upgradePolicy?: VmwareClusterUpgradePolicy;
118 /**
119 * Binary Authorization evaluation mode.
120 */
121 binaryAuthorization?: BinaryAuthorization;
122 /**
123 * Enable control plane V2.
124 * @default false
125 */
126 enableControlPlaneV2?: boolean;
127 /**
128 * Enable advanced cluster.
129 */
130 enableAdvancedCluster?: boolean;
131 /**
132 * Disable bundled ingress.
133 */
134 disableBundledIngress?: boolean;
135 /**
136 * Enable VM tracking.
137 */
138 vmTrackingEnabled?: boolean;
139 /**
140 * Human-readable description. Clusters have no GCP labels field, so
141 * Alchemy stamps ownership into annotations and a `[alchemy …]`
142 * description prefix and strips both from attributes.
143 */
144 description?: string;
145 /**
146 * Kubernetes-style annotations. Alchemy ownership keys are merged in.
147 */
148 annotations?: Record<string, string>;
149 /**
150 * User labels stored as annotations (keys sanitized like GCP labels).
151 * Alchemy ownership labels are merged in automatically.
152 */
153 labels?: Record<string, string>;
154 };
155
156 export type VmwareCluster = Resource<
157 "GCP.GKEOnPrem.VmwareCluster",
158 VmwareClusterProps,
159 {
160 /** Full resource name. */
161 name: string;
162 /** Cluster id (last path segment). */
163 vmwareClusterId: string;
164 /** Project id. */
165 project: string;
166 /** Location id. */
167 location: string;
168 /** Admin cluster Hub membership. */
169 adminClusterMembership: string | undefined;
170 /** Output-only admin cluster resource name. */
171 adminClusterName: string | undefined;
172 /** Anthos on-prem version. */
173 onPremVersion: string | undefined;
174 /** Control plane node configuration. */
175 controlPlaneNode: VmwareControlPlaneNodeConfig | undefined;
176 /** Network configuration. */
177 networkConfig: VmwareNetworkConfig | undefined;
178 /** Load balancer configuration. */
179 loadBalancer: VmwareLoadBalancerConfig | undefined;
180 /** Storage configuration. */
181 storage: VmwareStorageConfig | undefined;
182 /** vCenter configuration. */
183 vcenter: VmwareVCenterConfig | undefined;
184 /** Dataplane V2 configuration. */
185 dataplaneV2: VmwareDataplaneV2Config | undefined;
186 /** Anti-affinity configuration. */
187 antiAffinityGroups: VmwareAAGConfig | undefined;
188 /** Bootstrap RBAC. */
189 authorization: Authorization | undefined;
190 /** Auto-repair configuration. */
191 autoRepairConfig: VmwareAutoRepairConfig | undefined;
192 /** Upgrade policy. */
193 upgradePolicy: VmwareClusterUpgradePolicy | undefined;
194 /** Binary Authorization configuration. */
195 binaryAuthorization: BinaryAuthorization | undefined;
196 /** Control plane V2 enabled. */
197 enableControlPlaneV2: boolean | undefined;
198 /** Advanced cluster enabled. */
199 enableAdvancedCluster: boolean | undefined;
200 /** Bundled ingress disabled. */
201 disableBundledIngress: boolean | undefined;
202 /** VM tracking enabled. */
203 vmTrackingEnabled: boolean | undefined;
204 /** User description with the Alchemy ownership prefix stripped. */
205 description: string | undefined;
206 /** User annotations (Alchemy ownership keys stripped). */
207 annotations: Record<string, string>;
208 /** User labels (Alchemy ownership keys stripped). */
209 labels: Record<string, string>;
210 /** Output-only Kubernetes API endpoint. */
211 endpoint: string | undefined;
212 /** Output-only Fleet membership. */
213 fleet: Fleet | undefined;
214 /** Local CR name on the admin cluster. */
215 localName: string | undefined;
216 /** Server-reported state. */
217 state: string | undefined;
218 /** Server-generated resource uid. */
219 uid: string | undefined;
220 /** Whether a change is in flight. */
221 reconciling: boolean | undefined;
222 /** Controller error message. */
223 errorMessage: string | undefined;
224 /** RFC3339 creation timestamp. */
225 createTime: string | undefined;
226 /** RFC3339 last-update timestamp. */
227 updateTime: string | undefined;
228 /** RFC3339 deletion timestamp. */
229 deleteTime: string | undefined;
230 /** Server etag. */
231 etag: string | undefined;
232 },
233 never,
234 Providers
235 >;
236
237 /**
238 * An Anthos on VMware user cluster registered with the GKE On-Prem API.
239 * Creating a cluster requires a connected admin cluster (Hub membership)
240 * and vSphere infrastructure.
241 *
242 * Clusters have no GCP labels field, so Alchemy stamps ownership into
243 * annotations and a `[alchemy …]` description prefix for `list` / nuke.
244 * Cluster id, location, and admin membership are identity — changing
245 * them replaces the cluster. Other fields update in place.
246 *
247 * ### Creating a VMware Cluster
248 * **Example:** User cluster with MetalLB
249 * ```typescript
250 * const cluster = yield* GCP.GKEOnPrem.VmwareCluster("Workload", {
251 * adminClusterMembership:
252 * "projects/my-project/locations/global/memberships/admin",
253 * onPremVersion: "1.28.0-gke.1",
254 * controlPlaneNode: { cpus: "4", memory: "8192", replicas: "1" },
255 * networkConfig: {
256 * serviceAddressCidrBlocks: ["10.96.0.0/12"],
257 * podAddressCidrBlocks: ["192.168.0.0/16"],
258 * dhcpIpConfig: { enabled: true },
259 * },
260 * loadBalancer: {
261 * vipConfig: { controlPlaneVip: "10.200.0.8", ingressVip: "10.200.0.9" },
262 * metalLbConfig: {
263 * addressPools: [{ pool: "pool-1", addresses: ["10.200.0.10-10.200.0.20"] }],
264 * },
265 * },
266 * description: "app user cluster",
267 * });
268 * ```
269 *
270 * ### Updating a VMware Cluster
271 * Re-declare the same logical id with changed props; the engine keeps the
272 * physical resource and updates it in place.
273 *
274 * **Example:** Description and version
275 * ```typescript
276 * const cluster = yield* GCP.GKEOnPrem.VmwareCluster("Workload", {
277 * adminClusterMembership:
278 * "projects/my-project/locations/global/memberships/admin",
279 * onPremVersion: "1.29.0-gke.1",
280 * controlPlaneNode: { cpus: "4", memory: "8192", replicas: "1" },
281 * networkConfig: {
282 * serviceAddressCidrBlocks: ["10.96.0.0/12"],
283 * podAddressCidrBlocks: ["192.168.0.0/16"],
284 * dhcpIpConfig: { enabled: true },
285 * },
286 * loadBalancer: {
287 * vipConfig: { controlPlaneVip: "10.200.0.8", ingressVip: "10.200.0.9" },
288 * metalLbConfig: {
289 * addressPools: [{ pool: "pool-1", addresses: ["10.200.0.10-10.200.0.20"] }],
290 * },
291 * },
292 * description: "app user cluster v2",
293 * });
294 * ```
295 *
296 * @resource
297 * @category GKEOnPrem
298 */
299 export const VmwareCluster = Resource<VmwareCluster>("GCP.GKEOnPrem.VmwareCluster");
300
301 const resourceName = (project: string, location: string, vmwareClusterId: string) =>
302 `${parentOf(project, location)}/${COLLECTION}/${vmwareClusterId}`;
303
304 const toAttrs = (item: gkeonprem.VmwareCluster, project: string, region: string) => {
305 const name = item.name ?? "";
306 const parsed = parseName(name, COLLECTION, region);
307 const ownership = parseOwnership(item.description);
308 const annotations = userLabels(item.annotations);
309 return {
310 name,
311 vmwareClusterId: parsed.id,
312 project: parsed.project || project,
313 location: parsed.location,
314 adminClusterMembership: item.adminClusterMembership,
315 adminClusterName: item.adminClusterName,
316 onPremVersion: item.onPremVersion,
317 controlPlaneNode: item.controlPlaneNode,
318 networkConfig: item.networkConfig,
319 loadBalancer: item.loadBalancer,
320 storage: item.storage,
321 vcenter: item.vcenter,
322 dataplaneV2: item.dataplaneV2,
323 antiAffinityGroups: item.antiAffinityGroups,
324 authorization: item.authorization,
325 autoRepairConfig: item.autoRepairConfig,
326 upgradePolicy: item.upgradePolicy,
327 binaryAuthorization: item.binaryAuthorization,
328 enableControlPlaneV2: item.enableControlPlaneV2,
329 enableAdvancedCluster: item.enableAdvancedCluster,
330 disableBundledIngress: item.disableBundledIngress,
331 vmTrackingEnabled: item.vmTrackingEnabled,
332 description: ownership.text,
333 annotations,
334 labels: annotations,
335 endpoint: item.endpoint,
336 fleet: item.fleet,
337 localName: item.localName,
338 state: textState(item.state),
339 uid: item.uid,
340 reconciling: item.reconciling,
341 errorMessage: item.status?.errorMessage,
342 createTime: item.createTime,
343 updateTime: item.updateTime,
344 deleteTime: item.deleteTime,
345 etag: item.etag,
346 };
347 };
348
349 const getByName = (name: string) =>
350 gkeonprem
351 .getProjectsLocationsVmwareClusters({ name, view: "FULL" })
352 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
353
354 const listOwned = (project: string, region: string) =>
355 listAtLocation(project, region, (parent) =>
356 collectPages(
357 gkeonprem.listProjectsLocationsVmwareClusters.pages({
358 parent,
359 pageSize: 1000,
360 view: "FULL",
361 }),
362 (page): readonly gkeonprem.VmwareCluster[] | undefined => page.vmwareClusters,
363 ),
364 ).pipe(
365 Effect.map((items) =>
366 items.filter((item: gkeonprem.VmwareCluster) => isOwned(item.annotations, item.description)),
367 ),
368 );
369
370 const toBody = (
371 news: VmwareClusterProps,
372 annotations: Record<string, string>,
373 description: string,
374 membership: string,
375 ): gkeonprem.VmwareCluster => ({
376 adminClusterMembership: membership,
377 onPremVersion: news.onPremVersion,
378 controlPlaneNode: news.controlPlaneNode,
379 networkConfig: news.networkConfig,
380 loadBalancer: news.loadBalancer,
381 storage: news.storage,
382 vcenter: news.vcenter,
383 dataplaneV2: news.dataplaneV2,
384 antiAffinityGroups: news.antiAffinityGroups,
385 authorization: news.authorization,
386 autoRepairConfig: news.autoRepairConfig,
387 upgradePolicy: news.upgradePolicy,
388 binaryAuthorization: news.binaryAuthorization,
389 enableControlPlaneV2: news.enableControlPlaneV2,
390 enableAdvancedCluster: news.enableAdvancedCluster,
391 disableBundledIngress: news.disableBundledIngress,
392 vmTrackingEnabled: news.vmTrackingEnabled,
393 description,
394 annotations,
395 });
396
397 export const VmwareClusterProvider = () =>
398 Provider.succeed(VmwareCluster, {
399 stables: ["name", "vmwareClusterId", "project", "location", "uid", "createTime"],
400
401 diff: Effect.fn(function* ({ news, olds, output }) {
402 if (!isResolved(news)) return undefined;
403 const env = yield* GcpEnvironment.current;
404 const previousMembership = olds?.adminClusterMembership ?? output?.adminClusterMembership;
405 const nextMembership = news.adminClusterMembership;
406 return replaceOnIdentity({
407 previousId: olds?.vmwareClusterId ?? output?.vmwareClusterId,
408 nextId: news.vmwareClusterId
409 ? rfc1035(news.vmwareClusterId, "vmwarecluster", VMWARE_NAME_LENGTH)
410 : (olds?.vmwareClusterId ?? output?.vmwareClusterId),
411 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
412 nextLocation: normalizeLocation(
413 news.location ?? olds?.location ?? output?.location,
414 env.region,
415 ),
416 extra:
417 previousMembership !== undefined &&
418 nextMembership !== undefined &&
419 previousMembership !== nextMembership &&
420 !previousMembership.endsWith(`/${nextMembership}`),
421 });
422 }),
423
424 read: Effect.fn(function* ({ id, olds, output }) {
425 const env = yield* GcpEnvironment.current;
426 const vmwareClusterId = yield* toPhysicalId(
427 id,
428 olds?.vmwareClusterId,
429 output?.vmwareClusterId,
430 "vmwarecluster",
431 VMWARE_NAME_LENGTH,
432 );
433 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
434 const name = output?.name ?? resourceName(env.project, location, vmwareClusterId);
435 const existing = yield* getByName(name);
436 if (existing === undefined) return undefined;
437 const attrs = toAttrs(existing, env.project, env.region);
438 const fromDescription = parseOwnership(existing.description).labels;
439 const owned =
440 (yield* hasAlchemyLabels(id, tagRecord(existing.annotations))) ||
441 (yield* hasAlchemyLabels(id, fromDescription));
442 return owned ? attrs : Unowned(attrs);
443 }),
444
445 list: () =>
446 Effect.gen(function* () {
447 const env = yield* GcpEnvironment.current;
448 const items = yield* listOwned(env.project, env.region);
449 return items.map((item: gkeonprem.VmwareCluster) => toAttrs(item, env.project, env.region));
450 }),
451
452 reconcile: Effect.fn(function* ({ id, news, output }) {
453 const env = yield* GcpEnvironment.current;
454 const vmwareClusterId = yield* toPhysicalId(
455 id,
456 news.vmwareClusterId,
457 output?.vmwareClusterId,
458 "vmwarecluster",
459 VMWARE_NAME_LENGTH,
460 );
461 const location = normalizeLocation(news.location ?? output?.location, env.region);
462 const name = resourceName(env.project, location, vmwareClusterId);
463 const ownership = yield* createInternalLabels(id);
464 const annotations = desiredAnnotations(ownership, news.labels, news.annotations);
465 const description = encodeOwnership(ownership, news.description);
466 const membership = membershipName(news.adminClusterMembership, env.project);
467 const body = toBody(news, annotations, description, membership);
468
469 let current = yield* getByName(output?.name ?? name);
470
471 if (current === undefined) {
472 const created = yield* gkeonprem
473 .createProjectsLocationsVmwareClusters({
474 parent: parentOf(env.project, location),
475 vmwareClusterId,
476 body,
477 })
478 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
479 if (created !== undefined) {
480 yield* waitForOperation(created);
481 }
482 current = yield* waitUntilExists(getByName(name), name);
483 }
484
485 if (current === undefined) {
486 return yield* new ResourceNotResolved({ resourceName: name });
487 }
488
489 const mask = fieldMask([
490 differs(current.annotations, annotations) && "annotations",
491 !sameText(parseOwnership(current.description).text, news.description) && "description",
492 differs(current.onPremVersion, news.onPremVersion) && "onPremVersion",
493 differs(current.controlPlaneNode, news.controlPlaneNode) && "controlPlaneNode",
494 differs(current.networkConfig, news.networkConfig) && "networkConfig",
495 differs(current.loadBalancer, news.loadBalancer) && "loadBalancer",
496 differs(current.storage, news.storage) && "storage",
497 differs(current.vcenter, news.vcenter) && "vcenter",
498 differs(current.dataplaneV2, news.dataplaneV2) && "dataplaneV2",
499 differs(current.antiAffinityGroups, news.antiAffinityGroups) && "antiAffinityGroups",
500 differs(current.authorization, news.authorization) && "authorization",
501 differs(current.autoRepairConfig, news.autoRepairConfig) && "autoRepairConfig",
502 differs(current.upgradePolicy, news.upgradePolicy) && "upgradePolicy",
503 differs(current.binaryAuthorization, news.binaryAuthorization) && "binaryAuthorization",
504 news.enableControlPlaneV2 !== undefined &&
505 news.enableControlPlaneV2 !== current.enableControlPlaneV2 &&
506 "enableControlPlaneV2",
507 news.enableAdvancedCluster !== undefined &&
508 news.enableAdvancedCluster !== current.enableAdvancedCluster &&
509 "enableAdvancedCluster",
510 news.disableBundledIngress !== undefined &&
511 news.disableBundledIngress !== current.disableBundledIngress &&
512 "disableBundledIngress",
513 news.vmTrackingEnabled !== undefined &&
514 news.vmTrackingEnabled !== current.vmTrackingEnabled &&
515 "vmTrackingEnabled",
516 ]);
517
518 if (mask.length > 0) {
519 const operation = yield* gkeonprem.patchProjectsLocationsVmwareClusters({
520 name: current.name ?? name,
521 updateMask: mask,
522 body: {
523 ...body,
524 etag: current.etag,
525 },
526 });
527 yield* waitForOperation(operation);
528 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
529 }
530
531 if (current === undefined) {
532 return yield* new ResourceNotResolved({ resourceName: name });
533 }
534 return toAttrs(current, env.project, env.region);
535 }),
536
537 delete: Effect.fn(function* ({ output }) {
538 const operation = yield* gkeonprem
539 .deleteProjectsLocationsVmwareClusters({
540 name: output.name,
541 allowMissing: true,
542 force: true,
543 etag: output.etag,
544 })
545 .pipe(
546 Effect.retry({
547 while: (error) => error._tag === "Conflict",
548 times: 8,
549 schedule: Schedule.spaced("2 seconds"),
550 }),
551 Effect.catchTag("NotFound", () => Effect.undefined),
552 );
553 if (operation !== undefined) {
554 yield* waitForOperation(operation, { notFoundOk: true });
555 }
556 yield* waitUntilGone(getByName(output.name), output.name);
557 }),
558 });