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 { |
| 2 | ClusterAdapter, |
| 3 | ClusterNotFoundError, |
| 4 | type ClusterAdapterService, |
| 5 | type ClusterTransport, |
| 6 | type ImageRegistryResolveOptions, |
| 7 | type WorkloadIdentityReconcileOptions, |
| 8 | } from "@alchemy.run/kubernetes/ClusterAdapter"; |
| 9 | import type { Connection } from "@alchemy.run/kubernetes/Connection"; |
| 10 | import { Credentials } from "@distilled.cloud/aws/Credentials"; |
| 11 | import * as ecr from "@distilled.cloud/aws/ecr"; |
| 12 | import * as eks from "@distilled.cloud/aws/eks"; |
| 13 | import { Region, type RegionName } from "@distilled.cloud/aws/Region"; |
| 14 | import * as SigV4 from "@distilled.cloud/aws/SigV4"; |
| 15 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 16 | import { Self } from "alchemy/Self"; |
| 17 | import * as Data from "effect/Data"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as FileSystem from "effect/FileSystem"; |
| 20 | import type { HttpClient } from "effect/http/HttpClient"; |
| 21 | import * as Layer from "effect/Layer"; |
| 22 | import * as Path from "effect/Path"; |
| 23 | import * as Redacted from "effect/Redacted"; |
| 24 | import { makeImageSource, type ImageSourceLike } from "../ECR/ImageSource.ts"; |
| 25 | import { AWSEnvironment } from "../Environment.ts"; |
| 26 | import type { PolicyStatement } from "../IAM/Policy.ts"; |
| 27 | /** |
| 28 | * The `aws-eks` {@link ClusterAdapter}: everything platform-specific about |
| 29 | * running `Kubernetes.*` workloads on Amazon EKS. |
| 30 | * |
| 31 | * - **connect** — SigV4 bearer tokens (STS presign) against the cluster |
| 32 | * endpoint, re-describing the cluster when the connection doesn't carry |
| 33 | * endpoint/CA (or they've gone stale). |
| 34 | * - **identity** — EKS Pod Identity: a generated IAM role + |
| 35 | * `PodIdentityAssociation`, with `policyStatements` host bindings landed |
| 36 | * as the role's inline policy. |
| 37 | * - **registry** — a per-workload ECR repository; `main` programs are |
| 38 | * bundled, `context` Dockerfiles built, and `image` refs mirrored into |
| 39 | * it. |
| 40 | * - **bootstrap** — generated container entries wiring the AWS credential |
| 41 | * chain so Pod Identity's container-credentials endpoint resolves inside |
| 42 | * the pod. |
| 43 | * - **loadBalancerDefaults** — EKS Auto Mode's `loadBalancerClass` and the |
| 44 | * internet-facing NLB scheme. |
| 45 | * |
| 46 | * Registered by `AWS.providers()`; resolved dynamically by the |
| 47 | * `Kubernetes.*` providers via the connection's `auth.kind`. |
| 48 | */ |
| 49 | import { |
| 50 | attachPolicyStatements, |
| 51 | deleteAssociation, |
| 52 | deletePodRole, |
| 53 | ensureAssociation, |
| 54 | ensurePodRole, |
| 55 | } from "./internal/podIdentity.ts"; |
| 56 | |
| 57 | export class KubernetesAdapterNotReady extends Data.TaggedError("KubernetesAdapterNotReady")<{ |
| 58 | readonly message: string; |
| 59 | readonly cause?: unknown; |
| 60 | }> {} |
| 61 | |
| 62 | declare module "@alchemy.run/kubernetes/Connection" { |
| 63 | interface AuthRegistry { |
| 64 | /** |
| 65 | * Authenticate against an Amazon EKS cluster with SigV4 bearer tokens |
| 66 | * minted from the ambient AWS credentials. Contributed by |
| 67 | * `AWS.providers()` — `AWS.EKS.Cluster` attributes expose a ready-made |
| 68 | * `connection` carrying this descriptor. |
| 69 | */ |
| 70 | "aws-eks": { |
| 71 | /** The EKS cluster name. */ |
| 72 | clusterName: string; |
| 73 | /** |
| 74 | * The cluster's region. |
| 75 | * @default the ambient AWS region |
| 76 | */ |
| 77 | region?: string; |
| 78 | }; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | declare module "@alchemy.run/kubernetes/ClusterAdapter" { |
| 83 | interface IdentityStateRegistry { |
| 84 | /** EKS Pod Identity: generated IAM role + association. */ |
| 85 | "aws-pod-identity": { |
| 86 | /** The ARN of the IAM role pods assume via Pod Identity. */ |
| 87 | roleArn: string; |
| 88 | /** The name of the IAM role pods assume via Pod Identity. */ |
| 89 | roleName: string; |
| 90 | /** The ARN of the Pod Identity association binding the role. */ |
| 91 | associationArn: string; |
| 92 | /** The ID of the Pod Identity association binding the role. */ |
| 93 | associationId: string; |
| 94 | }; |
| 95 | } |
| 96 | interface RegistryStateRegistry { |
| 97 | /** The per-workload ECR repository holding the image. */ |
| 98 | "aws-ecr": { |
| 99 | /** The name of the ECR repository holding the image. */ |
| 100 | repositoryName: string; |
| 101 | /** The URI of the ECR repository holding the image. */ |
| 102 | repositoryUri: string; |
| 103 | }; |
| 104 | } |
| 105 | interface WorkloadIdentityOptions { |
| 106 | /** |
| 107 | * Managed policy ARNs attached to the generated pod-identity role in |
| 108 | * addition to the inline policy synthesized from bindings (EKS only). |
| 109 | */ |
| 110 | managedPolicyArns?: string[]; |
| 111 | } |
| 112 | interface WorkloadBindingContract { |
| 113 | /** |
| 114 | * IAM policy statements landed on the workload's pod-identity role |
| 115 | * (EKS only) — the same host-binding channel as `AWS.Lambda.Function` |
| 116 | * and `AWS.ECS.Task`. |
| 117 | */ |
| 118 | policyStatements?: PolicyStatement[]; |
| 119 | } |
| 120 | interface WorkloadServicesRegistry { |
| 121 | /** AWS credential-chain services ambient inside EKS workload pods. */ |
| 122 | aws: Credentials | Region | AWSEnvironment; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /** Services the adapter's methods close over at layer build. */ |
| 127 | type EksAdapterDeps = |
| 128 | | Credentials |
| 129 | | HttpClient |
| 130 | | Region |
| 131 | | AWSEnvironment |
| 132 | | FileSystem.FileSystem |
| 133 | | Path.Path; |
| 134 | |
| 135 | /** Mint an EKS SigV4 bearer token (STS `GetCallerIdentity` presign). */ |
| 136 | const mintEksToken = Effect.fn(function* (clusterName: string, region: string) { |
| 137 | const credentials = yield* yield* Credentials; |
| 138 | |
| 139 | const presigned = yield* SigV4.sign({ |
| 140 | method: "GET", |
| 141 | url: `https://sts.${region}.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15&X-Amz-Expires=60`, |
| 142 | headers: { "x-k8s-aws-id": clusterName }, |
| 143 | accessKeyId: Redacted.value(credentials.accessKeyId), |
| 144 | secretAccessKey: credentials.secretAccessKey, |
| 145 | sessionToken: credentials.sessionToken, |
| 146 | service: "sts", |
| 147 | region, |
| 148 | signQuery: true, |
| 149 | allHeaders: true, |
| 150 | }); |
| 151 | |
| 152 | return `k8s-aws-v1.${Buffer.from(presigned.url).toString("base64url")}`; |
| 153 | }); |
| 154 | |
| 155 | /** |
| 156 | * Build a {@link ClusterTransport} for an EKS cluster from known |
| 157 | * endpoint/CA. Captures the ambient AWS services so the per-request token |
| 158 | * mint is self-contained — used by the adapter and by the |
| 159 | * `AWS.EKS.Cluster` provider's own kubernetes-object binding channel. |
| 160 | */ |
| 161 | export const makeEksTransport = Effect.fn(function* (options: { |
| 162 | clusterName: string; |
| 163 | region?: string | undefined; |
| 164 | endpoint: string; |
| 165 | certificateAuthorityData: string; |
| 166 | }) { |
| 167 | const context = yield* Effect.context<Credentials | AWSEnvironment>(); |
| 168 | const region = options.region ?? (yield* AWSEnvironment.current).region; |
| 169 | return { |
| 170 | endpoint: options.endpoint, |
| 171 | certificateAuthorityData: options.certificateAuthorityData, |
| 172 | headers: mintEksToken(options.clusterName, region).pipe( |
| 173 | Effect.map((token) => ({ Authorization: `Bearer ${token}` })), |
| 174 | Effect.provideContext(context), |
| 175 | ), |
| 176 | } satisfies ClusterTransport; |
| 177 | }); |
| 178 | |
| 179 | /** |
| 180 | * The `Kubernetes.Connection` of an EKS cluster — stamped on |
| 181 | * `AWS.EKS.Cluster` attributes so the cluster resource can be passed |
| 182 | * directly as any `Kubernetes.*` workload's `cluster`. |
| 183 | */ |
| 184 | export const eksConnectionOf = (options: { |
| 185 | clusterName: string; |
| 186 | region: string; |
| 187 | endpoint?: string | undefined; |
| 188 | certificateAuthorityData?: string | undefined; |
| 189 | }): Connection => ({ |
| 190 | endpoint: options.endpoint, |
| 191 | certificateAuthorityData: options.certificateAuthorityData, |
| 192 | auth: { |
| 193 | kind: "aws-eks", |
| 194 | clusterName: options.clusterName, |
| 195 | region: options.region, |
| 196 | }, |
| 197 | }); |
| 198 | |
| 199 | const narrowEksAuth = (connection: Connection) => |
| 200 | connection.auth.kind === "aws-eks" |
| 201 | ? Effect.succeed(connection.auth) |
| 202 | : Effect.die(new Error(`aws-eks adapter received auth kind '${connection.auth.kind}'`)); |
| 203 | |
| 204 | /** |
| 205 | * Provide a per-connection region override so a cluster in another region |
| 206 | * than the ambient one describes correctly. |
| 207 | */ |
| 208 | const withRegion = |
| 209 | (region: string | undefined) => |
| 210 | <A, E, R>(self: Effect.Effect<A, E, R>) => |
| 211 | region === undefined |
| 212 | ? self |
| 213 | : Effect.provideService(self, Region, Effect.succeed(region as RegionName)); |
| 214 | |
| 215 | const createRoleName = (id: string) => createPhysicalName({ id: `${id}-pod-role`, maxLength: 64 }); |
| 216 | |
| 217 | const createPolicyName = (id: string) => |
| 218 | createPhysicalName({ id: `${id}-pod-policy`, maxLength: 128 }); |
| 219 | |
| 220 | const createRepositoryName = (id: string) => |
| 221 | createPhysicalName({ |
| 222 | id: `${id}-repo`, |
| 223 | maxLength: 256, |
| 224 | lowercase: true, |
| 225 | }); |
| 226 | |
| 227 | /** |
| 228 | * Generated container entry for an Effect-native EKS server: resolves the |
| 229 | * program's registered runners and serves the returned `{ fetch }` handler |
| 230 | * on `PORT`. Credentials use the full chain so EKS Pod Identity's |
| 231 | * container-credentials endpoint resolves inside the pod. |
| 232 | */ |
| 233 | export const makeEksServerBootstrap = |
| 234 | (handler: string) => |
| 235 | (importPath: string): string => |
| 236 | ` |
| 237 | import { BunServices } from "@effect/platform-bun"; |
| 238 | import { BunHttpServer } from "alchemy/Http"; |
| 239 | import { Stack } from "alchemy/Stack"; |
| 240 | import { Stage } from "alchemy/Stage"; |
| 241 | import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime"; |
| 242 | import { provideProcessTelemetry } from "alchemy/Telemetry"; |
| 243 | import * as Context from "effect/Context"; |
| 244 | import * as Config from "effect/Config"; |
| 245 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 246 | import * as Credentials from "@distilled.cloud/aws/Credentials"; |
| 247 | import * as Effect from "effect/Effect"; |
| 248 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 249 | import * as Layer from "effect/Layer"; |
| 250 | import * as Logger from "effect/Logger"; |
| 251 | import * as Region from "@distilled.cloud/aws/Region"; |
| 252 | |
| 253 | import { ${handler} as entrypoint } from ${JSON.stringify(importPath)}; |
| 254 | |
| 255 | // Normalize the entrypoint export: an inline-effect class default export is |
| 256 | // an Effect resolving the platform instance, while the tagged form |
| 257 | // (X.make(props, impl)) exports a Layer providing the Self tag. Both fold |
| 258 | // into a Layer via makeEntrypointLayer (same pattern as the ECS/Lambda/ |
| 259 | // Cloudflare Container bridges). |
| 260 | const tag = Context.Service("${Self.key}"); |
| 261 | const layer = makeEntrypointLayer(tag, entrypoint); |
| 262 | |
| 263 | const platform = Layer.mergeAll( |
| 264 | BunServices.layer, |
| 265 | FetchHttpClient.layer, |
| 266 | Logger.layer([Logger.consolePretty()]), |
| 267 | ); |
| 268 | |
| 269 | // Resolve the bundled program (the runners registered via host.run / serve) |
| 270 | // and run it with a Bun HTTP server bound to PORT, so a returned { fetch } |
| 271 | // handler is served and host.run loops stay alive. Credentials use the full |
| 272 | // chain so EKS Pod Identity's container-credentials endpoint |
| 273 | // (AWS_CONTAINER_CREDENTIALS_FULL_URI + token file) resolves inside the pod. |
| 274 | const program = tag.pipe( |
| 275 | // Process-lifetime telemetry: built once into the root scope; exporters |
| 276 | // batch on their intervals and flush when the scope closes on graceful |
| 277 | // shutdown. |
| 278 | Effect.flatMap((host) => |
| 279 | host.RuntimeContext.exports.pipe( |
| 280 | Effect.flatMap((exports) => exports.program), |
| 281 | provideProcessTelemetry(host.RuntimeContext), |
| 282 | ), |
| 283 | ), |
| 284 | Effect.provide( |
| 285 | layer.pipe(Layer.provideMerge(Layer.mergeAll( |
| 286 | Layer.effect( |
| 287 | Stack, |
| 288 | Effect.all([ |
| 289 | Config.String("ALCHEMY_STACK_NAME"), |
| 290 | Config.String("ALCHEMY_STAGE") |
| 291 | ]).pipe( |
| 292 | Effect.map(([name, stage]) => ({ |
| 293 | name, |
| 294 | stage, |
| 295 | bindings: {}, |
| 296 | resources: {} |
| 297 | })) |
| 298 | ) |
| 299 | ), |
| 300 | // Module-scope declarations shared with the Stack may read the stage. |
| 301 | Layer.effect(Stage, Config.String("ALCHEMY_STAGE")), |
| 302 | )), |
| 303 | Layer.provideMerge(Credentials.fromChain()), |
| 304 | Layer.provideMerge(Region.fromEnv()), |
| 305 | Layer.provideMerge(BunHttpServer()), |
| 306 | Layer.provideMerge(platform), |
| 307 | Layer.provideMerge( |
| 308 | Layer.succeed( |
| 309 | ConfigProvider.ConfigProvider, |
| 310 | reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env) |
| 311 | ) |
| 312 | ), |
| 313 | ) |
| 314 | ), |
| 315 | Effect.scoped |
| 316 | ); |
| 317 | |
| 318 | console.log(\`EKS Deployment bootstrap starting on port \${process.env.PORT ?? 3000}...\`); |
| 319 | await Effect.runPromise(program).catch((err) => { |
| 320 | console.error("EKS Deployment bootstrap failed:", err); |
| 321 | process.exit(1); |
| 322 | }); |
| 323 | `; |
| 324 | |
| 325 | /** |
| 326 | * Generated container entry for an Effect-native EKS Job: resolves the |
| 327 | * program's `run` effect, executes it to completion, and exits. No HTTP |
| 328 | * server is started. Credentials use the full chain so EKS Pod Identity's |
| 329 | * container-credentials endpoint resolves inside the pod. |
| 330 | */ |
| 331 | export const makeEksJobBootstrap = |
| 332 | (handler: string) => |
| 333 | (importPath: string): string => |
| 334 | ` |
| 335 | import { BunServices } from "@effect/platform-bun"; |
| 336 | import { Stack } from "alchemy/Stack"; |
| 337 | import { Stage } from "alchemy/Stage"; |
| 338 | import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime"; |
| 339 | import { provideProcessTelemetry } from "alchemy/Telemetry"; |
| 340 | import * as Context from "effect/Context"; |
| 341 | import * as Config from "effect/Config"; |
| 342 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 343 | import * as Credentials from "@distilled.cloud/aws/Credentials"; |
| 344 | import * as Effect from "effect/Effect"; |
| 345 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 346 | import * as Layer from "effect/Layer"; |
| 347 | import * as Logger from "effect/Logger"; |
| 348 | import * as Region from "@distilled.cloud/aws/Region"; |
| 349 | |
| 350 | import { ${handler} as entrypoint } from ${JSON.stringify(importPath)}; |
| 351 | |
| 352 | // Normalize the entrypoint export (see the server bootstrap). |
| 353 | const tag = Context.Service("${Self.key}"); |
| 354 | const layer = makeEntrypointLayer(tag, entrypoint); |
| 355 | |
| 356 | const platform = Layer.mergeAll( |
| 357 | BunServices.layer, |
| 358 | FetchHttpClient.layer, |
| 359 | Logger.layer([Logger.consolePretty()]), |
| 360 | ); |
| 361 | |
| 362 | // Resolve the bundled program's registered one-shot runners (the shape's |
| 363 | // \`run\` effect and any host.run work) and execute them to completion. |
| 364 | const program = tag.pipe( |
| 365 | // Process-lifetime telemetry: built once into the root scope; exporters |
| 366 | // batch on their intervals and flush when the scope closes as the |
| 367 | // one-shot program completes. |
| 368 | Effect.flatMap((host) => |
| 369 | host.RuntimeContext.exports.pipe( |
| 370 | Effect.flatMap((exports) => exports.program), |
| 371 | provideProcessTelemetry(host.RuntimeContext), |
| 372 | ), |
| 373 | ), |
| 374 | Effect.provide( |
| 375 | layer.pipe(Layer.provideMerge(Layer.mergeAll( |
| 376 | Layer.effect( |
| 377 | Stack, |
| 378 | Effect.all([ |
| 379 | Config.String("ALCHEMY_STACK_NAME"), |
| 380 | Config.String("ALCHEMY_STAGE") |
| 381 | ]).pipe( |
| 382 | Effect.map(([name, stage]) => ({ |
| 383 | name, |
| 384 | stage, |
| 385 | bindings: {}, |
| 386 | resources: {} |
| 387 | })) |
| 388 | ) |
| 389 | ), |
| 390 | // Module-scope declarations shared with the Stack may read the stage. |
| 391 | Layer.effect(Stage, Config.String("ALCHEMY_STAGE")), |
| 392 | )), |
| 393 | Layer.provideMerge(Credentials.fromChain()), |
| 394 | Layer.provideMerge(Region.fromEnv()), |
| 395 | Layer.provideMerge(platform), |
| 396 | Layer.provideMerge( |
| 397 | Layer.succeed( |
| 398 | ConfigProvider.ConfigProvider, |
| 399 | reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env) |
| 400 | ) |
| 401 | ), |
| 402 | ) |
| 403 | ), |
| 404 | Effect.scoped |
| 405 | ); |
| 406 | |
| 407 | console.log("EKS Job bootstrap starting..."); |
| 408 | await Effect.runPromise(program).catch((err) => { |
| 409 | console.error("EKS Job bootstrap failed:", err); |
| 410 | process.exit(1); |
| 411 | }); |
| 412 | // Run-to-completion semantics: exit 0 explicitly so lingering handles |
| 413 | // (sockets, timers) never keep the pod alive after the work is done. |
| 414 | process.exit(0); |
| 415 | `; |
| 416 | |
| 417 | /** |
| 418 | * The `aws-eks` cluster adapter layer. Provided (merged) by |
| 419 | * `AWS.providers()` so the `Kubernetes.*` workload providers can resolve |
| 420 | * it from the stack context. |
| 421 | */ |
| 422 | export const EksKubernetesAdapter = () => |
| 423 | Layer.effect( |
| 424 | ClusterAdapter("aws-eks"), |
| 425 | Effect.gen(function* () { |
| 426 | const imageSource = yield* makeImageSource; |
| 427 | const context = yield* Effect.context<EksAdapterDeps>(); |
| 428 | |
| 429 | // Discharge the layer-captured AWS services; per-resource engine |
| 430 | // services (ResourceContext/Stack/Stage) stay ambient — they are provided |
| 431 | // by the invoking lifecycle operation, never captured here. |
| 432 | const withAws = |
| 433 | (region: string | undefined) => |
| 434 | <A, E, R>(self: Effect.Effect<A, E, R>) => |
| 435 | Effect.provideContext(withRegion(region)(self), context); |
| 436 | |
| 437 | /** |
| 438 | * Describe the cluster. NotFound is gone. DELETING is gone only when |
| 439 | * the API endpoint is gone. A live endpoint still needs Service |
| 440 | * deletion so a load balancer finalizer can release the NLB. A missing |
| 441 | * CA with that endpoint is not "gone": connect fails and destroy retries. |
| 442 | */ |
| 443 | const describeLiveCluster = Effect.fn(function* (auth: { |
| 444 | clusterName: string; |
| 445 | region?: string | undefined; |
| 446 | }) { |
| 447 | const described = yield* eks.describeCluster({ name: auth.clusterName }).pipe( |
| 448 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 449 | withAws(auth.region), |
| 450 | ); |
| 451 | const cluster = described?.cluster; |
| 452 | const apiGone = cluster?.status === "DELETING" && !cluster.endpoint; |
| 453 | if (!cluster || apiGone) { |
| 454 | return yield* new ClusterNotFoundError({ |
| 455 | message: `EKS cluster '${auth.clusterName}' no longer exists`, |
| 456 | }); |
| 457 | } |
| 458 | return cluster; |
| 459 | }); |
| 460 | |
| 461 | const connect = Effect.fn(function* (connection: Connection) { |
| 462 | const auth = yield* narrowEksAuth(connection); |
| 463 | // Always describe. A persisted endpoint does not prove the cluster |
| 464 | // still exists, and delete uses ClusterNotFoundError to skip |
| 465 | // in-cluster objects and still remove the pod role and repository. |
| 466 | // Describe also picks up an endpoint rotation. |
| 467 | const cluster = yield* describeLiveCluster(auth); |
| 468 | const endpoint = cluster.endpoint; |
| 469 | const certificateAuthorityData = cluster.certificateAuthority?.data; |
| 470 | if (!endpoint || !certificateAuthorityData) { |
| 471 | return yield* new KubernetesAdapterNotReady({ |
| 472 | message: |
| 473 | `EKS cluster '${auth.clusterName}' has no endpoint or ` + |
| 474 | "certificate authority data yet (still creating?)", |
| 475 | }); |
| 476 | } |
| 477 | return yield* makeEksTransport({ |
| 478 | clusterName: auth.clusterName, |
| 479 | region: auth.region, |
| 480 | endpoint, |
| 481 | certificateAuthorityData, |
| 482 | }).pipe(withAws(auth.region)); |
| 483 | }); |
| 484 | |
| 485 | const identityReconcile = Effect.fn(function* (options: WorkloadIdentityReconcileOptions) { |
| 486 | const auth = yield* narrowEksAuth(options.connection); |
| 487 | return yield* Effect.gen(function* () { |
| 488 | const state = options.state; |
| 489 | const roleName = |
| 490 | typeof state?.roleName === "string" |
| 491 | ? state.roleName |
| 492 | : yield* createRoleName(options.id); |
| 493 | const policyName = yield* createPolicyName(options.id); |
| 494 | |
| 495 | // Ensure IAM role + inline policy from bindings. |
| 496 | const roleArn = |
| 497 | typeof state?.roleArn === "string" |
| 498 | ? state.roleArn |
| 499 | : yield* ensurePodRole({ |
| 500 | id: options.id, |
| 501 | roleName, |
| 502 | managedPolicyArns: options.options?.managedPolicyArns, |
| 503 | }); |
| 504 | yield* attachPolicyStatements({ |
| 505 | roleName, |
| 506 | policyName, |
| 507 | bindings: options.bindings, |
| 508 | }); |
| 509 | |
| 510 | // Ensure the pod identity association wires the role to the SA. |
| 511 | const { associationArn, associationId } = yield* ensureAssociation({ |
| 512 | id: options.id, |
| 513 | clusterName: auth.clusterName, |
| 514 | namespace: options.namespace, |
| 515 | serviceAccount: options.serviceAccount, |
| 516 | roleArn, |
| 517 | }); |
| 518 | |
| 519 | // Unlike ECS/Fargate (whose agent injects `AWS_REGION`), EKS pods |
| 520 | // get no region env var — inject it so the bootstrap's |
| 521 | // `Region.fromEnv()` resolves inside the pod. |
| 522 | const { region } = yield* AWSEnvironment.current; |
| 523 | |
| 524 | return { |
| 525 | env: { |
| 526 | AWS_REGION: auth.region ?? region, |
| 527 | }, |
| 528 | state: { |
| 529 | kind: "aws-pod-identity" as const, |
| 530 | roleArn, |
| 531 | roleName, |
| 532 | associationArn, |
| 533 | associationId, |
| 534 | }, |
| 535 | }; |
| 536 | }).pipe(withAws(auth.region)); |
| 537 | }); |
| 538 | |
| 539 | const identityDelete = Effect.fn(function* (options: { |
| 540 | connection: Connection | undefined; |
| 541 | state: Record<string, unknown> | undefined; |
| 542 | }) { |
| 543 | const state = options.state; |
| 544 | const auth = |
| 545 | options.connection !== undefined ? yield* narrowEksAuth(options.connection) : undefined; |
| 546 | yield* Effect.gen(function* () { |
| 547 | // The association is cluster-scoped: skip it when the cluster is |
| 548 | // gone or DELETING (it dies with the cluster; EKS also rejects |
| 549 | // the delete with `InvalidRequestException: Cluster is in |
| 550 | // invalid state` mid-teardown). |
| 551 | if (auth !== undefined && typeof state?.associationId === "string") { |
| 552 | const cluster = yield* describeLiveCluster(auth).pipe( |
| 553 | Effect.catchTag("Kubernetes.ClusterNotFoundError", () => Effect.undefined), |
| 554 | ); |
| 555 | if (cluster) { |
| 556 | yield* deleteAssociation({ |
| 557 | clusterName: auth.clusterName, |
| 558 | associationId: state.associationId, |
| 559 | }).pipe(Effect.catchTag("InvalidRequestException", () => Effect.void)); |
| 560 | } |
| 561 | } |
| 562 | if (typeof state?.roleName === "string") { |
| 563 | yield* deletePodRole(state.roleName); |
| 564 | } |
| 565 | }).pipe(withAws(auth?.region)); |
| 566 | }); |
| 567 | |
| 568 | const registryResolve = Effect.fn(function* (options: ImageRegistryResolveOptions) { |
| 569 | const state = options.state; |
| 570 | const repositoryName = |
| 571 | typeof state?.repositoryName === "string" |
| 572 | ? state.repositoryName |
| 573 | : // Physical-name generation reads the resource's ambient |
| 574 | // ResourceContext/Stack/Stage — do not shadow them with the |
| 575 | // layer-captured context. |
| 576 | yield* createRepositoryName(options.id); |
| 577 | const repositoryUri = |
| 578 | typeof state?.repositoryUri === "string" && state.repositoryName === repositoryName |
| 579 | ? state.repositoryUri |
| 580 | : undefined; |
| 581 | const resolved = yield* imageSource |
| 582 | .resolve({ |
| 583 | id: options.id, |
| 584 | source: options.source as ImageSourceLike, |
| 585 | repositoryName, |
| 586 | repositoryUri, |
| 587 | tags: options.tags, |
| 588 | platform: options.platform, |
| 589 | port: options.port, |
| 590 | isExternal: options.isExternal, |
| 591 | bootstrap: options.bootstrap, |
| 592 | session: options.session, |
| 593 | }) |
| 594 | .pipe(Effect.provideContext(context)); |
| 595 | return { |
| 596 | imageUri: resolved.imageUri, |
| 597 | codeHash: resolved.codeHash, |
| 598 | state: { |
| 599 | kind: "aws-ecr" as const, |
| 600 | repositoryName: resolved.repositoryName, |
| 601 | repositoryUri: resolved.repositoryUri, |
| 602 | }, |
| 603 | }; |
| 604 | }); |
| 605 | |
| 606 | const registryHash = Effect.fn(function* (options: { |
| 607 | source: ImageSourceLike; |
| 608 | platform: string; |
| 609 | port?: number | undefined; |
| 610 | isExternal?: boolean | undefined; |
| 611 | bootstrap: (importPath: string) => string; |
| 612 | }) { |
| 613 | return yield* imageSource |
| 614 | .hash({ |
| 615 | source: options.source, |
| 616 | platform: options.platform, |
| 617 | port: options.port, |
| 618 | isExternal: options.isExternal, |
| 619 | bootstrap: options.bootstrap, |
| 620 | }) |
| 621 | .pipe(Effect.provideContext(context)); |
| 622 | }); |
| 623 | |
| 624 | const registryDelete = Effect.fn(function* (options: { |
| 625 | state: Record<string, unknown> | undefined; |
| 626 | }) { |
| 627 | if (typeof options.state?.repositoryName !== "string") return; |
| 628 | yield* ecr |
| 629 | .deleteRepository({ |
| 630 | repositoryName: options.state.repositoryName, |
| 631 | force: true, |
| 632 | }) |
| 633 | .pipe( |
| 634 | Effect.catchTag("RepositoryNotFoundException", () => Effect.void), |
| 635 | Effect.provideContext(context), |
| 636 | ); |
| 637 | }); |
| 638 | |
| 639 | const loadBalancerDefaults = Effect.fn(function* (options: { connection: Connection }) { |
| 640 | const auth = yield* narrowEksAuth(options.connection); |
| 641 | // EKS Auto Mode's built-in load balancer controller only |
| 642 | // reconciles `LoadBalancer` Services whose `spec.loadBalancerClass` |
| 643 | // is `eks.amazonaws.com/nlb` (there is no in-tree cloud provider on |
| 644 | // Auto Mode), and it defaults new NLBs to the *internal* scheme. |
| 645 | // Detect the Auto Mode LB capability from the live cluster and |
| 646 | // default to an internet-facing NLB so the returned `url` is |
| 647 | // actually reachable. |
| 648 | const cluster = yield* describeLiveCluster(auth).pipe( |
| 649 | Effect.catchTag("Kubernetes.ClusterNotFoundError", () => Effect.undefined), |
| 650 | ); |
| 651 | return { |
| 652 | loadBalancerClass: cluster?.kubernetesNetworkConfig?.elasticLoadBalancing?.enabled |
| 653 | ? "eks.amazonaws.com/nlb" |
| 654 | : undefined, |
| 655 | annotations: { |
| 656 | "service.beta.kubernetes.io/aws-load-balancer-scheme": "internet-facing", |
| 657 | }, |
| 658 | }; |
| 659 | }); |
| 660 | |
| 661 | return { |
| 662 | kind: "Kubernetes.ClusterAdapter" as const, |
| 663 | connect, |
| 664 | identity: { |
| 665 | reconcile: identityReconcile, |
| 666 | delete: identityDelete, |
| 667 | }, |
| 668 | registry: { |
| 669 | resolve: registryResolve, |
| 670 | hash: registryHash, |
| 671 | delete: registryDelete, |
| 672 | }, |
| 673 | bootstrap: { |
| 674 | server: makeEksServerBootstrap, |
| 675 | job: makeEksJobBootstrap, |
| 676 | }, |
| 677 | loadBalancerDefaults, |
| 678 | } satisfies ClusterAdapterService; |
| 679 | }), |
| 680 | ); |