The best way to control Claude Code, Codex and more from any computer or phone

main
ts 348 lines 13.2 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Network } from "@alchemy.run/aws/EC2/Network";
3 import { Cluster } from "@alchemy.run/aws/EKS/Cluster";
4 import { makeEksTransport } from "@alchemy.run/aws/EKS/KubernetesAdapter";
5 import * as Kubernetes from "@alchemy.run/kubernetes";
6 import { readObject } from "@alchemy.run/kubernetes/Client";
7 import { describe, expect } from "@alchemy.run/test";
8 import * as Test from "@alchemy.run/test/Alchemy";
9 import * as Core from "@alchemy.run/test/Core";
10 import * as dynamodb from "@distilled.cloud/aws/dynamodb";
11 import * as Provider from "alchemy/Provider";
12 import * as Cause from "effect/Cause";
13 import * as Effect from "effect/Effect";
14 import * as Exit from "effect/Exit";
15 import * as HttpClient from "effect/http/HttpClient";
16 import * as Layer from "effect/Layer";
17 import * as Redacted from "effect/Redacted";
18 import * as Schedule from "effect/Schedule";
19 import EksHostApi from "./fixtures/deployment.ts";
20 import {
21 destroyKindStack,
22 KindTestCluster,
23 kubectlGet,
24 removeRbac,
25 restrictedConnection,
26 updateRole,
27 type KindCluster,
28 } from "./fixtures/kind.ts";
29
30 const testOptions = { providers: Layer.mergeAll(AWS.providers(), Kubernetes.providers()) };
31 const { test, beforeAll, afterAll } = Test.make(testOptions);
32
33 // Ungated probe: `Deployment` is a composite host (in-cluster
34 // Deployment/Service plus adapter-owned cloud resources — ECR repo,
35 // pod-identity role, PodIdentityAssociation on EKS). It has no faithful
36 // single-API enumeration, so `list()` is intentionally empty. This probe
37 // proves the provider is registered, its record type-checks (a missing /
38 // mistyped `list` collapses Provider.of inference), and it runs live —
39 // without paying the ~15-minute EKS control-plane create.
40 test.provider(
41 "list returns an empty array (composite host, not enumerable)",
42 () =>
43 Effect.gen(function* () {
44 const provider = yield* Provider.findProvider(Kubernetes.Deployment);
45 const all = yield* provider.list();
46 expect(Array.isArray(all)).toBe(true);
47 expect(all).toEqual([]);
48 }),
49 { tags: ["provider:aws", "provider:kubernetes", "provider:kubernetes:deployment", "live"] },
50 );
51
52 const kindStack = Core.scratchStack(testOptions, "KubernetesDeploymentKind");
53
54 // Creates a real kind cluster (~30s); needs Docker, kind, and kubectl. The
55 // pods run a pre-built image; these cases assert on the applied objects, not
56 // on pod readiness.
57 describe(
58 "Kubernetes Deployment on kind",
59 {
60 tags: [
61 "provider:kubernetes",
62 "provider:kubernetes:deployment",
63 "provider:kubernetes:localcluster",
64 "live",
65 ],
66 },
67 () => {
68 let cluster: KindCluster;
69 const image = "registry.k8s.io/pause:3.10";
70 const ns = ["--namespace", "default"];
71 const objectsOf = (name: string) =>
72 Effect.all({
73 serviceAccount: kubectlGet(cluster, ["serviceaccount", name, ...ns]),
74 deployment: kubectlGet(cluster, ["deployment", name, ...ns]),
75 service: kubectlGet(cluster, ["service", name, ...ns]),
76 });
77
78 beforeAll(
79 Effect.gen(function* () {
80 yield* kindStack.destroy();
81 cluster = yield* kindStack.deploy(KindTestCluster("deployment", 5064));
82 }),
83 { timeout: 300_000 },
84 );
85
86 afterAll.skipIf(!!process.env.NO_DESTROY)(
87 Effect.suspend(() => destroyKindStack(kindStack, cluster)),
88 { timeout: 180_000 },
89 );
90
91 test.provider(
92 "Redacted env values reach the container unwrapped",
93 (stack) =>
94 Effect.gen(function* () {
95 yield* stack.destroy();
96 const token = "deployment-token-sentinel";
97 const nested = "deployment-nested-sentinel";
98 yield* stack.deploy(
99 Kubernetes.Deployment("SecretEnv", {
100 cluster: cluster.connection,
101 name: "secret-env",
102 image,
103 port: 8080,
104 serviceType: "ClusterIP",
105 env: {
106 TOKEN: Redacted.make(token),
107 CONFIG: Redacted.make({ nested }),
108 },
109 }),
110 );
111
112 const { deployment } = yield* objectsOf("secret-env");
113 const env = Object.fromEntries(
114 (
115 deployment.spec.template.spec.containers[0].env as { name: string; value: string }[]
116 ).map((entry) => [entry.name, entry.value]),
117 );
118 expect(env.TOKEN).toBe(token);
119 expect(env.CONFIG).toBe(JSON.stringify({ nested }));
120
121 yield* stack.destroy();
122 expect(yield* objectsOf("secret-env")).toEqual({
123 serviceAccount: undefined,
124 deployment: undefined,
125 service: undefined,
126 });
127 }),
128 { timeout: 120_000 },
129 );
130
131 test.provider(
132 "destroy surfaces a 403 and leaves the objects in place",
133 (stack) =>
134 Effect.gen(function* () {
135 yield* stack.destroy();
136 const account = "deployment-no-delete";
137 const rules = (verbs: string[]) => [
138 { apiGroups: [""], resources: ["serviceaccounts", "services"], verbs },
139 { apiGroups: ["apps"], resources: ["deployments"], verbs },
140 ];
141 const restricted = yield* restrictedConnection(
142 cluster,
143 account,
144 rules(["get", "list", "create", "patch", "update"]),
145 );
146 yield* stack.deploy(
147 Kubernetes.Deployment("Kept", {
148 cluster: restricted,
149 name: "kept",
150 image,
151 port: 8080,
152 serviceType: "ClusterIP",
153 }),
154 );
155
156 const exit = yield* Effect.exit(stack.destroy());
157 expect(Exit.isFailure(exit)).toBe(true);
158 if (Exit.isFailure(exit)) {
159 expect(Cause.pretty(exit.cause)).toContain("403");
160 }
161 const kept = yield* objectsOf("kept");
162 expect(kept.deployment).toBeDefined();
163 expect(kept.service).toBeDefined();
164
165 // Granting delete lets the same destroy converge.
166 yield* updateRole(
167 cluster,
168 account,
169 rules(["get", "list", "create", "patch", "update", "delete"]),
170 );
171 yield* stack
172 .destroy()
173 .pipe(Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 5 }));
174 expect(yield* objectsOf("kept")).toEqual({
175 serviceAccount: undefined,
176 deployment: undefined,
177 service: undefined,
178 });
179 yield* removeRbac(cluster, account);
180 }),
181 { timeout: 120_000 },
182 );
183 },
184 );
185
186 // Full end-to-end (gated). An EKS Auto Mode cluster takes ~10–15 min to
187 // provision, plus image build/push, pod scheduling, and NLB provisioning —
188 // well beyond the routine speed-doctrine ceiling. Skip it under `--fast`.
189 //
190 // It deploys, in two phases (refs read committed stack state, not the in-flight
191 // plan): (1) a public network + a `compute: "auto"` cluster (the provider owns
192 // the cluster/node IAM roles); (2) the same infra + the `Deployment` fixture,
193 // which binds DynamoDB `PutItem`. The bound policy lands on the generated
194 // pod-identity role and the table name is injected into the pod; the pod
195 // resolves credentials via the EKS Pod Identity container-credentials chain.
196 // The test curls the LoadBalancer `/put` route, then asserts the item was
197 // written by reading it back out-of-band through the DynamoDB API — proving
198 // the binding, pod identity, image pipeline, and server-side-apply path in one
199 // shot.
200 //
201 // NOTE: this path has not been run green live in this factory wave (cluster
202 // create alone exceeds the agent budget). It is gated + skip-clean; run on an
203 // account with Auto Mode Pod Identity unless `--fast` is set.
204
205 // Cluster declared at a TOP-LEVEL logical id so the fixture can resolve it
206 // with `Cluster.ref("EksHostCluster")` (no namespace nesting). `compute:
207 // "auto"` exercises the AutoCluster fold-in: the provider creates and owns the
208 // cluster + node IAM roles.
209 const infra = Effect.gen(function* () {
210 const network = yield* Network("EksHostNetwork", {
211 cidrBlock: "10.84.0.0/16",
212 availabilityZones: 2,
213 });
214
215 const cluster = yield* Cluster("EksHostCluster", {
216 compute: "auto",
217 resourcesVpcConfig: {
218 subnetIds: network.publicSubnetIds,
219 endpointPublicAccess: true,
220 endpointPrivateAccess: true,
221 },
222 });
223
224 return { cluster, network };
225 });
226
227 const sharedStack = Core.scratchStack(testOptions, "EksServerHost");
228
229 describe.skipIf(!!process.env.FAST)(
230 "Kubernetes Deployment E2E",
231 {
232 tags: [
233 "provider:aws",
234 "provider:aws:dynamodb",
235 "provider:aws:ec2",
236 "provider:aws:eks",
237 "provider:kubernetes",
238 "provider:kubernetes:deployment",
239 "provider:kubernetes:helmchart",
240 "live",
241 ],
242 },
243 () => {
244 let baseUrl: string;
245 let helmRelease: Kubernetes.HelmChart["Attributes"];
246 let helmCluster: Cluster["Attributes"];
247
248 beforeAll(
249 Effect.gen(function* () {
250 yield* sharedStack.destroy();
251 // Phase 1: cluster + network only.
252 yield* sharedStack.deploy(infra);
253 // Phase 2: same infra + the Deployment fixture (refs the cluster) +
254 // a HelmChart rendering the local fixture chart onto the cluster.
255 const { host, cluster, release } = yield* sharedStack.deploy(
256 Effect.gen(function* () {
257 const { cluster } = yield* infra;
258 const release = yield* Kubernetes.HelmChart("E2EHelmChart", {
259 cluster,
260 chart: `${import.meta.dirname}/fixtures/chart`,
261 values: { message: "helm-e2e", secondConfigMap: { enabled: true } },
262 });
263 const host = yield* EksHostApi;
264 return { host, cluster, release };
265 }),
266 );
267 helmRelease = release;
268 helmCluster = cluster;
269 // `url` is a full URL (`http://<nlb-hostname>:<port>` — the NLB
270 // listener is the Service port, not 80).
271 expect(host.url).toBeTruthy();
272 baseUrl = host.url!.replace(/\/+$/, "");
273
274 // NLB DNS + pod readiness ramp — retry /health.
275 yield* HttpClient.get(`${baseUrl}/health`).pipe(
276 Effect.flatMap((res) =>
277 res.status === 200
278 ? Effect.succeed(res)
279 : Effect.fail(new Error(`/health ${res.status}`)),
280 ),
281 Effect.tapError((e) => Effect.logWarning(String(e))),
282 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 60 }),
283 );
284 }),
285 // Cluster create (~18 min) + image build/push + Auto Mode node launch +
286 // NLB provisioning/DNS + URL readiness poll (~5–10 min) routinely total
287 // 35+ min end-to-end.
288 { timeout: 2_700_000 },
289 );
290
291 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 600_000 });
292
293 test.provider(
294 "bound DynamoDB PutItem writes an item from inside the pod",
295 () =>
296 Effect.gen(function* () {
297 // Deterministic id: the table is created fresh by this suite's deploy
298 // (beforeAll starts with a destroy), so no stale item can pre-exist,
299 // and a stable id keeps re-runs convergent instead of accreting items.
300 const itemId = "eks-deployment-put-item";
301 const res = yield* HttpClient.get(`${baseUrl}/put?id=${itemId}`).pipe(
302 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 12 }),
303 );
304 expect(res.status).toBe(200);
305 const body = (yield* res.json) as { written: string; table: string };
306 expect(body.written).toBe(itemId);
307
308 // Prove the binding actually reached DynamoDB: read the item back
309 // out-of-band via the control-plane API.
310 const got = yield* dynamodb
311 .getItem({ TableName: body.table, Key: { pk: { S: itemId } } })
312 .pipe(Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 10 }));
313 expect(got.Item?.pk?.S).toBe(itemId);
314 }),
315 { timeout: 180_000 },
316 );
317
318 test.provider(
319 "HelmChart renders and applies its objects onto the cluster",
320 () =>
321 Effect.gen(function* () {
322 // The chart rendered both ConfigMaps (the conditional one was
323 // toggled on via values) into the default namespace.
324 expect(helmRelease.objects).toHaveLength(2);
325 expect(helmRelease.namespace).toBe("default");
326 // The generic attributes persist the cluster connection for
327 // adapter-based delete.
328 expect(helmRelease.connection.auth.kind).toBe("aws-eks");
329
330 // Read the primary ConfigMap back out-of-band through the
331 // Kubernetes API and prove the values reached the cluster.
332 const configRef = helmRelease.objects.find((object) => object.name.endsWith("-config"))!;
333 expect(configRef).toBeDefined();
334 const transport = yield* makeEksTransport({
335 clusterName: helmCluster.clusterName,
336 endpoint: helmCluster.endpoint!,
337 certificateAuthorityData: helmCluster.certificateAuthorityData!,
338 });
339 const applied = (yield* readObject({ transport, object: configRef })) as
340 | { data?: Record<string, string> }
341 | undefined;
342 expect(applied?.data?.message).toBe("helm-e2e");
343 expect(applied?.data?.release).toBe(helmRelease.releaseName);
344 }),
345 { timeout: 120_000 },
346 );
347 },
348 );