The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as eks from "@distilled.cloud/aws/eks"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 4 | import type { Input } from "alchemy/Input"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | export class AddonOperationFailed extends Data.TaggedError("AddonOperationFailed")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export interface AddonProps { |
| 21 | /** |
| 22 | * Target cluster name. |
| 23 | */ |
| 24 | clusterName: Input<string>; |
| 25 | /** |
| 26 | * Add-on name, such as `metrics-server`. |
| 27 | */ |
| 28 | addonName: string; |
| 29 | /** |
| 30 | * Optional add-on version. If omitted, EKS chooses the default compatible version. |
| 31 | */ |
| 32 | addonVersion?: string; |
| 33 | /** |
| 34 | * IAM role ARN used by the add-on's service account. |
| 35 | */ |
| 36 | serviceAccountRoleArn?: Input<string>; |
| 37 | /** |
| 38 | * Conflict resolution strategy used during create and update. |
| 39 | */ |
| 40 | resolveConflicts?: eks.ResolveConflicts; |
| 41 | /** |
| 42 | * Optional add-on configuration JSON string. |
| 43 | */ |
| 44 | configurationValues?: string; |
| 45 | /** |
| 46 | * Optional pod identity associations managed by the add-on. |
| 47 | */ |
| 48 | podIdentityAssociations?: eks.AddonPodIdentityAssociations[]; |
| 49 | /** |
| 50 | * Optional namespace override. Changing this requires replacement. |
| 51 | */ |
| 52 | namespaceConfig?: eks.AddonNamespaceConfigRequest; |
| 53 | /** |
| 54 | * Preserve the add-on installation when the Alchemy resource is deleted. |
| 55 | */ |
| 56 | preserveOnDelete?: boolean; |
| 57 | /** |
| 58 | * User-defined tags to apply to the add-on. |
| 59 | */ |
| 60 | tags?: Record<string, string>; |
| 61 | } |
| 62 | |
| 63 | export interface Addon extends Resource< |
| 64 | "AWS.EKS.Addon", |
| 65 | AddonProps, |
| 66 | { |
| 67 | /** The ARN of the add-on. */ |
| 68 | addonArn: string; |
| 69 | /** The name of the add-on (e.g. `vpc-cni`, `coredns`). */ |
| 70 | addonName: string; |
| 71 | /** The name of the EKS cluster the add-on is installed on. */ |
| 72 | clusterName: string; |
| 73 | /** The add-on status (e.g. `ACTIVE`, `DEGRADED`). */ |
| 74 | status: eks.AddonStatus; |
| 75 | /** The installed version of the add-on. */ |
| 76 | addonVersion: string | undefined; |
| 77 | /** The IAM role ARN bound to the add-on's service account, if any. */ |
| 78 | serviceAccountRoleArn: string | undefined; |
| 79 | /** The add-on's configuration values (JSON or YAML). */ |
| 80 | configurationValues: string | undefined; |
| 81 | /** The ARNs of the pod identity associations owned by the add-on. */ |
| 82 | podIdentityAssociations: string[]; |
| 83 | /** The Kubernetes namespace the add-on is installed in. */ |
| 84 | namespace: string | undefined; |
| 85 | /** The publisher of the add-on. */ |
| 86 | publisher: string | undefined; |
| 87 | /** The owner of the add-on. */ |
| 88 | owner: string | undefined; |
| 89 | /** The tags applied to the add-on. */ |
| 90 | tags: Record<string, string>; |
| 91 | /** Health issues currently reported for the add-on. */ |
| 92 | healthIssues: eks.AddonIssue[]; |
| 93 | }, |
| 94 | never, |
| 95 | Providers |
| 96 | > {} |
| 97 | |
| 98 | /** |
| 99 | * An Amazon EKS managed add-on installed on a cluster. |
| 100 | * |
| 101 | * `Addon` is intended for optional managed add-ons. On Auto Mode clusters, many |
| 102 | * core components are already provided by AWS and do not need to be modeled as |
| 103 | * explicit add-on resources. |
| 104 | * ### Managing Add-ons |
| 105 | * **Example:** Install Metrics Server |
| 106 | * ```typescript |
| 107 | * const metricsServer = yield* Addon("MetricsServer", { |
| 108 | * clusterName: cluster.clusterName, |
| 109 | * addonName: "metrics-server", |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * @resource |
| 114 | */ |
| 115 | export const Addon = Resource<Addon>("AWS.EKS.Addon"); |
| 116 | |
| 117 | const normalizeTags = (tags: Record<string, string | undefined> | undefined) => |
| 118 | Object.fromEntries( |
| 119 | Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined), |
| 120 | ); |
| 121 | |
| 122 | const mapAddon = (addon: eks.Addon) => ({ |
| 123 | addonArn: addon.addonArn!, |
| 124 | addonName: addon.addonName!, |
| 125 | clusterName: addon.clusterName!, |
| 126 | status: addon.status ?? "CREATING", |
| 127 | addonVersion: addon.addonVersion, |
| 128 | serviceAccountRoleArn: addon.serviceAccountRoleArn, |
| 129 | configurationValues: addon.configurationValues, |
| 130 | podIdentityAssociations: addon.podIdentityAssociations ?? [], |
| 131 | namespace: addon.namespaceConfig?.namespace, |
| 132 | publisher: addon.publisher, |
| 133 | owner: addon.owner, |
| 134 | tags: normalizeTags(addon.tags), |
| 135 | healthIssues: addon.health?.issues ?? [], |
| 136 | }); |
| 137 | |
| 138 | const readAddon = Effect.fn(function* ({ |
| 139 | clusterName, |
| 140 | addonName, |
| 141 | }: { |
| 142 | clusterName: string; |
| 143 | addonName: string; |
| 144 | }) { |
| 145 | const response = yield* eks |
| 146 | .describeAddon({ |
| 147 | clusterName, |
| 148 | addonName, |
| 149 | }) |
| 150 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 151 | |
| 152 | const addon = response?.addon; |
| 153 | if (!addon?.addonArn || !addon.addonName || !addon.clusterName) { |
| 154 | return undefined; |
| 155 | } |
| 156 | |
| 157 | return mapAddon(addon); |
| 158 | }); |
| 159 | |
| 160 | class AddonNotReady extends Data.TaggedError("AddonNotReady")<{ |
| 161 | readonly clusterName: string; |
| 162 | readonly addonName: string; |
| 163 | readonly status: string | undefined; |
| 164 | }> { |
| 165 | override get message(): string { |
| 166 | return `addon '${this.clusterName}/${this.addonName}' is not ACTIVE (status: ${this.status ?? "absent"})`; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | class AddonStillExists extends Data.TaggedError("AddonStillExists")<{ |
| 171 | readonly clusterName: string; |
| 172 | readonly addonName: string; |
| 173 | }> {} |
| 174 | export const AddonProvider = () => |
| 175 | Provider.effect( |
| 176 | Addon, |
| 177 | Effect.gen(function* () { |
| 178 | const toClientRequestToken = (id: string, action: string) => |
| 179 | createPhysicalName({ |
| 180 | id: `${id}-${action}`, |
| 181 | maxLength: 64, |
| 182 | delimiter: "-", |
| 183 | }); |
| 184 | |
| 185 | return { |
| 186 | stables: ["addonArn"], |
| 187 | // Add-ons are keyed by (clusterName, addonName) and `listAddons` |
| 188 | // requires a cluster. Enumerate every cluster, list its add-ons, |
| 189 | // then hydrate each via `describeAddon` to produce full Attributes. |
| 190 | list: () => |
| 191 | Effect.gen(function* () { |
| 192 | const clusterNames = yield* eks.listClusters.pages({}).pipe( |
| 193 | Stream.runCollect, |
| 194 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.clusters ?? [])), |
| 195 | ); |
| 196 | |
| 197 | const perCluster = yield* Effect.forEach( |
| 198 | clusterNames, |
| 199 | (clusterName) => |
| 200 | eks.listAddons.pages({ clusterName }).pipe( |
| 201 | Stream.runCollect, |
| 202 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.addons ?? [])), |
| 203 | Effect.flatMap((addonNames) => |
| 204 | Effect.forEach( |
| 205 | addonNames, |
| 206 | (addonName) => readAddon({ clusterName, addonName }), |
| 207 | { concurrency: 5 }, |
| 208 | ), |
| 209 | ), |
| 210 | ), |
| 211 | { concurrency: 5 }, |
| 212 | ); |
| 213 | |
| 214 | return perCluster |
| 215 | .flat() |
| 216 | .filter((addon): addon is NonNullable<typeof addon> => addon !== undefined); |
| 217 | }), |
| 218 | diff: Effect.fn(function* ({ olds, news }) { |
| 219 | if (!isResolved(news)) return; |
| 220 | if (olds.clusterName !== news.clusterName) { |
| 221 | return { action: "replace" } as const; |
| 222 | } |
| 223 | |
| 224 | if (olds.addonName !== news.addonName) { |
| 225 | return { action: "replace" } as const; |
| 226 | } |
| 227 | |
| 228 | if (!deepEqual(olds.namespaceConfig, news.namespaceConfig)) { |
| 229 | return { action: "replace" } as const; |
| 230 | } |
| 231 | }), |
| 232 | read: Effect.fn(function* ({ id, olds }) { |
| 233 | const clusterName = olds.clusterName as string | undefined; |
| 234 | // A crashed prior run can persist a row before its unresolved |
| 235 | // inputs were stripped — nothing observable yet. |
| 236 | if (clusterName === undefined || olds.addonName === undefined) { |
| 237 | return undefined; |
| 238 | } |
| 239 | const state = yield* readAddon({ |
| 240 | clusterName, |
| 241 | addonName: olds.addonName, |
| 242 | }); |
| 243 | if (!state) return undefined; |
| 244 | return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state); |
| 245 | }), |
| 246 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 247 | const clusterName = news.clusterName as string; |
| 248 | const addonName = news.addonName; |
| 249 | const desiredTags = { |
| 250 | ...(yield* createInternalTags(id)), |
| 251 | ...news.tags, |
| 252 | }; |
| 253 | |
| 254 | // Observe — fetch live cloud state by (clusterName, addonName). |
| 255 | let state = yield* readAddon({ |
| 256 | clusterName, |
| 257 | addonName, |
| 258 | }); |
| 259 | |
| 260 | // Ensure — create if missing. Tolerate `ResourceInUseException` |
| 261 | // as a race with a peer reconciler: re-read and continue with |
| 262 | // sync. |
| 263 | if (!state) { |
| 264 | yield* eks |
| 265 | .createAddon({ |
| 266 | clusterName, |
| 267 | addonName, |
| 268 | addonVersion: news.addonVersion, |
| 269 | serviceAccountRoleArn: news.serviceAccountRoleArn as string | undefined, |
| 270 | resolveConflicts: news.resolveConflicts, |
| 271 | configurationValues: news.configurationValues, |
| 272 | podIdentityAssociations: news.podIdentityAssociations, |
| 273 | namespaceConfig: news.namespaceConfig, |
| 274 | tags: desiredTags, |
| 275 | clientRequestToken: yield* toClientRequestToken(id, "create"), |
| 276 | }) |
| 277 | .pipe(Effect.catchTag("ResourceInUseException", () => Effect.void)); |
| 278 | |
| 279 | state = yield* waitForAddonActive({ |
| 280 | clusterName, |
| 281 | addonName, |
| 282 | }); |
| 283 | } |
| 284 | |
| 285 | // Sync addon version / config — diff observed against desired. |
| 286 | // updateAddon handles version, role, resolve conflicts, config |
| 287 | // values, and pod identity associations atomically. |
| 288 | const podIdentityChanged = |
| 289 | JSON.stringify(state.podIdentityAssociations ?? []) !== |
| 290 | JSON.stringify(news.podIdentityAssociations ?? []); |
| 291 | if ( |
| 292 | (news.addonVersion !== undefined && state.addonVersion !== news.addonVersion) || |
| 293 | state.serviceAccountRoleArn !== (news.serviceAccountRoleArn as string | undefined) || |
| 294 | state.configurationValues !== news.configurationValues || |
| 295 | podIdentityChanged |
| 296 | ) { |
| 297 | yield* eks.updateAddon({ |
| 298 | clusterName, |
| 299 | addonName, |
| 300 | addonVersion: news.addonVersion, |
| 301 | serviceAccountRoleArn: news.serviceAccountRoleArn as string | undefined, |
| 302 | resolveConflicts: news.resolveConflicts, |
| 303 | configurationValues: news.configurationValues, |
| 304 | podIdentityAssociations: news.podIdentityAssociations, |
| 305 | clientRequestToken: yield* toClientRequestToken(id, "update"), |
| 306 | }); |
| 307 | state = yield* waitForAddonActive({ |
| 308 | clusterName, |
| 309 | addonName, |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | // Sync tags — diff observed cloud tags against desired. |
| 314 | const { removed, upsert } = diffTags(state.tags, desiredTags); |
| 315 | if (upsert.length > 0) { |
| 316 | yield* eks.tagResource({ |
| 317 | resourceArn: state.addonArn, |
| 318 | tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value] as const)), |
| 319 | }); |
| 320 | } |
| 321 | if (removed.length > 0) { |
| 322 | yield* eks.untagResource({ |
| 323 | resourceArn: state.addonArn, |
| 324 | tagKeys: removed, |
| 325 | }); |
| 326 | } |
| 327 | |
| 328 | yield* session.note(state.addonArn); |
| 329 | return state; |
| 330 | }), |
| 331 | delete: Effect.fn(function* ({ olds, output }) { |
| 332 | yield* eks |
| 333 | .deleteAddon({ |
| 334 | clusterName: output.clusterName, |
| 335 | addonName: output.addonName, |
| 336 | preserve: olds.preserveOnDelete, |
| 337 | }) |
| 338 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 339 | |
| 340 | if (!olds.preserveOnDelete) { |
| 341 | yield* waitForAddonDeleted({ |
| 342 | clusterName: output.clusterName, |
| 343 | addonName: output.addonName, |
| 344 | }); |
| 345 | } |
| 346 | }), |
| 347 | }; |
| 348 | }), |
| 349 | ); |
| 350 | |
| 351 | const waitForAddonActive = Effect.fn(function* ({ |
| 352 | clusterName, |
| 353 | addonName, |
| 354 | }: { |
| 355 | clusterName: string; |
| 356 | addonName: string; |
| 357 | }) { |
| 358 | return yield* readAddon({ |
| 359 | clusterName, |
| 360 | addonName, |
| 361 | }).pipe( |
| 362 | Effect.flatMap( |
| 363 | Effect.fnUntraced(function* (addon) { |
| 364 | if (!addon) { |
| 365 | return yield* new AddonNotReady({ |
| 366 | clusterName, |
| 367 | addonName, |
| 368 | status: undefined, |
| 369 | }); |
| 370 | } |
| 371 | |
| 372 | switch (addon.status) { |
| 373 | case "ACTIVE": |
| 374 | return addon; |
| 375 | case "CREATE_FAILED": |
| 376 | case "UPDATE_FAILED": |
| 377 | case "DELETE_FAILED": |
| 378 | return yield* new AddonOperationFailed({ |
| 379 | message: `Addon '${clusterName}/${addonName}' entered terminal status '${addon.status}'`, |
| 380 | }); |
| 381 | default: |
| 382 | return yield* new AddonNotReady({ |
| 383 | clusterName, |
| 384 | addonName, |
| 385 | status: addon.status, |
| 386 | }); |
| 387 | } |
| 388 | }), |
| 389 | ), |
| 390 | Effect.retry({ |
| 391 | while: (error) => error instanceof AddonNotReady, |
| 392 | // Flat 5s polls, ~20 min budget (uncapped exponential sleeps for |
| 393 | // multi-minute stretches late in the wait — looks like a deadlock). |
| 394 | // Node-bound addons (e.g. HyperPod task governance) stay DEGRADED |
| 395 | // until nodes join and pull images, which can take most of the |
| 396 | // budget when the addon installs alongside its node group. |
| 397 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(240)]), |
| 398 | }), |
| 399 | ); |
| 400 | }); |
| 401 | |
| 402 | const waitForAddonDeleted = Effect.fn(function* ({ |
| 403 | clusterName, |
| 404 | addonName, |
| 405 | }: { |
| 406 | clusterName: string; |
| 407 | addonName: string; |
| 408 | }) { |
| 409 | yield* readAddon({ |
| 410 | clusterName, |
| 411 | addonName, |
| 412 | }).pipe( |
| 413 | Effect.flatMap((addon) => |
| 414 | addon ? Effect.fail(new AddonStillExists({ clusterName, addonName })) : Effect.void, |
| 415 | ), |
| 416 | Effect.retry({ |
| 417 | while: (error) => error instanceof AddonStillExists, |
| 418 | // Flat 5s polls, ~10 min budget (uncapped exponential sleeps for |
| 419 | // multi-minute stretches late in the wait — looks like a deadlock). |
| 420 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(120)]), |
| 421 | }), |
| 422 | ); |
| 423 | }); |