@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 359 lines 13.6 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Core from "@alchemy.run/test/Core";
6 import * as docdbelastic from "@distilled.cloud/aws/docdb-elastic";
7 import * as EC2 from "@distilled.cloud/aws/ec2";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as Schedule from "effect/Schedule";
11 import { getDefaultVpc } from "../DefaultVpc.ts";
12 import DocDBElasticTestFunctionLive, { DocDBElasticTestFunction } from "./handler";
13 import DocDBElasticSlowTestFunctionLive, {
14 DocDBElasticSlowTestFunction,
15 SECURITY_GROUPS_ENV,
16 SUBNETS_ENV,
17 } from "./slow-handler";
18
19 const testOptions = { providers: AWS.providers() };
20 const { test, beforeAll, afterAll } = Test.make(testOptions);
21 const sharedStack = Core.scratchStack(testOptions, "DocDBElasticBindings");
22
23 const NONEXISTENT_UUID = "00000000-0000-0000-0000-000000000000";
24
25 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
26 // over 60s on a fresh deploy.
27 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
28
29 let baseUrl: string;
30
31 // Well-formed-but-nonexistent ARNs the probe routes are driven against.
32 // Computed inside test bodies (test.provider provides AWSEnvironment).
33 const probeArns = Effect.gen(function* () {
34 const { accountId, region } = yield* AWSEnvironment.current;
35 return {
36 snapshot: `arn:aws:docdb-elastic:${region}:${accountId}:cluster-snapshot/${NONEXISTENT_UUID}`,
37 cluster: `arn:aws:docdb-elastic:${region}:${accountId}:cluster/${NONEXISTENT_UUID}`,
38 };
39 });
40
41 const getJson = (path: string) =>
42 HttpClient.get(`${baseUrl}${path}`).pipe(
43 Effect.flatMap((response) =>
44 response.status >= 500
45 ? Effect.fail(new Error(`transient upstream ${response.status}`))
46 : Effect.succeed(response),
47 ),
48 Effect.retry({
49 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
50 }),
51 Effect.flatMap((r) => r.json),
52 );
53
54 describe.sequential(
55 "DocDBElastic Bindings",
56 { tags: ["provider:aws", "provider:aws:docdbelastic", "provider:aws:lambda", "live"] },
57 () => {
58 beforeAll(
59 Effect.gen(function* () {
60 yield* Effect.logInfo("DocDBElastic test setup: destroying previous resources");
61 yield* sharedStack.destroy();
62
63 yield* Effect.logInfo("DocDBElastic test setup: deploying fixture");
64 const { functionUrl } = yield* sharedStack.deploy(
65 Effect.gen(function* () {
66 return yield* DocDBElasticTestFunction;
67 }).pipe(Effect.provide(DocDBElasticTestFunctionLive)),
68 );
69
70 expect(functionUrl).toBeTruthy();
71 baseUrl = functionUrl!.replace(/\/+$/, "");
72
73 const readinessUrl = `${baseUrl}/bindings`;
74 yield* HttpClient.get(readinessUrl).pipe(
75 Effect.flatMap((response) =>
76 response.status === 200
77 ? Effect.succeed(response)
78 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
79 ),
80 Effect.retry({ schedule: readinessPolicy }),
81 );
82 }),
83 { timeout: 240_000 },
84 );
85
86 afterAll(sharedStack.destroy(), { timeout: 120_000 });
87
88 describe("binding registration", () => {
89 test.provider("all eight capabilities initialize in the runtime", () =>
90 Effect.gen(function* () {
91 const response = yield* getJson("/bindings");
92 expect((response as any).bound).toHaveLength(8);
93 }),
94 );
95 });
96
97 describe("ListClusterSnapshots", () => {
98 test.provider("lists the account's snapshots", () =>
99 Effect.gen(function* () {
100 const response = yield* getJson("/snapshots");
101 expect((response as any).count).toBeGreaterThanOrEqual(0);
102 }),
103 );
104 });
105
106 describe("ListPendingMaintenanceActions", () => {
107 test.provider("lists the account's pending maintenance", () =>
108 Effect.gen(function* () {
109 const response = yield* getJson("/maintenance");
110 expect((response as any).count).toBeGreaterThanOrEqual(0);
111 }),
112 );
113 });
114
115 describe("GetClusterSnapshot", () => {
116 test.provider("surfaces the typed not-found tag", () =>
117 Effect.gen(function* () {
118 const arns = yield* probeArns;
119 const response = yield* getJson(
120 `/snapshot-probe?arn=${encodeURIComponent(arns.snapshot)}`,
121 );
122 expect((response as any).tag).toBe("ResourceNotFoundException");
123 }),
124 );
125 });
126
127 describe("DeleteClusterSnapshot", () => {
128 test.provider("surfaces the typed not-found tag", () =>
129 Effect.gen(function* () {
130 const arns = yield* probeArns;
131 const response = yield* getJson(`/delete-probe?arn=${encodeURIComponent(arns.snapshot)}`);
132 expect((response as any).tag).toBe("ResourceNotFoundException");
133 }),
134 );
135 });
136
137 describe("CopyClusterSnapshot", () => {
138 test.provider("rejects a nonexistent source snapshot with a typed tag", () =>
139 Effect.gen(function* () {
140 const arns = yield* probeArns;
141 const response = yield* getJson(`/copy-probe?arn=${encodeURIComponent(arns.snapshot)}`);
142 // Copy authorizes against the source-snapshot resource; a
143 // nonexistent snapshot is reported as AccessDeniedException
144 // (existence non-disclosure) rather than not-found.
145 expect([
146 "ResourceNotFoundException",
147 "ValidationException",
148 "AccessDeniedException",
149 ]).toContain((response as any).tag);
150 }),
151 );
152 });
153
154 describe("RestoreClusterFromSnapshot", () => {
155 test.provider("rejects a nonexistent source snapshot with a typed tag", () =>
156 Effect.gen(function* () {
157 const arns = yield* probeArns;
158 const response = yield* getJson(
159 `/restore-probe?arn=${encodeURIComponent(arns.snapshot)}`,
160 );
161 // Restore authorizes against the source-snapshot resource; a
162 // nonexistent snapshot is reported as AccessDeniedException
163 // (existence non-disclosure) rather than not-found.
164 expect([
165 "ResourceNotFoundException",
166 "ValidationException",
167 "AccessDeniedException",
168 ]).toContain((response as any).tag);
169 }),
170 );
171 });
172
173 describe("GetPendingMaintenanceAction", () => {
174 test.provider("surfaces a typed tag for a nonexistent cluster", () =>
175 Effect.gen(function* () {
176 const arns = yield* probeArns;
177 const response = yield* getJson(`/pending-probe?arn=${encodeURIComponent(arns.cluster)}`);
178 expect(["ResourceNotFoundException", "ValidationException"]).toContain(
179 (response as any).tag,
180 );
181 }),
182 );
183 });
184
185 describe("ApplyPendingMaintenanceAction", () => {
186 test.provider("surfaces a typed tag for a nonexistent cluster", () =>
187 Effect.gen(function* () {
188 const arns = yield* probeArns;
189 const response = yield* getJson(`/apply-probe?arn=${encodeURIComponent(arns.cluster)}`);
190 expect(["ResourceNotFoundException", "ValidationException"]).toContain(
191 (response as any).tag,
192 );
193 }),
194 );
195 });
196 },
197 );
198
199 // ---------------------------------------------------------------------------
200 // Cluster-scoped bindings (CreateClusterSnapshot, StopCluster, StartCluster)
201 // need a real elastic cluster (~10 min to provision, billed per
202 // shard-vCPU-hour) — skipped under `--fast` like the Cluster lifecycle
203 // test.
204 // ---------------------------------------------------------------------------
205
206 const slowStack = Core.scratchStack(testOptions, "DocDBElasticSlowBindings");
207
208 const SLOW_SNAPSHOT_NAME = "alchemy-docdb-elastic-bindings-snap";
209
210 // Resolve two default-for-AZ subnets from the region's first three AZs
211 // (elastic clusters are not offered in every AZ, e.g. us-west-2d) and the
212 // default security group — same selection as Cluster.test.ts.
213 const defaultNetwork = Effect.gen(function* () {
214 const vpc = yield* getDefaultVpc;
215 const subnets = yield* EC2.describeSubnets({
216 Filters: [
217 { Name: "vpc-id", Values: [vpc.vpcId] },
218 { Name: "default-for-az", Values: ["true"] },
219 ],
220 });
221 const subnetIds = (subnets.Subnets ?? [])
222 .filter((s) => /[abc]$/.test(s.AvailabilityZone ?? ""))
223 .sort((l, r) => (l.AvailabilityZone ?? "").localeCompare(r.AvailabilityZone ?? ""))
224 .map((s) => s.SubnetId)
225 .filter((id): id is `subnet-${string}` => id !== undefined)
226 .slice(0, 2);
227 const groups = yield* EC2.describeSecurityGroups({
228 Filters: [
229 { Name: "vpc-id", Values: [vpc.vpcId] },
230 { Name: "group-name", Values: ["default"] },
231 ],
232 });
233 const securityGroupId = groups.SecurityGroups?.[0]?.GroupId;
234 if (subnetIds.length < 2 || securityGroupId === undefined) {
235 return yield* Effect.die(
236 new Error("default VPC is missing subnets or its default security group"),
237 );
238 }
239 return { subnetIds, securityGroupIds: [securityGroupId] };
240 });
241
242 // The snapshot the gated test creates is cleaned up out-of-band; deletion of
243 // a snapshot still CREATING conflicts, so retry (bounded) while it settles.
244 const deleteSnapshot = (snapshotArn: string) =>
245 docdbelastic.deleteClusterSnapshot({ snapshotArn }).pipe(
246 Effect.asVoid,
247 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
248 Effect.retry({
249 while: (e): boolean => e._tag === "ConflictException",
250 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
251 }),
252 );
253
254 // Snapshots outlive their cluster, so one left behind by an interrupted run
255 // makes the fixture's CreateClusterSnapshot fail with ConflictException ("A
256 // snapshot already exists with given name"). Clear it by name up front.
257 const deleteSnapshotsNamed = (name: string) =>
258 docdbelastic.listClusterSnapshots({}).pipe(
259 Effect.flatMap((r) =>
260 Effect.forEach(
261 (r.snapshots ?? []).filter((s) => s.snapshotName === name),
262 (s) => deleteSnapshot(s.snapshotArn),
263 { discard: true },
264 ),
265 ),
266 );
267
268 test.provider.skipIf(!!process.env.FAST)(
269 "snapshot + stop + start bindings against a live elastic cluster",
270 () =>
271 Effect.gen(function* () {
272 yield* slowStack.destroy();
273 yield* deleteSnapshotsNamed(SLOW_SNAPSHOT_NAME);
274 const network = yield* defaultNetwork;
275 yield* Effect.sync(() => {
276 process.env[SUBNETS_ENV] = JSON.stringify(network.subnetIds);
277 process.env[SECURITY_GROUPS_ENV] = JSON.stringify(network.securityGroupIds);
278 });
279
280 let snapshotArn: string | undefined;
281
282 yield* Effect.gen(function* () {
283 const { functionUrl } = yield* slowStack.deploy(
284 Effect.gen(function* () {
285 return yield* DocDBElasticSlowTestFunction;
286 }).pipe(Effect.provide(DocDBElasticSlowTestFunctionLive)),
287 );
288 expect(functionUrl).toBeTruthy();
289 const slowBaseUrl = functionUrl!.replace(/\/+$/, "");
290
291 // A non-200 is a test failure carrying the status — the fixture
292 // answers an empty 500 on a defect, which `r.json` decodes to null.
293 const get = (path: string) =>
294 HttpClient.get(`${slowBaseUrl}${path}`).pipe(
295 Effect.retry({
296 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
297 }),
298 Effect.flatMap((r) =>
299 r.status === 200 ? r.json : Effect.fail(new Error(`${path} returned ${r.status}`)),
300 ),
301 );
302
303 // Take an on-demand snapshot of the live cluster.
304 const snapshot = (yield* get(`/snapshot?name=${SLOW_SNAPSHOT_NAME}`)) as {
305 snapshotArn: string;
306 status: string;
307 };
308 expect(snapshot.snapshotArn).toContain(":cluster-snapshot/");
309 snapshotArn = snapshot.snapshotArn;
310
311 // Wait (bounded) for the snapshot to become ACTIVE (the elastic
312 // API's ready status) so the stop call below does not conflict with
313 // the in-flight snapshot.
314 const snapshotStatus = yield* docdbelastic
315 .getClusterSnapshot({ snapshotArn: snapshot.snapshotArn })
316 .pipe(
317 Effect.map((r) => r.snapshot.status),
318 Effect.repeat({
319 schedule: Schedule.spaced("10 seconds"),
320 until: (status): boolean => status === "ACTIVE",
321 times: 60,
322 }),
323 );
324 expect(snapshotStatus).toBe("ACTIVE");
325
326 // Stop the cluster (compute billing pauses).
327 const stop = (yield* get("/stop")) as { status: string };
328 expect(["STOPPING", "STOPPED"]).toContain(stop.status);
329
330 // Starting while STOPPING surfaces a typed rejection; a fully
331 // stopped cluster reports STARTING. Both prove the grant.
332 const start = (yield* get("/start")) as { status: string };
333 expect(["STARTING", "ValidationException"]).toContain(start.status);
334 }).pipe(
335 Effect.ensuring(
336 Effect.gen(function* () {
337 yield* slowStack.destroy();
338 if (snapshotArn !== undefined) {
339 yield* deleteSnapshot(snapshotArn);
340 }
341 }).pipe(Effect.orDie),
342 ),
343 );
344 }),
345 // cluster create (~10-15 min) + snapshot + stop + destroy in one test.
346 // Destroy is slow by necessity: a STOPPING cluster takes ~11 min to reach
347 // STOPPED, and only an ACTIVE cluster is deletable, so the provider starts
348 // it again (~10 min) before DeleteCluster.
349 {
350 tags: [
351 "provider:aws",
352 "provider:aws:docdbelastic",
353 "provider:aws:ec2",
354 "provider:aws:lambda",
355 "live",
356 ],
357 timeout: 3_600_000,
358 },
359 );