@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 306 lines 12.6 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 eventbridge from "@distilled.cloud/aws/eventbridge";
6 import * as imagebuilder from "@distilled.cloud/aws/imagebuilder";
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 ImageBuilderTestFunctionLive, { ImageBuilderTestFunction } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "ImageBuilderBindings");
17
18 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
19 // over 60s on a fresh deploy.
20 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
21
22 let baseUrl: string;
23 let functionArn: string;
24
25 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
26 readonly status: number;
27 readonly body: string;
28 }> {}
29
30 // The shared Lambda fixture occasionally answers a transient 5xx under load
31 // (cold re-init, IAM propagation on the freshly attached policy that the
32 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
33 // 4xx/assertion failure surfaces immediately.
34 const send = (request: HttpClientRequest.HttpClientRequest) =>
35 HttpClient.execute(request).pipe(
36 Effect.flatMap((response) =>
37 response.status >= 500
38 ? response.text.pipe(
39 Effect.flatMap((body) =>
40 Effect.fail(new TransientUpstream({ status: response.status, body })),
41 ),
42 )
43 : Effect.succeed(response),
44 ),
45 Effect.retry({
46 while: (e) => e._tag === "TransientUpstream",
47 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
48 }),
49 );
50
51 const getJson = (path: string) =>
52 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
53
54 const postJson = (path: string) =>
55 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
56
57 const deleteJson = (path: string) =>
58 send(HttpClientRequest.delete(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
59
60 describe.sequential(
61 "ImageBuilder Bindings",
62 {
63 tags: [
64 "provider:aws",
65 "provider:aws:iam",
66 "provider:aws:imagebuilder",
67 "provider:aws:lambda",
68 "live",
69 ],
70 },
71 () => {
72 beforeAll(
73 Effect.gen(function* () {
74 yield* Effect.logInfo("ImageBuilder test setup: destroying previous resources");
75 yield* sharedStack.destroy();
76
77 yield* Effect.logInfo("ImageBuilder test setup: deploying fixture");
78 const attrs = yield* sharedStack.deploy(
79 Effect.gen(function* () {
80 return yield* ImageBuilderTestFunction;
81 }).pipe(Effect.provide(ImageBuilderTestFunctionLive)),
82 );
83
84 expect(attrs.functionUrl).toBeTruthy();
85 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
86 functionArn = attrs.functionArn;
87
88 const readinessUrl = `${baseUrl}/bindings`;
89 yield* Effect.logInfo(`ImageBuilder test setup: probing readiness at ${readinessUrl}`);
90 yield* HttpClient.get(readinessUrl).pipe(
91 Effect.flatMap((response) =>
92 response.status === 200
93 ? Effect.succeed(response)
94 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
95 ),
96 Effect.tapError((error) =>
97 Effect.logWarning(`ImageBuilder test setup: fixture not ready yet (${String(error)})`),
98 ),
99 Effect.retry({ schedule: readinessPolicy }),
100 );
101 }),
102 { timeout: 300_000 },
103 );
104
105 afterAll(sharedStack.destroy(), { timeout: 180_000 });
106
107 describe("binding registration", () => {
108 test.provider("all eighteen capabilities initialize in the runtime", () =>
109 Effect.gen(function* () {
110 const response = (yield* getJson("/bindings")) as { bound: string[] };
111 expect(response.bound).toHaveLength(18);
112 // SendWorkflowStepAction needs a WAIT_FOR_ACTION step and RetryImage
113 // a FAILED build — registration/IAM wiring only.
114 expect(response.bound).toContain("sendWorkflowStepAction");
115 expect(response.bound).toContain("retryImage");
116 }),
117 );
118 });
119
120 describe("GetImagePipeline", () => {
121 test.provider("reads the bound pipeline's state (injected pipeline arn)", () =>
122 Effect.gen(function* () {
123 const response = (yield* getJson("/pipeline")) as {
124 arn: string;
125 name: string;
126 status: string;
127 timeoutMinutes: number;
128 };
129 expect(response.arn).toContain(":image-pipeline/");
130 expect(response.status).toBe("ENABLED");
131 // The fixture's Duration timeout ("1 hour") landed as 60 wire
132 // minutes — proves the renamed duration prop converts correctly.
133 expect(response.timeoutMinutes).toBe(60);
134 }),
135 );
136 });
137
138 describe("ListImagePipelineImages", () => {
139 test.provider("enumerates the pipeline's builds", () =>
140 Effect.gen(function* () {
141 const response = (yield* getJson("/pipeline-images")) as { arns: string[] };
142 expect(Array.isArray(response.arns)).toBe(true);
143 }),
144 );
145 });
146
147 describe("ListImages", () => {
148 test.provider("enumerates the account's images", () =>
149 Effect.gen(function* () {
150 const response = (yield* getJson("/images")) as { count: number };
151 expect(response.count).toBeGreaterThanOrEqual(0);
152 }),
153 );
154 });
155
156 describe("account-level reads", () => {
157 test.provider(
158 "ListImageScanFindings + ListImageScanFindingAggregations + ListWaitingWorkflowSteps",
159 () =>
160 Effect.gen(function* () {
161 const findings = (yield* getJson("/scan-findings")) as { count: number };
162 expect(findings.count).toBeGreaterThanOrEqual(0);
163
164 const aggregations = (yield* getJson("/scan-aggregations")) as { count: number };
165 expect(aggregations.count).toBeGreaterThanOrEqual(0);
166
167 const waiting = (yield* getJson("/waiting-steps")) as { count: number };
168 expect(waiting.count).toBeGreaterThanOrEqual(0);
169 }),
170 { timeout: 60_000 },
171 );
172 });
173
174 describe("build lifecycle", () => {
175 test.provider(
176 "Start → Cancel → GetImage → ListWorkflowExecutions → DeleteImage",
177 () =>
178 Effect.gen(function* () {
179 // Kick off a real build of the bound pipeline via the binding.
180 const started = (yield* postJson("/build/start")) as { imageBuildVersionArn: string };
181 expect(started.imageBuildVersionArn).toContain(":image/");
182 const arn = encodeURIComponent(started.imageBuildVersionArn);
183
184 const run = Effect.gen(function* () {
185 // Cancel it — early build states can briefly reject the
186 // cancellation, so retry through the window (bounded).
187 const cancelled = yield* postJson(`/build/cancel?arn=${arn}`).pipe(
188 Effect.map((body) => body as { imageBuildVersionArn?: string; reason?: string }),
189 Effect.repeat({
190 schedule: Schedule.spaced("5 seconds"),
191 until: (body): boolean => body.imageBuildVersionArn !== undefined,
192 times: 12,
193 }),
194 );
195 expect(cancelled.imageBuildVersionArn).toBe(started.imageBuildVersionArn);
196
197 // The build's workflow drill-down responds (may be empty this
198 // early in the build).
199 const workflows = (yield* getJson(`/build/workflows?arn=${arn}`)) as {
200 ids: string[];
201 };
202 expect(Array.isArray(workflows.ids)).toBe(true);
203
204 // If the build already spawned a workflow execution, drill into
205 // it through the workflow-monitoring bindings.
206 const executionId = workflows.ids[0];
207 if (executionId !== undefined) {
208 const execution = (yield* getJson(
209 `/workflow-execution?id=${encodeURIComponent(executionId)}`,
210 )) as { id?: string; status?: string };
211 expect(execution.id).toBe(executionId);
212
213 const steps = (yield* getJson(
214 `/workflow-steps?id=${encodeURIComponent(executionId)}`,
215 )) as { ids: string[] };
216 expect(Array.isArray(steps.ids)).toBe(true);
217
218 const stepId = steps.ids[0];
219 if (stepId !== undefined) {
220 const step = (yield* getJson(
221 `/workflow-step?id=${encodeURIComponent(stepId)}`,
222 )) as { name?: string; status?: string };
223 expect(typeof step.status).toBe("string");
224 }
225 }
226
227 // The build version shows up under its image version ARN
228 // (…:image/{name}/{version} — strip the build-number suffix).
229 const imageVersionArn = started.imageBuildVersionArn.replace(/\/\d+$/, "");
230 const versions = (yield* getJson(
231 `/build-versions?arn=${encodeURIComponent(imageVersionArn)}`,
232 )) as { arns: string[] };
233 expect(versions.arns).toContain(started.imageBuildVersionArn);
234
235 // Packages exist only for AVAILABLE builds — this in-flight or
236 // cancelled build reports the typed rejection instead.
237 const packages = (yield* getJson(`/build/packages?arn=${arn}`)) as {
238 count?: number;
239 reason?: string;
240 };
241 expect(packages.count !== undefined || packages.reason !== undefined).toBe(true);
242
243 // Observe the build settle into CANCELLED via the GetImage
244 // binding (bounded).
245 const settled = yield* getJson(`/build?arn=${arn}`).pipe(
246 Effect.map((body) => body as { status?: string }),
247 Effect.repeat({
248 schedule: Schedule.spaced("5 seconds"),
249 until: (body): boolean => body.status === "CANCELLED" || body.status === "FAILED",
250 times: 24,
251 }),
252 );
253 expect(settled.status).toBe("CANCELLED");
254
255 // Prune the cancelled build via the DeleteImage binding; poll
256 // through the not-yet-deletable window (bounded).
257 const deleted = yield* deleteJson(`/build?arn=${arn}`).pipe(
258 Effect.map((body) => body as { deleted: boolean; reason?: string }),
259 Effect.repeat({
260 schedule: Schedule.spaced("5 seconds"),
261 until: (body): boolean => body.deleted,
262 times: 12,
263 }),
264 );
265 expect(deleted.deleted).toBe(true);
266 });
267
268 // Zero-orphan guarantee: whatever happens above, the build
269 // version is removed out-of-band via distilled before the test
270 // ends (idempotent — tolerates the happy path's delete).
271 yield* run.pipe(
272 Effect.ensuring(
273 imagebuilder
274 .deleteImage({ imageBuildVersionArn: started.imageBuildVersionArn })
275 .pipe(
276 Effect.retry({
277 while: (e): boolean =>
278 e._tag === "InvalidRequestException" ||
279 e._tag === "ResourceDependencyException",
280 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(10)]),
281 }),
282 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
283 Effect.catch(() => Effect.void),
284 ),
285 ),
286 );
287 }),
288 { timeout: 240_000 },
289 );
290 });
291
292 describe("consumeImageEvents", { tags: ["provider:aws:eventbridge"] }, () => {
293 test.provider("the deploy created an EventBridge rule targeting the function", () =>
294 Effect.gen(function* () {
295 // Out-of-band via distilled: the fixture's consumeImageEvents
296 // must have materialized as a rule on the default bus with the
297 // Lambda as target.
298 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
299 TargetArn: functionArn,
300 });
301 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
302 }),
303 );
304 });
305 },
306 );