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

main
ts 520 lines 17.1 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_GLOBAL,
12 DEFAULT_ZONE,
13 VmwareengineNotResolved,
14 canonicalizeLink,
15 changedFields,
16 collectPages,
17 createInternalLabels,
18 encodeOwnership,
19 expandName,
20 hasAlchemyLabels,
21 hasOwnershipMarker,
22 listAcrossLocations,
23 normalizeLocation,
24 parentOf,
25 parseName,
26 parseOwnership,
27 replaceOnIdentity,
28 rfc1035,
29 sameJson,
30 toPhysicalId,
31 waitForOperation,
32 waitUntilGone,
33 waitUntilPresent,
34 waitUntilReady,
35 } from "./internal.ts";
36
37 const COLLECTION = "privateClouds";
38 const VEN_COLLECTION = "vmwareEngineNetworks";
39 const DEFAULT_TYPE = "STANDARD";
40 const DEFAULT_MGMT_CLUSTER_ID = "mgmt";
41 const DEFAULT_NODE_TYPE = "standard-72";
42 const DEFAULT_NODE_COUNT = 3;
43 const DEFAULT_MANAGEMENT_CIDR = "192.168.1.0/24";
44
45 export type StretchedClusterConfig = {
46 /** Preferred zone that stays up if the inter-zone link is lost. */
47 preferredLocation?: string;
48 /** Additional zone for availability. */
49 secondaryLocation?: string;
50 };
51
52 export type NodeTypeConfig = {
53 /** Custom core count per node. `0` uses the node type maximum. */
54 customCoreCount?: number;
55 /** Number of nodes of this type. */
56 nodeCount?: number;
57 };
58
59 export type ManagementCluster = {
60 /** Stretched-cluster zones. Required for `STRETCHED` private clouds. */
61 stretchedClusterConfig?: StretchedClusterConfig;
62 /**
63 * Map of node type id to config. Keys are canonical node type ids
64 * (`standard-72`, …).
65 */
66 nodeTypeConfigs?: Record<string, NodeTypeConfig | undefined>;
67 /** User-provided cluster id for the management cluster. Immutable. */
68 clusterId?: string;
69 };
70
71 export type NetworkConfig = {
72 /** Management CIDR used by VMware appliances. Immutable. */
73 managementCidr?: string;
74 /** VMware Engine network to attach. Immutable. */
75 vmwareEngineNetwork?: string;
76 /** Output-only IP layout version. */
77 managementIpAddressLayoutVersion?: number;
78 /** Output-only DNS server IP. */
79 dnsServerIp?: string;
80 /** Output-only canonical VMware Engine network name. */
81 vmwareEngineNetworkCanonical?: string;
82 };
83
84 export type EncryptionConfig = {
85 /** KMS key for CMEK. */
86 cryptoKeyName?: string;
87 /** Encryption type (`CMEK`, `LEGACY_CMEK`, `OTHER`). */
88 type?: vmwareengine.EncryptionConfigTypeEnum | (string & {});
89 };
90
91 export type Appliance = {
92 /** Fully qualified domain name. */
93 fqdn?: string;
94 /** Internal IP address. */
95 internalIp?: string;
96 /** Appliance state. */
97 state?: string;
98 /** Appliance version. */
99 version?: string;
100 };
101
102 export type PrivateCloudProps = {
103 /**
104 * Private cloud id (the `{privateCloud}` segment of
105 * `projects/{project}/locations/{location}/privateClouds/{privateCloud}`).
106 * If omitted, a unique RFC1035 name is generated. Immutable.
107 */
108 privateCloudId?: string;
109 /**
110 * Location. `STANDARD` and `TIME_LIMITED` clouds are zonal
111 * (`us-central1-a`); `STRETCHED` clouds are regional. Immutable.
112 * @default "us-central1-a"
113 */
114 location?: string;
115 /**
116 * Private cloud type.
117 * @default "STANDARD"
118 */
119 type?: vmwareengine.PrivateCloudTypeEnum | (string & {});
120 /**
121 * Management cluster. Required on create. `clusterId` and node type
122 * identity are immutable.
123 */
124 managementCluster?: ManagementCluster;
125 /**
126 * Consumer-project network configuration. `managementCidr` is
127 * required on create. Immutable.
128 */
129 networkConfig?: NetworkConfig;
130 /**
131 * Customer-managed encryption. Immutable.
132 */
133 encryptionConfig?: EncryptionConfig;
134 /**
135 * Human-readable description. Private clouds have no labels field, so
136 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
137 * from attributes. Description is the only in-place update.
138 */
139 description?: string;
140 };
141
142 export type PrivateCloud = Resource<
143 "GCP.VMwareEngine.PrivateCloud",
144 PrivateCloudProps,
145 {
146 /** Full resource name. */
147 name: string;
148 /** Private cloud id (last path segment). */
149 privateCloudId: string;
150 /** Project id. */
151 project: string;
152 /** Location id (zone or region). */
153 location: string;
154 /** Private cloud type. */
155 type: string | undefined;
156 /** Management cluster configuration. */
157 managementCluster: ManagementCluster | undefined;
158 /** Network configuration, including output-only DNS and layout. */
159 networkConfig: NetworkConfig | undefined;
160 /** Encryption configuration. */
161 encryptionConfig: EncryptionConfig | undefined;
162 /** HCX appliance. */
163 hcx: Appliance | undefined;
164 /** vCenter appliance. */
165 vcenter: Appliance | undefined;
166 /** NSX appliance. */
167 nsx: Appliance | undefined;
168 /** User description with the Alchemy ownership prefix stripped. */
169 description: string | undefined;
170 /** Server-reported state. */
171 state: string | undefined;
172 /** System-generated unique identifier. */
173 uid: string | undefined;
174 /** RFC3339 creation timestamp. */
175 createTime: string | undefined;
176 /** RFC3339 last-update timestamp. */
177 updateTime: string | undefined;
178 /** Time the cloud was scheduled for deletion. */
179 deleteTime: string | undefined;
180 /** Time the cloud will be irreversibly deleted. */
181 expireTime: string | undefined;
182 },
183 never,
184 Providers
185 >;
186
187 /**
188 * A Google Cloud VMware Engine private cloud. `STANDARD` and
189 * `TIME_LIMITED` clouds are zonal; `STRETCHED` clouds are regional.
190 * Creating a private cloud also creates its management cluster.
191 *
192 * Private clouds have no labels field, so Alchemy stamps ownership into
193 * the description for `list` / nuke. Type, location, management cluster
194 * identity, and network config are immutable. Description updates in
195 * place. Delete uses `delayHours=0` so billing stops immediately.
196 *
197 * Provisioning typically takes 30-120 minutes.
198 *
199 * ### Creating a PrivateCloud
200 * **Example:** Standard three-node cloud
201 * ```typescript
202 * const cloud = yield* GCP.VMwareEngine.PrivateCloud("Sddc", {
203 * location: "us-central1-a",
204 * type: "STANDARD",
205 * networkConfig: {
206 * managementCidr: "192.168.1.0/24",
207 * vmwareEngineNetwork: ven.name,
208 * },
209 * managementCluster: {
210 * clusterId: "mgmt",
211 * nodeTypeConfigs: {
212 * "standard-72": { nodeCount: 3 },
213 * },
214 * },
215 * description: "app sddc",
216 * });
217 * ```
218 *
219 * @resource
220 * @category VMwareEngine
221 */
222 export const PrivateCloud = Resource<PrivateCloud>("GCP.VMwareEngine.PrivateCloud");
223
224 const resourceName = (project: string, location: string, privateCloudId: string) =>
225 `${parentOf(project, location)}/${COLLECTION}/${privateCloudId}`;
226
227 const nodeTypeConfigsOf = (
228 value: vmwareengine.NodeTypeConfigMap | undefined,
229 ): Record<string, NodeTypeConfig | undefined> | undefined => {
230 if (value === undefined) return undefined;
231 return Object.fromEntries(
232 Object.entries(value).map(([key, config]) => [
233 key,
234 config === undefined
235 ? undefined
236 : {
237 customCoreCount: config.customCoreCount,
238 nodeCount: config.nodeCount,
239 },
240 ]),
241 );
242 };
243
244 const stretchedOf = (
245 value: vmwareengine.StretchedClusterConfig | undefined,
246 ): StretchedClusterConfig | undefined => {
247 if (value === undefined) return undefined;
248 return {
249 preferredLocation: value.preferredLocation,
250 secondaryLocation: value.secondaryLocation,
251 };
252 };
253
254 const managementClusterOf = (
255 value: vmwareengine.ManagementCluster | ManagementCluster | undefined,
256 ): ManagementCluster | undefined => {
257 if (value === undefined) return undefined;
258 return {
259 clusterId: value.clusterId,
260 nodeTypeConfigs: nodeTypeConfigsOf(value.nodeTypeConfigs),
261 stretchedClusterConfig: stretchedOf(value.stretchedClusterConfig),
262 };
263 };
264
265 const networkConfigOf = (
266 value: vmwareengine.NetworkConfig | NetworkConfig | undefined,
267 ): NetworkConfig | undefined => {
268 if (value === undefined) return undefined;
269 return {
270 managementCidr: value.managementCidr,
271 vmwareEngineNetwork: value.vmwareEngineNetwork,
272 managementIpAddressLayoutVersion: value.managementIpAddressLayoutVersion,
273 dnsServerIp: value.dnsServerIp,
274 vmwareEngineNetworkCanonical: value.vmwareEngineNetworkCanonical,
275 };
276 };
277
278 const encryptionOf = (
279 value: vmwareengine.EncryptionConfig | EncryptionConfig | undefined,
280 ): EncryptionConfig | undefined => {
281 if (value === undefined) return undefined;
282 return {
283 cryptoKeyName: value.cryptoKeyName,
284 type: value.type,
285 };
286 };
287
288 const applianceOf = (
289 value: vmwareengine.Hcx | vmwareengine.Vcenter | vmwareengine.Nsx | undefined,
290 ): Appliance | undefined => {
291 if (value === undefined) return undefined;
292 return {
293 fqdn: value.fqdn,
294 internalIp: value.internalIp,
295 state: value.state,
296 version: value.version,
297 };
298 };
299
300 const defaultManagementCluster = (value: ManagementCluster | undefined): ManagementCluster => ({
301 clusterId: value?.clusterId ?? DEFAULT_MGMT_CLUSTER_ID,
302 stretchedClusterConfig: value?.stretchedClusterConfig,
303 nodeTypeConfigs: value?.nodeTypeConfigs ?? {
304 [DEFAULT_NODE_TYPE]: { nodeCount: DEFAULT_NODE_COUNT },
305 },
306 });
307
308 const defaultNetworkConfig = (
309 project: string,
310 value: NetworkConfig | undefined,
311 ): NetworkConfig => ({
312 managementCidr: value?.managementCidr ?? DEFAULT_MANAGEMENT_CIDR,
313 vmwareEngineNetwork: value?.vmwareEngineNetwork
314 ? expandName(value.vmwareEngineNetwork, project, DEFAULT_GLOBAL, VEN_COLLECTION)
315 : undefined,
316 });
317
318 const toAttrs = (item: vmwareengine.PrivateCloud, project: string) => {
319 const name = item.name ?? "";
320 const parsed = parseName(name, COLLECTION, DEFAULT_ZONE);
321 const ownership = parseOwnership(item.description);
322 return {
323 name,
324 privateCloudId: parsed.id,
325 project: parsed.project || project,
326 location: parsed.location,
327 type: item.type,
328 managementCluster: managementClusterOf(item.managementCluster),
329 networkConfig: networkConfigOf(item.networkConfig),
330 encryptionConfig: encryptionOf(item.encryptionConfig),
331 hcx: applianceOf(item.hcx),
332 vcenter: applianceOf(item.vcenter),
333 nsx: applianceOf(item.nsx),
334 description: ownership.text,
335 state: item.state,
336 uid: item.uid,
337 createTime: item.createTime,
338 updateTime: item.updateTime,
339 deleteTime: item.deleteTime,
340 expireTime: item.expireTime,
341 };
342 };
343
344 const getByName = (name: string) =>
345 vmwareengine
346 .getProjectsLocationsPrivateClouds({ name })
347 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
348
349 export const PrivateCloudProvider = () =>
350 Provider.succeed(PrivateCloud, {
351 stables: ["name", "privateCloudId", "project", "location", "uid", "createTime"],
352
353 diff: Effect.fn(function* ({ news, olds, output }) {
354 if (!isResolved(news)) return undefined;
355 const previousType = olds?.type ?? output?.type ?? DEFAULT_TYPE;
356 const nextType = news.type ?? previousType;
357 const previousCidr =
358 olds?.networkConfig?.managementCidr ?? output?.networkConfig?.managementCidr ?? "";
359 const nextCidr = news.networkConfig?.managementCidr ?? previousCidr;
360 const previousVen = canonicalizeLink(
361 olds?.networkConfig?.vmwareEngineNetwork ?? output?.networkConfig?.vmwareEngineNetwork,
362 );
363 const nextVen = canonicalizeLink(news.networkConfig?.vmwareEngineNetwork);
364 const previousClusterId =
365 olds?.managementCluster?.clusterId ?? output?.managementCluster?.clusterId ?? "";
366 const nextClusterId = news.managementCluster?.clusterId ?? previousClusterId;
367 return replaceOnIdentity({
368 previousId: olds?.privateCloudId ?? output?.privateCloudId,
369 nextId: news.privateCloudId
370 ? rfc1035(news.privateCloudId, "privatecloud")
371 : (olds?.privateCloudId ?? output?.privateCloudId),
372 previousLocation: normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE),
373 nextLocation: normalizeLocation(
374 news.location ?? olds?.location ?? output?.location,
375 DEFAULT_ZONE,
376 ),
377 extra:
378 previousType !== nextType ||
379 (previousCidr.length > 0 && previousCidr !== nextCidr) ||
380 (previousVen.length > 0 && nextVen.length > 0 && previousVen !== nextVen) ||
381 (previousClusterId.length > 0 &&
382 nextClusterId.length > 0 &&
383 previousClusterId !== nextClusterId) ||
384 !sameJson(news.encryptionConfig, olds?.encryptionConfig ?? output?.encryptionConfig),
385 });
386 }),
387
388 read: Effect.fn(function* ({ id, olds, output }) {
389 const env = yield* GcpEnvironment.current;
390 const privateCloudId = yield* toPhysicalId(
391 id,
392 olds?.privateCloudId,
393 output?.privateCloudId,
394 "privatecloud",
395 );
396 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
397 const name = output?.name ?? resourceName(env.project, location, privateCloudId);
398 const existing = yield* getByName(name);
399 if (existing === undefined) return undefined;
400 const attrs = toAttrs(existing, env.project);
401 const { labels } = parseOwnership(existing.description);
402 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
403 }),
404
405 list: () =>
406 Effect.gen(function* () {
407 const env = yield* GcpEnvironment.current;
408 const items = yield* listAcrossLocations(env.project, env.region, (parent) =>
409 collectPages(
410 vmwareengine.listProjectsLocationsPrivateClouds.pages({
411 parent,
412 pageSize: 1000,
413 }),
414 (page) => page.privateClouds,
415 ),
416 );
417 return items
418 .filter((item) => hasOwnershipMarker(item.description))
419 .map((item) => toAttrs(item, env.project));
420 }),
421
422 reconcile: Effect.fn(function* ({ id, news, output }) {
423 const env = yield* GcpEnvironment.current;
424 const privateCloudId = yield* toPhysicalId(
425 id,
426 news.privateCloudId,
427 output?.privateCloudId,
428 "privatecloud",
429 );
430 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_ZONE);
431 const name = resourceName(env.project, location, privateCloudId);
432 const ownership = yield* createInternalLabels(id);
433 const desiredDescription = encodeOwnership(ownership, news.description);
434 const type = news.type ?? DEFAULT_TYPE;
435 const managementCluster = defaultManagementCluster(news.managementCluster);
436 const networkConfig = defaultNetworkConfig(env.project, news.networkConfig);
437
438 let current = yield* getByName(output?.name ?? name);
439
440 if (current === undefined) {
441 const created = yield* vmwareengine
442 .createProjectsLocationsPrivateClouds({
443 parent: parentOf(env.project, location),
444 privateCloudId,
445 body: {
446 type,
447 description: desiredDescription,
448 managementCluster,
449 networkConfig,
450 encryptionConfig: news.encryptionConfig,
451 },
452 })
453 .pipe(
454 Effect.retry({
455 while: (error) => error._tag === "Conflict",
456 times: 5,
457 schedule: Schedule.spaced("2 seconds"),
458 }),
459 Effect.catchTag("Conflict", () => Effect.undefined),
460 );
461 if (created !== undefined) {
462 yield* waitForOperation(created);
463 }
464 current = yield* waitUntilPresent(getByName(name), name);
465 }
466
467 if (current === undefined) {
468 return yield* new VmwareengineNotResolved({ resourceName: name });
469 }
470
471 current = yield* waitUntilReady(
472 getByName(current.name ?? name),
473 current.name ?? name,
474 (item) => item.state,
475 );
476
477 const descriptionChanged = (current.description ?? "") !== desiredDescription;
478 const updateMask = changedFields([["description", descriptionChanged]]);
479
480 if (updateMask.length > 0) {
481 const operation = yield* vmwareengine.patchProjectsLocationsPrivateClouds({
482 name: current.name ?? name,
483 updateMask: updateMask.join(","),
484 body: {
485 name: current.name ?? name,
486 description: desiredDescription,
487 },
488 });
489 yield* waitForOperation(operation);
490 current = yield* waitUntilReady(
491 getByName(current.name ?? name),
492 current.name ?? name,
493 (item) => item.state,
494 );
495 }
496
497 return toAttrs(current, env.project);
498 }),
499
500 delete: Effect.fn(function* ({ output }) {
501 const operation = yield* vmwareengine
502 .deleteProjectsLocationsPrivateClouds({
503 name: output.name,
504 delayHours: 0,
505 force: true,
506 })
507 .pipe(
508 Effect.retry({
509 while: (error) => error._tag === "Conflict",
510 times: 8,
511 schedule: Schedule.spaced("2 seconds"),
512 }),
513 Effect.catchTag("NotFound", () => Effect.undefined),
514 );
515 if (operation !== undefined) {
516 yield* waitForOperation(operation, { notFoundOk: true });
517 }
518 yield* waitUntilGone(getByName(output.name), output.name);
519 }),
520 });