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
| 1 | import * as eks from "@distilled.cloud/aws/eks"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { 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 FargateProfileOperationFailed extends Data.TaggedError( |
| 16 | "FargateProfileOperationFailed", |
| 17 | )<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | export class FargateProfileUnexpectedResponse extends Data.TaggedError( |
| 23 | "FargateProfileUnexpectedResponse", |
| 24 | )<{ |
| 25 | readonly message: string; |
| 26 | readonly cause?: unknown; |
| 27 | }> {} |
| 28 | |
| 29 | export interface FargateProfileProps { |
| 30 | /** |
| 31 | * Name of the EKS cluster that owns this Fargate profile. |
| 32 | */ |
| 33 | clusterName: Input<string>; |
| 34 | /** |
| 35 | * Name of the Fargate profile. If omitted, a unique name is generated. |
| 36 | */ |
| 37 | fargateProfileName?: string; |
| 38 | /** |
| 39 | * ARN of the pod execution IAM role that Fargate pods assume. The role must |
| 40 | * trust `eks-fargate-pods.amazonaws.com`. Changing this replaces the profile. |
| 41 | */ |
| 42 | podExecutionRoleArn: Input<string>; |
| 43 | /** |
| 44 | * Selectors (namespace + optional labels) that decide which pods run on |
| 45 | * Fargate. Changing this replaces the profile. |
| 46 | */ |
| 47 | selectors: eks.FargateProfileSelector[]; |
| 48 | /** |
| 49 | * Subnet IDs to run Fargate pods in. **Fargate pods require PRIVATE subnets |
| 50 | * only** — a subnet that auto-assigns a public IP is rejected by EKS. Changing |
| 51 | * this replaces the profile. |
| 52 | */ |
| 53 | subnets?: Input<string>[]; |
| 54 | /** |
| 55 | * User-defined tags to apply to the Fargate profile. |
| 56 | */ |
| 57 | tags?: Record<string, string>; |
| 58 | } |
| 59 | |
| 60 | export interface FargateProfile extends Resource< |
| 61 | "AWS.EKS.FargateProfile", |
| 62 | FargateProfileProps, |
| 63 | { |
| 64 | /** The name of the Fargate profile. */ |
| 65 | fargateProfileName: string; |
| 66 | /** The ARN of the Fargate profile. */ |
| 67 | fargateProfileArn: string; |
| 68 | /** The name of the EKS cluster the profile belongs to. */ |
| 69 | clusterName: string; |
| 70 | /** The profile status (e.g. `CREATING`, `ACTIVE`). */ |
| 71 | status: eks.FargateProfileStatus; |
| 72 | /** The ARN of the pod execution role used by pods matched by the profile. */ |
| 73 | podExecutionRoleArn: string; |
| 74 | /** The IDs of the (private) subnets pods are launched into. */ |
| 75 | subnets: string[]; |
| 76 | /** The namespace/label selectors that route pods onto Fargate. */ |
| 77 | selectors: eks.FargateProfileSelector[]; |
| 78 | /** The tags applied to the Fargate profile. */ |
| 79 | tags: Record<string, string>; |
| 80 | }, |
| 81 | never, |
| 82 | Providers |
| 83 | > {} |
| 84 | |
| 85 | /** |
| 86 | * An Amazon EKS Fargate profile — declares which pods (by namespace + labels) |
| 87 | * run on AWS Fargate serverless compute instead of on EC2 nodes. |
| 88 | * |
| 89 | * Fargate profiles are immutable except for tags: any change to selectors, the |
| 90 | * pod execution role, or subnets forces a replacement. Create and delete are |
| 91 | * asynchronous (`CREATING` → `ACTIVE`, `DELETING` → gone, ~1–2 min each) and the |
| 92 | * provider waits for the terminal state. EKS allows only one Fargate profile per |
| 93 | * cluster to be creating or deleting at a time, so the provider retries the |
| 94 | * `ResourceInUseException` that surfaces when a peer profile operation is in |
| 95 | * flight. |
| 96 | * |
| 97 | * **Fargate pods must run in private subnets** — pass private subnet IDs only. |
| 98 | * ### Creating Fargate Profiles |
| 99 | * **Example:** Run the `default` Namespace on Fargate |
| 100 | * ```typescript |
| 101 | * const profile = yield* FargateProfile("DefaultFargate", { |
| 102 | * clusterName: cluster.clusterName, |
| 103 | * podExecutionRoleArn: podRole.roleArn, |
| 104 | * subnets: network.privateSubnetIds, |
| 105 | * selectors: [{ namespace: "default" }], |
| 106 | * }); |
| 107 | * ``` |
| 108 | * |
| 109 | * **Example:** Select Pods by Namespace and Labels |
| 110 | * ```typescript |
| 111 | * const profile = yield* FargateProfile("BatchFargate", { |
| 112 | * clusterName: cluster.clusterName, |
| 113 | * podExecutionRoleArn: podRole.roleArn, |
| 114 | * subnets: network.privateSubnetIds, |
| 115 | * selectors: [ |
| 116 | * { namespace: "batch", labels: { compute: "fargate" } }, |
| 117 | * ], |
| 118 | * }); |
| 119 | * ``` |
| 120 | * |
| 121 | * @resource |
| 122 | */ |
| 123 | export const FargateProfile = Resource<FargateProfile>("AWS.EKS.FargateProfile"); |
| 124 | |
| 125 | class FargateProfileNotReady extends Data.TaggedError("EKS.FargateProfileNotReady")<{ |
| 126 | status: eks.FargateProfileStatus | undefined; |
| 127 | }> {} |
| 128 | |
| 129 | class FargateProfileStillExists extends Data.TaggedError("EKS.FargateProfileStillExists")<{}> {} |
| 130 | |
| 131 | class FargateProfileBusy extends Data.TaggedError("EKS.FargateProfileBusy")<{}> {} |
| 132 | |
| 133 | const normalizeTags = (tags: Record<string, string | undefined> | undefined) => |
| 134 | Object.fromEntries( |
| 135 | Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined), |
| 136 | ); |
| 137 | |
| 138 | // ~10 min at 5s spacing — Fargate profile transitions complete in 1–2 min. |
| 139 | const waitSchedule = Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(120)]); |
| 140 | |
| 141 | // One profile per cluster may be creating/deleting at a time; back off on the |
| 142 | // ResourceInUseException that peer operations raise (bounded). |
| 143 | const busySchedule = Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(30)]); |
| 144 | |
| 145 | const mapFargateProfile = ( |
| 146 | profile: eks.FargateProfile, |
| 147 | tags: Record<string, string>, |
| 148 | ): FargateProfile["Attributes"] => ({ |
| 149 | fargateProfileName: profile.fargateProfileName!, |
| 150 | fargateProfileArn: profile.fargateProfileArn!, |
| 151 | clusterName: profile.clusterName!, |
| 152 | status: profile.status ?? "CREATING", |
| 153 | podExecutionRoleArn: profile.podExecutionRoleArn!, |
| 154 | subnets: profile.subnets ?? [], |
| 155 | selectors: profile.selectors ?? [], |
| 156 | tags, |
| 157 | }); |
| 158 | |
| 159 | export const FargateProfileProvider = () => |
| 160 | Provider.effect( |
| 161 | FargateProfile, |
| 162 | Effect.gen(function* () { |
| 163 | const toProfileName = (id: string, props: { fargateProfileName?: string } = {}) => |
| 164 | props.fargateProfileName |
| 165 | ? Effect.succeed(props.fargateProfileName) |
| 166 | : createPhysicalName({ id, maxLength: 63 }); |
| 167 | |
| 168 | const toClientRequestToken = (id: string, action: string) => |
| 169 | createPhysicalName({ |
| 170 | id: `${id}-${action}`, |
| 171 | maxLength: 64, |
| 172 | delimiter: "-", |
| 173 | }); |
| 174 | |
| 175 | const readProfile = Effect.fn(function* ({ |
| 176 | clusterName, |
| 177 | fargateProfileName, |
| 178 | }: { |
| 179 | clusterName: string; |
| 180 | fargateProfileName: string; |
| 181 | }) { |
| 182 | const described = yield* eks |
| 183 | .describeFargateProfile({ clusterName, fargateProfileName }) |
| 184 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 185 | const profile = described?.fargateProfile; |
| 186 | if ( |
| 187 | !profile?.fargateProfileArn || |
| 188 | !profile.fargateProfileName || |
| 189 | !profile.clusterName || |
| 190 | !profile.podExecutionRoleArn |
| 191 | ) { |
| 192 | return undefined; |
| 193 | } |
| 194 | return mapFargateProfile(profile, normalizeTags(profile.tags)); |
| 195 | }); |
| 196 | |
| 197 | const waitForProfileActive = (clusterName: string, fargateProfileName: string) => |
| 198 | readProfile({ clusterName, fargateProfileName }).pipe( |
| 199 | Effect.flatMap( |
| 200 | Effect.fnUntraced(function* (state) { |
| 201 | if (!state) { |
| 202 | return yield* new FargateProfileNotReady({ status: undefined }); |
| 203 | } |
| 204 | if (state.status === "ACTIVE") { |
| 205 | return state; |
| 206 | } |
| 207 | if (state.status === "CREATE_FAILED" || state.status === "DELETE_FAILED") { |
| 208 | return yield* new FargateProfileOperationFailed({ |
| 209 | message: `EKS Fargate profile '${fargateProfileName}' entered ${state.status}`, |
| 210 | }); |
| 211 | } |
| 212 | return yield* new FargateProfileNotReady({ status: state.status }); |
| 213 | }), |
| 214 | ), |
| 215 | Effect.retry({ |
| 216 | while: (error) => error instanceof FargateProfileNotReady, |
| 217 | schedule: waitSchedule, |
| 218 | }), |
| 219 | ); |
| 220 | |
| 221 | const waitForProfileDeleted = (clusterName: string, fargateProfileName: string) => |
| 222 | readProfile({ clusterName, fargateProfileName }).pipe( |
| 223 | Effect.flatMap((state) => |
| 224 | state ? Effect.fail(new FargateProfileStillExists()) : Effect.undefined, |
| 225 | ), |
| 226 | Effect.retry({ |
| 227 | while: (error) => error instanceof FargateProfileStillExists, |
| 228 | schedule: waitSchedule, |
| 229 | }), |
| 230 | ); |
| 231 | |
| 232 | return { |
| 233 | stables: ["fargateProfileArn", "fargateProfileName", "clusterName"], |
| 234 | // Enumerate every Fargate profile across the account/region. |
| 235 | // `listFargateProfiles` is cluster-scoped, so first enumerate all |
| 236 | // clusters, list each cluster's profiles, then hydrate via |
| 237 | // `describeFargateProfile`. |
| 238 | list: () => |
| 239 | Effect.gen(function* () { |
| 240 | const clusterNames = yield* eks.listClusters.pages({}).pipe( |
| 241 | Stream.runCollect, |
| 242 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.clusters ?? [])), |
| 243 | ); |
| 244 | |
| 245 | const perCluster = yield* Effect.forEach( |
| 246 | clusterNames, |
| 247 | (clusterName) => |
| 248 | eks.listFargateProfiles.pages({ clusterName }).pipe( |
| 249 | Stream.runCollect, |
| 250 | Effect.map((chunk) => |
| 251 | Array.from(chunk).flatMap((page) => page.fargateProfileNames ?? []), |
| 252 | ), |
| 253 | Effect.flatMap((names) => |
| 254 | Effect.forEach( |
| 255 | names, |
| 256 | (fargateProfileName) => readProfile({ clusterName, fargateProfileName }), |
| 257 | { concurrency: 5 }, |
| 258 | ), |
| 259 | ), |
| 260 | ), |
| 261 | { concurrency: 5 }, |
| 262 | ); |
| 263 | |
| 264 | return perCluster |
| 265 | .flat() |
| 266 | .filter((state): state is FargateProfile["Attributes"] => state !== undefined); |
| 267 | }), |
| 268 | diff: Effect.fn(function* ({ id, olds = {} as FargateProfileProps, news }) { |
| 269 | if (!isResolved(news)) return; |
| 270 | if ((yield* toProfileName(id, olds)) !== (yield* toProfileName(id, news ?? {}))) { |
| 271 | return { action: "replace" } as const; |
| 272 | } |
| 273 | if (olds.clusterName !== news.clusterName) { |
| 274 | return { action: "replace" } as const; |
| 275 | } |
| 276 | if (olds.podExecutionRoleArn !== news.podExecutionRoleArn) { |
| 277 | return { action: "replace" } as const; |
| 278 | } |
| 279 | if (JSON.stringify(olds.subnets ?? []) !== JSON.stringify(news.subnets ?? [])) { |
| 280 | return { action: "replace" } as const; |
| 281 | } |
| 282 | if (JSON.stringify(olds.selectors ?? []) !== JSON.stringify(news.selectors ?? [])) { |
| 283 | return { action: "replace" } as const; |
| 284 | } |
| 285 | }), |
| 286 | read: Effect.fn(function* ({ id, olds, output }) { |
| 287 | const clusterName = (output?.clusterName ?? (olds?.clusterName as string | undefined)) as |
| 288 | | string |
| 289 | | undefined; |
| 290 | if (!clusterName) return undefined; |
| 291 | const fargateProfileName = |
| 292 | output?.fargateProfileName ?? (yield* toProfileName(id, olds ?? {})); |
| 293 | const state = yield* readProfile({ clusterName, fargateProfileName }); |
| 294 | if (!state) return undefined; |
| 295 | return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state); |
| 296 | }), |
| 297 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 298 | const clusterName = news.clusterName as string; |
| 299 | const fargateProfileName = yield* toProfileName(id, news); |
| 300 | const desiredTags = { |
| 301 | ...(yield* createInternalTags(id)), |
| 302 | ...news.tags, |
| 303 | }; |
| 304 | |
| 305 | // Observe — cloud state is authoritative. |
| 306 | let state = yield* readProfile({ clusterName, fargateProfileName }); |
| 307 | |
| 308 | // Ensure — create if missing. A create raises ResourceInUseException |
| 309 | // if another profile on the cluster is creating/deleting; back off |
| 310 | // and retry. Tolerate a create race with a peer reconciler. |
| 311 | if (!state) { |
| 312 | yield* eks |
| 313 | .createFargateProfile({ |
| 314 | clusterName, |
| 315 | fargateProfileName, |
| 316 | podExecutionRoleArn: news.podExecutionRoleArn as string, |
| 317 | selectors: news.selectors, |
| 318 | subnets: news.subnets as string[] | undefined, |
| 319 | tags: desiredTags, |
| 320 | clientRequestToken: yield* toClientRequestToken(id, "create"), |
| 321 | }) |
| 322 | .pipe( |
| 323 | Effect.catchTag("ResourceInUseException", () => |
| 324 | Effect.fail(new FargateProfileBusy()), |
| 325 | ), |
| 326 | Effect.retry({ |
| 327 | while: (error) => error instanceof FargateProfileBusy, |
| 328 | schedule: busySchedule, |
| 329 | }), |
| 330 | Effect.catchIf( |
| 331 | (error) => error instanceof FargateProfileBusy, |
| 332 | () => Effect.void, |
| 333 | ), |
| 334 | ); |
| 335 | |
| 336 | yield* session.note(`Creating EKS Fargate profile ${fargateProfileName}...`); |
| 337 | state = yield* waitForProfileActive(clusterName, fargateProfileName); |
| 338 | } |
| 339 | |
| 340 | // Sync tags — the only mutable aspect. Diff observed cloud tags |
| 341 | // against desired. |
| 342 | const { removed, upsert } = diffTags(state.tags, desiredTags); |
| 343 | if (upsert.length > 0) { |
| 344 | yield* eks.tagResource({ |
| 345 | resourceArn: state.fargateProfileArn, |
| 346 | tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value] as const)), |
| 347 | }); |
| 348 | } |
| 349 | if (removed.length > 0) { |
| 350 | yield* eks.untagResource({ |
| 351 | resourceArn: state.fargateProfileArn, |
| 352 | tagKeys: removed, |
| 353 | }); |
| 354 | } |
| 355 | |
| 356 | yield* session.note(state.fargateProfileArn); |
| 357 | |
| 358 | const final = yield* readProfile({ clusterName, fargateProfileName }); |
| 359 | if (!final) { |
| 360 | return yield* new FargateProfileUnexpectedResponse({ |
| 361 | message: `EKS Fargate profile '${fargateProfileName}' could not be read after reconcile`, |
| 362 | }); |
| 363 | } |
| 364 | return final; |
| 365 | }), |
| 366 | delete: Effect.fn(function* ({ output }) { |
| 367 | yield* eks |
| 368 | .deleteFargateProfile({ |
| 369 | clusterName: output.clusterName, |
| 370 | fargateProfileName: output.fargateProfileName, |
| 371 | }) |
| 372 | .pipe( |
| 373 | Effect.catchTags({ |
| 374 | ResourceNotFoundException: () => Effect.void, |
| 375 | // A concurrent profile create/delete on the cluster raises |
| 376 | // ResourceInUseException — back off and retry the delete. |
| 377 | ResourceInUseException: () => Effect.fail(new FargateProfileBusy()), |
| 378 | }), |
| 379 | Effect.retry({ |
| 380 | while: (error) => error instanceof FargateProfileBusy, |
| 381 | schedule: busySchedule, |
| 382 | }), |
| 383 | Effect.catchIf( |
| 384 | (error) => error instanceof FargateProfileBusy, |
| 385 | () => Effect.void, |
| 386 | ), |
| 387 | ); |
| 388 | yield* waitForProfileDeleted(output.clusterName, output.fargateProfileName); |
| 389 | }), |
| 390 | }; |
| 391 | }), |
| 392 | ); |