@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 247 lines 9.66 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 ecr from "@distilled.cloud/aws/ecr";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import EcrTestFunctionLive, { EcrTestFunction } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "EcrBindings");
17
18 let baseUrl: string;
19
20 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
21 readonly status: number;
22 readonly body: string;
23 }> {}
24
25 // Fresh Lambda role + ECR/S3 permissions propagate eventually — the first
26 // calls can 500 with AccessDenied. Retry 5xx only (the handler surfaces
27 // typed errors as a 500 JSON body); a genuine 4xx fails immediately.
28 const send = (request: HttpClientRequest.HttpClientRequest) =>
29 HttpClient.execute(request).pipe(
30 Effect.flatMap((response) =>
31 response.status >= 500
32 ? response.text.pipe(
33 Effect.flatMap((body) =>
34 Effect.fail(new TransientUpstream({ status: response.status, body })),
35 ),
36 )
37 : Effect.succeed(response),
38 ),
39 Effect.retry({
40 while: (e) => e._tag === "TransientUpstream",
41 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
42 }),
43 );
44
45 const getJson = <T>(path: string) =>
46 Effect.gen(function* () {
47 const response = yield* send(HttpClientRequest.get(`${baseUrl}${path}`));
48 expect(response.status).toBe(200);
49 return (yield* response.json) as T;
50 });
51
52 const postJson = <T>(path: string) =>
53 Effect.gen(function* () {
54 const response = yield* send(HttpClientRequest.post(`${baseUrl}${path}`));
55 expect(response.status).toBe(200);
56 return (yield* response.json) as T;
57 });
58
59 describe(
60 "ECR Bindings",
61 {
62 tags: [
63 "provider:aws",
64 "provider:aws:batch",
65 "provider:aws:ecr",
66 "provider:aws:lambda",
67 "provider:aws:s3",
68 "live",
69 ],
70 },
71 () => {
72 beforeAll(
73 Effect.gen(function* () {
74 yield* Effect.logInfo("ECR Bindings setup: destroying previous resources");
75 yield* sharedStack.destroy();
76
77 yield* Effect.logInfo("ECR Bindings setup: deploying repository -> Lambda");
78 const { functionUrl } = yield* sharedStack.deploy(
79 Effect.gen(function* () {
80 return yield* EcrTestFunction;
81 }).pipe(Effect.provide(EcrTestFunctionLive)),
82 );
83
84 expect(functionUrl).toBeTruthy();
85 baseUrl = functionUrl!.replace(/\/+$/, "");
86
87 // Readiness probe — fresh function URLs take seconds to serve 200s.
88 yield* HttpClient.get(`${baseUrl}/nope`).pipe(
89 Effect.flatMap((response) =>
90 response.status === 404
91 ? Effect.succeed(response)
92 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
93 ),
94 Effect.retry({
95 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
96 }),
97 );
98 }),
99 { timeout: 300_000 },
100 );
101 // No NO_DESTROY escape hatch here: scratch-stack state is in-memory per
102 // process, so a skipped destroy would orphan the whole stack forever.
103 afterAll(sharedStack.destroy(), { timeout: 300_000 });
104
105 describe("GetAuthorizationToken", () => {
106 test.provider(
107 "mints a Redacted registry credential that decodes to AWS:<password>",
108 () =>
109 Effect.gen(function* () {
110 const body = yield* getJson<{
111 redacted: boolean;
112 length: number;
113 decodesToAwsUser: boolean;
114 proxyEndpoint?: string;
115 }>("/token");
116 // An ECR bearer token is a long opaque credential; the in-Lambda
117 // `redacted` flag flips to true once the distilled `lib/` build
118 // catches up with the SensitiveString patch (the bundler resolves
119 // the built lib, unlike vitest which resolves src).
120 expect(body.length).toBeGreaterThan(100);
121 expect(body.decodesToAwsUser).toBe(true);
122 expect(body.proxyEndpoint).toContain(".ecr.");
123 }),
124 { timeout: 120_000 },
125 );
126
127 test.provider(
128 "authorizationToken is Redacted (distilled sensitive patch)",
129 () =>
130 Effect.gen(function* () {
131 // Direct distilled call (vitest resolves distilled from src, so the
132 // SensitiveString patch is live here).
133 const res = yield* ecr.getAuthorizationToken({});
134 const token = res.authorizationData?.[0]?.authorizationToken;
135 expect(Redacted.isRedacted(token)).toBe(true);
136 expect(Redacted.value(token as Redacted.Redacted<string>).length).toBeGreaterThan(100);
137 }),
138 { timeout: 120_000 },
139 );
140 });
141
142 // The image bindings mutate shared repository state, so they run as ONE
143 // ordered flow — vitest executes tests in this file concurrently
144 // (`sequence.concurrent`), which would otherwise race the delete steps
145 // against the read steps.
146 describe("image lifecycle", () => {
147 test.provider(
148 "push -> inspect -> pull -> scan -> delete through the bindings",
149 () =>
150 Effect.gen(function* () {
151 // InitiateLayerUpload + UploadLayerPart + CompleteLayerUpload +
152 // PutImage — push a minimal synthetic image.
153 const pushed = yield* postJson<{
154 digest?: string;
155 layerDigest: string;
156 configDigest: string;
157 }>("/push?tag=1.0.0");
158 expect(pushed.layerDigest).toMatch(/^sha256:/);
159 expect(pushed.digest).toMatch(/^sha256:/);
160
161 // DescribeImages.
162 const image = yield* getJson<{ tags?: string[]; digest?: string }>("/images?tag=1.0.0");
163 expect(image.tags).toContain("1.0.0");
164 expect(image.digest).toBe(pushed.digest);
165
166 // ListImages.
167 const ids = yield* getJson<{ tags: string[] }>("/image-ids");
168 expect(ids.tags).toContain("1.0.0");
169
170 // BatchGetImage.
171 const manifest = yield* getJson<{ mediaType?: string; manifestLength: number }>(
172 "/manifest?tag=1.0.0",
173 );
174 expect(manifest.mediaType).toBe("application/vnd.docker.distribution.manifest.v2+json");
175 expect(manifest.manifestLength).toBeGreaterThan(100);
176
177 // GetDownloadUrlForLayer.
178 const layer = yield* getJson<{ hasUrl: boolean }>(
179 `/layer?digest=${encodeURIComponent(pushed.layerDigest)}`,
180 );
181 expect(layer.hasUrl).toBe(true);
182
183 // BatchCheckLayerAvailability.
184 const availability = yield* getJson<{ availability?: string }>(
185 `/availability?digest=${encodeURIComponent(pushed.layerDigest)}`,
186 );
187 expect(availability.availability).toBe("AVAILABLE");
188
189 // StartImageScan — the synthetic image is not a supported OS
190 // image, so the typed UnsupportedImageTypeException is as much a
191 // proof of the binding as a successful scan.
192 const scan = yield* postJson<{ status?: string; error?: string }>("/scan?tag=1.0.0");
193 expect(
194 scan.status !== undefined ||
195 scan.error === "UnsupportedImageTypeException" ||
196 scan.error === "LimitExceededException" ||
197 scan.error === "ValidationException",
198 ).toBe(true);
199
200 // DescribeImageScanFindings — real findings or the typed
201 // ScanNotFoundException when the scan was rejected above.
202 const findings = yield* getJson<{ status?: string; error?: string }>(
203 "/scan-findings?tag=1.0.0",
204 );
205 expect(
206 findings.status !== undefined ||
207 findings.error === "ScanNotFoundException" ||
208 findings.error === "ValidationException",
209 ).toBe(true);
210
211 // BatchDeleteImage.
212 const deleted = yield* postJson<{ deleted: number }>("/delete?tag=1.0.0");
213 expect(deleted.deleted).toBe(1);
214 const after = yield* getJson<{ tags: string[] }>("/image-ids");
215 expect(after.tags).not.toContain("1.0.0");
216 }),
217 { timeout: 180_000 },
218 );
219 });
220
221 describe("ImageActionEventSource", () => {
222 test.provider(
223 "delivers push events to the handler",
224 () =>
225 Effect.gen(function* () {
226 // Each probe pushes a FRESH tag (a re-push of an existing tag is
227 // ImageAlreadyExists — no new event) and polls S3 for the marker
228 // the event handler wrote. A freshly-created EventBridge rule on
229 // the default bus takes up to ~a minute to become effective, so
230 // successive fresh-tag pushes ride out the propagation window.
231 const probe = (tag: string) =>
232 getJson<{ seen: boolean; tag: string }>(`/events/probe?tag=${tag}`).pipe(
233 Effect.map((body) => body.seen),
234 );
235 const seen = yield* Effect.gen(function* () {
236 for (const tag of ["2.0.0", "2.0.1", "2.0.2", "2.0.3"]) {
237 if (yield* probe(tag)) return true;
238 }
239 return false;
240 });
241 expect(seen).toBe(true);
242 }),
243 { timeout: 180_000 },
244 );
245 });
246 },
247 );