@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 436 lines 16.4 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 sd from "@distilled.cloud/aws/servicediscovery";
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 Schedule from "effect/Schedule";
11 import CloudMapTestFunctionLive, { CloudMapTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "CloudMapBindings");
16
17 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
18
19 let baseUrl: string;
20 let serviceId: string;
21 let customServiceId: string;
22
23 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
24 readonly status: number;
25 readonly body: string;
26 }> {}
27
28 // Retry transient 5xx from the shared fixture under parallel-suite load;
29 // genuine 4xx failures surface immediately.
30 const send = (request: HttpClientRequest.HttpClientRequest) =>
31 HttpClient.execute(request).pipe(
32 Effect.flatMap((response) =>
33 response.status >= 500
34 ? response.text.pipe(
35 Effect.flatMap((body) =>
36 Effect.fail(new TransientUpstream({ status: response.status, body })),
37 ),
38 )
39 : Effect.succeed(response),
40 ),
41 Effect.retry({
42 while: (e) => e._tag === "TransientUpstream",
43 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
44 }),
45 );
46
47 class CloudMapOperationPending extends Data.TaggedError("CloudMapOperationPending")<{
48 readonly operationId: string;
49 }> {}
50
51 /** Await a Cloud Map async operation out-of-band (bounded). */
52 const waitOperation = (operationId: string) =>
53 sd.getOperation({ OperationId: operationId }).pipe(
54 Effect.map((r) => r.Operation),
55 Effect.repeat({
56 schedule: Schedule.spaced("2 seconds"),
57 until: (op) => op?.Status === "SUCCESS" || op?.Status === "FAIL",
58 times: 45,
59 }),
60 Effect.flatMap((op) =>
61 op?.Status === "SUCCESS"
62 ? Effect.void
63 : Effect.fail(new CloudMapOperationPending({ operationId })),
64 ),
65 );
66
67 const registerOutOfBand = (instanceId: string, ipv4: string) =>
68 sd
69 .registerInstance({
70 ServiceId: serviceId,
71 InstanceId: instanceId,
72 Attributes: { AWS_INSTANCE_IPV4: ipv4 },
73 })
74 .pipe(
75 Effect.flatMap((r) =>
76 r.OperationId !== undefined ? waitOperation(r.OperationId) : Effect.void,
77 ),
78 );
79
80 const deregisterOutOfBand = (instanceId: string, inServiceId?: string) =>
81 sd.deregisterInstance({ ServiceId: inServiceId ?? serviceId, InstanceId: instanceId }).pipe(
82 Effect.flatMap((r) =>
83 r.OperationId !== undefined ? waitOperation(r.OperationId) : Effect.void,
84 ),
85 Effect.catchTag("InstanceNotFound", () => Effect.void),
86 );
87
88 interface DiscoveredInstance {
89 instanceId: string;
90 healthStatus: string | undefined;
91 attributes: Record<string, string>;
92 }
93
94 /** Call the deployed Lambda's /discover route (through the binding). */
95 const discoverViaLambda = Effect.gen(function* () {
96 const response = yield* send(HttpClientRequest.get(`${baseUrl}/discover?health=ALL`));
97 const body = (yield* response.json) as unknown as { instances: DiscoveredInstance[] };
98 return body.instances;
99 });
100
101 class UnexpectedInstances extends Data.TaggedError("UnexpectedInstances")<{
102 readonly expected: string[];
103 readonly actual: string[];
104 }> {}
105
106 /**
107 * Poll the Lambda's /discover route until — restricted to the given id
108 * prefix — exactly `expected` instance ids are visible (bounded; the
109 * data-plane view is eventually consistent after register/deregister).
110 */
111 const expectDiscovered = (prefix: string, expected: string[]) =>
112 discoverViaLambda.pipe(
113 Effect.flatMap((instances) => {
114 const actual = instances
115 .map((i) => i.instanceId)
116 .filter((id): id is string => id !== undefined)
117 .filter((id) => id.startsWith(prefix))
118 .sort();
119 const want = [...expected].sort();
120 return actual.length === want.length && actual.every((id, i) => id === want[i])
121 ? Effect.succeed(instances)
122 : Effect.fail(new UnexpectedInstances({ expected: want, actual }));
123 }),
124 Effect.retry({
125 while: (e) => e._tag === "UnexpectedInstances",
126 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(20)]),
127 }),
128 );
129
130 class InstanceNotVisible extends Data.TaggedError("InstanceNotVisible")<{
131 readonly instanceId: string;
132 }> {}
133
134 const expectInstanceState = (instanceId: string, present: boolean) =>
135 sd.getInstance({ ServiceId: serviceId, InstanceId: instanceId }).pipe(
136 Effect.map(() => true),
137 Effect.catchTag("InstanceNotFound", () => Effect.succeed(false)),
138 Effect.flatMap((exists) =>
139 exists === present ? Effect.void : Effect.fail(new InstanceNotVisible({ instanceId })),
140 ),
141 Effect.retry({
142 while: (e) => e._tag === "InstanceNotVisible",
143 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(20)]),
144 }),
145 );
146
147 describe(
148 "CloudMap Bindings",
149 {
150 tags: [
151 "provider:aws",
152 "provider:aws:cloudmap",
153 "provider:aws:ec2",
154 "provider:aws:lambda",
155 "live",
156 ],
157 },
158 () => {
159 beforeAll(
160 Effect.gen(function* () {
161 yield* Effect.logInfo("CloudMap test setup: destroying previous resources");
162 yield* sharedStack.destroy();
163
164 yield* Effect.logInfo("CloudMap test setup: deploying fixture");
165 const { functionUrl } = yield* sharedStack.deploy(
166 Effect.gen(function* () {
167 return yield* CloudMapTestFunction;
168 }).pipe(Effect.provide(CloudMapTestFunctionLive)),
169 );
170
171 expect(functionUrl).toBeTruthy();
172 baseUrl = functionUrl!.replace(/\/+$/, "");
173
174 yield* Effect.logInfo(`CloudMap test setup: probing readiness at ${baseUrl}/info`);
175 // readiness = 200 AND the Output-backed env vars are visible. Lambda
176 // applies the code update and the env-var configuration update
177 // separately, so there is a brief window where the real handler serves
178 // 200 while `FixtureService_*` env vars are still missing.
179 const info = yield* HttpClient.get(`${baseUrl}/info`).pipe(
180 Effect.flatMap((response) =>
181 response.status === 200
182 ? response.json
183 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
184 ),
185 Effect.flatMap((body) =>
186 (body as { serviceId?: string }).serviceId
187 ? Effect.succeed(body)
188 : Effect.fail(new Error("env vars not yet propagated")),
189 ),
190 Effect.retry({ schedule: readinessPolicy }),
191 );
192 yield* Effect.logInfo(`CloudMap test setup: fixture info = ${JSON.stringify(info)}`);
193 serviceId = (info as { serviceId: string }).serviceId;
194 customServiceId = (info as { customServiceId: string }).customServiceId;
195 expect(serviceId).toBeTruthy();
196 expect(customServiceId).toBeTruthy();
197 }),
198 { timeout: 300_000 },
199 );
200
201 afterAll.skipIf(!!process.env.NO_DESTROY)(
202 // The out-of-band listInstances/deregisterInstance calls need the AWS
203 // providers (Credentials/HttpClient/Region); afterAll effects run with
204 // R=never, so provide them explicitly (Stack/Stage come from destroy()).
205 Core.withProviders(
206 Effect.gen(function* () {
207 // deregister any instances the tests left behind so the services (and
208 // then the namespace) can delete without ResourceInUse churn
209 for (const cleanupServiceId of [serviceId, customServiceId]) {
210 if (cleanupServiceId !== undefined) {
211 const instances = yield* sd.listInstances({ ServiceId: cleanupServiceId }).pipe(
212 Effect.map((r) => r.Instances ?? []),
213 Effect.catchTag("ServiceNotFound", () => Effect.succeed([])),
214 );
215 yield* Effect.forEach(
216 instances,
217 (instance) =>
218 instance.Id !== undefined
219 ? deregisterOutOfBand(instance.Id, cleanupServiceId)
220 : Effect.void,
221 { concurrency: 4 },
222 );
223 }
224 }
225 yield* sharedStack.destroy();
226 }),
227 testOptions,
228 "CloudMapBindings",
229 ),
230 { timeout: 240_000 },
231 );
232
233 describe("DiscoverInstances", () => {
234 test.provider(
235 "lambda discovers instances registered out-of-band; deregistration converges",
236 (_stack) =>
237 Effect.gen(function* () {
238 // register two instances out-of-band via distilled
239 yield* registerOutOfBand("disc-a", "10.0.0.1");
240 yield* registerOutOfBand("disc-b", "10.0.0.2");
241
242 // the deployed Lambda sees both through the DiscoverInstances binding
243 const instances = yield* expectDiscovered("disc-", ["disc-a", "disc-b"]);
244 const discA = instances.find((i) => i.instanceId === "disc-a");
245 expect(discA?.attributes.AWS_INSTANCE_IPV4).toBe("10.0.0.1");
246
247 // deregister one; a bounded re-poll sees exactly the survivor
248 yield* deregisterOutOfBand("disc-a");
249 yield* expectDiscovered("disc-", ["disc-b"]);
250
251 // cleanup
252 yield* deregisterOutOfBand("disc-b");
253 yield* expectInstanceState("disc-b", false);
254 }),
255 { timeout: 180_000 },
256 );
257 });
258
259 describe("RegisterInstance", () => {
260 test.provider(
261 "lambda self-registers an instance through the binding",
262 (_stack) =>
263 Effect.gen(function* () {
264 const response = yield* send(
265 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/register`), {
266 instanceId: "bind-reg",
267 attributes: { AWS_INSTANCE_IPV4: "10.0.0.9" },
268 }),
269 );
270 expect(response.status).toBe(200);
271 const body = (yield* response.json) as { operationId?: string };
272 expect(body.operationId).toBeTruthy();
273
274 // visible out-of-band once the async registration completes
275 yield* expectInstanceState("bind-reg", true);
276 const instance = yield* sd.getInstance({
277 ServiceId: serviceId,
278 InstanceId: "bind-reg",
279 });
280 expect(instance.Instance?.Attributes?.AWS_INSTANCE_IPV4).toBe("10.0.0.9");
281
282 // cleanup
283 yield* deregisterOutOfBand("bind-reg");
284 }),
285 { timeout: 180_000 },
286 );
287 });
288
289 describe("DeregisterInstance", () => {
290 test.provider(
291 "lambda deregisters an instance through the binding",
292 (_stack) =>
293 Effect.gen(function* () {
294 yield* registerOutOfBand("bind-dereg", "10.0.0.8");
295 yield* expectInstanceState("bind-dereg", true);
296
297 const response = yield* send(
298 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/deregister`), {
299 instanceId: "bind-dereg",
300 }),
301 );
302 expect(response.status).toBe(200);
303
304 yield* expectInstanceState("bind-dereg", false);
305 }),
306 { timeout: 180_000 },
307 );
308 });
309
310 describe("GetInstance + ListInstances", () => {
311 test.provider(
312 "lambda reads a registered instance through the control-plane bindings",
313 (_stack) =>
314 Effect.gen(function* () {
315 yield* registerOutOfBand("read-a", "10.0.0.31");
316
317 // GetInstance — full attribute map by id
318 const single = yield* send(HttpClientRequest.get(`${baseUrl}/instance?id=read-a`));
319 expect(single.status).toBe(200);
320 const singleBody = (yield* single.json) as {
321 instanceId: string;
322 attributes: Record<string, string>;
323 };
324 expect(singleBody.instanceId).toBe("read-a");
325 expect(singleBody.attributes.AWS_INSTANCE_IPV4).toBe("10.0.0.31");
326
327 // ListInstances — control-plane enumeration includes it
328 const listed = yield* send(HttpClientRequest.get(`${baseUrl}/instances`));
329 expect(listed.status).toBe(200);
330 const listedBody = (yield* listed.json) as { instances: { instanceId: string }[] };
331 expect(listedBody.instances.map((i) => i.instanceId)).toContain("read-a");
332
333 // cleanup
334 yield* deregisterOutOfBand("read-a");
335 }),
336 { timeout: 180_000 },
337 );
338 });
339
340 describe("DiscoverInstancesRevision", () => {
341 test.provider(
342 "lambda reads the instance-set revision through the binding",
343 (_stack) =>
344 Effect.gen(function* () {
345 const response = yield* send(HttpClientRequest.get(`${baseUrl}/revision`));
346 expect(response.status).toBe(200);
347 const body = (yield* response.json) as { revision: number };
348 expect(typeof body.revision).toBe("number");
349 }),
350 { timeout: 120_000 },
351 );
352 });
353
354 describe("GetServiceAttributes", () => {
355 test.provider(
356 "lambda reads the service attributes declared on the Service resource",
357 (_stack) =>
358 Effect.gen(function* () {
359 const response = yield* send(HttpClientRequest.get(`${baseUrl}/service-attributes`));
360 expect(response.status).toBe(200);
361 const body = (yield* response.json) as { attributes: Record<string, string> };
362 expect(body.attributes).toEqual({ tier: "backend", version: "1" });
363 }),
364 { timeout: 120_000 },
365 );
366 });
367
368 describe("UpdateInstanceCustomHealthStatus + GetInstancesHealthStatus + GetOperation", () => {
369 test.provider(
370 "lambda registers, awaits the operation, pushes custom health, and reads it back",
371 (_stack) =>
372 Effect.gen(function* () {
373 // register an instance on the custom-health service via the binding
374 const registered = yield* send(
375 HttpClientRequest.bodyJsonUnsafe(
376 HttpClientRequest.post(`${baseUrl}/custom/register`),
377 { instanceId: "cust-1", attributes: { AWS_INSTANCE_IPV4: "10.0.0.41" } },
378 ),
379 );
380 expect(registered.status).toBe(200);
381 const { operationId } = (yield* registered.json) as { operationId: string };
382 expect(operationId).toBeTruthy();
383
384 // await the async registration THROUGH the GetOperation binding
385 const operation = yield* send(
386 HttpClientRequest.get(`${baseUrl}/operation?id=${operationId}`),
387 ).pipe(
388 Effect.flatMap((r) => r.json),
389 Effect.map((body) => body as { status?: string }),
390 Effect.repeat({
391 schedule: Schedule.spaced("2 seconds"),
392 until: (op): boolean => op.status === "SUCCESS" || op.status === "FAIL",
393 times: 45,
394 }),
395 );
396 expect(operation.status).toBe("SUCCESS");
397
398 const pushHealth = (status: "HEALTHY" | "UNHEALTHY") =>
399 send(
400 HttpClientRequest.bodyJsonUnsafe(
401 HttpClientRequest.post(`${baseUrl}/custom/health`),
402 { instanceId: "cust-1", status },
403 ),
404 );
405
406 const readHealth = send(HttpClientRequest.get(`${baseUrl}/custom/health-status`)).pipe(
407 Effect.flatMap((r) => r.json),
408 Effect.map(
409 (body) => (body as { status: Record<string, string | undefined> }).status["cust-1"],
410 ),
411 );
412
413 const expectHealth = (expected: "HEALTHY" | "UNHEALTHY") =>
414 readHealth.pipe(
415 Effect.repeat({
416 schedule: Schedule.spaced("3 seconds"),
417 until: (status): boolean => status === expected,
418 times: 20,
419 }),
420 Effect.map((status) => expect(status).toBe(expected)),
421 );
422
423 // push UNHEALTHY then HEALTHY and observe both through the bindings
424 yield* pushHealth("UNHEALTHY");
425 yield* expectHealth("UNHEALTHY");
426 yield* pushHealth("HEALTHY");
427 yield* expectHealth("HEALTHY");
428
429 // cleanup
430 yield* deregisterOutOfBand("cust-1", customServiceId);
431 }),
432 { timeout: 300_000 },
433 );
434 });
435 },
436 );