@alchemy.run/kubernetes 0.0.0 → 2.0.0-beta.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +41 -4
  3. package/lib/BuiltinAdapters.d.ts +23 -0
  4. package/lib/BuiltinAdapters.d.ts.map +1 -0
  5. package/lib/BuiltinAdapters.js +124 -0
  6. package/lib/BuiltinAdapters.js.map +1 -0
  7. package/lib/Client.d.ts +80 -0
  8. package/lib/Client.d.ts.map +1 -0
  9. package/lib/Client.js +296 -0
  10. package/lib/Client.js.map +1 -0
  11. package/lib/ClusterAdapter.d.ts +322 -0
  12. package/lib/ClusterAdapter.d.ts.map +1 -0
  13. package/lib/ClusterAdapter.js +65 -0
  14. package/lib/ClusterAdapter.js.map +1 -0
  15. package/lib/Connection.d.ts +210 -0
  16. package/lib/Connection.d.ts.map +1 -0
  17. package/lib/Connection.js +58 -0
  18. package/lib/Connection.js.map +1 -0
  19. package/lib/Deployment.d.ts +382 -0
  20. package/lib/Deployment.d.ts.map +1 -0
  21. package/lib/Deployment.js +533 -0
  22. package/lib/Deployment.js.map +1 -0
  23. package/lib/HelmChart.d.ts +147 -0
  24. package/lib/HelmChart.d.ts.map +1 -0
  25. package/lib/HelmChart.js +248 -0
  26. package/lib/HelmChart.js.map +1 -0
  27. package/lib/Job.d.ts +314 -0
  28. package/lib/Job.d.ts.map +1 -0
  29. package/lib/Job.js +426 -0
  30. package/lib/Job.js.map +1 -0
  31. package/lib/LocalCluster.d.ts +243 -0
  32. package/lib/LocalCluster.d.ts.map +1 -0
  33. package/lib/LocalCluster.js +359 -0
  34. package/lib/LocalCluster.js.map +1 -0
  35. package/lib/Manifest.d.ts +148 -0
  36. package/lib/Manifest.d.ts.map +1 -0
  37. package/lib/Manifest.js +200 -0
  38. package/lib/Manifest.js.map +1 -0
  39. package/lib/Objects.d.ts +60 -0
  40. package/lib/Objects.d.ts.map +1 -0
  41. package/lib/Objects.js +132 -0
  42. package/lib/Objects.js.map +1 -0
  43. package/lib/Providers.d.ts +24 -0
  44. package/lib/Providers.d.ts.map +1 -0
  45. package/lib/Providers.js +36 -0
  46. package/lib/Providers.js.map +1 -0
  47. package/lib/index.d.ts +10 -0
  48. package/lib/index.d.ts.map +1 -0
  49. package/lib/index.js +10 -0
  50. package/lib/index.js.map +1 -0
  51. package/lib/internal/declared.d.ts +19 -0
  52. package/lib/internal/declared.d.ts.map +1 -0
  53. package/lib/internal/declared.js +435 -0
  54. package/lib/internal/declared.js.map +1 -0
  55. package/lib/internal/helm.d.ts +65 -0
  56. package/lib/internal/helm.d.ts.map +1 -0
  57. package/lib/internal/helm.js +173 -0
  58. package/lib/internal/helm.js.map +1 -0
  59. package/lib/internal/kind.d.ts +17 -0
  60. package/lib/internal/kind.d.ts.map +1 -0
  61. package/lib/internal/kind.js +31 -0
  62. package/lib/internal/kind.js.map +1 -0
  63. package/lib/internal/kubeconfig.d.ts +79 -0
  64. package/lib/internal/kubeconfig.d.ts.map +1 -0
  65. package/lib/internal/kubeconfig.js +222 -0
  66. package/lib/internal/kubeconfig.js.map +1 -0
  67. package/lib/internal/registry.d.ts +44 -0
  68. package/lib/internal/registry.d.ts.map +1 -0
  69. package/lib/internal/registry.js +72 -0
  70. package/lib/internal/registry.js.map +1 -0
  71. package/lib/internal/workload.d.ts +127 -0
  72. package/lib/internal/workload.d.ts.map +1 -0
  73. package/lib/internal/workload.js +411 -0
  74. package/lib/internal/workload.js.map +1 -0
  75. package/package.json +55 -3
  76. package/src/BuiltinAdapters.ts +194 -0
  77. package/src/Client.ts +465 -0
  78. package/src/ClusterAdapter.ts +370 -0
  79. package/src/Connection.ts +234 -0
  80. package/src/Deployment.ts +851 -0
  81. package/src/HelmChart.ts +388 -0
  82. package/src/Job.ts +689 -0
  83. package/src/LocalCluster.ts +631 -0
  84. package/src/Manifest.ts +295 -0
  85. package/src/Objects.ts +213 -0
  86. package/src/Providers.ts +52 -0
  87. package/src/globals.d.ts +2 -0
  88. package/src/index.ts +9 -0
  89. package/src/internal/declared.ts +471 -0
  90. package/src/internal/helm.ts +245 -0
  91. package/src/internal/kind.ts +43 -0
  92. package/src/internal/kubeconfig.ts +364 -0
  93. package/src/internal/registry.ts +108 -0
  94. package/src/internal/workload.ts +503 -0
