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

main
ts 568 lines 19.8 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 collectPages,
15 createInternalLabels,
16 desiredAnnotations,
17 differs,
18 encodeOwnership,
19 fieldMask,
20 isOwned,
21 listAtLocation,
22 membershipName,
23 normalizeLocation,
24 parentOf,
25 parseName,
26 parseOwnership,
27 replaceOnIdentity,
28 rfc1035,
29 sameText,
30 textState,
31 toPhysicalId,
32 userLabels,
33 waitForOperation,
34 waitUntilExists,
35 waitUntilGone,
36 } from "./internal.ts";
37 import type {
38 BareMetalClusterOperationsConfig,
39 BareMetalClusterUpgradePolicy,
40 BareMetalControlPlaneConfig,
41 BareMetalLoadBalancerConfig,
42 BareMetalMaintenanceConfig,
43 BareMetalNetworkConfig,
44 BareMetalNodeAccessConfig,
45 BareMetalOsEnvironmentConfig,
46 BareMetalProxyConfig,
47 BareMetalSecurityConfig,
48 BareMetalStorageConfig,
49 BareMetalWorkloadNodeConfig,
50 BinaryAuthorization,
51 } from "./types.ts";
52
53 const COLLECTION = "bareMetalClusters";
54
55 export type BareMetalClusterProps = {
56 /**
57 * Cluster id (the `{bareMetalCluster}` segment). If omitted, a unique
58 * RFC1035 name is generated from the stack, stage, and logical id.
59 * Immutable — changing it replaces the cluster.
60 */
61 bareMetalClusterId?: 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 bare metal version for the user cluster.
76 */
77 bareMetalVersion: string;
78 /**
79 * Control plane configuration, including the control plane node pool.
80 */
81 controlPlane: BareMetalControlPlaneConfig;
82 /**
83 * Local PV storage configuration.
84 */
85 storage: BareMetalStorageConfig;
86 /**
87 * Cluster network configuration (island-mode CIDRs, SR-IOV, …).
88 */
89 networkConfig: BareMetalNetworkConfig;
90 /**
91 * Load balancer configuration (MetalLB, BGP, or manual).
92 */
93 loadBalancer: BareMetalLoadBalancerConfig;
94 /**
95 * Human-readable description. Clusters have no GCP labels field, so
96 * Alchemy stamps ownership into annotations and a `[alchemy …]`
97 * description prefix and strips both from attributes.
98 */
99 description?: string;
100 /**
101 * Security / bootstrap RBAC configuration.
102 */
103 securityConfig?: BareMetalSecurityConfig;
104 /**
105 * HTTP(S) proxy used by cluster machines.
106 */
107 proxy?: BareMetalProxyConfig;
108 /**
109 * Cluster upgrade policy.
110 */
111 upgradePolicy?: BareMetalClusterUpgradePolicy;
112 /**
113 * SSH login user for node machines.
114 */
115 nodeAccessConfig?: BareMetalNodeAccessConfig;
116 /**
117 * CIDRs whose nodes are placed into maintenance.
118 */
119 maintenanceConfig?: BareMetalMaintenanceConfig;
120 /**
121 * Binary Authorization evaluation mode.
122 */
123 binaryAuthorization?: BinaryAuthorization;
124 /**
125 * Workload node defaults (max pods, container runtime).
126 */
127 nodeConfig?: BareMetalWorkloadNodeConfig;
128 /**
129 * Observability: application logs and metrics.
130 */
131 clusterOperations?: BareMetalClusterOperationsConfig;
132 /**
133 * OS environment settings (package repo).
134 */
135 osEnvironmentConfig?: BareMetalOsEnvironmentConfig;
136 /**
137 * Kubernetes-style annotations. Alchemy ownership keys are merged in.
138 */
139 annotations?: Record<string, string>;
140 /**
141 * User labels stored as annotations (keys sanitized like GCP labels).
142 * Alchemy ownership labels are merged in automatically.
143 */
144 labels?: Record<string, string>;
145 };
146
147 export type BareMetalCluster = Resource<
148 "GCP.GKEOnPrem.BareMetalCluster",
149 BareMetalClusterProps,
150 {
151 /** Full resource name. */
152 name: string;
153 /** Cluster id (last path segment). */
154 bareMetalClusterId: string;
155 /** Project id. */
156 project: string;
157 /** Location id. */
158 location: string;
159 /** Admin cluster Hub membership. */
160 adminClusterMembership: string | undefined;
161 /** Output-only admin cluster resource name. */
162 adminClusterName: string | undefined;
163 /** Anthos on-prem version. */
164 bareMetalVersion: string | undefined;
165 /** Control plane configuration. */
166 controlPlane: gkeonprem.BareMetalControlPlaneConfig | undefined;
167 /** Storage configuration. */
168 storage: gkeonprem.BareMetalStorageConfig | undefined;
169 /** Network configuration. */
170 networkConfig: gkeonprem.BareMetalNetworkConfig | undefined;
171 /** Load balancer configuration. */
172 loadBalancer: gkeonprem.BareMetalLoadBalancerConfig | undefined;
173 /** User description with the Alchemy ownership prefix stripped. */
174 description: string | undefined;
175 /** Security configuration. */
176 securityConfig: gkeonprem.BareMetalSecurityConfig | undefined;
177 /** Proxy configuration. */
178 proxy: gkeonprem.BareMetalProxyConfig | undefined;
179 /** Upgrade policy. */
180 upgradePolicy: gkeonprem.BareMetalClusterUpgradePolicy | undefined;
181 /** Node access configuration. */
182 nodeAccessConfig: gkeonprem.BareMetalNodeAccessConfig | undefined;
183 /** Maintenance configuration. */
184 maintenanceConfig: gkeonprem.BareMetalMaintenanceConfig | undefined;
185 /** Binary Authorization configuration. */
186 binaryAuthorization: gkeonprem.BinaryAuthorization | undefined;
187 /** Workload node defaults. */
188 nodeConfig: gkeonprem.BareMetalWorkloadNodeConfig | undefined;
189 /** Cluster operations configuration. */
190 clusterOperations: gkeonprem.BareMetalClusterOperationsConfig | undefined;
191 /** OS environment configuration. */
192 osEnvironmentConfig: gkeonprem.BareMetalOsEnvironmentConfig | undefined;
193 /** User annotations (Alchemy ownership keys stripped). */
194 annotations: Record<string, string>;
195 /** User labels (Alchemy ownership keys stripped). */
196 labels: Record<string, string>;
197 /** Output-only Kubernetes API endpoint. */
198 endpoint: string | undefined;
199 /** Output-only Fleet membership. */
200 fleet: gkeonprem.Fleet | undefined;
201 /** Local CR name on the admin cluster. */
202 localName: string | undefined;
203 /** Local namespace on the admin cluster. */
204 localNamespace: string | undefined;
205 /** Server-reported state. */
206 state: string | undefined;
207 /** Server-generated resource uid. */
208 uid: string | undefined;
209 /** Whether a change is in flight. */
210 reconciling: boolean | undefined;
211 /** Controller error message. */
212 errorMessage: string | undefined;
213 /** RFC3339 creation timestamp. */
214 createTime: string | undefined;
215 /** RFC3339 last-update timestamp. */
216 updateTime: string | undefined;
217 /** RFC3339 deletion timestamp. */
218 deleteTime: string | undefined;
219 /** Server etag. */
220 etag: string | undefined;
221 },
222 never,
223 Providers
224 >;
225
226 /**
227 * An Anthos on bare metal user cluster registered with the GKE On-Prem
228 * API. Creating a cluster requires a connected admin cluster (Hub
229 * membership) and on-prem hardware.
230 *
231 * Clusters have no GCP labels field, so Alchemy stamps ownership into
232 * annotations and a `[alchemy …]` description prefix for `list` / nuke.
233 * Cluster id, location, and admin membership are identity — changing
234 * them replaces the cluster. Other fields update in place.
235 *
236 * ### Creating a Bare Metal Cluster
237 * **Example:** User cluster with MetalLB
238 * ```typescript
239 * const cluster = yield* GCP.GKEOnPrem.BareMetalCluster("Workload", {
240 * adminClusterMembership:
241 * "projects/my-project/locations/global/memberships/admin",
242 * bareMetalVersion: "1.28.0-gke.1",
243 * controlPlane: {
244 * controlPlaneNodePoolConfig: {
245 * nodePoolConfig: {
246 * nodeConfigs: [{ nodeIp: "10.200.0.2" }],
247 * },
248 * },
249 * },
250 * storage: {
251 * lvpShareConfig: {
252 * lvpConfig: { path: "/mnt/localpv-share", storageClass: "local-shared" },
253 * },
254 * lvpNodeMountsConfig: {
255 * path: "/mnt/localpv-disk",
256 * storageClass: "local-disks",
257 * },
258 * },
259 * networkConfig: {
260 * islandModeCidr: {
261 * serviceAddressCidrBlocks: ["10.96.0.0/12"],
262 * podAddressCidrBlocks: ["192.168.0.0/16"],
263 * },
264 * },
265 * loadBalancer: {
266 * vipConfig: { controlPlaneVip: "10.200.0.8", ingressVip: "10.200.0.9" },
267 * metalLbConfig: {
268 * addressPools: [{ pool: "pool-1", addresses: ["10.200.0.10-10.200.0.20"] }],
269 * },
270 * },
271 * description: "app user cluster",
272 * });
273 * ```
274 *
275 * ### Updating a Bare Metal Cluster
276 * Re-declare the same logical id with changed props; the engine keeps the
277 * physical resource and updates it in place.
278 *
279 * **Example:** Description and version
280 * ```typescript
281 * const cluster = yield* GCP.GKEOnPrem.BareMetalCluster("Workload", {
282 * adminClusterMembership:
283 * "projects/my-project/locations/global/memberships/admin",
284 * bareMetalVersion: "1.29.0-gke.1",
285 * controlPlane: {
286 * controlPlaneNodePoolConfig: {
287 * nodePoolConfig: {
288 * nodeConfigs: [{ nodeIp: "10.200.0.2" }],
289 * },
290 * },
291 * },
292 * storage: {
293 * lvpShareConfig: {
294 * lvpConfig: { path: "/mnt/localpv-share", storageClass: "local-shared" },
295 * },
296 * lvpNodeMountsConfig: {
297 * path: "/mnt/localpv-disk",
298 * storageClass: "local-disks",
299 * },
300 * },
301 * networkConfig: {
302 * islandModeCidr: {
303 * serviceAddressCidrBlocks: ["10.96.0.0/12"],
304 * podAddressCidrBlocks: ["192.168.0.0/16"],
305 * },
306 * },
307 * loadBalancer: {
308 * vipConfig: { controlPlaneVip: "10.200.0.8", ingressVip: "10.200.0.9" },
309 * metalLbConfig: {
310 * addressPools: [{ pool: "pool-1", addresses: ["10.200.0.10-10.200.0.20"] }],
311 * },
312 * },
313 * description: "app user cluster v2",
314 * });
315 * ```
316 *
317 * @resource
318 * @category GKEOnPrem
319 */
320 export const BareMetalCluster = Resource<BareMetalCluster>("GCP.GKEOnPrem.BareMetalCluster");
321
322 const resourceName = (project: string, location: string, bareMetalClusterId: string) =>
323 `${parentOf(project, location)}/${COLLECTION}/${bareMetalClusterId}`;
324
325 const toAttrs = (item: gkeonprem.BareMetalCluster, project: string, region: string) => {
326 const name = item.name ?? "";
327 const parsed = parseName(name, COLLECTION, region);
328 const ownership = parseOwnership(item.description);
329 const annotations = userLabels(item.annotations);
330 return {
331 name,
332 bareMetalClusterId: parsed.id,
333 project: parsed.project || project,
334 location: parsed.location,
335 adminClusterMembership: item.adminClusterMembership,
336 adminClusterName: item.adminClusterName,
337 bareMetalVersion: item.bareMetalVersion,
338 controlPlane: item.controlPlane,
339 storage: item.storage,
340 networkConfig: item.networkConfig,
341 loadBalancer: item.loadBalancer,
342 description: ownership.text,
343 securityConfig: item.securityConfig,
344 proxy: item.proxy,
345 upgradePolicy: item.upgradePolicy,
346 nodeAccessConfig: item.nodeAccessConfig,
347 maintenanceConfig: item.maintenanceConfig,
348 binaryAuthorization: item.binaryAuthorization,
349 nodeConfig: item.nodeConfig,
350 clusterOperations: item.clusterOperations,
351 osEnvironmentConfig: item.osEnvironmentConfig,
352 annotations,
353 labels: annotations,
354 endpoint: item.endpoint,
355 fleet: item.fleet,
356 localName: item.localName,
357 localNamespace: item.localNamespace,
358 state: textState(item.state),
359 uid: item.uid,
360 reconciling: item.reconciling,
361 errorMessage: item.status?.errorMessage,
362 createTime: item.createTime,
363 updateTime: item.updateTime,
364 deleteTime: item.deleteTime,
365 etag: item.etag,
366 };
367 };
368
369 const getByName = (name: string) =>
370 gkeonprem
371 .getProjectsLocationsBareMetalClusters({ name, view: "FULL" })
372 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
373
374 const listOwned = (project: string, region: string) =>
375 listAtLocation(project, region, (parent) =>
376 collectPages(
377 gkeonprem.listProjectsLocationsBareMetalClusters.pages({
378 parent,
379 pageSize: 1000,
380 view: "FULL",
381 }),
382 (page): readonly gkeonprem.BareMetalCluster[] | undefined => page.bareMetalClusters,
383 ),
384 ).pipe(
385 Effect.map((items) =>
386 items.filter((item: gkeonprem.BareMetalCluster) =>
387 isOwned(item.annotations, item.description),
388 ),
389 ),
390 );
391
392 const toBody = (
393 news: BareMetalClusterProps,
394 annotations: Record<string, string>,
395 description: string,
396 membership: string,
397 ): gkeonprem.BareMetalCluster => ({
398 adminClusterMembership: membership,
399 bareMetalVersion: news.bareMetalVersion,
400 controlPlane: news.controlPlane,
401 storage: news.storage,
402 networkConfig: news.networkConfig,
403 loadBalancer: news.loadBalancer,
404 description,
405 securityConfig: news.securityConfig,
406 proxy: news.proxy,
407 upgradePolicy: news.upgradePolicy,
408 nodeAccessConfig: news.nodeAccessConfig,
409 maintenanceConfig: news.maintenanceConfig,
410 binaryAuthorization: news.binaryAuthorization,
411 nodeConfig: news.nodeConfig,
412 clusterOperations: news.clusterOperations,
413 osEnvironmentConfig: news.osEnvironmentConfig,
414 annotations,
415 });
416
417 export const BareMetalClusterProvider = () =>
418 Provider.succeed(BareMetalCluster, {
419 stables: ["name", "bareMetalClusterId", "project", "location", "uid", "createTime"],
420
421 diff: Effect.fn(function* ({ news, olds, output }) {
422 if (!isResolved(news)) return undefined;
423 const env = yield* GcpEnvironment.current;
424 const previousMembership = olds?.adminClusterMembership ?? output?.adminClusterMembership;
425 const nextMembership = news.adminClusterMembership;
426 return replaceOnIdentity({
427 previousId: olds?.bareMetalClusterId ?? output?.bareMetalClusterId,
428 nextId: news.bareMetalClusterId
429 ? rfc1035(news.bareMetalClusterId, "baremetalcluster")
430 : (olds?.bareMetalClusterId ?? output?.bareMetalClusterId),
431 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
432 nextLocation: normalizeLocation(
433 news.location ?? olds?.location ?? output?.location,
434 env.region,
435 ),
436 extra:
437 previousMembership !== undefined &&
438 nextMembership !== undefined &&
439 previousMembership !== nextMembership &&
440 !previousMembership.endsWith(`/${nextMembership}`),
441 });
442 }),
443
444 read: Effect.fn(function* ({ id, olds, output }) {
445 const env = yield* GcpEnvironment.current;
446 const bareMetalClusterId = yield* toPhysicalId(
447 id,
448 olds?.bareMetalClusterId,
449 output?.bareMetalClusterId,
450 "baremetalcluster",
451 );
452 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
453 const name = output?.name ?? resourceName(env.project, location, bareMetalClusterId);
454 const existing = yield* getByName(name);
455 if (existing === undefined) return undefined;
456 const attrs = toAttrs(existing, env.project, env.region);
457 const fromDescription = parseOwnership(existing.description).labels;
458 const owned =
459 (yield* hasAlchemyLabels(id, tagRecord(existing.annotations))) ||
460 (yield* hasAlchemyLabels(id, fromDescription));
461 return owned ? attrs : Unowned(attrs);
462 }),
463
464 list: () =>
465 Effect.gen(function* () {
466 const env = yield* GcpEnvironment.current;
467 const items = yield* listOwned(env.project, env.region);
468 return items.map((item: gkeonprem.BareMetalCluster) =>
469 toAttrs(item, env.project, env.region),
470 );
471 }),
472
473 reconcile: Effect.fn(function* ({ id, news, output }) {
474 const env = yield* GcpEnvironment.current;
475 const bareMetalClusterId = yield* toPhysicalId(
476 id,
477 news.bareMetalClusterId,
478 output?.bareMetalClusterId,
479 "baremetalcluster",
480 );
481 const location = normalizeLocation(news.location ?? output?.location, env.region);
482 const name = resourceName(env.project, location, bareMetalClusterId);
483 const ownership = yield* createInternalLabels(id);
484 const annotations = desiredAnnotations(ownership, news.labels, news.annotations);
485 const description = encodeOwnership(ownership, news.description);
486 const membership = membershipName(news.adminClusterMembership, env.project);
487 const body = toBody(news, annotations, description, membership);
488
489 let current = yield* getByName(output?.name ?? name);
490
491 if (current === undefined) {
492 const created = yield* gkeonprem
493 .createProjectsLocationsBareMetalClusters({
494 parent: parentOf(env.project, location),
495 bareMetalClusterId,
496 body,
497 })
498 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
499 if (created !== undefined) {
500 yield* waitForOperation(created);
501 }
502 current = yield* waitUntilExists(getByName(name), name);
503 }
504
505 if (current === undefined) {
506 return yield* new ResourceNotResolved({ resourceName: name });
507 }
508
509 const mask = fieldMask([
510 differs(current.annotations, annotations) && "annotations",
511 !sameText(parseOwnership(current.description).text, news.description) && "description",
512 differs(current.bareMetalVersion, news.bareMetalVersion) && "bareMetalVersion",
513 differs(current.controlPlane, news.controlPlane) && "controlPlane",
514 differs(current.storage, news.storage) && "storage",
515 differs(current.networkConfig, news.networkConfig) && "networkConfig",
516 differs(current.loadBalancer, news.loadBalancer) && "loadBalancer",
517 differs(current.securityConfig, news.securityConfig) && "securityConfig",
518 differs(current.proxy, news.proxy) && "proxy",
519 differs(current.upgradePolicy, news.upgradePolicy) && "upgradePolicy",
520 differs(current.nodeAccessConfig, news.nodeAccessConfig) && "nodeAccessConfig",
521 differs(current.maintenanceConfig, news.maintenanceConfig) && "maintenanceConfig",
522 differs(current.binaryAuthorization, news.binaryAuthorization) && "binaryAuthorization",
523 differs(current.nodeConfig, news.nodeConfig) && "nodeConfig",
524 differs(current.clusterOperations, news.clusterOperations) && "clusterOperations",
525 differs(current.osEnvironmentConfig, news.osEnvironmentConfig) && "osEnvironmentConfig",
526 ]);
527
528 if (mask.length > 0) {
529 const operation = yield* gkeonprem.patchProjectsLocationsBareMetalClusters({
530 name: current.name ?? name,
531 updateMask: mask,
532 body: {
533 ...body,
534 etag: current.etag,
535 },
536 });
537 yield* waitForOperation(operation);
538 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
539 }
540
541 if (current === undefined) {
542 return yield* new ResourceNotResolved({ resourceName: name });
543 }
544 return toAttrs(current, env.project, env.region);
545 }),
546
547 delete: Effect.fn(function* ({ output }) {
548 const operation = yield* gkeonprem
549 .deleteProjectsLocationsBareMetalClusters({
550 name: output.name,
551 allowMissing: true,
552 force: true,
553 etag: output.etag,
554 })
555 .pipe(
556 Effect.retry({
557 while: (error) => error._tag === "Conflict",
558 times: 8,
559 schedule: Schedule.spaced("2 seconds"),
560 }),
561 Effect.catchTag("NotFound", () => Effect.undefined),
562 );
563 if (operation !== undefined) {
564 yield* waitForOperation(operation, { notFoundOk: true });
565 }
566 yield* waitUntilGone(getByName(output.name), output.name);
567 }),
568 });