@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 315 lines 11.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 SQS from "@distilled.cloud/aws/sqs";
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 IoTWirelessTestFunctionLive, { IoTWirelessTestFunction } from "./fixtures/handler.ts";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "IoTWirelessBindings");
16
17 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]);
18
19 let baseUrl: string;
20 let resultQueueUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // POST a fixture route; retry 5xx (cold-start IAM propagation surfaces as
28 // a typed-error 500 from the fixture until the fresh role policy is
29 // visible to IoT Wireless).
30 const post = (path: string) =>
31 HttpClient.execute(HttpClientRequest.post(`${baseUrl}${path}`)).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("1 second"), Schedule.recurs(6)]),
44 }),
45 );
46
47 const postJson = (path: string) => post(path).pipe(Effect.flatMap((response) => response.json));
48
49 describe(
50 "IoTWireless Bindings",
51 {
52 tags: [
53 "provider:aws",
54 "provider:aws:iam",
55 "provider:aws:iotwireless",
56 "provider:aws:lambda",
57 "provider:aws:sqs",
58 "live",
59 ],
60 },
61 () => {
62 beforeAll(
63 Effect.gen(function* () {
64 yield* Effect.logInfo("IoTWireless test setup: destroying previous resources");
65 yield* sharedStack.destroy();
66
67 yield* Effect.logInfo("IoTWireless test setup: deploying fixture");
68 const { functionUrl } = yield* sharedStack.deploy(
69 Effect.gen(function* () {
70 return yield* IoTWirelessTestFunction;
71 }).pipe(Effect.provide(IoTWirelessTestFunctionLive)),
72 );
73
74 expect(functionUrl).toBeTruthy();
75 baseUrl = functionUrl!.replace(/\/+$/, "");
76 const readinessUrl = `${baseUrl}/ping`;
77
78 yield* Effect.logInfo(`IoTWireless test setup: probing readiness at ${readinessUrl}`);
79 // Ride out cold-start / URL propagation until /ping reports the
80 // result queue (early invocations can briefly resolve outputs late).
81 const ready = yield* HttpClient.get(readinessUrl).pipe(
82 Effect.flatMap((response) =>
83 response.status === 200
84 ? (response.json as Effect.Effect<{ ok: boolean; resultQueueUrl?: string }>)
85 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
86 ),
87 Effect.flatMap((body) =>
88 body.resultQueueUrl
89 ? Effect.succeed(body as { resultQueueUrl: string })
90 : Effect.fail(new Error("no result queue url yet")),
91 ),
92 Effect.tapError((error) =>
93 Effect.logWarning(`IoTWireless test setup: fixture not ready yet (${String(error)})`),
94 ),
95 Effect.retry({ schedule: readinessPolicy }),
96 );
97 resultQueueUrl = ready.resultQueueUrl;
98 }),
99 { timeout: 300_000 },
100 );
101
102 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 180_000 });
103
104 describe("GetServiceEndpoint", () => {
105 test.provider(
106 "reads the account's LNS endpoint",
107 (_stack) =>
108 Effect.gen(function* () {
109 const response = (yield* postJson("/service-endpoint")) as {
110 serviceType: string | null;
111 serviceEndpoint: string | null;
112 };
113 expect(response.serviceType).toBe("LNS");
114 expect(response.serviceEndpoint).toBeTruthy();
115 }),
116 { timeout: 120_000 },
117 );
118 });
119
120 describe("SendDataToWirelessDevice", () => {
121 test.provider(
122 "queues a downlink to the bound ABP device",
123 (_stack) =>
124 Effect.gen(function* () {
125 const response = (yield* postJson("/send")) as { messageId: string | null };
126 expect(response.messageId).toBeTruthy();
127 }),
128 { timeout: 120_000 },
129 );
130 });
131
132 describe("ListQueuedMessages", () => {
133 test.provider(
134 "sees the queued downlink",
135 (_stack) =>
136 Effect.gen(function* () {
137 const response = (yield* postJson("/queued").pipe(
138 Effect.repeat({
139 schedule: Schedule.spaced("2 seconds"),
140 until: (r): boolean => (r as { count: number }).count >= 1,
141 times: 15,
142 }),
143 )) as { count: number; messageIds: (string | null)[] };
144 expect(response.count).toBeGreaterThanOrEqual(1);
145 }),
146 { timeout: 120_000 },
147 );
148 });
149
150 describe("DeleteQueuedMessages", () => {
151 test.provider(
152 "purges the downlink queue",
153 (_stack) =>
154 Effect.gen(function* () {
155 const purge = (yield* postJson("/purge")) as { ok: boolean };
156 expect(purge.ok).toBe(true);
157
158 const drained = (yield* postJson("/queued").pipe(
159 Effect.repeat({
160 schedule: Schedule.spaced("2 seconds"),
161 until: (r): boolean => (r as { count: number }).count === 0,
162 times: 15,
163 }),
164 )) as { count: number };
165 expect(drained.count).toBe(0);
166 }),
167 { timeout: 120_000 },
168 );
169 });
170
171 describe("GetWirelessDeviceStatistics", () => {
172 test.provider(
173 "reads the bound device's operating information",
174 (_stack) =>
175 Effect.gen(function* () {
176 const response = (yield* postJson("/device-stats")) as {
177 wirelessDeviceId: string | null;
178 };
179 expect(response.wirelessDeviceId).toBeTruthy();
180 }),
181 { timeout: 120_000 },
182 );
183 });
184
185 describe("GetWirelessGatewayStatistics", () => {
186 test.provider(
187 "reads the bound gateway's connection status",
188 (_stack) =>
189 Effect.gen(function* () {
190 const response = (yield* postJson("/gateway-stats")) as {
191 wirelessGatewayId: string | null;
192 connectionStatus: string | null;
193 };
194 expect(response.wirelessGatewayId).toBeTruthy();
195 }),
196 { timeout: 120_000 },
197 );
198 });
199
200 describe("UpdateResourcePosition + GetResourcePosition", () => {
201 test.provider(
202 "writes a static position and reads it back",
203 (_stack) =>
204 Effect.gen(function* () {
205 const updated = (yield* postJson("/update-position")) as { ok: boolean };
206 expect(updated.ok).toBe(true);
207
208 const read = (yield* postJson("/position").pipe(
209 Effect.repeat({
210 schedule: Schedule.spaced("2 seconds"),
211 until: (r): boolean =>
212 typeof (r as { geoJson: string | null }).geoJson === "string" &&
213 ((r as { geoJson: string }).geoJson.includes("-122.33") ||
214 (r as { geoJson: string }).geoJson.includes("coordinates")),
215 times: 10,
216 }),
217 )) as { geoJson: string | null };
218 expect(read.geoJson).toBeTruthy();
219 const parsed = JSON.parse(read.geoJson!) as { coordinates?: number[] };
220 expect(parsed.coordinates?.[0]).toBeCloseTo(-122.33, 2);
221 expect(parsed.coordinates?.[1]).toBeCloseTo(47.61, 2);
222 }),
223 { timeout: 120_000 },
224 );
225 });
226
227 describe("GetPositionEstimate", () => {
228 test.provider(
229 "invokes the position solver with fabricated WiFi scans",
230 (_stack) =>
231 Effect.gen(function* () {
232 const response = (yield* postJson("/position-estimate")) as {
233 ok: boolean;
234 tag?: string;
235 geoJson?: string | null;
236 };
237 // Fabricated MACs may not resolve to a position — the solver
238 // then returns a typed not-found/validation error. Either way the
239 // IAM grant and the call path are proven (an access failure
240 // would surface as a retried-then-failing 500 instead).
241 if (response.ok) {
242 expect(response.geoJson).toBeTruthy();
243 } else {
244 expect(["ResourceNotFoundException", "ValidationException"]).toContain(response.tag);
245 }
246 }),
247 { timeout: 120_000 },
248 );
249 });
250
251 describe("TestWirelessDevice", () => {
252 test.provider(
253 "simulates an uplink from the bound device",
254 (_stack) =>
255 Effect.gen(function* () {
256 const response = (yield* postJson("/test-device")) as { result: string | null };
257 expect(response.result).toBeTruthy();
258 }),
259 { timeout: 120_000 },
260 );
261 });
262
263 describe("DestinationEventSource (consumeUplinks)", () => {
264 test.provider(
265 "routes a simulated uplink through the destination's rule into the handler",
266 (_stack) =>
267 Effect.gen(function* () {
268 const { wirelessDeviceId } = (yield* postJson("/device-stats")) as {
269 wirelessDeviceId: string;
270 };
271 expect(wirelessDeviceId).toBeTruthy();
272
273 // Fire a simulated "Hello" uplink; IoT Wireless routes it through
274 // the destination's rule, which invokes the fixture Lambda, whose
275 // consumeUplinks handler forwards the envelope into the result
276 // queue. Re-fire on each poll retry to ride out rule/permission
277 // propagation on a fresh deploy.
278 yield* postJson("/test-device");
279
280 const body = yield* Effect.gen(function* () {
281 const received = yield* SQS.receiveMessage({
282 QueueUrl: resultQueueUrl,
283 MaxNumberOfMessages: 10,
284 WaitTimeSeconds: 2,
285 });
286 const match = (received.Messages ?? []).find((message) =>
287 message.Body?.includes(wirelessDeviceId),
288 );
289 if (!match?.ReceiptHandle) {
290 yield* postJson("/test-device").pipe(Effect.ignore);
291 return yield* Effect.fail(new UplinkNotDelivered());
292 }
293 yield* SQS.deleteMessage({
294 QueueUrl: resultQueueUrl,
295 ReceiptHandle: match.ReceiptHandle,
296 });
297 return match.Body!;
298 }).pipe(
299 Effect.retry({
300 while: (error): boolean => error._tag === "UplinkNotDelivered",
301 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(40)]),
302 }),
303 );
304
305 const uplink = JSON.parse(body) as { WirelessDeviceId: string; PayloadData: string };
306 expect(uplink.WirelessDeviceId).toBe(wirelessDeviceId);
307 expect(uplink.PayloadData).toBeTruthy();
308 }),
309 { timeout: 240_000 },
310 );
311 });
312 },
313 );
314
315 class UplinkNotDelivered extends Data.TaggedError("UplinkNotDelivered") {}