@@ -0,0 +1,851 @@
1
+ import { isResolved } from "alchemy/Diff";
2
+ import type { Input } from "alchemy/Input";
3
+ import { createPhysicalName } from "alchemy/PhysicalName";
4
+ import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
5
+ import * as Provider from "alchemy/Provider";
6
+ import { Resource } from "alchemy/Resource";
7
+ import {
8
+ createHostRuntimeContext,
9
+ type HostRuntimeContext,
10
+ type ServerHost as ServerHostService,
11
+ } from "alchemy/Runtime/Process";
12
+ import { Stack } from "alchemy/Stack";
13
+ import { createInternalTags } from "alchemy/Tags";
14
+ import * as Data from "effect/Data";
15
+ import * as Effect from "effect/Effect";
16
+ import * as Schedule from "effect/Schedule";
17
+ import {
18
+ connectCluster,
19
+ deleteObjects,
20
+ ifClusterExists,
21
+ readObject,
22
+ reconcileObjects,
23
+ } from "./Client.ts";
24
+ import {
25
+ findClusterAdapter,
26
+ type ClusterTransport,
27
+ type IdentityState,
28
+ type RegistryState,
29
+ type WorkloadBindingContract,
30
+ type WorkloadIdentityOptions,
31
+ type WorkloadImageSource,
32
+ type WorkloadServices,
33
+ } from "./ClusterAdapter.ts";
34
+ import { toConnection, type ClusterLike, type Connection } from "./Connection.ts";
35
+ import { makeConnectionRegistry } from "./internal/registry.ts";
36
+ import {
37
+ collectBindingEnv,
38
+ containerEnvValue,
39
+ connectionIdentity,
40
+ connectionOfOutput,
41
+ deepMerge,
42
+ imagePlatformOf,
43
+ makeServerBootstrap,
44
+ resolveWorkloadImage,
45
+ tryConnectionOf,
46
+ workloadImageHash,
47
+ } from "./internal/workload.ts";
48
+ import {
49
+ toKubernetesObjectRef,
50
+ type KubernetesObjectDefinition,
51
+ type KubernetesObjectRef,
52
+ } from "./Objects.ts";
53
+ import type { Providers } from "./Providers.ts";
54
+
55
+ export const isDeployment = (value: any): value is Deployment =>
56
+ typeof value === "object" &&
57
+ value !== null &&
58
+ "Type" in value &&
59
+ value.Type === "Kubernetes.Deployment";
60
+
61
+ /**
62
+ * The image-source props shared by the workload platforms. Exactly one of
63
+ * `main` (bundle an inline Effect program), `context`/`dockerfile` (build
64
+ * the user's own Dockerfile), or `image` (a pre-built registry reference).
65
+ */
66
+ export interface DeploymentPropsBase extends PlatformProps {
67
+ /**
68
+ * Target cluster the workload is deployed onto: a cluster resource
69
+ * (`Kubernetes.LocalCluster`, `AWS.EKS.Cluster`), a
70
+ * `Kubernetes.KubeConfig(...)`, or a raw `Kubernetes.Connection`. The
71
+ * connection supplies authentication and the registry `main` / `context`
72
+ * images are pushed to. Also accepts an Effect that produces any of
73
+ * these, so `{ cluster: Cluster }` and `{ cluster: yield* Cluster }`
74
+ * both type-check.
75
+ */
76
+ cluster: ClusterLike | Effect.Effect<Input<ClusterLike>, never, any>;
77
+ /**
78
+ * Base name for the generated Deployment / Service / ServiceAccount. If
79
+ * omitted, a deterministic name is derived from the stack, stage, and
80
+ * logical id.
81
+ */
82
+ name?: string;
83
+ /**
84
+ * Kubernetes namespace to deploy into. The namespace must already exist.
85
+ * @default "default"
86
+ */
87
+ namespace?: string;
88
+ /**
89
+ * HTTP port exposed by the container and the Service.
90
+ * @default 3000
91
+ */
92
+ port?: number;
93
+ /**
94
+ * Replica count for the Deployment.
95
+ * @default 1
96
+ */
97
+ replicas?: number;
98
+ /**
99
+ * Kubernetes Service type. `LoadBalancer` provisions the platform's
100
+ * cloud load balancer and exposes its hostname as the Deployment `url`.
101
+ * @default "LoadBalancer"
102
+ */
103
+ serviceType?: "ClusterIP" | "NodePort" | "LoadBalancer";
104
+ /**
105
+ * Annotations applied to the Service (e.g. load-balancer scheme /
106
+ * target-type hints).
107
+ */
108
+ serviceAnnotations?: Record<string, string>;
109
+ /**
110
+ * Container entrypoint override (Kubernetes `command`). Mostly useful with
111
+ * `image` / `context` sources.
112
+ */
113
+ command?: string[];
114
+ /**
115
+ * Container arguments (Kubernetes `args`).
116
+ */
117
+ args?: string[];
118
+ /**
119
+ * Container CPU/memory requests + limits (Kubernetes resource quantities).
120
+ */
121
+ resources?: {
122
+ requests?: { cpu?: string; memory?: string };
123
+ limits?: { cpu?: string; memory?: string };
124
+ };
125
+ /**
126
+ * Additional environment variables for the container.
127
+ */
128
+ env?: Record<string, any>;
129
+ /**
130
+ * Container image build architecture.
131
+ * @default the connection's `architecture`, else "amd64"
132
+ */
133
+ architecture?: "amd64" | "arm64";
134
+ /**
135
+ * Deep-partial Kubernetes Pod template merged into the synthesized
136
+ * template (objects merge recursively; arrays and primitives replace) —
137
+ * a literal object in the shape of `PodTemplateSpec`, e.g.
138
+ * `{ spec: { tolerations: [...], nodeSelector: {...} } }`.
139
+ */
140
+ podTemplate?: Record<string, unknown>;
141
+ /**
142
+ * Cloud-specific workload-identity options, consumed by the cluster
143
+ * platform's identity adapter (on EKS: `{ managedPolicyArns: [...] }`
144
+ * attaches extra managed policies to the generated pod-identity role; on
145
+ * GKE: `{ gcpServiceAccount }` runs the pods as an existing Google
146
+ * service account instead of the ServiceAccount's own principal).
147
+ */
148
+ identity?: WorkloadIdentityOptions;
149
+ /**
150
+ * Deployment / pod labels, merged over the generated
151
+ * `app.kubernetes.io/name` label. Also used as the Service selector.
152
+ */
153
+ labels?: Record<string, string>;
154
+ /**
155
+ * User-defined tags applied to workload-owned cloud resources (identity
156
+ * roles, image repositories).
157
+ */
158
+ tags?: Record<string, string>;
159
+ }
160
+
161
+ /** Bundle an inline Effect program (`main`) into a generated image. */
162
+ export interface BundledDeploymentProps extends DeploymentPropsBase {
163
+ /**
164
+ * Module entrypoint for the bundled program. This should typically be
165
+ * `import.meta.url` from an inline Effect program.
166
+ */
167
+ main: string;
168
+ /**
169
+ * Environment image used as the generated Dockerfile's `FROM`; must be
170
+ * able to run the bun runtime.
171
+ * @default "oven/bun:1"
172
+ */
173
+ image?: string;
174
+ /** Named export to load from `main`. @default "default" */
175
+ handler?: string;
176
+ /** Bundler configuration for the entrypoint. */
177
+ build?: WorkloadImageSource["build"];
178
+ /** Environment Dockerfile (path or inline content). */
179
+ dockerfile?: WorkloadImageSource["dockerfile"];
180
+ /** Build context for a path {@link dockerfile} environment. */
181
+ context?: string;
182
+ }
183
+
184
+ /** Build the user's own Dockerfile (`context` + optional `dockerfile` path). */
185
+ export interface DockerfileDeploymentProps extends DeploymentPropsBase {
186
+ /** Docker build context directory. */
187
+ context?: string;
188
+ /**
189
+ * Path to the Dockerfile (relative to the cwd), or inline content.
190
+ * @default `${context}/Dockerfile`
191
+ */
192
+ dockerfile?: WorkloadImageSource["dockerfile"];
193
+ }
194
+
195
+ /** Run a pre-built registry image. */
196
+ export interface ImageDeploymentProps extends DeploymentPropsBase {
197
+ /**
198
+ * A pre-built image reference, e.g. `nginx:1.27`, pulled by the nodes as
199
+ * written. EKS clusters mirror it into ECR first.
200
+ */
201
+ image: string;
202
+ }
203
+
204
+ export type DeploymentProps =
205
+ | BundledDeploymentProps
206
+ | DockerfileDeploymentProps
207
+ | ImageDeploymentProps;
208
+
209
+ export interface Deployment extends Resource<
210
+ "Kubernetes.Deployment",
211
+ DeploymentProps,
212
+ {
213
+ /** The connection of the cluster the deployment runs on. */
214
+ connection: Connection;
215
+ /** The Kubernetes namespace the deployment's objects live in. */
216
+ namespace: string;
217
+ /** The name of the Kubernetes Deployment. */
218
+ deploymentName: string;
219
+ /** The name of the Kubernetes Service exposing the deployment. */
220
+ serviceName: string;
221
+ /** The name of the service account the pods run as. */
222
+ serviceAccountName: string;
223
+ /** The container port the server listens on. */
224
+ port: number;
225
+ /** The URI of the container image the deployment runs. */
226
+ imageUri: string;
227
+ /**
228
+ * Workload-identity state provisioned by the cluster platform's
229
+ * adapter (on EKS: the pod-identity role + association; on GKE: the
230
+ * Workload Identity principal and the IAM grants applied to it).
231
+ */
232
+ identity: IdentityState | undefined;
233
+ /**
234
+ * Image-registry state provisioned by the cluster platform's adapter
235
+ * (on EKS: the ECR repository).
236
+ */
237
+ registry: RegistryState | undefined;
238
+ /**
239
+ * The LoadBalancer URL (`http://<hostname>[:port]` — the cloud load
240
+ * balancer listens on the Service `port`, so a non-80 port is part of
241
+ * the URL) when `serviceType` is `LoadBalancer`, otherwise
242
+ * `undefined`. May be `undefined` immediately after a create while
243
+ * the cloud load balancer is still provisioning.
244
+ */
245
+ url: string | undefined;
246
+ /** References to the Kubernetes objects created for the deployment. */
247
+ kubernetesObjects: KubernetesObjectRef[];
248
+ /** The content hash of the container image source. */
249
+ code: { hash: string };
250
+ },
251
+ WorkloadBindingContract,
252
+ Providers
253
+ > {}
254
+
255
+ export type DeploymentServices = ServerHostService | WorkloadServices;
256
+
257
+ export type DeploymentShape = Main<DeploymentServices>;
258
+
259
+ export interface DeploymentRuntimeContext extends HostRuntimeContext {
260
+ readonly Type: "Kubernetes.Deployment";
261
+ }
262
+
263
+ /**
264
+ * A replicated Kubernetes server on any cluster, running a container image
265
+ * or an HTTP server written in Effect.
266
+ *
267
+ * `Deployment` provisions a Kubernetes `Deployment` + `Service` (+
268
+ * `ServiceAccount`) via server-side apply, with the container image from
269
+ * exactly one of three sources flat on props: `main` (bundle an inline
270
+ * Effect program), `context` (build your own Dockerfile), or `image` (a
271
+ * pre-built registry reference). `main` and `context` images are built on
272
+ * the deploying machine and pushed to the connection's registry
273
+ * (`Kubernetes.LocalCluster` includes one; EKS uses ECR; GKE uses
274
+ * Artifact Registry). Bindings attach environment variables on any
275
+ * cluster; cloud credential grants need a platform with workload identity.
276
+ * On `AWS.EKS.Cluster` targets it accepts the `{ env, policyStatements }`
277
+ * contract of `AWS.Lambda.Function`: IAM policy statements go to a
278
+ * generated pod-identity role. On `GCP.Container.Cluster` targets it
279
+ * accepts the `{ env, iam }` contract of `GCP.Run.Service`: IAM roles are
280
+ * granted to the Kubernetes ServiceAccount's Workload Identity Federation
281
+ * principal.
282
+ * ### Creating a Deployment
283
+ * **Example:** Run an image on a local cluster
284
+ * ```typescript
285
+ * const cluster = yield* Kubernetes.LocalCluster("Cluster", {
286
+ * name: "alchemy",
287
+ * });
288
+ *
289
+ * const web = yield* Kubernetes.Deployment("Web", {
290
+ * cluster,
291
+ * image: "ghcr.io/stefanprodan/podinfo:6.15.0",
292
+ * replicas: 2,
293
+ * port: 9898,
294
+ * serviceType: "ClusterIP",
295
+ * });
296
+ * web.serviceName; // K8s-native attrs
297
+ * ```
298
+ *
299
+ * **Example:** Any cluster via kubeconfig
300
+ * ```typescript
301
+ * const cluster = Kubernetes.KubeConfig({ context: "prod-east" });
302
+ *
303
+ * const nginx = yield* Kubernetes.Deployment("Nginx", {
304
+ * cluster,
305
+ * image: "nginx:1.27",
306
+ * replicas: 3,
307
+ * port: 80,
308
+ * serviceType: "LoadBalancer",
309
+ * });
310
+ * nginx.url; // the load balancer's address
311
+ * ```
312
+ *
313
+ * **Example:** Build your own Dockerfile
314
+ * ```typescript
315
+ * const legacy = yield* Kubernetes.Deployment("LegacyApp", {
316
+ * cluster,
317
+ * context: "./legacy",
318
+ * replicas: 2,
319
+ * port: 8080,
320
+ * });
321
+ * ```
322
+ *
323
+ * ### Effect Servers
324
+ * **Example:** Inline Effect server
325
+ * ```typescript
326
+ * const api = yield* Kubernetes.Deployment(
327
+ * "Api",
328
+ * { cluster, main: import.meta.url, port: 3000, replicas: 2 },
329
+ * Effect.gen(function* () {
330
+ * return {
331
+ * fetch: Effect.succeed(HttpServerResponse.text("ok")),
332
+ * };
333
+ * }),
334
+ * );
335
+ * ```
336
+ *
337
+ * **Example:** Push to your own registry
338
+ * ```typescript
339
+ * const cluster = Kubernetes.KubeConfig({
340
+ * context: "prod-east",
341
+ * registry: { server: "ghcr.io/acme" },
342
+ * });
343
+ *
344
+ * const api = yield* Kubernetes.Deployment(
345
+ * "Api",
346
+ * { cluster, main: import.meta.url, port: 3000 },
347
+ * Effect.gen(function* () {
348
+ * return {
349
+ * fetch: Effect.succeed(HttpServerResponse.text("ok")),
350
+ * };
351
+ * }),
352
+ * );
353
+ * ```
354
+ *
355
+ * **Example:** DynamoDB binding on EKS
356
+ * ```typescript
357
+ * const cluster = yield* AWS.EKS.Cluster("Cluster", { compute: "auto" });
358
+ *
359
+ * const api = yield* Kubernetes.Deployment(
360
+ * "Api",
361
+ * { cluster, main: import.meta.url, port: 3000 },
362
+ * Effect.gen(function* () {
363
+ * const putItem = yield* AWS.DynamoDB.PutItem(table);
364
+ * return {
365
+ * fetch: Effect.gen(function* () {
366
+ * yield* putItem({ Item: { id: { S: "1" } } });
367
+ * return HttpServerResponse.text("ok");
368
+ * }),
369
+ * };
370
+ * }).pipe(Effect.provide(AWS.DynamoDB.PutItemHttp)),
371
+ * );
372
+ * ```
373
+ *
374
+ * **Example:** Tagged Effect server
375
+ * ```typescript
376
+ * export class Api extends Kubernetes.Deployment<Api, {
377
+ * health: () => Effect.Effect<string>;
378
+ * }>()("Api") {}
379
+ *
380
+ * export default Api.make(
381
+ * { cluster, main: import.meta.url, port: 3000 },
382
+ * Effect.gen(function* () {
383
+ * return {
384
+ * fetch: Effect.gen(function* () {
385
+ * return HttpServerResponse.text("ok");
386
+ * }),
387
+ * health: () => Effect.succeed("ok"),
388
+ * };
389
+ * }),
390
+ * );
391
+ * ```
392
+ *
393
+ * ### Bundling & Tree-shaking
394
+ * `main` is bundled with rolldown at deploy time. Unused code is
395
+ * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
396
+ * pure so unused parts prune more aggressively. Your app is not
397
+ * marked pure.
398
+ *
399
+ * **Example:** Mark additional packages as pure
400
+ * Only list packages with no top-level side effects.
401
+ * ```typescript
402
+ * {
403
+ * main: import.meta.url,
404
+ * build: {
405
+ * pure: { packages: ["my-lib", "@my-scope/*"] },
406
+ * },
407
+ * }
408
+ * ```
409
+ *
410
+ * **Example:** Turn it off
411
+ * ```typescript
412
+ * {
413
+ * main: import.meta.url,
414
+ * build: { pure: false },
415
+ * }
416
+ * ```
417
+ *
418
+ * ### Kubernetes Escape Hatch
419
+ * **Example:** Tune the synthesized pod template
420
+ * ```typescript
421
+ * const tuned = yield* Kubernetes.Deployment("Api", {
422
+ * cluster,
423
+ * main: import.meta.url,
424
+ * port: 3000,
425
+ * podTemplate: {
426
+ * spec: {
427
+ * tolerations: [{ key: "gpu", operator: "Exists" }],
428
+ * nodeSelector: { pool: "arm" },
429
+ * },
430
+ * },
431
+ * });
432
+ * ```
433
+ *
434
+ * @resource
435
+ * @product Workloads
436
+ */
437
+ export const Deployment: Platform<
438
+ Deployment,
439
+ DeploymentServices,
440
+ DeploymentShape,
441
+ DeploymentRuntimeContext
442
+ > = Platform("Kubernetes.Deployment", {
443
+ aliases: ["AWS.EKS.Deployment"],
444
+ // `{ cluster: Cluster }` at module scope is an Effect. Yield it here so the
445
+ // cluster is registered and `news.cluster` is resolved at reconcile (same
446
+ // as `yield* Cluster` inside Effect.gen).
447
+ transformProps: (_id, props) =>
448
+ Effect.gen(function* () {
449
+ if (globalThis.__ALCHEMY_RUNTIME__) return props;
450
+ const cluster = Effect.isEffect(props.cluster)
451
+ ? yield* props.cluster as Effect.Effect<ClusterLike>
452
+ : props.cluster;
453
+ return { ...props, cluster };
454
+ }),
455
+ createRuntimeContext: createHostRuntimeContext("Kubernetes.Deployment") as (
456
+ id: string,
457
+ ) => DeploymentRuntimeContext,
458
+ });
459
+
460
+ /**
461
+ * `cluster` as the provider sees it. `transformProps` yields an Effect-valued
462
+ * `cluster` before any lifecycle operation runs, so only the resolved shape
463
+ * reaches the provider.
464
+ */
465
+ const clusterOf = (cluster: DeploymentPropsBase["cluster"] | undefined) =>
466
+ cluster as ClusterLike | undefined;
467
+
468
+ class ServiceNotReady extends Data.TaggedError("Kubernetes.ServiceNotReady")<{}> {}
469
+
470
+ // Bounded ~3 min wait for the cloud load balancer to publish its hostname
471
+ // (an EKS Auto Mode NLB typically appears within 2–3 min of the Service
472
+ // apply).
473
+ const loadBalancerRetrySchedule = Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(36)]);
474
+
475
+ /**
476
+ * Explicitly-typed pipeable retry for the LB-hostname wait. An inline
477
+ * `Effect.retry` in the provider leaks `Retry.Return`'s conditional into
478
+ * declaration emit and widens the provider layer to `unknown` R.
479
+ */
480
+ const retryUntilServiceReady = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
481
+ Effect.retry(self, {
482
+ while: (error) => error instanceof ServiceNotReady,
483
+ schedule: loadBalancerRetrySchedule,
484
+ });
485
+
486
+ class ServiceStillExists extends Data.TaggedError("Kubernetes.ServiceStillExists")<{}> {}
487
+
488
+ /**
489
+ * Bounded (~3 min) wait for a deleted Service to disappear, i.e. for the
490
+ * cloud controller to tear down its load balancer and drop the finalizer.
491
+ */
492
+ const waitForServiceGone = (
493
+ transport: ClusterTransport,
494
+ service: KubernetesObjectRef,
495
+ ): Effect.Effect<void, unknown> =>
496
+ Effect.retry(
497
+ readObject({ transport, object: service }).pipe(
498
+ Effect.flatMap(() => Effect.fail(new ServiceStillExists())),
499
+ Effect.catchTag("KubernetesNotFound", () => Effect.void),
500
+ ),
501
+ { while: (error) => error instanceof ServiceStillExists, schedule: loadBalancerRetrySchedule },
502
+ );
503
+
504
+ export const DeploymentProvider = () =>
505
+ Provider.effect(
506
+ Deployment,
507
+ Effect.gen(function* () {
508
+ const stack = yield* Stack;
509
+ const connectionRegistry = yield* makeConnectionRegistry;
510
+
511
+ const alchemyEnv = {
512
+ ALCHEMY_STACK_NAME: stack.name,
513
+ ALCHEMY_STAGE: stack.stage,
514
+ ALCHEMY_PHASE: "runtime",
515
+ };
516
+
517
+ // The base name doubles as the `app.kubernetes.io/name` label value
518
+ // (and the Service name), both capped at 63 characters.
519
+ const toBaseName = (id: string, props: { name?: string } = {}) =>
520
+ props.name
521
+ ? Effect.succeed(props.name)
522
+ : createPhysicalName({ id, maxLength: 63, lowercase: true }).pipe(
523
+ Effect.map((name) => name.replaceAll(/[^a-z0-9-]/g, "-")),
524
+ );
525
+
526
+ // Read a LoadBalancer Service's assigned hostname (bounded wait).
527
+ const waitForLoadBalancer = (transport: ClusterTransport, service: KubernetesObjectRef) =>
528
+ readObject({ transport, object: service }).pipe(
529
+ Effect.map((response) => {
530
+ const ingress = (
531
+ response as {
532
+ status?: { loadBalancer?: { ingress?: { hostname?: string; ip?: string }[] } };
533
+ }
534
+ )?.status?.loadBalancer?.ingress?.[0];
535
+ return ingress?.hostname ?? ingress?.ip;
536
+ }),
537
+ Effect.flatMap((hostname) =>
538
+ hostname ? Effect.succeed(hostname) : Effect.fail(new ServiceNotReady()),
539
+ ),
540
+ retryUntilServiceReady,
541
+ Effect.catchTag("Kubernetes.ServiceNotReady", () => Effect.succeed(undefined)),
542
+ );
543
+
544
+ return {
545
+ stables: [
546
+ "connection",
547
+ "namespace",
548
+ "serviceAccountName",
549
+ "deploymentName",
550
+ "serviceName",
551
+ "identity",
552
+ "registry",
553
+ ],
554
+ // A Deployment's identity spans in-cluster Kubernetes objects plus
555
+ // adapter-owned cloud resources (identity role, image repository).
556
+ // There is no single enumeration that faithfully reconstructs that
557
+ // composite, so enumeration is intentionally empty — `read` (below)
558
+ // refreshes a known instance from its persisted output.
559
+ list: () => Effect.succeed([] as Deployment["Attributes"][]),
560
+ diff: Effect.fn(function* ({ olds = {} as DeploymentProps, news: input, output }) {
561
+ // `exports` carries the program's runtime Effects (never plain
562
+ // data); everything else must be resolved to diff.
563
+ const { exports: _exports, ...declared } = input as typeof input & { exports?: unknown };
564
+ if (!isResolved(declared)) return;
565
+ const news = input as unknown as DeploymentProps;
566
+ const oldCluster = connectionIdentity(tryConnectionOf(clusterOf(olds.cluster)));
567
+ const newCluster = connectionIdentity(tryConnectionOf(clusterOf(news.cluster)));
568
+ // Workload identity keys on (cluster, namespace, serviceAccount);
569
+ // a change to either forces a replacement. Only compare when the
570
+ // old value is present so a first create (empty `olds`) doesn't
571
+ // spuriously replace.
572
+ if (oldCluster !== undefined && newCluster !== undefined && oldCluster !== newCluster) {
573
+ return { action: "replace" } as const;
574
+ }
575
+ if (
576
+ oldCluster !== undefined &&
577
+ (olds.namespace ?? "default") !== (news.namespace ?? "default")
578
+ ) {
579
+ return { action: "replace" } as const;
580
+ }
581
+ // Content drift: the props don't change when files under a build
582
+ // context (or the bundled program) do, so surface hash drift as
583
+ // an update.
584
+ const connection = tryConnectionOf(clusterOf(news.cluster));
585
+ if (output && connection) {
586
+ const adapter = yield* findClusterAdapter(connection.auth.kind);
587
+ const source = news as WorkloadImageSource;
588
+ const hash = yield* workloadImageHash({
589
+ adapter,
590
+ connection,
591
+ connectionRegistry,
592
+ source,
593
+ platform: imagePlatformOf(news.architecture, connection),
594
+ port: news.port ?? 3000,
595
+ isExternal: news.isExternal,
596
+ bootstrap: (adapter.bootstrap?.server ?? makeServerBootstrap)(
597
+ source.handler ?? "default",
598
+ ),
599
+ });
600
+ if (hash !== undefined && hash !== output.code.hash) {
601
+ return { action: "update" } as const;
602
+ }
603
+ }
604
+ }),
605
+ read: Effect.fn(function* ({ output }) {
606
+ if (!output) return undefined;
607
+ const connection = connectionOfOutput(output);
608
+ if (!connection) return undefined;
609
+ const transport = yield* connectCluster(connection);
610
+ // The ServiceAccount is the stable first object of the workload
611
+ // (one-shot Job objects are content-addressed and may have been
612
+ // TTL-collected, so they are not an existence signal).
613
+ const anchor = (output.kubernetesObjects ?? [])[0];
614
+ if (!anchor) return output;
615
+ const observed = yield* readObject({ transport, object: anchor }).pipe(
616
+ Effect.catchTag("KubernetesNotFound", () => Effect.succeed(undefined)),
617
+ );
618
+ if (observed === undefined) return undefined;
619
+ return output;
620
+ }),
621
+ reconcile: Effect.fn(function* ({ id, news, bindings, output, session }) {
622
+ const connection = toConnection(clusterOf(news.cluster)!);
623
+ const adapter = yield* findClusterAdapter(connection.auth.kind);
624
+ const transport = yield* adapter.connect(connection);
625
+ const namespace = news.namespace ?? "default";
626
+ const port = news.port ?? 3000;
627
+ const serviceType = news.serviceType ?? "LoadBalancer";
628
+
629
+ const baseName = output?.deploymentName ?? (yield* toBaseName(id, news));
630
+ const serviceAccountName = output?.serviceAccountName ?? baseName;
631
+ const tags = { ...(yield* createInternalTags(id)), ...news.tags };
632
+
633
+ // Environment from bindings is collected generically; cloud
634
+ // credential grants (any non-env binding channel) require the
635
+ // cluster platform's identity adapter.
636
+ const { env: bindingEnv, grantKeys } = collectBindingEnv(bindings);
637
+ if (grantKeys.length > 0 && adapter.identity === undefined) {
638
+ return yield* Effect.die(
639
+ new Error(
640
+ `'${id}': bindings carry cloud credential grants ` +
641
+ `(${grantKeys.join(", ")}) but this cluster's platform ` +
642
+ "has no workload-identity adapter. Target a managed " +
643
+ "cluster (e.g. AWS.EKS.Cluster) or bind through " +
644
+ "environment variables instead.",
645
+ ),
646
+ );
647
+ }
648
+ const identity = adapter.identity
649
+ ? yield* adapter.identity.reconcile({
650
+ id,
651
+ connection,
652
+ namespace,
653
+ serviceAccount: serviceAccountName,
654
+ bindings,
655
+ options: news.identity,
656
+ state:
657
+ (output?.identity as Record<string, unknown> | undefined) ??
658
+ (output as Record<string, unknown> | undefined),
659
+ tags,
660
+ })
661
+ : undefined;
662
+
663
+ // Resolve the container image from whichever source the props
664
+ // declare (`main` | `context` | `image`) through the platform's
665
+ // registry adapter (pre-built `image` refs pass through verbatim
666
+ // on registry-less clusters).
667
+ const source = news as WorkloadImageSource;
668
+ const resolved = yield* resolveWorkloadImage({
669
+ adapter,
670
+ connection,
671
+ connectionRegistry,
672
+ id,
673
+ source,
674
+ platform: imagePlatformOf(news.architecture, connection),
675
+ port,
676
+ isExternal: news.isExternal,
677
+ bootstrap: (adapter.bootstrap?.server ?? makeServerBootstrap)(
678
+ source.handler ?? "default",
679
+ ),
680
+ tags,
681
+ state:
682
+ (output?.registry as Record<string, unknown> | undefined) ??
683
+ (output as Record<string, unknown> | undefined),
684
+ session,
685
+ });
686
+
687
+ // Synthesize the Kubernetes objects. Container env merges binding
688
+ // env (Output-referenced resource attributes flow via the
689
+ // RuntimeContext into `news.env`), adapter env (e.g. AWS_REGION on
690
+ // EKS), alchemy env, and user env. The generated name label is
691
+ // always present so the Service selector stays workload-unique
692
+ // even when user labels are set.
693
+ const labels = { "app.kubernetes.io/name": baseName, ...news.labels };
694
+ const containerEnv = {
695
+ ...bindingEnv,
696
+ ...identity?.env,
697
+ ...alchemyEnv,
698
+ PORT: String(port),
699
+ ...news.env,
700
+ };
701
+
702
+ const serviceAccountObject: KubernetesObjectDefinition = {
703
+ apiVersion: "v1",
704
+ kind: "ServiceAccount",
705
+ metadata: {
706
+ name: serviceAccountName,
707
+ namespace,
708
+ labels,
709
+ ...(identity?.serviceAccountAnnotations
710
+ ? { annotations: identity.serviceAccountAnnotations }
711
+ : {}),
712
+ },
713
+ };
714
+ const podTemplate = deepMerge(
715
+ {
716
+ metadata: { labels },
717
+ spec: {
718
+ serviceAccountName,
719
+ containers: [
720
+ {
721
+ name: baseName,
722
+ image: resolved.imageUri,
723
+ command: news.command,
724
+ args: news.args,
725
+ ports: [{ containerPort: port }],
726
+ env: Object.entries(containerEnv).map(([name, value]) => ({
727
+ name,
728
+ value: containerEnvValue(value),
729
+ })),
730
+ resources: news.resources,
731
+ },
732
+ ],
733
+ },
734
+ },
735
+ news.podTemplate,
736
+ );
737
+ const deploymentObject: KubernetesObjectDefinition = {
738
+ apiVersion: "apps/v1",
739
+ kind: "Deployment",
740
+ metadata: { name: baseName, namespace, labels },
741
+ spec: {
742
+ replicas: news.replicas ?? 1,
743
+ selector: { matchLabels: labels },
744
+ template: podTemplate,
745
+ },
746
+ };
747
+ // `LoadBalancer` Services need platform defaults on some managed
748
+ // clouds (EKS Auto Mode only reconciles Services carrying its
749
+ // `loadBalancerClass`, and defaults new NLBs to the internal
750
+ // scheme) — ask the adapter. User `serviceAnnotations` always win.
751
+ let loadBalancerClass: string | undefined;
752
+ let serviceAnnotations = news.serviceAnnotations;
753
+ if (serviceType === "LoadBalancer") {
754
+ const defaults = adapter.loadBalancerDefaults
755
+ ? yield* adapter.loadBalancerDefaults({ connection })
756
+ : undefined;
757
+ loadBalancerClass = defaults?.loadBalancerClass;
758
+ serviceAnnotations = { ...defaults?.annotations, ...news.serviceAnnotations };
759
+ }
760
+ const serviceObject: KubernetesObjectDefinition = {
761
+ apiVersion: "v1",
762
+ kind: "Service",
763
+ metadata: { name: baseName, namespace, labels, annotations: serviceAnnotations },
764
+ spec: {
765
+ type: serviceType,
766
+ ...(loadBalancerClass !== undefined ? { loadBalancerClass } : {}),
767
+ selector: labels,
768
+ ports: [{ port, targetPort: port, protocol: "TCP" }],
769
+ },
770
+ };
771
+
772
+ const desiredObjects = [serviceAccountObject, deploymentObject, serviceObject];
773
+
774
+ const kubernetesObjects = yield* reconcileObjects({
775
+ transport,
776
+ previousObjects: output?.kubernetesObjects ?? [],
777
+ desiredObjects,
778
+ });
779
+
780
+ yield* session.note(`Applied Kubernetes Deployment ${namespace}/${baseName}`);
781
+
782
+ // Resolve the LoadBalancer URL if applicable. The cloud listener
783
+ // is the Service `port` (Kubernetes maps `spec.ports[].port` 1:1
784
+ // to it), so the URL carries the port unless it's 80 — mirroring
785
+ // `AWS.ECS.Service`'s url semantics.
786
+ const hostname =
787
+ serviceType === "LoadBalancer"
788
+ ? yield* waitForLoadBalancer(transport, toKubernetesObjectRef(serviceObject))
789
+ : undefined;
790
+ const url =
791
+ hostname === undefined
792
+ ? undefined
793
+ : port === 80
794
+ ? `http://${hostname}`
795
+ : `http://${hostname}:${port}`;
796
+
797
+ return {
798
+ connection,
799
+ namespace,
800
+ deploymentName: baseName,
801
+ serviceName: baseName,
802
+ serviceAccountName,
803
+ port,
804
+ imageUri: resolved.imageUri,
805
+ identity: identity?.state,
806
+ registry: resolved.state,
807
+ url,
808
+ kubernetesObjects,
809
+ code: { hash: resolved.codeHash },
810
+ };
811
+ }),
812
+ delete: Effect.fn(function* ({ output }) {
813
+ const connection = connectionOfOutput(output);
814
+ if (!connection) return;
815
+ const adapter = yield* findClusterAdapter(connection.auth.kind);
816
+
817
+ // Skip only a missing cluster, then still clean up adapter-owned
818
+ // cloud resources (image repository, identity role).
819
+ const transport = yield* ifClusterExists(adapter.connect(connection));
820
+ if (transport && (output.kubernetesObjects ?? []).length > 0) {
821
+ yield* deleteObjects({ transport, objects: output.kubernetesObjects ?? [] });
822
+ // A LoadBalancer Service carries the cloud controller's cleanup
823
+ // finalizer; wait for it so the cloud load balancer is gone
824
+ // before the cluster (and its controller) can be deleted —
825
+ // deleting the cluster first leaks the load balancer.
826
+ yield* Effect.forEach(
827
+ (output.kubernetesObjects ?? []).filter((object) => object.kind === "Service"),
828
+ (service) => waitForServiceGone(transport, service),
829
+ { discard: true },
830
+ );
831
+ }
832
+
833
+ if (adapter.identity) {
834
+ yield* adapter.identity.delete({
835
+ connection,
836
+ state:
837
+ (output.identity as Record<string, unknown> | undefined) ??
838
+ (output as Record<string, unknown>),
839
+ });
840
+ }
841
+ if (adapter.registry) {
842
+ yield* adapter.registry.delete({
843
+ state:
844
+ (output.registry as Record<string, unknown> | undefined) ??
845
+ (output as Record<string, unknown>),
846
+ });
847
+ }
848
+ }),
849
+ };
850
+ }),
851
+ );