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

main
ts 229 lines 8.58 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as dax from "@distilled.cloud/aws/dax";
6 import * as EC2 from "@distilled.cloud/aws/ec2";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as Schedule from "effect/Schedule";
10 import { getDefaultVpc } from "../DefaultVpc.ts";
11 import DAXTestFunctionLive, { DAXTestFunction } from "./handler";
12 import DAXSlowTestFunctionLive, {
13 DAXSlowTestFunction,
14 SLOW_SUBNET_GROUP_NAME,
15 } from "./slow-handler";
16
17 const testOptions = { providers: AWS.providers() };
18 const { test, beforeAll, afterAll } = Test.make(testOptions);
19 const sharedStack = Core.scratchStack(testOptions, "DAXBindings");
20
21 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
22 // over 60s on a fresh deploy.
23 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
24
25 let baseUrl: string;
26
27 const getJson = (path: string) =>
28 HttpClient.get(`${baseUrl}${path}`).pipe(
29 Effect.flatMap((response) =>
30 response.status >= 500
31 ? Effect.fail(new Error(`transient upstream ${response.status}`))
32 : Effect.succeed(response),
33 ),
34 Effect.retry({
35 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
36 }),
37 Effect.flatMap((r) => r.json),
38 );
39
40 describe.sequential(
41 "DAX Bindings",
42 { tags: ["provider:aws", "provider:aws:dax", "provider:aws:lambda", "live"] },
43 () => {
44 beforeAll(
45 Effect.gen(function* () {
46 yield* Effect.logInfo("DAX test setup: destroying previous resources");
47 yield* sharedStack.destroy();
48
49 yield* Effect.logInfo("DAX test setup: deploying fixture");
50 const { functionUrl } = yield* sharedStack.deploy(
51 Effect.gen(function* () {
52 return yield* DAXTestFunction;
53 }).pipe(Effect.provide(DAXTestFunctionLive)),
54 );
55
56 expect(functionUrl).toBeTruthy();
57 baseUrl = functionUrl!.replace(/\/+$/, "");
58
59 const readinessUrl = `${baseUrl}/bindings`;
60 yield* HttpClient.get(readinessUrl).pipe(
61 Effect.flatMap((response) =>
62 response.status === 200
63 ? Effect.succeed(response)
64 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
65 ),
66 Effect.retry({ schedule: readinessPolicy }),
67 );
68 }),
69 { timeout: 240_000 },
70 );
71
72 afterAll(sharedStack.destroy(), { timeout: 120_000 });
73
74 describe("binding registration", () => {
75 test.provider("both capabilities initialize in the runtime", (_stack) =>
76 Effect.gen(function* () {
77 const response = yield* getJson("/bindings");
78 expect((response as any).bound).toHaveLength(2);
79 }),
80 );
81 });
82
83 describe("DescribeClusters", () => {
84 test.provider("surfaces the typed not-found tag for a nonexistent cluster", (_stack) =>
85 Effect.gen(function* () {
86 const response = yield* getJson("/clusters");
87 expect((response as any).tag).toBe("ClusterNotFoundFault");
88 }),
89 );
90 });
91
92 describe("DescribeEvents", () => {
93 test.provider("lists the account's recent DAX events", (_stack) =>
94 Effect.gen(function* () {
95 const response = yield* getJson("/events");
96 expect((response as any).count).toBeGreaterThanOrEqual(0);
97 }),
98 );
99 });
100 },
101 );
102
103 // ---------------------------------------------------------------------------
104 // Cluster-scoped bindings (ConnectReadWrite, RebootNode) need a real DAX
105 // cluster (~10 min to provision, billed per node-hour) — skipped under
106 // `--fast` like the Cluster lifecycle test.
107 // ---------------------------------------------------------------------------
108
109 const slowStack = Core.scratchStack(testOptions, "DAXSlowBindings");
110
111 // Resolve two default-for-AZ subnets from the region's first three AZs (DAX
112 // is not offered in every AZ, e.g. us-west-2d).
113 const defaultSubnetIds = Effect.gen(function* () {
114 const vpc = yield* getDefaultVpc;
115 const subnets = yield* EC2.describeSubnets({
116 Filters: [
117 { Name: "vpc-id", Values: [vpc.vpcId] },
118 { Name: "default-for-az", Values: ["true"] },
119 ],
120 });
121 const subnetIds = (subnets.Subnets ?? [])
122 .filter((s) => /[abc]$/.test(s.AvailabilityZone ?? ""))
123 .sort((l, r) => (l.AvailabilityZone ?? "").localeCompare(r.AvailabilityZone ?? ""))
124 .map((s) => s.SubnetId)
125 .filter((id): id is `subnet-${string}` => id !== undefined)
126 .slice(0, 2);
127 if (subnetIds.length < 2) {
128 return yield* Effect.die(new Error("default VPC is missing subnets"));
129 }
130 return subnetIds;
131 });
132
133 // The fixture module cannot look up subnet ids, so the subnet group is
134 // managed out-of-band under a deterministic name.
135 const ensureSubnetGroup = (subnetIds: string[]) =>
136 dax
137 .createSubnetGroup({
138 SubnetGroupName: SLOW_SUBNET_GROUP_NAME,
139 Description: "alchemy dax bindings test subnets",
140 SubnetIds: subnetIds,
141 })
142 .pipe(Effect.catchTag("SubnetGroupAlreadyExistsFault", () => Effect.void));
143
144 // The subnet group is only deletable once the cluster is fully gone —
145 // deletion takes several minutes after destroy initiates it, so retry
146 // through SubnetGroupInUseFault (gated test: generous bounded budget).
147 const deleteSubnetGroup = dax.deleteSubnetGroup({ SubnetGroupName: SLOW_SUBNET_GROUP_NAME }).pipe(
148 Effect.catchTag("SubnetGroupNotFoundFault", () => Effect.void),
149 Effect.retry({
150 while: (e) => e._tag === "SubnetGroupInUseFault",
151 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]),
152 }),
153 );
154
155 test.provider.skipIf(!!process.env.FAST)(
156 "connect + scaling + reboot-node bindings against a live cluster",
157 () =>
158 Effect.gen(function* () {
159 yield* slowStack.destroy();
160 const subnetIds = yield* defaultSubnetIds;
161 yield* ensureSubnetGroup(subnetIds);
162
163 yield* Effect.gen(function* () {
164 const { functionUrl } = yield* slowStack.deploy(
165 Effect.gen(function* () {
166 return yield* DAXSlowTestFunction;
167 }).pipe(Effect.provide(DAXSlowTestFunctionLive)),
168 );
169 expect(functionUrl).toBeTruthy();
170 const slowBaseUrl = functionUrl!.replace(/\/+$/, "");
171
172 const get = (path: string) =>
173 HttpClient.get(`${slowBaseUrl}${path}`).pipe(
174 Effect.retry({
175 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
176 }),
177 Effect.flatMap((r) => r.json),
178 );
179
180 // Connection info resolves from both the runtime attributes and the
181 // published environment variables.
182 const connect = (yield* get("/connect")) as {
183 info: { host: string; port: number; url: string; tls: boolean };
184 env: { host?: string; port?: string; url?: string; tls?: string };
185 };
186 expect(connect.info.host).toBeTruthy();
187 expect(connect.info.port).toBe(8111);
188 expect(connect.info.url).toContain("dax://");
189 expect(connect.info.tls).toBe(false);
190 expect(connect.env.host).toBe(connect.info.host);
191 expect(connect.env.port).toBe(String(connect.info.port));
192 expect(connect.env.url).toBe(connect.info.url);
193 expect(connect.env.tls).toBe("false");
194
195 // Scaling bindings: invalid target factors reach service-side
196 // validation and surface typed tags — proves the per-cluster IAM
197 // grant and the ClusterName injection for both bindings.
198 const scale = (yield* get("/scale-probe")) as { increaseTag: string; decreaseTag: string };
199 expect(["InvalidParameterValueException", "InvalidClusterStateFault"]).toContain(
200 scale.increaseTag,
201 );
202 expect(["InvalidParameterValueException", "InvalidClusterStateFault"]).toContain(
203 scale.decreaseTag,
204 );
205
206 // Reboot the cluster's only node and observe it transition.
207 const nodes = (yield* get("/nodes")) as { nodeIds: string[] };
208 expect(nodes.nodeIds.length).toBe(1);
209 const reboot = (yield* get(`/reboot?nodeId=${nodes.nodeIds[0]}`)) as {
210 nodeStatus?: string;
211 };
212 expect(reboot.nodeStatus).toBeDefined();
213 }).pipe(
214 Effect.ensuring(slowStack.destroy().pipe(Effect.andThen(deleteSubnetGroup), Effect.orDie)),
215 );
216 }),
217 // cluster create (~10 min) + probes + delete (~10 min) in one test.
218 {
219 tags: [
220 "provider:aws",
221 "provider:aws:dax",
222 "provider:aws:ec2",
223 "provider:aws:iam",
224 "provider:aws:lambda",
225 "live",
226 ],
227 timeout: 2_400_000,
228 },
229 );