@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 314 lines 12.5 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 cloudfront from "@distilled.cloud/aws/cloudfront";
6 import * as kvs from "@distilled.cloud/aws/cloudfront-keyvaluestore";
7 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
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 Redacted from "effect/Redacted";
12 import * as Schedule from "effect/Schedule";
13 import CloudFrontTestFunctionLive, { CloudFrontTestFunction } from "./handler.ts";
14 import CloudFrontKvsTestFunctionLive, { CloudFrontKvsTestFunction } from "./kvs-handler.ts";
15
16 // The fixture deploys a CloudFront Distribution, which takes 3-10 minutes to
17 // reach `Deployed` — gate the live run per the catalog's slow-test guidance.
18 const runLive = !process.env.FAST;
19
20 const testOptions = { providers: AWS.providers() };
21 const { test, beforeAll, afterAll } = Test.make(testOptions);
22 const sharedStack = Core.scratchStack(testOptions, "CloudFrontBindings");
23
24 let baseUrl: string;
25
26 // Resolve the fixture's distribution out-of-band by its deterministic
27 // comment (runtime Output resolution inside the Lambda is not available for
28 // resources declared in the fixture, so the test looks the id up itself).
29 // Runs inside the test body — `beforeAll` has no distilled credentials
30 // context. `listDistributions` is eventually consistent for a
31 // freshly-created distribution, so retry the lookup for up to ~60s.
32 const findFixtureDistributionId = Effect.gen(function* () {
33 const response = yield* cloudfront.listDistributions({});
34 const match = (response.DistributionList?.Items ?? []).find(
35 // Comment is a sensitive field — distilled decodes it as Redacted.
36 (item) =>
37 (typeof item.Comment === "string" ? item.Comment : Redacted.value(item.Comment)) ===
38 "alchemy-cf-bindings-fixture",
39 );
40 if (!match) {
41 return yield* Effect.fail(new Error("fixture distribution not found by comment"));
42 }
43 return match.Id;
44 }).pipe(
45 Effect.retry({
46 while: (e) => e instanceof Error,
47 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
48 }),
49 );
50
51 describe(
52 "CloudFront Bindings",
53 {
54 tags: [
55 "provider:aws",
56 "provider:aws:cloudfront",
57 "provider:aws:lambda",
58 "provider:aws:s3",
59 "live",
60 ],
61 },
62 () => {
63 beforeAll(
64 runLive
65 ? Effect.gen(function* () {
66 yield* Effect.logInfo("CloudFront bindings: destroying previous");
67 yield* sharedStack.destroy();
68
69 yield* Effect.logInfo(
70 "CloudFront bindings: deploying fixture (distribution deploy is slow)",
71 );
72 const { functionUrl } = yield* sharedStack.deploy(
73 Effect.gen(function* () {
74 return yield* CloudFrontTestFunction;
75 }).pipe(Effect.provide(CloudFrontTestFunctionLive)),
76 );
77
78 expect(functionUrl).toBeTruthy();
79 baseUrl = functionUrl!.replace(/\/+$/, "");
80
81 // Fresh function URLs take a few seconds to start serving.
82 yield* HttpClient.get(`${baseUrl}/health`).pipe(
83 Effect.flatMap((response) =>
84 response.status === 200
85 ? Effect.void
86 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
87 ),
88 Effect.retry({
89 while: (e) => e instanceof Error,
90 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]),
91 }),
92 );
93 })
94 : Effect.void,
95 { timeout: 900_000 },
96 );
97 afterAll(runLive ? sharedStack.destroy() : Effect.void, { timeout: 900_000 });
98
99 describe("CreateInvalidation", () => {
100 test.provider.skipIf(!runLive)(
101 "creates an invalidation for the bound distribution at runtime",
102 (_stack) =>
103 Effect.gen(function* () {
104 const response = yield* HttpClient.execute(
105 HttpClientRequest.post(`${baseUrl}/invalidate`).pipe(
106 HttpClientRequest.bodyJsonUnsafe({
107 callerReference: "alchemy-test-invalidation-1",
108 paths: ["/index.html"],
109 }),
110 ),
111 );
112 expect(response.status).toBe(200);
113 const body = (yield* response.json) as { invalidationId: string; status: string };
114 expect(body.invalidationId).toBeTruthy();
115 expect(["InProgress", "Completed"]).toContain(body.status);
116
117 // Out-of-band: the invalidation exists on the distribution.
118 const distributionId = yield* findFixtureDistributionId;
119 const observed = yield* cloudfront.getInvalidation({
120 DistributionId: distributionId,
121 Id: body.invalidationId,
122 });
123 expect(observed.Invalidation?.Id).toBe(body.invalidationId);
124 }),
125 { timeout: 120_000 },
126 );
127 });
128
129 describe("GetInvalidation + ListInvalidations", () => {
130 test.provider.skipIf(!runLive)(
131 "reads and lists invalidations for the bound distribution at runtime",
132 (_stack) =>
133 Effect.gen(function* () {
134 // Create one via the runtime binding first.
135 const created = yield* HttpClient.execute(
136 HttpClientRequest.post(`${baseUrl}/invalidate`).pipe(
137 HttpClientRequest.bodyJsonUnsafe({
138 callerReference: "alchemy-test-invalidation-2",
139 paths: ["/about.html"],
140 }),
141 ),
142 );
143 expect(created.status).toBe(200);
144 const { invalidationId } = (yield* created.json) as { invalidationId: string };
145
146 // GetInvalidation reads its status through the binding.
147 const got = yield* HttpClient.get(`${baseUrl}/invalidation?id=${invalidationId}`);
148 expect(got.status).toBe(200);
149 const gotBody = (yield* got.json) as { invalidationId: string; status: string };
150 expect(gotBody.invalidationId).toBe(invalidationId);
151 expect(["InProgress", "Completed"]).toContain(gotBody.status);
152
153 // ListInvalidations includes it.
154 const listed = yield* HttpClient.get(`${baseUrl}/invalidations`);
155 expect(listed.status).toBe(200);
156 const listedBody = (yield* listed.json) as { invalidationIds: string[] };
157 expect(listedBody.invalidationIds).toContain(invalidationId);
158 }),
159 { timeout: 120_000 },
160 );
161 });
162 },
163 );
164
165 // The KVS fixture only needs a KeyValueStore + Lambda (no distribution), so
166 // it deploys in well under a minute and runs ungated.
167 const kvsStack = Core.scratchStack(testOptions, "CloudFrontKvsBindings");
168
169 let kvsBaseUrl: string;
170
171 // Resolve the fixture's store ARN through the deployed function's
172 // DescribeKeyValueStore binding (the response carries `KvsARN`), avoiding a
173 // paginated account-wide list lookup.
174 const findFixtureStoreArn = Effect.suspend(() =>
175 // `kvsBaseUrl` is assigned in `beforeAll`, so build the request lazily.
176 HttpClient.get(`${kvsBaseUrl}/describe`),
177 ).pipe(
178 Effect.flatMap((response) => response.json),
179 Effect.map((body) => (body as { kvsArn: string }).kvsArn),
180 );
181
182 describe(
183 "CloudFront KeyValueStore Bindings",
184 { tags: ["provider:aws", "provider:aws:cloudfront", "provider:aws:lambda", "live"] },
185 () => {
186 beforeAll(
187 Effect.gen(function* () {
188 yield* kvsStack.destroy();
189
190 const { functionUrl } = yield* kvsStack.deploy(
191 Effect.gen(function* () {
192 return yield* CloudFrontKvsTestFunction;
193 }).pipe(Effect.provide(CloudFrontKvsTestFunctionLive)),
194 );
195
196 expect(functionUrl).toBeTruthy();
197 kvsBaseUrl = functionUrl!.replace(/\/+$/, "");
198
199 // Fresh function URLs take a few seconds to start serving, and the
200 // store's data plane can briefly 500 while the store finishes
201 // provisioning + the role propagates.
202 yield* HttpClient.get(`${kvsBaseUrl}/describe`).pipe(
203 Effect.flatMap((response) =>
204 response.status === 200
205 ? Effect.void
206 : response.text.pipe(
207 Effect.flatMap((body) =>
208 Effect.fail(new Error(`KVS not ready: ${response.status}: ${body}`)),
209 ),
210 ),
211 ),
212 Effect.retry({
213 while: (e): boolean => e instanceof Error,
214 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]),
215 }),
216 );
217 }),
218 { timeout: 300_000 },
219 );
220 afterAll(kvsStack.destroy(), { timeout: 300_000 });
221
222 describe("DescribeKeyValueStore", () => {
223 test.provider(
224 "reads the store's data-plane metadata at runtime",
225 (_stack) =>
226 Effect.gen(function* () {
227 const response = yield* HttpClient.get(`${kvsBaseUrl}/describe`);
228 expect(response.status).toBe(200);
229 const body = (yield* response.json) as { etag: string; itemCount: number };
230 expect(body.etag).toBeTruthy();
231 expect(body.itemCount).toBeGreaterThanOrEqual(0);
232 }),
233 { timeout: 60_000 },
234 );
235 });
236
237 describe("PutKey + GetKey + ListKeys", () => {
238 test.provider(
239 "puts, gets, and lists a key at runtime",
240 (_stack) =>
241 Effect.gen(function* () {
242 const put = yield* HttpClient.execute(
243 HttpClientRequest.post(`${kvsBaseUrl}/put`).pipe(
244 HttpClientRequest.bodyJsonUnsafe({ key: "routes:/about", value: "/about.html" }),
245 ),
246 );
247 expect(put.status).toBe(200);
248 const putBody = (yield* put.json) as { etag: string };
249 expect(putBody.etag).toBeTruthy();
250
251 const got = yield* HttpClient.get(
252 `${kvsBaseUrl}/key?key=${encodeURIComponent("routes:/about")}`,
253 );
254 expect(got.status).toBe(200);
255 const gotBody = (yield* got.json) as { key: string; value: string };
256 expect(gotBody.key).toBe("routes:/about");
257 expect(gotBody.value).toBe("/about.html");
258
259 const listed = yield* HttpClient.get(`${kvsBaseUrl}/keys`);
260 expect(listed.status).toBe(200);
261 const listedBody = (yield* listed.json) as { keys: { key: string; value: string }[] };
262 expect(listedBody.keys.map((k) => k.key)).toContain("routes:/about");
263
264 // Out-of-band: the key is visible through distilled directly.
265 // KVS data-plane calls only accept us-east-1 signatures (see
266 // `common.ts`), so pin the Region like the resource providers do.
267 const storeArn = yield* findFixtureStoreArn;
268 const observed = yield* kvs
269 .getKey({ KvsARN: storeArn, Key: "routes:/about" })
270 .pipe(Effect.provideService(AwsRegion, Effect.succeed("us-east-1")));
271 expect(
272 typeof observed.Value === "string" ? observed.Value : Redacted.value(observed.Value),
273 ).toBe("/about.html");
274 }),
275 { timeout: 60_000 },
276 );
277 });
278
279 describe("UpdateKeys + DeleteKey", () => {
280 test.provider(
281 "batch-updates and deletes keys at runtime",
282 (_stack) =>
283 Effect.gen(function* () {
284 const updated = yield* HttpClient.execute(
285 HttpClientRequest.post(`${kvsBaseUrl}/update`).pipe(
286 HttpClientRequest.bodyJsonUnsafe({
287 puts: [
288 { key: "routes:/", value: "/index.html" },
289 { key: "routes:/tmp", value: "/tmp.html" },
290 ],
291 }),
292 ),
293 );
294 expect(updated.status).toBe(200);
295
296 const deleted = yield* HttpClient.execute(
297 HttpClientRequest.post(`${kvsBaseUrl}/delete`).pipe(
298 HttpClientRequest.bodyJsonUnsafe({ key: "routes:/tmp" }),
299 ),
300 );
301 expect(deleted.status).toBe(200);
302
303 const listed = yield* HttpClient.get(`${kvsBaseUrl}/keys`);
304 expect(listed.status).toBe(200);
305 const listedBody = (yield* listed.json) as { keys: { key: string; value: string }[] };
306 const keys = listedBody.keys.map((k) => k.key);
307 expect(keys).toContain("routes:/");
308 expect(keys).not.toContain("routes:/tmp");
309 }),
310 { timeout: 60_000 },
311 );
312 });
313 },
314 );