@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 371 lines 13.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 Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import IoTBindingsFunctionLive, {
11 IoTBindingsFunction,
12 RETAINED_TOPIC,
13 } from "./iot-bindings-handler.ts";
14
15 const testOptions = { providers: AWS.providers() };
16 const { test, beforeAll, afterAll } = Test.make(testOptions);
17 const sharedStack = Core.scratchStack(testOptions, "IoTBindings");
18
19 // Bound environment propagation can lag the code update; keep the readiness
20 // wait bounded to about 50 seconds.
21 const readinessPolicy = Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(10)]);
22
23 let baseUrl: string;
24 let thingName: string;
25
26 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
27 readonly status: number;
28 readonly body: string;
29 }> {}
30
31 class NotYetConsistent extends Data.TaggedError("NotYetConsistent")<{ readonly what: string }> {}
32
33 // Retry transient 5xx (cold re-init, IAM propagation surfaced by the
34 // handler's Effect.orDie as a 500). Genuine 4xx returns immediately.
35 const send = (request: HttpClientRequest.HttpClientRequest) =>
36 HttpClient.execute(request).pipe(
37 Effect.flatMap((response) =>
38 response.status >= 500
39 ? response.text.pipe(
40 Effect.flatMap((body) =>
41 Effect.fail(new TransientUpstream({ status: response.status, body })),
42 ),
43 )
44 : Effect.succeed(response),
45 ),
46 Effect.retry({
47 while: (e) => e._tag === "TransientUpstream",
48 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
49 }),
50 );
51
52 const getJson = (path: string) =>
53 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
54
55 const postJson = (path: string, body: unknown) =>
56 send(HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}${path}`), body)).pipe(
57 Effect.flatMap((r) => r.json),
58 );
59
60 const del = (path: string) =>
61 send(HttpClientRequest.delete(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
62
63 describe(
64 "IoT Bindings",
65 { tags: ["provider:aws", "provider:aws:iot", "provider:aws:lambda", "live"] },
66 () => {
67 beforeAll(
68 Effect.gen(function* () {
69 yield* sharedStack.destroy();
70
71 const { functionUrl } = yield* sharedStack.deploy(
72 Effect.gen(function* () {
73 return yield* IoTBindingsFunction;
74 }).pipe(Effect.provide(IoTBindingsFunctionLive)),
75 );
76
77 expect(functionUrl).toBeTruthy();
78 baseUrl = functionUrl!.replace(/\/+$/, "");
79
80 // Readiness requires `thingName` to be present, not just a 200: the
81 // function is pre-created as a stub (no env) and the env-carrying
82 // UpdateFunctionConfiguration is async, so the very first execution
83 // environment can serve with stale env. Retry until a fresh
84 // environment picks up the bound env.
85 const ready = yield* HttpClient.get(`${baseUrl}/ready`).pipe(
86 Effect.flatMap((response) =>
87 response.status === 200
88 ? (response.json as Effect.Effect<{ thingName?: string }>)
89 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
90 ),
91 Effect.flatMap((body) =>
92 body.thingName
93 ? Effect.succeed(body as { thingName: string })
94 : Effect.fail(new Error("Function env not yet propagated")),
95 ),
96 Effect.retry({ schedule: readinessPolicy }),
97 );
98 thingName = ready.thingName;
99 expect(thingName).toBeTruthy();
100 }),
101 { timeout: 240_000 },
102 );
103
104 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 120_000 });
105
106 describe("UpdateThingShadow / GetThingShadow", () => {
107 test.provider(
108 "writes and reads the classic shadow",
109 (_stack) =>
110 Effect.gen(function* () {
111 const update = (yield* postJson("/shadow", { state: { desired: { led: "on" } } })) as {
112 ok: boolean;
113 };
114 expect(update.ok).toBe(true);
115
116 const shadow = (yield* getJson("/shadow")) as { found: boolean; payload?: string };
117 expect(shadow.found).toBe(true);
118 expect(JSON.parse(shadow.payload!).state.desired.led).toBe("on");
119 }),
120 { timeout: 120_000 },
121 );
122
123 test.provider(
124 "writes and reads a named shadow",
125 (_stack) =>
126 Effect.gen(function* () {
127 yield* postJson("/shadow?shadowName=telemetry", {
128 shadowName: "telemetry",
129 state: { reported: { t: 22.5 } },
130 });
131
132 const shadow = (yield* getJson("/shadow?shadowName=telemetry")) as {
133 found: boolean;
134 payload?: string;
135 };
136 expect(shadow.found).toBe(true);
137 expect(JSON.parse(shadow.payload!).state.reported.t).toBe(22.5);
138 }),
139 { timeout: 120_000 },
140 );
141 });
142
143 describe("ListNamedShadowsForThing", () => {
144 test.provider(
145 "lists the named shadow",
146 (_stack) =>
147 Effect.gen(function* () {
148 yield* postJson("/shadow", {
149 shadowName: "inventory",
150 state: { reported: { count: 1 } },
151 });
152
153 // Named-shadow listing is eventually consistent.
154 const result = yield* getJson("/shadow/list").pipe(
155 Effect.flatMap((r) => {
156 const { results } = r as { results: string[] };
157 return results.includes("inventory")
158 ? Effect.succeed(results)
159 : Effect.fail(new NotYetConsistent({ what: "shadow list" }));
160 }),
161 Effect.retry({
162 while: (e): boolean => e._tag === "NotYetConsistent",
163 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
164 }),
165 );
166 expect(result).toContain("inventory");
167 }),
168 { timeout: 120_000 },
169 );
170 });
171
172 describe("DeleteThingShadow", () => {
173 test.provider(
174 "deletes a named shadow",
175 (_stack) =>
176 Effect.gen(function* () {
177 yield* postJson("/shadow", {
178 shadowName: "doomed",
179 state: { reported: { alive: true } },
180 });
181
182 const deleted = (yield* del("/shadow?shadowName=doomed")) as { ok: boolean };
183 expect(deleted.ok).toBe(true);
184
185 const shadow = (yield* getJson("/shadow?shadowName=doomed")) as { found: boolean };
186 expect(shadow.found).toBe(false);
187 }),
188 { timeout: 120_000 },
189 );
190 });
191
192 describe("DescribeThing", () => {
193 test.provider(
194 "reads the thing's registry entry",
195 (_stack) =>
196 Effect.gen(function* () {
197 const result = (yield* getJson("/thing")) as {
198 thingName: string;
199 attributes: Record<string, string>;
200 };
201 expect(result.thingName).toBe(thingName);
202 expect(result.attributes.purpose).toBe("bindings-test");
203 }),
204 { timeout: 120_000 },
205 );
206 });
207
208 describe("ListThings", () => {
209 test.provider(
210 "lists the deployed thing",
211 (_stack) =>
212 Effect.gen(function* () {
213 // Registry listing is eventually consistent.
214 const names = yield* getJson("/things").pipe(
215 Effect.flatMap((r) => {
216 const { thingNames } = r as { thingNames: string[] };
217 return thingNames.includes(thingName)
218 ? Effect.succeed(thingNames)
219 : Effect.fail(new NotYetConsistent({ what: "thing list" }));
220 }),
221 Effect.retry({
222 while: (e): boolean => e._tag === "NotYetConsistent",
223 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
224 }),
225 );
226 expect(names).toContain(thingName);
227 }),
228 { timeout: 120_000 },
229 );
230 });
231
232 describe("DescribeEndpoint", () => {
233 test.provider(
234 "returns the account's ATS data endpoint",
235 (_stack) =>
236 Effect.gen(function* () {
237 const result = (yield* getJson("/endpoint")) as { endpointAddress?: string };
238 expect(result.endpointAddress).toBeTruthy();
239 expect(result.endpointAddress).toContain("iot");
240 expect(result.endpointAddress).toContain("amazonaws.com");
241 }),
242 { timeout: 120_000 },
243 );
244 });
245
246 describe("Publish / GetRetainedMessage / ListRetainedMessages", () => {
247 test.provider(
248 "publishes a retained message, reads it back, lists it, and clears it",
249 (_stack) =>
250 Effect.gen(function* () {
251 const marker = "retained-marker-1";
252 yield* postJson("/retained", {
253 topic: RETAINED_TOPIC,
254 payload: JSON.stringify({ marker }),
255 });
256
257 // Retained-message read is eventually consistent after publish.
258 const read = yield* getJson(
259 `/retained?topic=${encodeURIComponent(RETAINED_TOPIC)}`,
260 ).pipe(
261 Effect.flatMap((r) => {
262 const result = r as { found: boolean; payload?: string };
263 return result.found
264 ? Effect.succeed(result)
265 : Effect.fail(new NotYetConsistent({ what: "retained message" }));
266 }),
267 Effect.retry({
268 while: (e): boolean => e._tag === "NotYetConsistent",
269 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
270 }),
271 );
272 expect(JSON.parse(read.payload!).marker).toBe(marker);
273
274 const listed = (yield* getJson("/retained/list")) as { topics: string[] };
275 expect(listed.topics).toContain(RETAINED_TOPIC);
276
277 // Clear the retained message (empty retained payload) so the
278 // account carries no leftovers after the test.
279 yield* postJson("/retained", { topic: RETAINED_TOPIC });
280 const cleared = yield* getJson(
281 `/retained?topic=${encodeURIComponent(RETAINED_TOPIC)}`,
282 ).pipe(
283 Effect.flatMap((r) => {
284 const result = r as { found: boolean };
285 return result.found
286 ? Effect.fail(new NotYetConsistent({ what: "retained clear" }))
287 : Effect.succeed(result);
288 }),
289 Effect.retry({
290 while: (e): boolean => e._tag === "NotYetConsistent",
291 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
292 }),
293 );
294 expect(cleared.found).toBe(false);
295 }),
296 { timeout: 120_000 },
297 );
298 });
299
300 describe("GetConnection", () => {
301 test.provider(
302 "returns a typed ResourceNotFoundException for a never-connected client",
303 (_stack) =>
304 Effect.gen(function* () {
305 const result = (yield* getJson(
306 "/connection?clientId=alchemy-bindings-nonexistent",
307 )) as { ok: boolean; tag?: string; connected?: boolean };
308 if (result.ok) {
309 // Some accounts report never-connected clients as disconnected
310 // instead of missing.
311 expect(result.connected).toBe(false);
312 } else {
313 expect(result.tag).toBe("ResourceNotFoundException");
314 }
315 }),
316 { timeout: 120_000 },
317 );
318 });
319
320 describe("ListSubscriptions", () => {
321 test.provider(
322 "returns a typed ResourceNotFoundException for a never-connected client",
323 (_stack) =>
324 Effect.gen(function* () {
325 const result = (yield* getJson(
326 "/subscriptions?clientId=alchemy-bindings-nonexistent",
327 )) as { ok: boolean; tag?: string; subscriptions?: unknown[] };
328 if (result.ok) {
329 expect(result.subscriptions).toEqual([]);
330 } else {
331 expect(result.tag).toBe("ResourceNotFoundException");
332 }
333 }),
334 { timeout: 120_000 },
335 );
336 });
337
338 describe("DeleteConnection", () => {
339 test.provider(
340 "returns a typed ResourceNotFoundException for a never-connected client",
341 (_stack) =>
342 Effect.gen(function* () {
343 const result = (yield* del("/connection?clientId=alchemy-bindings-nonexistent")) as {
344 ok: boolean;
345 tag?: string;
346 };
347 expect(result.ok).toBe(false);
348 expect(result.tag).toBe("ResourceNotFoundException");
349 }),
350 { timeout: 120_000 },
351 );
352 });
353
354 describe("SendDirectMessage", () => {
355 test.provider(
356 "returns a typed ResourceNotFoundException for a never-connected client",
357 (_stack) =>
358 Effect.gen(function* () {
359 const result = (yield* postJson("/direct", {
360 clientId: "alchemy-bindings-nonexistent",
361 topic: "commands/noop",
362 payload: JSON.stringify({ noop: true }),
363 })) as { ok: boolean; tag?: string };
364 expect(result.ok).toBe(false);
365 expect(result.tag).toBe("ResourceNotFoundException");
366 }),
367 { timeout: 120_000 },
368 );
369 });
370 },
371 );