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

main
ts 185 lines 7.39 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Cluster } from "@alchemy.run/aws/EKS";
3 import { VirtualCluster } from "@alchemy.run/aws/EMRContainers";
4 import { Role } from "@alchemy.run/aws/IAM";
5 import { expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as ec2 from "@distilled.cloud/aws/ec2";
8 import * as emrc from "@distilled.cloud/aws/emr-containers";
9 import * as Provider from "alchemy/Provider";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 // Deterministic names — same on every run of the test case.
16 const EKS_CLUSTER_NAME = "alchemy-test-emrc-eks";
17 const VC_NAME = "alchemy-test-emrc-vc";
18
19 // Ungated typed-error probe: proves the tags the observe/read/delete paths
20 // depend on. describeVirtualCluster on a well-formed nonexistent id must
21 // surface the typed ResourceNotFoundException; deleteVirtualCluster on the
22 // same id must surface the typed ValidationException the idempotent delete
23 // path swallows (its typed union has no not-found tag — the API reports
24 // missing/terminated ids as validation errors).
25 test.provider(
26 "typed error semantics on a nonexistent virtual cluster",
27 () =>
28 Effect.gen(function* () {
29 const id = "abcdefabcdefabcdefabcdef01";
30
31 const describeError = yield* Effect.flip(emrc.describeVirtualCluster({ id }));
32 expect(describeError._tag).toBe("ResourceNotFoundException");
33
34 const deleteError = yield* Effect.flip(emrc.deleteVirtualCluster({ id }));
35 expect(deleteError._tag).toBe("ValidationException");
36 }),
37 { tags: ["provider:aws", "provider:aws:emrcontainers", "live"] },
38 );
39
40 // Ungated typed-error probe for the job-run data plane the VC-scoped
41 // bindings (DescribeJobRun / CancelJobRun / ListJobRuns) call: each op on a
42 // well-formed nonexistent virtual cluster id must surface a typed tag from
43 // its inferred error union — never a catch-all. Observed live: the API
44 // reports job-run-addressed ops on a nonexistent virtual cluster as
45 // validation errors, and ListJobRuns succeeds with an empty page.
46 // (StartJobRun's tag depends on the caller's IAM scope — AccessDenied for
47 // unauthorized arbitrary cluster ARNs — so it is not asserted here; the
48 // binding grants on the bound cluster's ARN.)
49 test.provider(
50 "typed error semantics for job run ops on a nonexistent vc",
51 () =>
52 Effect.gen(function* () {
53 const virtualClusterId = "abcdefabcdefabcdefabcdef01";
54 const jobRunId = "abcdefabcdefabcdefa";
55
56 const describeError = yield* Effect.flip(
57 emrc.describeJobRun({ id: jobRunId, virtualClusterId }),
58 );
59 expect(describeError._tag).toBe("ValidationException");
60
61 const cancelError = yield* Effect.flip(emrc.cancelJobRun({ id: jobRunId, virtualClusterId }));
62 expect(cancelError._tag).toBe("ValidationException");
63
64 const list = yield* emrc.listJobRuns({ virtualClusterId });
65 expect(list.jobRuns ?? []).toHaveLength(0);
66 }),
67 { tags: ["provider:aws", "provider:aws:emrcontainers", "live"] },
68 );
69
70 // Ungated list() probe: enumerates live virtual clusters in the ambient
71 // account/region — proves the pagination + attribute mapping wiring without
72 // needing an EKS cluster.
73 test.provider(
74 "list returns a well-formed array of virtual clusters",
75 () =>
76 Effect.gen(function* () {
77 const provider = yield* Provider.findProvider(VirtualCluster);
78 const all = yield* provider.list();
79
80 expect(Array.isArray(all)).toBe(true);
81 for (const vc of all) {
82 expect(typeof vc.virtualClusterId).toBe("string");
83 expect(typeof vc.virtualClusterName).toBe("string");
84 expect(vc.virtualClusterArn).toContain(":/virtualclusters/");
85 }
86 }),
87 { tags: ["provider:aws", "provider:aws:emrcontainers", "live"] },
88 );
89
90 // Full lifecycle: a virtual cluster itself is free and provisions instantly,
91 // but it requires a live EKS cluster (~10 min control-plane create + ~5 min
92 // delete), so the whole path is skipped under `--fast`. The EKS cluster
93 // uses API authentication mode so EMR on EKS registers its access entries
94 // automatically — no kubectl/aws-auth step.
95 test.provider.skipIf(!!process.env.FAST)(
96 "virtual cluster lifecycle on a live EKS cluster",
97 (stack) =>
98 Effect.gen(function* () {
99 // Clean slate in case a previous run died mid-flight.
100 yield* stack.destroy();
101
102 // Default-VPC subnets in >= 2 AZs (never create NAT gateways).
103 const subnetsResult = yield* ec2.describeSubnets({
104 Filters: [{ Name: "default-for-az", Values: ["true"] }],
105 });
106 const byAz = new Map<string, string>();
107 for (const s of subnetsResult.Subnets ?? []) {
108 if (s.State === "available" && s.SubnetId && s.AvailabilityZone) {
109 if (!byAz.has(s.AvailabilityZone)) {
110 byAz.set(s.AvailabilityZone, s.SubnetId);
111 }
112 }
113 }
114 const subnetIds = Array.from(byAz.values()).slice(0, 3);
115 expect(subnetIds.length).toBeGreaterThanOrEqual(2);
116
117 const vc = yield* stack.deploy(
118 Effect.gen(function* () {
119 const clusterRole = yield* Role("EksRole", {
120 assumeRolePolicyDocument: {
121 Version: "2012-10-17",
122 Statement: [
123 {
124 Effect: "Allow",
125 Principal: { Service: "eks.amazonaws.com" },
126 Action: ["sts:AssumeRole"],
127 },
128 ],
129 },
130 managedPolicyArns: ["arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"],
131 });
132 const cluster = yield* Cluster("Cluster", {
133 clusterName: EKS_CLUSTER_NAME,
134 roleArn: clusterRole.roleArn,
135 resourcesVpcConfig: { subnetIds },
136 accessConfig: { authenticationMode: "API_AND_CONFIG_MAP" },
137 });
138 return yield* VirtualCluster("VC", {
139 virtualClusterName: VC_NAME,
140 containerProvider: {
141 id: cluster.clusterName,
142 info: { eksInfo: { namespace: "default" } },
143 },
144 });
145 }),
146 );
147
148 expect(vc.virtualClusterName).toBe(VC_NAME);
149 expect(vc.eksClusterName).toBe(EKS_CLUSTER_NAME);
150 expect(vc.state).toBe("RUNNING");
151
152 // Out-of-band verification via distilled.
153 const observed = yield* emrc.describeVirtualCluster({ id: vc.virtualClusterId });
154 expect(observed.virtualCluster?.name).toBe(VC_NAME);
155 expect(observed.virtualCluster?.containerProvider?.id).toBe(EKS_CLUSTER_NAME);
156
157 // Destroy immediately and verify the virtual cluster terminated.
158 yield* stack.destroy();
159 yield* assertVirtualClusterGone(vc.virtualClusterId);
160 }),
161 {
162 tags: [
163 "provider:aws",
164 "provider:aws:ec2",
165 "provider:aws:eks",
166 "provider:aws:emrcontainers",
167 "provider:aws:iam",
168 "live",
169 ],
170 timeout: 1_800_000,
171 },
172 );
173
174 const assertVirtualClusterGone = (id: string) =>
175 Effect.gen(function* () {
176 const state = yield* emrc.describeVirtualCluster({ id }).pipe(
177 Effect.map((response) => response.virtualCluster?.state ?? "gone"),
178 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("gone")),
179 );
180 if (state !== "gone" && state !== "TERMINATED" && state !== "TERMINATING") {
181 return yield* Effect.fail(new Error(`virtual cluster ${id} still exists (${state})`));
182 }
183 }).pipe(
184 Effect.retry({ schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]) }),
185 );