@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 274 lines 10.2 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Core from "@alchemy.run/test/Core";
4 import * as ec2 from "@distilled.cloud/aws/ec2";
5 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
6 import * as Output from "alchemy/Output";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Schedule from "effect/Schedule";
12 import Ec2BindingsFunctionLive, { Ec2BindingsFunction } from "./fixtures/bindings-handler.ts";
13 import * as Test from "./VpcTest.ts";
14
15 const testOptions = { providers: AWS.providers() };
16 const { test, beforeAll, afterAll } = Test.make(testOptions);
17 const sharedStack = Core.scratchStack(testOptions, "Ec2Bindings", "test/AWS/EC2/Bindings.test.ts");
18
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22
23 // A `type` (not `interface`) so it carries an implicit index signature and is
24 // comparable to the `JsonObject` member of `response.json`'s union.
25 type RouteResult = {
26 ok: boolean;
27 tag: string;
28 state?: string;
29 count?: number;
30 hasField?: boolean;
31 redacted?: boolean | null;
32 snapshotId?: string;
33 };
34
35 class SnapshotNotReady extends Data.TaggedError("SnapshotNotReady")<{
36 snapshotId: string;
37 state: string;
38 }> {}
39
40 class SnapshotStillVisible extends Data.TaggedError("SnapshotStillVisible")<{
41 snapshotId: string;
42 }> {}
43
44 // Call a fixture route, repeating (bounded) while the response still shows an
45 // authorization failure — a freshly attached IAM policy is eventually
46 // consistent and the first invocations after deploy can see EC2's
47 // `UnauthorizedOperation`.
48 const callRoute = (method: "GET" | "POST", path: string) =>
49 Effect.gen(function* () {
50 const request =
51 method === "GET"
52 ? HttpClientRequest.get(`${baseUrl}${path}`)
53 : HttpClientRequest.post(`${baseUrl}${path}`);
54 return yield* HttpClient.execute(request).pipe(
55 Effect.flatMap((response) =>
56 response.status === 200
57 ? response.json
58 : Effect.fail(new Error(`Route ${path} not ready: ${response.status}`)),
59 ),
60 // A freshly deployed Function URL can briefly return 502 while the
61 // Lambda execution environment is still initializing. Retry transport
62 // readiness separately from the typed IAM-propagation result below.
63 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 10 }),
64 Effect.map((json) => json as RouteResult),
65 Effect.repeat({
66 until: (body): boolean =>
67 body.tag !== "UnauthorizedOperation" &&
68 body.tag !== "AccessDenied" &&
69 body.tag !== "AccessDeniedException",
70 schedule: Schedule.spaced("3 seconds"),
71 times: 10,
72 }),
73 );
74 });
75
76 // Deploys a Lambda bound to a real t3.micro instance, a 1 GiB volume, and an
77 // empty security group, with every EC2 runtime binding plus the instance
78 // state-change EventBridge subscription. Every route reports the typed result
79 // tag; `/stop` runs last since it powers the instance off.
80 describe(
81 "EC2 runtime bindings",
82 { tags: ["provider:aws", "provider:aws:ec2", "provider:aws:lambda", "live"] },
83 () => {
84 beforeAll(
85 Effect.gen(function* () {
86 yield* sharedStack.destroy();
87
88 const { fn } = yield* sharedStack.deploy(
89 Effect.gen(function* () {
90 const fn = yield* Ec2BindingsFunction;
91 return { fn };
92 }).pipe(Effect.provide(Ec2BindingsFunctionLive)),
93 );
94
95 expect(fn.functionUrl).toBeTruthy();
96 baseUrl = fn.functionUrl!.replace(/\/+$/, "");
97
98 yield* HttpClient.get(`${baseUrl}/health`).pipe(
99 Effect.flatMap((response) =>
100 response.status === 200
101 ? Effect.succeed(response)
102 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
103 ),
104 Effect.retry({ schedule: readinessPolicy }),
105 );
106 }),
107 { timeout: 420_000 },
108 );
109
110 afterAll(sharedStack.destroy(), { timeout: 300_000 });
111
112 test.provider(
113 "DescribeInstance returns the bound instance's live state",
114 (_stack) =>
115 Effect.gen(function* () {
116 const body = yield* callRoute("GET", "/describe");
117 expect(body.tag).toBe("Success");
118 expect(body.ok).toBe(true);
119 expect(body.state).toBeTruthy();
120 }),
121 { timeout: 90_000 },
122 );
123
124 test.provider(
125 "DescribeInstanceStatus lists the bound instance's status checks",
126 (_stack) =>
127 Effect.gen(function* () {
128 const body = yield* callRoute("GET", "/status");
129 expect(body.tag).toBe("Success");
130 expect(body.ok).toBe(true);
131 expect(body.count).toBeGreaterThanOrEqual(1);
132 }),
133 { timeout: 90_000 },
134 );
135
136 test.provider(
137 "GetConsoleOutput fetches the instance's console output",
138 (_stack) =>
139 Effect.gen(function* () {
140 const body = yield* callRoute("GET", "/console");
141 expect(body.ok).toBe(true);
142 }),
143 { timeout: 90_000 },
144 );
145
146 test.provider(
147 "GetPasswordData succeeds and surfaces PasswordData as Redacted",
148 (_stack) =>
149 Effect.gen(function* () {
150 const body = yield* callRoute("GET", "/password");
151 expect(body.ok).toBe(true);
152 // Linux without a key pair: the field is either absent or Redacted —
153 // never a raw string.
154 if (body.hasField) {
155 expect(body.redacted).toBe(true);
156 }
157 }),
158 { timeout: 90_000 },
159 );
160
161 test.provider(
162 "StartInstance succeeds against the already-running instance",
163 (_stack) =>
164 Effect.gen(function* () {
165 const body = yield* callRoute("POST", "/start");
166 expect(body.ok).toBe(true);
167 }),
168 { timeout: 90_000 },
169 );
170
171 test.provider(
172 "RebootInstance requests an asynchronous reboot",
173 (_stack) =>
174 Effect.gen(function* () {
175 const body = yield* callRoute("POST", "/reboot");
176 expect(body.ok).toBe(true);
177 }),
178 { timeout: 90_000 },
179 );
180
181 test.provider(
182 "Authorize/RevokeSecurityGroupIngress round-trip a dynamic rule",
183 (_stack) =>
184 Effect.gen(function* () {
185 // A failed earlier run may have left the rule behind: authorize then
186 // tolerates the duplicate, revoke always finds one to remove.
187 const authorize = yield* callRoute("POST", "/authorize");
188 expect(["Success", "InvalidPermission.Duplicate"]).toContain(authorize.tag);
189 const revoke = yield* callRoute("POST", "/revoke");
190 expect(revoke.tag).toEqual("Success");
191 }),
192 { timeout: 90_000 },
193 );
194
195 test.provider(
196 "CreateSnapshot snapshots the bound volume",
197 (_stack) =>
198 Effect.gen(function* () {
199 const body = yield* callRoute("POST", "/snapshot");
200 expect(body.ok).toBe(true);
201 expect(body.snapshotId).toBeTruthy();
202
203 // Do not delete a pending snapshot. AWS accepts that request and hides
204 // the snapshot immediately, but its background copy can keep the
205 // source volume stuck in `deleting` for many minutes. Wait for this
206 // tiny empty-volume snapshot to finish before removing it.
207 yield* ec2.describeSnapshots({ SnapshotIds: [body.snapshotId!] }).pipe(
208 Effect.flatMap((result) => {
209 const state = result.Snapshots?.[0]?.State ?? "missing";
210 if (state === "completed") return Effect.void;
211 if (state === "error") {
212 return Effect.fail(new Error(`Snapshot ${body.snapshotId} entered error state`));
213 }
214 return Effect.fail(new SnapshotNotReady({ snapshotId: body.snapshotId!, state }));
215 }),
216 Effect.retry({
217 while: (error) => error instanceof SnapshotNotReady,
218 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(29)]),
219 }),
220 );
221
222 // The runtime-created snapshot is not stack-managed — delete it
223 // out-of-band and confirm the exact ID is no longer enumerable.
224 yield* ec2
225 .deleteSnapshot({ SnapshotId: body.snapshotId! })
226 .pipe(Effect.catchTag("InvalidSnapshot.NotFound", () => Effect.void));
227 yield* ec2.describeSnapshots({ SnapshotIds: [body.snapshotId!] }).pipe(
228 Effect.flatMap((result) =>
229 (result.Snapshots ?? []).length === 0
230 ? Effect.void
231 : Effect.fail(new SnapshotStillVisible({ snapshotId: body.snapshotId! })),
232 ),
233 Effect.catchTag("InvalidSnapshot.NotFound", () => Effect.void),
234 Effect.retry({
235 while: (error) => error instanceof SnapshotStillVisible,
236 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(10)]),
237 }),
238 );
239 }),
240 { timeout: 90_000 },
241 );
242
243 test.provider(
244 "consumeInstanceStateEvents created the EventBridge rule",
245 (_stack) =>
246 Effect.gen(function* () {
247 const ref = yield* AWS.EventBridge.Rule.ref("BindingsInstance-InstanceState", {
248 stack: sharedStack.name,
249 stage: sharedStack.stage,
250 });
251 const { Name, EventBusName } = yield* Effect.all({
252 Name: Output.evaluate(ref.ruleName, {}),
253 EventBusName: Output.evaluate(ref.eventBusName, {}),
254 }).pipe(Effect.provide(sharedStack.state));
255 const rule = yield* eventbridge.describeRule({ Name, EventBusName });
256 expect(rule?.EventPattern).toContain("aws.ec2");
257 expect(rule?.EventPattern).toContain("EC2 Instance State-change Notification");
258 }),
259 { tags: ["provider:aws:eventbridge"], timeout: 60_000 },
260 );
261
262 // Runs last: the instance stays stopped until the stack is destroyed.
263 test.provider(
264 "StopInstance powers the instance off",
265 (_stack) =>
266 Effect.gen(function* () {
267 const body = yield* callRoute("POST", "/stop");
268 expect(body.ok).toBe(true);
269 expect(["stopping", "stopped"]).toContain(body.state);
270 }),
271 { timeout: 90_000 },
272 );
273 },
274 );