The best way to control Claude Code, Codex and more from any computer or phone

main
ts 505 lines 16.9 KB
Raw
1 import * as vmwareengine from "@distilled.cloud/gcp/vmwareengine_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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_ZONE,
12 VmwareengineNotResolved,
13 changedFields,
14 collectPages,
15 createInternalLabels,
16 expandName,
17 hasOwnershipMarker,
18 listAcrossLocations,
19 locationFromName,
20 normalizeLocation,
21 parseName,
22 replaceOnIdentity,
23 rfc1035,
24 sameJson,
25 toPhysicalId,
26 waitForOperation,
27 waitUntilGone,
28 waitUntilPresent,
29 waitUntilReady,
30 } from "./internal.ts";
31 import type { NodeTypeConfig, StretchedClusterConfig } from "./PrivateCloud.ts";
32
33 const COLLECTION = "clusters";
34 const PARENT_COLLECTION = "privateClouds";
35 const DEFAULT_NODE_TYPE = "standard-72";
36 const DEFAULT_NODE_COUNT = 3;
37
38 export type Thresholds = {
39 /** Utilization percent that triggers scale-out. */
40 scaleOut?: number;
41 /** Utilization percent that triggers scale-in. */
42 scaleIn?: number;
43 };
44
45 export type AutoscalingPolicy = {
46 /** Canonical node type id this policy scales. */
47 nodeTypeId?: string;
48 /** Storage utilization thresholds. */
49 storageThresholds?: Thresholds;
50 /** CPU utilization thresholds. */
51 cpuThresholds?: Thresholds;
52 /** Granted-memory utilization thresholds. */
53 grantedMemoryThresholds?: Thresholds;
54 /** Consumed-memory utilization thresholds. */
55 consumedMemoryThresholds?: Thresholds;
56 /** Nodes added per scale-out. Must be even for stretched clusters. */
57 scaleOutSize?: number;
58 };
59
60 export type AutoscalingSettings = {
61 /** Minimum nodes of any type. */
62 minClusterNodeCount?: number;
63 /** Cool-down between autoscale operations (duration string). */
64 coolDownPeriod?: string;
65 /** Map of policy id to autoscaling policy. */
66 autoscalingPolicies?: Record<string, AutoscalingPolicy | undefined>;
67 /** Maximum nodes of any type. */
68 maxClusterNodeCount?: number;
69 };
70
71 export type DatastoreNetwork = {
72 /** Output-only network peering used to reach the file share. */
73 networkPeering?: string;
74 /** NFS connections from each ESXi host (`1`–`4`). */
75 connectionCount?: number;
76 /** Subnet resource name. */
77 subnet?: string;
78 /** VMKernel adapter MTU. */
79 mtu?: number;
80 };
81
82 export type DatastoreMountConfig = {
83 /** Output-only file share name. */
84 fileShare?: string;
85 /** NFS protocol. Default `NFS_V3`. */
86 nfsVersion?: vmwareengine.DatastoreMountConfigNfsVersionEnum | (string & {});
87 /** Datastore resource name to mount. */
88 datastore?: string;
89 /** Access mode. Default `READ_WRITE`. */
90 accessMode?: vmwareengine.DatastoreMountConfigAccessModeEnum | (string & {});
91 /** Network configuration for the mount. */
92 datastoreNetwork?: DatastoreNetwork;
93 /** Output-only NFS server addresses. */
94 servers?: string[];
95 };
96
97 export type PrivateCloudsClusterProps = {
98 /**
99 * Parent PrivateCloud resource name
100 * (`projects/{project}/locations/{location}/privateClouds/{privateCloud}`)
101 * or the cloud id. Immutable — changing it replaces the cluster.
102 */
103 privateCloud: string;
104 /**
105 * Cluster id (the `{cluster}` segment of
106 * `.../privateClouds/{privateCloud}/clusters/{cluster}`). If omitted, a
107 * unique RFC1035 name is generated. Immutable.
108 */
109 clusterId?: string;
110 /**
111 * Location of the parent private cloud. Inferred from `privateCloud`
112 * when that value is a full resource name. Immutable.
113 * @default "us-central1-a"
114 */
115 location?: string;
116 /**
117 * Map of node type id to config. Keys are canonical node type ids.
118 * @default { "standard-72": { nodeCount: 3 } }
119 */
120 nodeTypeConfigs?: Record<string, NodeTypeConfig | undefined>;
121 /**
122 * Autoscaling applied to this cluster.
123 */
124 autoscalingSettings?: AutoscalingSettings;
125 /**
126 * Stretched-cluster zones. Required for clusters on a `STRETCHED`
127 * private cloud. Immutable.
128 */
129 stretchedClusterConfig?: StretchedClusterConfig;
130 };
131
132 export type PrivateCloudsCluster = Resource<
133 "GCP.VMwareEngine.PrivateCloudsCluster",
134 PrivateCloudsClusterProps,
135 {
136 /** Full resource name. */
137 name: string;
138 /** Cluster id (last path segment). */
139 clusterId: string;
140 /** Parent PrivateCloud resource name. */
141 privateCloud: string;
142 /** Project id. */
143 project: string;
144 /** Location id. */
145 location: string;
146 /** Node type configuration currently applied. */
147 nodeTypeConfigs: Record<string, NodeTypeConfig | undefined> | undefined;
148 /** Autoscaling configuration currently applied. */
149 autoscalingSettings: AutoscalingSettings | undefined;
150 /** Stretched-cluster configuration. */
151 stretchedClusterConfig: StretchedClusterConfig | undefined;
152 /** Mounted datastore configuration. */
153 datastoreMountConfig: DatastoreMountConfig[];
154 /** Whether this is the management cluster. */
155 management: boolean;
156 /** Server-reported state. */
157 state: string | undefined;
158 /** System-generated unique identifier. */
159 uid: string | undefined;
160 /** RFC3339 creation timestamp. */
161 createTime: string | undefined;
162 /** RFC3339 last-update timestamp. */
163 updateTime: string | undefined;
164 },
165 never,
166 Providers
167 >;
168
169 /**
170 * A workload cluster in a VMware Engine private cloud. The management
171 * cluster is created with the private cloud and cannot be deleted
172 * independently.
173 *
174 * Clusters have no labels or description field, so Alchemy treats
175 * clusters whose parent private cloud carries the `[alchemy …]`
176 * ownership marker as owned for `list` / nuke. Changing the parent
177 * cloud, cluster id, location, or stretched config replaces the
178 * cluster. Node counts and autoscaling update in place.
179 *
180 * ### Creating a PrivateCloudsCluster
181 * **Example:** Three-node workload cluster
182 * ```typescript
183 * const cluster = yield* GCP.VMwareEngine.PrivateCloudsCluster("Work", {
184 * privateCloud: cloud.name,
185 * nodeTypeConfigs: {
186 * "standard-72": { nodeCount: 3 },
187 * },
188 * });
189 * ```
190 *
191 * @resource
192 * @category VMwareEngine
193 */
194 export const PrivateCloudsCluster = Resource<PrivateCloudsCluster>(
195 "GCP.VMwareEngine.PrivateCloudsCluster",
196 );
197
198 const parentCloudName = (project: string, location: string, privateCloud: string) =>
199 expandName(privateCloud, project, location, PARENT_COLLECTION);
200
201 const resourceNameOf = (parent: string, clusterId: string) =>
202 `${parent}/${COLLECTION}/${clusterId}`;
203
204 const nodeTypeConfigsOf = (
205 value: vmwareengine.NodeTypeConfigMap | undefined,
206 ): Record<string, NodeTypeConfig | undefined> | undefined => {
207 if (value === undefined) return undefined;
208 return Object.fromEntries(
209 Object.entries(value).map(([key, config]) => [
210 key,
211 config === undefined
212 ? undefined
213 : {
214 customCoreCount: config.customCoreCount,
215 nodeCount: config.nodeCount,
216 },
217 ]),
218 );
219 };
220
221 const thresholdsOf = (
222 value: vmwareengine.Thresholds | Thresholds | undefined,
223 ): Thresholds | undefined => {
224 if (value === undefined) return undefined;
225 return { scaleOut: value.scaleOut, scaleIn: value.scaleIn };
226 };
227
228 const autoscalingPolicyOf = (
229 value: vmwareengine.AutoscalingPolicy | AutoscalingPolicy | undefined,
230 ): AutoscalingPolicy | undefined => {
231 if (value === undefined) return undefined;
232 return {
233 nodeTypeId: value.nodeTypeId,
234 storageThresholds: thresholdsOf(value.storageThresholds),
235 cpuThresholds: thresholdsOf(value.cpuThresholds),
236 grantedMemoryThresholds: thresholdsOf(value.grantedMemoryThresholds),
237 consumedMemoryThresholds: thresholdsOf(value.consumedMemoryThresholds),
238 scaleOutSize: value.scaleOutSize,
239 };
240 };
241
242 const autoscalingOf = (
243 value: vmwareengine.AutoscalingSettings | AutoscalingSettings | undefined,
244 ): AutoscalingSettings | undefined => {
245 if (value === undefined) return undefined;
246 const policies = value.autoscalingPolicies
247 ? Object.fromEntries(
248 Object.entries(value.autoscalingPolicies).map(([key, policy]) => [
249 key,
250 autoscalingPolicyOf(policy),
251 ]),
252 )
253 : undefined;
254 return {
255 minClusterNodeCount: value.minClusterNodeCount,
256 coolDownPeriod: value.coolDownPeriod,
257 autoscalingPolicies: policies,
258 maxClusterNodeCount: value.maxClusterNodeCount,
259 };
260 };
261
262 const stretchedOf = (
263 value: vmwareengine.StretchedClusterConfig | StretchedClusterConfig | undefined,
264 ): StretchedClusterConfig | undefined => {
265 if (value === undefined) return undefined;
266 return {
267 preferredLocation: value.preferredLocation,
268 secondaryLocation: value.secondaryLocation,
269 };
270 };
271
272 const mountsOf = (
273 values: vmwareengine.DatastoreMountConfigList | undefined,
274 ): DatastoreMountConfig[] =>
275 (values ?? []).map((mount) => ({
276 fileShare: mount.fileShare,
277 nfsVersion: mount.nfsVersion,
278 datastore: mount.datastore,
279 accessMode: mount.accessMode,
280 datastoreNetwork:
281 mount.datastoreNetwork === undefined
282 ? undefined
283 : {
284 networkPeering: mount.datastoreNetwork.networkPeering,
285 connectionCount: mount.datastoreNetwork.connectionCount,
286 subnet: mount.datastoreNetwork.subnet,
287 mtu: mount.datastoreNetwork.mtu,
288 },
289 servers: mount.servers,
290 }));
291
292 const toAttrs = (item: vmwareengine.Cluster, project: string) => {
293 const name = item.name ?? "";
294 const parsed = parseName(name, COLLECTION, DEFAULT_ZONE);
295 return {
296 name,
297 clusterId: parsed.id,
298 privateCloud: parsed.parent,
299 project: parsed.project || project,
300 location: parsed.location,
301 nodeTypeConfigs: nodeTypeConfigsOf(item.nodeTypeConfigs),
302 autoscalingSettings: autoscalingOf(item.autoscalingSettings),
303 stretchedClusterConfig: stretchedOf(item.stretchedClusterConfig),
304 datastoreMountConfig: mountsOf(item.datastoreMountConfig),
305 management: item.management === true,
306 state: item.state,
307 uid: item.uid,
308 createTime: item.createTime,
309 updateTime: item.updateTime,
310 };
311 };
312
313 const getByName = (name: string) =>
314 vmwareengine
315 .getProjectsLocationsPrivateCloudsClusters({ name })
316 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
317
318 const getParentCloud = (name: string) =>
319 vmwareengine
320 .getProjectsLocationsPrivateClouds({ name })
321 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
322
323 const defaultNodeTypeConfigs = (value: Record<string, NodeTypeConfig | undefined> | undefined) =>
324 value ?? {
325 [DEFAULT_NODE_TYPE]: { nodeCount: DEFAULT_NODE_COUNT },
326 };
327
328 export const PrivateCloudsClusterProvider = () =>
329 Provider.succeed(PrivateCloudsCluster, {
330 stables: ["name", "clusterId", "privateCloud", "project", "location", "uid", "createTime"],
331
332 diff: Effect.fn(function* ({ news, olds, output }) {
333 if (!isResolved(news)) return undefined;
334 const previousLocation = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
335 return replaceOnIdentity({
336 previousId: olds?.clusterId ?? output?.clusterId,
337 nextId: news.clusterId
338 ? rfc1035(news.clusterId, "cluster")
339 : (olds?.clusterId ?? output?.clusterId),
340 previousLocation,
341 nextLocation: normalizeLocation(
342 news.location ?? locationFromName(news.privateCloud, previousLocation),
343 DEFAULT_ZONE,
344 ),
345 previousParent: olds?.privateCloud ?? output?.privateCloud,
346 nextParent: news.privateCloud,
347 extra: !sameJson(
348 stretchedOf(news.stretchedClusterConfig),
349 stretchedOf(olds?.stretchedClusterConfig ?? output?.stretchedClusterConfig),
350 ),
351 });
352 }),
353
354 read: Effect.fn(function* ({ id, olds, output }) {
355 const env = yield* GcpEnvironment.current;
356 const location = normalizeLocation(
357 olds?.location ??
358 output?.location ??
359 (olds?.privateCloud ? locationFromName(olds.privateCloud, DEFAULT_ZONE) : undefined),
360 DEFAULT_ZONE,
361 );
362 const parent = parentCloudName(
363 env.project,
364 location,
365 olds?.privateCloud ?? output?.privateCloud ?? "",
366 );
367 const clusterId = yield* toPhysicalId(id, olds?.clusterId, output?.clusterId, "cluster");
368 const name = output?.name ?? resourceNameOf(parent, clusterId);
369 const existing = yield* getByName(name);
370 if (existing === undefined) return undefined;
371 const attrs = toAttrs(existing, env.project);
372 if (output?.name === (existing.name ?? name)) return attrs;
373 const parentCloud = yield* getParentCloud(attrs.privateCloud);
374 return hasOwnershipMarker(parentCloud?.description) ? attrs : Unowned(attrs);
375 }),
376
377 list: () =>
378 Effect.gen(function* () {
379 const env = yield* GcpEnvironment.current;
380 const clouds = yield* listAcrossLocations(env.project, env.region, (parent) =>
381 collectPages(
382 vmwareengine.listProjectsLocationsPrivateClouds.pages({
383 parent,
384 pageSize: 1000,
385 }),
386 (page) => page.privateClouds,
387 ),
388 );
389 const ownedClouds = clouds.filter((cloud) => hasOwnershipMarker(cloud.description));
390 const nested = yield* Effect.forEach(
391 ownedClouds.filter((cloud) => (cloud.name ?? "").length > 0),
392 (cloud) =>
393 collectPages(
394 vmwareengine.listProjectsLocationsPrivateCloudsClusters.pages({
395 parent: cloud.name ?? "",
396 pageSize: 1000,
397 }),
398 (page) => page.clusters,
399 ),
400 { concurrency: 4 },
401 );
402 return nested
403 .flat()
404 .filter((item) => item.management !== true)
405 .map((item) => toAttrs(item, env.project));
406 }),
407
408 reconcile: Effect.fn(function* ({ id, news, output }) {
409 const env = yield* GcpEnvironment.current;
410 const location = normalizeLocation(
411 news.location ?? output?.location ?? locationFromName(news.privateCloud, DEFAULT_ZONE),
412 DEFAULT_ZONE,
413 );
414 const parent = parentCloudName(env.project, location, news.privateCloud);
415 const clusterId = yield* toPhysicalId(id, news.clusterId, output?.clusterId, "cluster");
416 const name = resourceNameOf(parent, clusterId);
417 yield* createInternalLabels(id);
418 const nodeTypeConfigs = defaultNodeTypeConfigs(news.nodeTypeConfigs);
419
420 let current = yield* getByName(output?.name ?? name);
421
422 if (current === undefined) {
423 const created = yield* vmwareengine
424 .createProjectsLocationsPrivateCloudsClusters({
425 parent,
426 clusterId,
427 body: {
428 nodeTypeConfigs,
429 autoscalingSettings: news.autoscalingSettings,
430 stretchedClusterConfig: news.stretchedClusterConfig,
431 },
432 })
433 .pipe(
434 Effect.retry({
435 while: (error) => error._tag === "Conflict",
436 times: 5,
437 schedule: Schedule.spaced("2 seconds"),
438 }),
439 Effect.catchTag("Conflict", () => Effect.undefined),
440 );
441 if (created !== undefined) {
442 yield* waitForOperation(created);
443 }
444 current = yield* waitUntilPresent(getByName(name), name);
445 }
446
447 if (current === undefined) {
448 return yield* new VmwareengineNotResolved({ resourceName: name });
449 }
450
451 current = yield* waitUntilReady(
452 getByName(current.name ?? name),
453 current.name ?? name,
454 (item) => item.state,
455 );
456
457 const nodesChanged = !sameJson(nodeTypeConfigsOf(current.nodeTypeConfigs), nodeTypeConfigs);
458 const autoscalingChanged = !sameJson(
459 autoscalingOf(current.autoscalingSettings),
460 autoscalingOf(news.autoscalingSettings),
461 );
462 const updateMask = changedFields([
463 ["nodeTypeConfigs", nodesChanged],
464 ["autoscalingSettings", autoscalingChanged],
465 ]);
466
467 if (updateMask.length > 0) {
468 const operation = yield* vmwareengine.patchProjectsLocationsPrivateCloudsClusters({
469 name: current.name ?? name,
470 updateMask: updateMask.join(","),
471 body: {
472 name: current.name ?? name,
473 nodeTypeConfigs,
474 autoscalingSettings: news.autoscalingSettings,
475 },
476 });
477 yield* waitForOperation(operation);
478 current = yield* waitUntilReady(
479 getByName(current.name ?? name),
480 current.name ?? name,
481 (item) => item.state,
482 );
483 }
484
485 return toAttrs(current, env.project);
486 }),
487
488 delete: Effect.fn(function* ({ output }) {
489 if (output.management) return;
490 const operation = yield* vmwareengine
491 .deleteProjectsLocationsPrivateCloudsClusters({ name: output.name })
492 .pipe(
493 Effect.retry({
494 while: (error) => error._tag === "Conflict",
495 times: 8,
496 schedule: Schedule.spaced("2 seconds"),
497 }),
498 Effect.catchTag("NotFound", () => Effect.undefined),
499 );
500 if (operation !== undefined) {
501 yield* waitForOperation(operation, { notFoundOk: true });
502 }
503 yield* waitUntilGone(getByName(output.name), output.name);
504 }),
505 });