@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 1,107 lines 40.7 KB
Raw
1 import { deleteObjects, reconcileObjects } from "@alchemy.run/kubernetes/Client";
2 import type { Connection } from "@alchemy.run/kubernetes/Connection";
3 import {
4 type KubernetesObjectBinding,
5 type KubernetesObjectDefinition,
6 type KubernetesObjectRef,
7 } from "@alchemy.run/kubernetes/Objects";
8 import * as eks from "@distilled.cloud/aws/eks";
9 import * as iam from "@distilled.cloud/aws/iam";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource, type ResourceBinding } from "alchemy/Resource";
15 import { createInternalTags, diffTags, hasAlchemyTags, hasTags } from "alchemy/Tags";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import * as Schedule from "effect/Schedule";
19 import * as Stream from "effect/Stream";
20 import type { AccountID } from "../Environment.ts";
21 import type { Providers } from "../Providers.ts";
22 import type { RegionID } from "../Region.ts";
23 import { eksConnectionOf, makeEksTransport } from "./KubernetesAdapter.ts";
24
25 export class EKSClusterUnexpectedResponse extends Data.TaggedError("EKSClusterUnexpectedResponse")<{
26 readonly message: string;
27 readonly cause?: unknown;
28 }> {}
29
30 export class EKSClusterInvalidProps extends Data.TaggedError("EKSClusterInvalidProps")<{
31 readonly message: string;
32 readonly cause?: unknown;
33 }> {}
34
35 export class EKSClusterConflict extends Data.TaggedError("EKSClusterConflict")<{
36 readonly message: string;
37 readonly cause?: unknown;
38 }> {}
39
40 export class EKSClusterOperationFailed extends Data.TaggedError("EKSClusterOperationFailed")<{
41 readonly message: string;
42 readonly cause?: unknown;
43 }> {}
44
45 export type ClusterName = string;
46 export type ClusterArn = `arn:aws:eks:${RegionID}:${AccountID}:cluster/${ClusterName}`;
47
48 export interface ClusterProps {
49 /**
50 * Cluster name. If omitted, a unique name is generated.
51 */
52 clusterName?: string;
53 /**
54 * `"auto"` turns on EKS Auto Mode with sensible defaults: managed compute
55 * (`system` + `general-purpose` node pools), block storage, elastic load
56 * balancing, and `API` authentication with bootstrap admin permissions.
57 * When `roleArn` (or `computeConfig.nodeRoleArn`) is omitted, the cluster
58 * provisions and owns the required IAM roles with the standard Auto Mode
59 * managed policies. Explicit `accessConfig` / `computeConfig` /
60 * `storageConfig` / `kubernetesNetworkConfig` props override the defaults.
61 */
62 compute?: "auto";
63 /**
64 * IAM role ARN assumed by the EKS control plane. Required unless
65 * `compute: "auto"`, in which case an Auto Mode cluster role is created
66 * and managed automatically when omitted.
67 */
68 roleArn?: string;
69 /**
70 * VPC configuration for the cluster control plane.
71 */
72 resourcesVpcConfig: eks.VpcConfigRequest;
73 /**
74 * Desired Kubernetes version.
75 */
76 version?: string;
77 /**
78 * Cluster access configuration.
79 */
80 accessConfig?: eks.CreateAccessConfigRequest;
81 /**
82 * Auto Mode compute configuration.
83 */
84 computeConfig?: eks.ComputeConfigRequest;
85 /**
86 * Auto Mode storage configuration.
87 */
88 storageConfig?: eks.StorageConfigRequest;
89 /**
90 * Kubernetes network configuration.
91 */
92 kubernetesNetworkConfig?: eks.KubernetesNetworkConfigRequest;
93 /**
94 * Control plane logging configuration.
95 */
96 logging?: eks.Logging;
97 /**
98 * Upgrade support policy for the cluster.
99 */
100 upgradePolicy?: eks.UpgradePolicyRequest;
101 /**
102 * Whether deletion protection is enabled.
103 * @default false
104 */
105 deletionProtection?: boolean;
106 /**
107 * User-defined tags to apply to the cluster.
108 */
109 tags?: Record<string, string>;
110 }
111
112 export interface Cluster extends Resource<
113 "AWS.EKS.Cluster",
114 ClusterProps,
115 {
116 /** The ARN of the cluster. */
117 clusterArn: ClusterArn;
118 /** The name of the cluster. */
119 clusterName: ClusterName;
120 /** The cluster status (e.g. `CREATING`, `ACTIVE`, `UPDATING`). */
121 status: string;
122 /** The Kubernetes API server endpoint URL. */
123 endpoint: string | undefined;
124 /** The base64-encoded certificate authority data for the cluster. */
125 certificateAuthorityData: string | undefined;
126 /** The Kubernetes version the cluster is running (e.g. `1.31`). */
127 version: string | undefined;
128 /** The EKS platform version of the cluster. */
129 platformVersion: string | undefined;
130 /** The ARN of the IAM role the EKS control plane assumes. */
131 roleArn: string;
132 /** The VPC configuration of the cluster (subnets, security groups, endpoint access). */
133 resourcesVpcConfig: eks.VpcConfigResponse;
134 /** The access configuration (authentication mode, bootstrap admin). */
135 accessConfig: eks.AccessConfigResponse | undefined;
136 /** The EKS Auto Mode compute configuration, if enabled. */
137 computeConfig: eks.ComputeConfigResponse | undefined;
138 /** The EKS Auto Mode block storage configuration, if enabled. */
139 storageConfig: eks.StorageConfigResponse | undefined;
140 /** The Kubernetes network configuration (service CIDR, IP family, elastic load balancing). */
141 kubernetesNetworkConfig: eks.KubernetesNetworkConfigResponse | undefined;
142 /** The control-plane log types shipped to CloudWatch. */
143 logging: eks.Logging | undefined;
144 /** The cluster's upgrade policy (support type). */
145 upgradePolicy: eks.UpgradePolicyResponse | undefined;
146 /** Whether deletion protection is enabled on the cluster. */
147 deletionProtection: boolean;
148 /** The OIDC identity provider issuer URL for the cluster. */
149 oidcIssuer: string | undefined;
150 /** The tags applied to the cluster. */
151 tags: Record<string, string>;
152 /** References to Kubernetes objects applied via `kubernetes` props. */
153 kubernetesObjects: KubernetesObjectRef[];
154 /**
155 * The cluster-agnostic `Kubernetes.Connection` for this cluster.
156 * Passing the whole cluster resource as a `Kubernetes.*` workload's
157 * `cluster` prop resolves through this — auth uses SigV4 tokens
158 * minted from the ambient AWS credentials.
159 */
160 connection: Connection;
161 /** The name of the cluster IAM role created for `compute: "auto"`, if managed by alchemy. */
162 managedClusterRoleName: string | undefined;
163 /** The name of the node IAM role created for `compute: "auto"`, if managed by alchemy. */
164 managedNodeRoleName: string | undefined;
165 },
166 KubernetesObjectBinding,
167 Providers
168 > {}
169
170 /**
171 * An Amazon EKS cluster with support for EKS Auto Mode settings.
172 * ### Creating Clusters
173 * **Example:** Auto Mode Cluster (managed roles)
174 * ```typescript
175 * const cluster = yield* Cluster("AppCluster", {
176 * compute: "auto",
177 * resourcesVpcConfig: {
178 * subnetIds: network.privateSubnetIds,
179 * },
180 * });
181 * ```
182 *
183 * **Example:** Auto Mode Cluster from Existing Roles and Subnets
184 * ```typescript
185 * const cluster = yield* Cluster("AppCluster", {
186 * roleArn: clusterRole.roleArn,
187 * resourcesVpcConfig: {
188 * subnetIds: network.privateSubnetIds,
189 * endpointPublicAccess: true,
190 * endpointPrivateAccess: true,
191 * },
192 * accessConfig: {
193 * authenticationMode: "API",
194 * },
195 * computeConfig: {
196 * enabled: true,
197 * nodeRoleArn: nodeRole.roleArn,
198 * nodePools: ["system", "general-purpose"],
199 * },
200 * kubernetesNetworkConfig: {
201 * elasticLoadBalancing: { enabled: true },
202 * },
203 * storageConfig: {
204 * blockStorage: { enabled: true },
205 * },
206 * });
207 * ```
208 *
209 * ### Running Workloads
210 * **Example:** Cluster with a Managed Node Group and an Add-on
211 * ```typescript
212 * const cluster = yield* AWS.EKS.Cluster("AppCluster", {
213 * roleArn: clusterRole.roleArn,
214 * resourcesVpcConfig: { subnetIds: network.privateSubnetIds },
215 * accessConfig: { authenticationMode: "API" },
216 * });
217 *
218 * const nodes = yield* AWS.EKS.Nodegroup("AppNodes", {
219 * clusterName: cluster.clusterName,
220 * nodeRole: nodeRole.roleArn,
221 * subnets: network.privateSubnetIds,
222 * instanceTypes: ["t3.medium"],
223 * scalingConfig: { minSize: 1, maxSize: 2, desiredSize: 1 },
224 * });
225 *
226 * const metricsServer = yield* AWS.EKS.Addon("MetricsServer", {
227 * clusterName: cluster.clusterName,
228 * addonName: "metrics-server",
229 * });
230 * ```
231 *
232 * @resource
233 */
234 export const Cluster = Resource<Cluster>("AWS.EKS.Cluster");
235
236 class ClusterNotReady extends Data.TaggedError("EKS.ClusterNotReady")<{
237 status: string | undefined;
238 }> {}
239
240 class ClusterStillExists extends Data.TaggedError("EKS.ClusterStillExists")<{}> {}
241
242 class ClusterUpdateNotComplete extends Data.TaggedError("EKS.ClusterUpdateNotComplete")<{
243 status: eks.UpdateStatus | undefined;
244 }> {}
245
246 const normalizeTags = (tags: Record<string, string | undefined> | undefined) =>
247 Object.fromEntries(
248 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
249 );
250
251 // Wait budget: ~30 min at 10s spacing. Cluster create/delete takes ~10–15 min
252 // and async config/version updates ~5–15 min. The interval MUST be flat, not
253 // exponential: `Schedule.exponential` with no delay cap sleeps 8.5/17/34 min
254 // between late attempts — a silent multi-minute park that presents as a
255 // deadlocked (0% CPU, no output) deploy and blows any hook budget.
256 const updateRetrySchedule = Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(180)]);
257
258 const getKubernetesTransport = (
259 state: Pick<
260 Cluster["Attributes"],
261 "clusterArn" | "clusterName" | "endpoint" | "certificateAuthorityData"
262 >,
263 ) =>
264 Effect.suspend(() => {
265 if (!state.endpoint || !state.certificateAuthorityData) {
266 throw new Error(
267 `EKS cluster '${state.clusterName}' is missing endpoint or certificate authority data`,
268 );
269 }
270 return makeEksTransport({
271 clusterName: state.clusterName,
272 region: regionOfClusterArn(state.clusterArn),
273 endpoint: state.endpoint,
274 certificateAuthorityData: state.certificateAuthorityData,
275 });
276 });
277
278 /** The region segment of a cluster ARN (`arn:aws:eks:REGION:...`). */
279 const regionOfClusterArn = (arn: string | undefined): string | undefined =>
280 arn?.split(":")[3] || undefined;
281
282 const getDesiredKubernetesObjects = (
283 bindings: ReadonlyArray<ResourceBinding<KubernetesObjectBinding>>,
284 ): KubernetesObjectDefinition[] =>
285 bindings
286 .filter(
287 (binding): binding is ResourceBinding<KubernetesObjectBinding> =>
288 binding.data.type === "kubernetes-object",
289 )
290 .map((binding) => binding.data.object);
291
292 const autoClusterManagedPolicyArns = [
293 "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
294 "arn:aws:iam::aws:policy/AmazonEKSComputePolicy",
295 "arn:aws:iam::aws:policy/AmazonEKSBlockStoragePolicy",
296 "arn:aws:iam::aws:policy/AmazonEKSLoadBalancingPolicy",
297 "arn:aws:iam::aws:policy/AmazonEKSNetworkingPolicy",
298 ];
299
300 const autoNodeManagedPolicyArns = [
301 "arn:aws:iam::aws:policy/AmazonEKSWorkerNodeMinimalPolicy",
302 "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPullOnly",
303 ];
304
305 /**
306 * Expand `compute: "auto"` into the concrete EKS Auto Mode configuration
307 * (explicit user props always win over the defaults).
308 */
309 const applyAutoModeDefaults = (
310 news: ClusterProps,
311 roles: { roleArn: string; nodeRoleArn: string | undefined },
312 ): ClusterProps & { roleArn: string } =>
313 news.compute === "auto"
314 ? {
315 ...news,
316 roleArn: roles.roleArn,
317 accessConfig: {
318 bootstrapClusterCreatorAdminPermissions: true,
319 authenticationMode: "API",
320 ...news.accessConfig,
321 },
322 computeConfig: {
323 enabled: true,
324 nodePools: ["system", "general-purpose"],
325 ...news.computeConfig,
326 nodeRoleArn: roles.nodeRoleArn,
327 },
328 kubernetesNetworkConfig: {
329 ...news.kubernetesNetworkConfig,
330 elasticLoadBalancing: {
331 enabled: true,
332 ...news.kubernetesNetworkConfig?.elasticLoadBalancing,
333 },
334 },
335 storageConfig: {
336 blockStorage: {
337 enabled: true,
338 ...news.storageConfig?.blockStorage,
339 },
340 },
341 }
342 : { ...news, roleArn: roles.roleArn };
343
344 const stringSetEqual = (a: readonly string[] | undefined, b: readonly string[] | undefined) =>
345 JSON.stringify([...(a ?? [])].sort()) === JSON.stringify([...(b ?? [])].sort());
346
347 /** Flatten an EKS `Logging` shape into a `logType -> enabled` map. */
348 const loggingByType = (logging: eks.Logging | undefined) => {
349 const byType: Record<string, boolean> = {};
350 for (const setup of logging?.clusterLogging ?? []) {
351 for (const type of setup.types ?? []) {
352 byType[type] = setup.enabled ?? false;
353 }
354 }
355 return byType;
356 };
357
358 interface ClusterConfigUpdate {
359 /** Stable category slug — also feeds the per-category idempotency token. */
360 category: string;
361 request: Omit<eks.UpdateClusterConfigRequest, "name" | "clientRequestToken">;
362 }
363
364 /**
365 * Plan the `updateClusterConfig` calls needed to converge observed cloud
366 * state to the desired props.
367 *
368 * EKS's UpdateClusterConfig API accepts exactly ONE update category per call
369 * (`InvalidParameterException: Only one type of update can be allowed.`), so
370 * drift is computed per category and each drifted category becomes its own
371 * request — the caller issues them serially, waiting for each async update
372 * to complete before the next.
373 *
374 * Comparison is desired-subset only: a field the user did not specify is
375 * "don't care" and is never diffed against server-populated response fields
376 * (vpcId, clusterSecurityGroupId, default upgradePolicy, ...). A freshly
377 * created cluster therefore plans zero updates.
378 */
379 const planClusterConfigUpdates = (
380 observed: Cluster["Attributes"],
381 desired: ClusterProps,
382 ): ClusterConfigUpdate[] => {
383 const updates: ClusterConfigUpdate[] = [];
384
385 // Access config — authenticationMode is the only mutable field.
386 const desiredAuthMode = desired.accessConfig?.authenticationMode;
387 if (
388 desiredAuthMode !== undefined &&
389 desiredAuthMode !== observed.accessConfig?.authenticationMode
390 ) {
391 updates.push({
392 category: "access",
393 request: { accessConfig: { authenticationMode: desiredAuthMode } },
394 });
395 }
396
397 // Auto Mode trio — computeConfig, storageConfig and kubernetesNetworkConfig
398 // count as ONE update category and must ship together in a single call.
399 const desiredCompute = desired.computeConfig;
400 const observedCompute = observed.computeConfig;
401 const computeDrift =
402 desiredCompute !== undefined &&
403 ((desiredCompute.enabled !== undefined &&
404 desiredCompute.enabled !== (observedCompute?.enabled ?? false)) ||
405 (desiredCompute.nodePools !== undefined &&
406 !stringSetEqual(desiredCompute.nodePools, observedCompute?.nodePools)) ||
407 (desiredCompute.nodeRoleArn !== undefined &&
408 desiredCompute.nodeRoleArn !== observedCompute?.nodeRoleArn));
409 const desiredBlockStorage = desired.storageConfig?.blockStorage?.enabled;
410 const storageDrift =
411 desiredBlockStorage !== undefined &&
412 desiredBlockStorage !== (observed.storageConfig?.blockStorage?.enabled ?? false);
413 const desiredElb = desired.kubernetesNetworkConfig?.elasticLoadBalancing?.enabled;
414 const elbDrift =
415 desiredElb !== undefined &&
416 desiredElb !== (observed.kubernetesNetworkConfig?.elasticLoadBalancing?.enabled ?? false);
417 if (computeDrift || storageDrift || elbDrift) {
418 updates.push({
419 category: "auto-mode",
420 request: {
421 computeConfig: desiredCompute ?? {
422 enabled: observedCompute?.enabled ?? false,
423 nodePools: observedCompute?.nodePools,
424 nodeRoleArn: observedCompute?.nodeRoleArn,
425 },
426 storageConfig: {
427 blockStorage: {
428 enabled: desiredBlockStorage ?? observed.storageConfig?.blockStorage?.enabled ?? false,
429 },
430 },
431 // serviceIpv4Cidr / ipFamily are create-only (diff replaces on
432 // change) — never send them on update.
433 kubernetesNetworkConfig: {
434 elasticLoadBalancing: {
435 enabled:
436 desiredElb ??
437 observed.kubernetesNetworkConfig?.elasticLoadBalancing?.enabled ??
438 false,
439 },
440 },
441 },
442 });
443 }
444
445 // VPC endpoint access (public/private endpoint + public access CIDRs).
446 const desiredVpc = desired.resourcesVpcConfig;
447 const observedVpc = observed.resourcesVpcConfig;
448 const endpointPublicDrift =
449 desiredVpc.endpointPublicAccess !== undefined &&
450 desiredVpc.endpointPublicAccess !== observedVpc.endpointPublicAccess;
451 const endpointPrivateDrift =
452 desiredVpc.endpointPrivateAccess !== undefined &&
453 desiredVpc.endpointPrivateAccess !== observedVpc.endpointPrivateAccess;
454 const publicCidrsDrift =
455 desiredVpc.publicAccessCidrs !== undefined &&
456 !stringSetEqual(desiredVpc.publicAccessCidrs, observedVpc.publicAccessCidrs);
457 if (endpointPublicDrift || endpointPrivateDrift || publicCidrsDrift) {
458 updates.push({
459 category: "vpc-endpoint",
460 request: {
461 resourcesVpcConfig: {
462 endpointPublicAccess: desiredVpc.endpointPublicAccess,
463 endpointPrivateAccess: desiredVpc.endpointPrivateAccess,
464 publicAccessCidrs: desiredVpc.publicAccessCidrs,
465 },
466 },
467 });
468 }
469
470 // VPC subnet / security-group membership — separate from endpoint access.
471 const subnetsDrift =
472 desiredVpc.subnetIds !== undefined &&
473 !stringSetEqual(desiredVpc.subnetIds, observedVpc.subnetIds);
474 const securityGroupsDrift =
475 desiredVpc.securityGroupIds !== undefined &&
476 !stringSetEqual(desiredVpc.securityGroupIds, observedVpc.securityGroupIds);
477 if (subnetsDrift || securityGroupsDrift) {
478 updates.push({
479 category: "vpc-network",
480 request: {
481 resourcesVpcConfig: {
482 subnetIds: desiredVpc.subnetIds,
483 securityGroupIds: desiredVpc.securityGroupIds,
484 },
485 },
486 });
487 }
488
489 // Control-plane logging — compare per log type; types the user didn't
490 // mention are "don't care".
491 if (desired.logging !== undefined) {
492 const observedLogging = loggingByType(observed.logging);
493 const desiredLogging = loggingByType(desired.logging);
494 if (
495 Object.entries(desiredLogging).some(
496 ([type, enabled]) => (observedLogging[type] ?? false) !== enabled,
497 )
498 ) {
499 updates.push({
500 category: "logging",
501 request: { logging: desired.logging },
502 });
503 }
504 }
505
506 // Upgrade policy.
507 if (
508 desired.upgradePolicy?.supportType !== undefined &&
509 desired.upgradePolicy.supportType !== observed.upgradePolicy?.supportType
510 ) {
511 updates.push({
512 category: "upgrade-policy",
513 request: { upgradePolicy: desired.upgradePolicy },
514 });
515 }
516
517 // Deletion protection.
518 if (
519 desired.deletionProtection !== undefined &&
520 desired.deletionProtection !== observed.deletionProtection
521 ) {
522 updates.push({
523 category: "deletion-protection",
524 request: { deletionProtection: desired.deletionProtection },
525 });
526 }
527
528 return updates;
529 };
530
531 const mapClusterState = (
532 cluster: eks.Cluster,
533 tags: Record<string, string>,
534 kubernetesObjects: KubernetesObjectRef[],
535 managedRoles: {
536 managedClusterRoleName?: string;
537 managedNodeRoleName?: string;
538 } = {},
539 ): Cluster["Attributes"] => ({
540 managedClusterRoleName: managedRoles.managedClusterRoleName,
541 managedNodeRoleName: managedRoles.managedNodeRoleName,
542 clusterArn: cluster.arn as ClusterArn,
543 clusterName: cluster.name!,
544 status: cluster.status ?? "CREATING",
545 endpoint: cluster.endpoint,
546 certificateAuthorityData: cluster.certificateAuthority?.data,
547 connection: eksConnectionOf({
548 clusterName: cluster.name!,
549 region: regionOfClusterArn(cluster.arn) ?? "",
550 endpoint: cluster.endpoint,
551 certificateAuthorityData: cluster.certificateAuthority?.data,
552 }),
553 version: cluster.version,
554 platformVersion: cluster.platformVersion,
555 roleArn: cluster.roleArn!,
556 resourcesVpcConfig: {
557 subnetIds: cluster.resourcesVpcConfig?.subnetIds ?? [],
558 securityGroupIds: cluster.resourcesVpcConfig?.securityGroupIds ?? [],
559 clusterSecurityGroupId: cluster.resourcesVpcConfig?.clusterSecurityGroupId,
560 vpcId: cluster.resourcesVpcConfig?.vpcId,
561 endpointPublicAccess: cluster.resourcesVpcConfig?.endpointPublicAccess,
562 endpointPrivateAccess: cluster.resourcesVpcConfig?.endpointPrivateAccess,
563 publicAccessCidrs: cluster.resourcesVpcConfig?.publicAccessCidrs ?? [],
564 },
565 accessConfig: cluster.accessConfig,
566 computeConfig: cluster.computeConfig,
567 storageConfig: cluster.storageConfig,
568 kubernetesNetworkConfig: cluster.kubernetesNetworkConfig,
569 logging: cluster.logging,
570 upgradePolicy: cluster.upgradePolicy,
571 deletionProtection: cluster.deletionProtection ?? false,
572 oidcIssuer: cluster.identity?.oidc?.issuer,
573 tags,
574 kubernetesObjects,
575 });
576
577 export const ClusterProvider = () =>
578 Provider.effect(
579 Cluster,
580 Effect.gen(function* () {
581 const toClusterName = (id: string, props: { clusterName?: string } = {}) =>
582 props.clusterName
583 ? Effect.succeed(props.clusterName)
584 : createPhysicalName({ id, maxLength: 100 });
585
586 const toClientRequestToken = (id: string, action: string) =>
587 createPhysicalName({
588 id: `${id}-${action}`,
589 maxLength: 64,
590 delimiter: "-",
591 });
592
593 const validateProps = Effect.fn(function* (props: ClusterProps) {
594 const subnetIds = props.resourcesVpcConfig.subnetIds ?? [];
595 if (subnetIds.length < 2) {
596 return yield* new EKSClusterInvalidProps({
597 message: "AWS.EKS.Cluster requires at least two subnet IDs",
598 });
599 }
600 if (!props.roleArn && props.compute !== "auto") {
601 return yield* new EKSClusterInvalidProps({
602 message: "AWS.EKS.Cluster requires roleArn unless compute is 'auto'",
603 });
604 }
605 if (
606 props.computeConfig?.enabled &&
607 props.accessConfig?.authenticationMode === "CONFIG_MAP"
608 ) {
609 return yield* new EKSClusterInvalidProps({
610 message:
611 "AWS.EKS.Cluster Auto Mode requires accessConfig.authenticationMode to include API access",
612 });
613 }
614 });
615
616 // Ensure an alchemy-managed IAM role for `compute: "auto"` (cluster or
617 // node role). Idempotent: creates on miss, adopts our own role on race,
618 // and converges managed policy attachments.
619 const ensureManagedRole = Effect.fn(function* ({
620 id,
621 roleName,
622 service,
623 actions,
624 managedPolicyArns,
625 userTags,
626 }: {
627 id: string;
628 roleName: string;
629 service: string;
630 actions: string[];
631 managedPolicyArns: string[];
632 userTags: Record<string, string> | undefined;
633 }) {
634 const tags = yield* createInternalTags(id);
635 const role = yield* iam
636 .createRole({
637 RoleName: roleName,
638 AssumeRolePolicyDocument: JSON.stringify({
639 Version: "2012-10-17",
640 Statement: [
641 {
642 Effect: "Allow",
643 Principal: { Service: service },
644 Action: actions,
645 },
646 ],
647 }),
648 Tags: Object.entries({ ...tags, ...userTags }).map(([Key, Value]) => ({ Key, Value })),
649 })
650 .pipe(
651 Effect.catchTag("EntityAlreadyExistsException", () =>
652 iam.getRole({ RoleName: roleName }).pipe(
653 Effect.filterOrFail(
654 (existing) => hasTags(tags, existing.Role?.Tags),
655 () =>
656 new EKSClusterConflict({
657 message: `Role '${roleName}' already exists and is not managed by alchemy`,
658 }),
659 ),
660 ),
661 ),
662 );
663 for (const policyArn of managedPolicyArns) {
664 yield* iam
665 .attachRolePolicy({ RoleName: roleName, PolicyArn: policyArn })
666 .pipe(Effect.catchTag("LimitExceededException", () => Effect.void));
667 }
668 return role.Role!.Arn!;
669 });
670
671 const deleteManagedRole = Effect.fn(function* (roleName: string) {
672 yield* iam.listAttachedRolePolicies.items({ RoleName: roleName }).pipe(
673 Stream.mapEffect((policy) =>
674 iam
675 .detachRolePolicy({
676 RoleName: roleName,
677 PolicyArn: policy.PolicyArn!,
678 })
679 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
680 ),
681 Stream.runDrain,
682 Effect.catchTag("NoSuchEntityException", () => Effect.void),
683 );
684 yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe(
685 Stream.mapEffect((policyName) =>
686 iam
687 .deleteRolePolicy({
688 RoleName: roleName,
689 PolicyName: policyName,
690 })
691 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
692 ),
693 Stream.runDrain,
694 Effect.catchTag("NoSuchEntityException", () => Effect.void),
695 );
696 yield* iam
697 .deleteRole({ RoleName: roleName })
698 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
699 });
700
701 const readCluster = Effect.fn(function* ({
702 clusterName,
703 kubernetesObjects,
704 managedRoles,
705 }: {
706 clusterName: string;
707 kubernetesObjects?: KubernetesObjectRef[];
708 managedRoles?: {
709 managedClusterRoleName?: string;
710 managedNodeRoleName?: string;
711 };
712 }) {
713 const described = yield* eks
714 .describeCluster({
715 name: clusterName,
716 })
717 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
718 const cluster = described?.cluster;
719 if (!cluster?.arn || !cluster.name || !cluster.roleArn) {
720 return undefined;
721 }
722 const listedTags = yield* eks
723 .listTagsForResource({
724 resourceArn: cluster.arn,
725 })
726 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
727 const tags = normalizeTags(listedTags?.tags ?? cluster.tags);
728 return mapClusterState(cluster, tags, kubernetesObjects ?? [], managedRoles);
729 });
730
731 const waitForClusterActive = (
732 clusterName: string,
733 kubernetesObjects: KubernetesObjectRef[] = [],
734 managedRoles?: {
735 managedClusterRoleName?: string;
736 managedNodeRoleName?: string;
737 },
738 ) =>
739 readCluster({
740 clusterName,
741 kubernetesObjects,
742 managedRoles,
743 }).pipe(
744 Effect.flatMap(
745 Effect.fnUntraced(function* (state) {
746 if (!state) {
747 return yield* new ClusterNotReady({
748 status: undefined,
749 });
750 }
751 if (state.status === "ACTIVE") {
752 return state;
753 }
754 if (state.status === "FAILED") {
755 return yield* new EKSClusterOperationFailed({
756 message: `EKS cluster '${clusterName}' entered FAILED state`,
757 });
758 }
759 return yield* new ClusterNotReady({
760 status: state.status,
761 });
762 }),
763 ),
764 Effect.retry({
765 while: (error) => error instanceof ClusterNotReady,
766 schedule: updateRetrySchedule,
767 }),
768 );
769
770 const waitForClusterDeleted = (clusterName: string) =>
771 readCluster({
772 clusterName,
773 }).pipe(
774 Effect.flatMap((state) =>
775 state ? Effect.fail(new ClusterStillExists()) : Effect.undefined,
776 ),
777 Effect.retry({
778 while: (error) => error instanceof ClusterStillExists,
779 schedule: updateRetrySchedule,
780 }),
781 );
782
783 const waitForUpdate = (clusterName: string, updateId: string) =>
784 eks
785 .describeUpdate({
786 name: clusterName,
787 updateId,
788 })
789 .pipe(
790 Effect.flatMap(
791 Effect.fnUntraced(function* ({ update }) {
792 if (update?.status === "Successful") {
793 return update;
794 }
795 if (update?.status === "Failed" || update?.status === "Cancelled") {
796 return yield* new EKSClusterOperationFailed({
797 message: `EKS cluster update '${updateId}' failed with status '${update?.status}'`,
798 });
799 }
800 return yield* new ClusterUpdateNotComplete({
801 status: update?.status,
802 });
803 }),
804 ),
805 Effect.retry({
806 while: (error) => error instanceof ClusterUpdateNotComplete,
807 schedule: updateRetrySchedule,
808 }),
809 );
810
811 return {
812 stables: ["clusterArn", "clusterName", "connection"],
813 // Enumerate every cluster in the ambient account/region. `listClusters`
814 // returns only names, so we paginate it exhaustively then hydrate each
815 // name through `readCluster` (describe + tags) to produce the full
816 // `Attributes` shape `read` returns. Concurrency is bounded so we don't
817 // stampede `describeCluster`.
818 list: () =>
819 Effect.gen(function* () {
820 const names = yield* eks.listClusters.pages({}).pipe(
821 Stream.runCollect,
822 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.clusters ?? [])),
823 );
824 const states = yield* Effect.forEach(
825 names,
826 (clusterName) => readCluster({ clusterName }),
827 { concurrency: 8 },
828 );
829 return states.filter((state): state is Cluster["Attributes"] => state !== undefined);
830 }),
831 diff: Effect.fn(function* ({ id, olds = {} as ClusterProps, news }) {
832 if (!isResolved(news)) return;
833 if ((yield* toClusterName(id, olds)) !== (yield* toClusterName(id, news ?? {}))) {
834 return { action: "replace" } as const;
835 }
836 if (olds.roleArn !== news.roleArn) {
837 return { action: "replace" } as const;
838 }
839 if (
840 olds.accessConfig?.bootstrapClusterCreatorAdminPermissions !==
841 news.accessConfig?.bootstrapClusterCreatorAdminPermissions
842 ) {
843 return { action: "replace" } as const;
844 }
845 if (
846 olds.kubernetesNetworkConfig?.serviceIpv4Cidr !==
847 news.kubernetesNetworkConfig?.serviceIpv4Cidr ||
848 olds.kubernetesNetworkConfig?.ipFamily !== news.kubernetesNetworkConfig?.ipFamily
849 ) {
850 return { action: "replace" } as const;
851 }
852 if (
853 olds.computeConfig?.nodeRoleArn !== news.computeConfig?.nodeRoleArn &&
854 (olds.computeConfig?.enabled || news.computeConfig?.enabled)
855 ) {
856 return { action: "replace" } as const;
857 }
858 }),
859 read: Effect.fn(function* ({ id, olds, output }) {
860 const clusterName = output?.clusterName ?? (yield* toClusterName(id, olds ?? {}));
861 const state = yield* readCluster({
862 clusterName,
863 kubernetesObjects: output?.kubernetesObjects,
864 managedRoles: output,
865 });
866 if (!state) return undefined;
867 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
868 }),
869 reconcile: Effect.fn(function* ({ id, news, output, bindings, session }) {
870 yield* validateProps(news);
871
872 const clusterName = yield* toClusterName(id, news);
873 const desiredObjects = getDesiredKubernetesObjects(bindings);
874 const desiredTags = {
875 ...(yield* createInternalTags(id)),
876 ...news.tags,
877 };
878
879 // Ensure `compute: "auto"` managed IAM roles before touching the
880 // cluster. Physical names are cached in the output so re-runs and
881 // updates converge on the same roles.
882 const auto = news.compute === "auto";
883 let managedClusterRoleName = output?.managedClusterRoleName;
884 let managedNodeRoleName = output?.managedNodeRoleName;
885 let roleArn = news.roleArn;
886 if (!roleArn && auto) {
887 managedClusterRoleName ??= yield* createPhysicalName({
888 id: `${id}-cluster-role`,
889 maxLength: 64,
890 });
891 roleArn = yield* ensureManagedRole({
892 id,
893 roleName: managedClusterRoleName,
894 service: "eks.amazonaws.com",
895 actions: ["sts:AssumeRole", "sts:TagSession"],
896 managedPolicyArns: autoClusterManagedPolicyArns,
897 userTags: news.tags,
898 });
899 } else if (roleArn) {
900 managedClusterRoleName = undefined;
901 }
902 let nodeRoleArn = news.computeConfig?.nodeRoleArn;
903 if (!nodeRoleArn && auto) {
904 managedNodeRoleName ??= yield* createPhysicalName({
905 id: `${id}-node-role`,
906 maxLength: 64,
907 });
908 nodeRoleArn = yield* ensureManagedRole({
909 id,
910 roleName: managedNodeRoleName,
911 service: "ec2.amazonaws.com",
912 actions: ["sts:AssumeRole"],
913 managedPolicyArns: autoNodeManagedPolicyArns,
914 userTags: news.tags,
915 });
916 } else if (nodeRoleArn) {
917 managedNodeRoleName = undefined;
918 }
919 if (!roleArn) {
920 return yield* new EKSClusterInvalidProps({
921 message: "AWS.EKS.Cluster requires roleArn unless compute is 'auto'",
922 });
923 }
924 const managedRoles = { managedClusterRoleName, managedNodeRoleName };
925 const effective = applyAutoModeDefaults(news, {
926 roleArn,
927 nodeRoleArn,
928 });
929
930 // Observe — fetch live cloud state. We always fetch fresh so
931 // adoption, drift, and partial-prior-runs all converge.
932 let state = yield* readCluster({
933 clusterName,
934 kubernetesObjects: output?.kubernetesObjects,
935 managedRoles,
936 });
937
938 // Ensure — create cluster if missing. Tolerate
939 // `ResourceInUseException` as a race with a peer reconciler:
940 // re-read and continue with the sync path. The control plane
941 // takes 10+ minutes; we wait for ACTIVE before any sync work.
942 if (!state) {
943 yield* eks
944 .createCluster({
945 name: clusterName,
946 version: effective.version,
947 roleArn: effective.roleArn,
948 resourcesVpcConfig: effective.resourcesVpcConfig,
949 kubernetesNetworkConfig: effective.kubernetesNetworkConfig,
950 logging: effective.logging,
951 accessConfig: effective.accessConfig,
952 computeConfig: effective.computeConfig,
953 storageConfig: effective.storageConfig,
954 deletionProtection: effective.deletionProtection,
955 upgradePolicy: effective.upgradePolicy,
956 tags: desiredTags,
957 clientRequestToken: yield* toClientRequestToken(id, "create"),
958 })
959 .pipe(Effect.catchTag("ResourceInUseException", () => Effect.void));
960
961 yield* session.note(`Creating EKS cluster ${clusterName}...`);
962 state = yield* waitForClusterActive(clusterName, [], managedRoles);
963 }
964
965 const clusterArn = state.clusterArn;
966
967 // Sync cluster config — EKS's UpdateClusterConfig accepts exactly
968 // ONE update category per call ("Only one type of update can be
969 // allowed"), so we plan the observed↔desired drift per category and
970 // issue one serialized updateClusterConfig per drifted category,
971 // waiting for each async update to land (Successful + cluster back
972 // to ACTIVE) before the next. Everything settable at create time is
973 // already passed to createCluster, so a greenfield create plans
974 // zero updates.
975 for (const { category, request } of planClusterConfigUpdates(state, effective)) {
976 const configUpdate = yield* eks.updateClusterConfig({
977 name: clusterName,
978 ...request,
979 clientRequestToken: yield* toClientRequestToken(id, `config-${category}`),
980 });
981 if (configUpdate.update?.id) {
982 yield* session.note(`Updating EKS cluster ${category} config (${clusterName})...`);
983 yield* waitForUpdate(clusterName, configUpdate.update.id);
984 state =
985 (yield* waitForClusterActive(
986 clusterName,
987 output?.kubernetesObjects ?? [],
988 managedRoles,
989 )) ?? state;
990 }
991 }
992
993 // Sync version — observed ↔ desired.
994 if (effective.version && state.version !== effective.version) {
995 const versionUpdate = yield* eks.updateClusterVersion({
996 name: clusterName,
997 version: effective.version,
998 clientRequestToken: yield* toClientRequestToken(id, "version"),
999 });
1000 if (versionUpdate.update?.id) {
1001 yield* session.note(`Updating EKS cluster version ${clusterName}...`);
1002 yield* waitForUpdate(clusterName, versionUpdate.update.id);
1003 state =
1004 (yield* waitForClusterActive(
1005 clusterName,
1006 output?.kubernetesObjects ?? [],
1007 managedRoles,
1008 )) ?? state;
1009 }
1010 }
1011
1012 // Sync tags — diff observed cloud tags against desired.
1013 const { removed, upsert } = diffTags(state.tags, desiredTags);
1014 if (upsert.length > 0) {
1015 yield* eks.tagResource({
1016 resourceArn: clusterArn,
1017 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value] as const)),
1018 });
1019 }
1020 if (removed.length > 0) {
1021 yield* eks.untagResource({
1022 resourceArn: clusterArn,
1023 tagKeys: removed,
1024 });
1025 }
1026
1027 yield* session.note(clusterArn);
1028
1029 // Re-read final state so returned attributes reflect the post-
1030 // sync cloud state.
1031 const final = yield* readCluster({
1032 clusterName,
1033 kubernetesObjects: output?.kubernetesObjects ?? [],
1034 managedRoles,
1035 });
1036 if (!final) {
1037 return yield* new EKSClusterUnexpectedResponse({
1038 message: `EKS cluster '${clusterName}' could not be read after reconcile`,
1039 });
1040 }
1041
1042 const kubernetesObjects = yield* reconcileObjects({
1043 transport: yield* getKubernetesTransport(final),
1044 previousObjects: output?.kubernetesObjects ?? [],
1045 desiredObjects,
1046 });
1047
1048 return {
1049 ...final,
1050 kubernetesObjects,
1051 };
1052 }),
1053 delete: Effect.fn(function* ({ id, output }) {
1054 if ((output.kubernetesObjects ?? []).length > 0) {
1055 yield* deleteObjects({
1056 transport: yield* getKubernetesTransport(output),
1057 objects: output.kubernetesObjects ?? [],
1058 });
1059 }
1060
1061 if (output.deletionProtection) {
1062 const disableDeletionProtection = yield* eks.updateClusterConfig({
1063 name: output.clusterName,
1064 deletionProtection: false,
1065 clientRequestToken: yield* toClientRequestToken(id, "disable-deletion-protection"),
1066 });
1067 if (disableDeletionProtection.update?.id) {
1068 yield* waitForUpdate(output.clusterName, disableDeletionProtection.update.id);
1069 yield* waitForClusterActive(output.clusterName, output.kubernetesObjects ?? []);
1070 }
1071 }
1072
1073 // A cluster with an update in flight (an access-entry or config change
1074 // a crashed deploy left behind) refuses deletion with
1075 // ResourceInUseException: let its updates settle first.
1076 const updateIds = yield* eks.listUpdates({ name: output.clusterName }).pipe(
1077 Effect.map((response) => response.updateIds ?? []),
1078 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as string[])),
1079 );
1080 for (const updateId of updateIds) {
1081 yield* waitForUpdate(output.clusterName, updateId).pipe(
1082 Effect.catchTag(
1083 ["EKSClusterOperationFailed", "ResourceNotFoundException"],
1084 () => Effect.void,
1085 ),
1086 );
1087 }
1088
1089 yield* eks
1090 .deleteCluster({
1091 name: output.clusterName,
1092 })
1093 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
1094
1095 yield* waitForClusterDeleted(output.clusterName);
1096
1097 // Delete the `compute: "auto"` managed IAM roles this cluster owns.
1098 if (output.managedClusterRoleName) {
1099 yield* deleteManagedRole(output.managedClusterRoleName);
1100 }
1101 if (output.managedNodeRoleName) {
1102 yield* deleteManagedRole(output.managedNodeRoleName);
1103 }
1104 }),
1105 };
1106 }),
1107 );