The best way to control Claude Code, Codex and more from any computer or phone

main
ts 306 lines 11.3 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as IoTWireless from "@alchemy.run/aws/IoTWireless";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Cause from "effect/Cause";
5 import * as Context from "effect/Context";
6 import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import { HttpServerRequest } from "effect/http/HttpServerRequest";
9 import * as HttpServerResponse from "effect/http/HttpServerResponse";
10 import * as Layer from "effect/Layer";
11 import * as Redacted from "effect/Redacted";
12 import * as Result from "effect/Result";
13 import * as Stream from "effect/Stream";
14 import path from "pathe";
15
16 const main = path.resolve(import.meta.dirname, "handler.ts");
17
18 // Deterministic fabricated radio identities — an ABP device pre-provisions
19 // its session keys, so the downlink queue works without any radio hardware
20 // ever joining. Distinct from the identities used by IoTWireless.test.ts.
21 const DEV_EUI = "1a2b3c4d5e6f7091";
22 const DEV_ADDR = "01020304";
23 const NWK_S_KEY = Redacted.make("000102030405060708090a0b0c0d0e0f");
24 const APP_S_KEY = Redacted.make("0f0e0d0c0b0a09080706050403020100");
25 const GATEWAY_EUI = "aa555a0000000201";
26
27 // base64("Hello, World!")
28 const PAYLOAD = "SGVsbG8sIFdvcmxkIQ==";
29
30 export class IoTWirelessTestFunction extends Lambda.Function<Lambda.Function>()(
31 "IoTWirelessTestFunction",
32 ) {}
33
34 // Result queue observed by the test: the DestinationEventSource handler
35 // forwards every uplink routed through the destination into this queue so
36 // delivery can be verified out-of-band.
37 export class ResultQueue extends Context.Service<ResultQueue, { result: AWS.SQS.Queue }>()(
38 "IoTWirelessResultQueue",
39 ) {}
40
41 export const ResultQueueLive = Layer.effect(
42 ResultQueue,
43 Effect.gen(function* () {
44 const result = yield* AWS.SQS.Queue("IoTWirelessUplinkResultQueue");
45 return { result };
46 }),
47 );
48
49 export default IoTWirelessTestFunction.make(
50 {
51 main,
52 functionUrl: true,
53 timeout: Duration.seconds(30),
54 },
55 Effect.gen(function* () {
56 // The IAM role IoT Wireless assumes to deliver uplinks to the rule.
57 const role = yield* AWS.IAM.Role("IotWirelessBindingsDelivery", {
58 assumeRolePolicyDocument: {
59 Version: "2012-10-17",
60 Statement: [
61 {
62 Effect: "Allow",
63 Principal: { Service: "iotwireless.amazonaws.com" },
64 Action: ["sts:AssumeRole"],
65 },
66 ],
67 },
68 inlinePolicies: {
69 deliver: {
70 Version: "2012-10-17",
71 Statement: [
72 {
73 Effect: "Allow",
74 Action: ["iot:DescribeEndpoint", "iot:Publish"],
75 Resource: ["*"],
76 },
77 ],
78 },
79 },
80 });
81
82 const destination = yield* IoTWireless.Destination("BindingsUplinks", {
83 expressionType: "RuleName",
84 expression: "alchemy_iot_wireless_bindings_rule",
85 roleArn: role.roleArn,
86 tags: { fixture: "iot-wireless-bindings" },
87 });
88 const serviceProfile = yield* IoTWireless.ServiceProfile("BindingsFleet", {
89 loRaWAN: { AddGwMetadata: true },
90 tags: { fixture: "iot-wireless-bindings" },
91 });
92 const deviceProfile = yield* IoTWireless.DeviceProfile("BindingsModel", {
93 loRaWAN: {
94 MacVersion: "1.0.3",
95 RegParamsRevision: "RP002-1.0.1",
96 RfRegion: "US915",
97 MaxEirp: 10,
98 SupportsJoin: false,
99 },
100 tags: { fixture: "iot-wireless-bindings" },
101 });
102 const device = yield* IoTWireless.WirelessDevice("BindingsSensor", {
103 type: "LoRaWAN",
104 destinationName: destination.destinationName,
105 description: "alchemy iot-wireless bindings fixture device",
106 positioning: "Enabled",
107 loRaWAN: {
108 DevEui: DEV_EUI,
109 DeviceProfileId: deviceProfile.deviceProfileId,
110 ServiceProfileId: serviceProfile.serviceProfileId,
111 AbpV1_0_x: {
112 DevAddr: DEV_ADDR,
113 SessionKeys: { NwkSKey: NWK_S_KEY, AppSKey: APP_S_KEY },
114 },
115 },
116 tags: { fixture: "iot-wireless-bindings" },
117 });
118 const gateway = yield* IoTWireless.WirelessGateway("BindingsGateway", {
119 description: "alchemy iot-wireless bindings fixture gateway",
120 loRaWAN: { GatewayEui: GATEWAY_EUI, RfRegion: "US915" },
121 tags: { fixture: "iot-wireless-bindings" },
122 });
123
124 // device-scoped
125 const sendData = yield* IoTWireless.SendDataToWirelessDevice(device);
126 const listQueued = yield* IoTWireless.ListQueuedMessages(device);
127 const deleteQueued = yield* IoTWireless.DeleteQueuedMessages(device);
128 const getDeviceStats = yield* IoTWireless.GetWirelessDeviceStatistics(device);
129 const testDevice = yield* IoTWireless.TestWirelessDevice(device);
130 const getPosition = yield* IoTWireless.GetResourcePosition(device);
131 const updatePosition = yield* IoTWireless.UpdateResourcePosition(device);
132 // gateway-scoped
133 const getGatewayStats = yield* IoTWireless.GetWirelessGatewayStatistics(gateway);
134 // account-level
135 const getEndpoint = yield* IoTWireless.GetServiceEndpoint();
136 const estimatePosition = yield* IoTWireless.GetPositionEstimate();
137
138 // Event source: every uplink routed through the destination (including
139 // TestWirelessDevice's simulated "Hello" uplink) invokes this function;
140 // forward each envelope into the result queue for the test to observe.
141 const { result } = yield* ResultQueue;
142 const sink = yield* AWS.SQS.QueueSink(result);
143 yield* IoTWireless.consumeUplinks(destination, (uplinks) =>
144 uplinks.pipe(
145 Stream.map((uplink) => ({ MessageBody: JSON.stringify(uplink) })),
146 Stream.run(sink),
147 Effect.orDie,
148 ),
149 );
150 const resultQueueUrl = yield* result.queueUrl;
151
152 const decodeGeoJson = (payload: Stream.Stream<Uint8Array, Error> | undefined) =>
153 payload === undefined
154 ? Effect.succeed(undefined)
155 : Stream.mkString(Stream.decodeText(payload));
156
157 return {
158 fetch: Effect.gen(function* () {
159 const request = yield* HttpServerRequest;
160 const pathname = new URL(request.originalUrl).pathname;
161
162 // Cheap readiness route — no AWS call.
163 if (request.method === "GET" && pathname === "/ping") {
164 return yield* HttpServerResponse.json({
165 ok: true,
166 resultQueueUrl: yield* resultQueueUrl,
167 });
168 }
169
170 if (request.method === "POST" && pathname === "/send") {
171 const result = yield* sendData({
172 PayloadData: PAYLOAD,
173 TransmitMode: 1,
174 WirelessMetadata: { LoRaWAN: { FPort: 1 } },
175 });
176 return yield* HttpServerResponse.json({
177 messageId: result.MessageId ?? null,
178 });
179 }
180
181 if (request.method === "POST" && pathname === "/queued") {
182 const result = yield* listQueued();
183 const messages = result.DownlinkQueueMessagesList ?? [];
184 return yield* HttpServerResponse.json({
185 count: messages.length,
186 messageIds: messages.map((m) => m.MessageId ?? null),
187 });
188 }
189
190 if (request.method === "POST" && pathname === "/purge") {
191 // "*" purges every queued downlink message.
192 yield* deleteQueued({ MessageId: "*" });
193 return yield* HttpServerResponse.json({ ok: true });
194 }
195
196 if (request.method === "POST" && pathname === "/device-stats") {
197 const stats = yield* getDeviceStats();
198 return yield* HttpServerResponse.json({
199 wirelessDeviceId: stats.WirelessDeviceId ?? null,
200 lastUplinkReceivedAt: stats.LastUplinkReceivedAt ?? null,
201 });
202 }
203
204 if (request.method === "POST" && pathname === "/test-device") {
205 const result = yield* testDevice();
206 return yield* HttpServerResponse.json({
207 result: result.Result ?? null,
208 });
209 }
210
211 if (request.method === "POST" && pathname === "/gateway-stats") {
212 const stats = yield* getGatewayStats();
213 return yield* HttpServerResponse.json({
214 wirelessGatewayId: stats.WirelessGatewayId ?? null,
215 connectionStatus: stats.ConnectionStatus ?? null,
216 });
217 }
218
219 if (request.method === "POST" && pathname === "/service-endpoint") {
220 const endpoint = yield* getEndpoint({ ServiceType: "LNS" });
221 return yield* HttpServerResponse.json({
222 serviceType: endpoint.ServiceType ?? null,
223 serviceEndpoint: endpoint.ServiceEndpoint ?? null,
224 });
225 }
226
227 if (request.method === "POST" && pathname === "/update-position") {
228 // Coordinates are [longitude, latitude, altitude].
229 yield* updatePosition({
230 GeoJsonPayload: JSON.stringify({
231 type: "Point",
232 coordinates: [-122.33, 47.61, 10],
233 }),
234 });
235 return yield* HttpServerResponse.json({ ok: true });
236 }
237
238 if (request.method === "POST" && pathname === "/position") {
239 const result = yield* getPosition();
240 const geoJson = yield* decodeGeoJson(result.GeoJsonPayload);
241 return yield* HttpServerResponse.json({ geoJson: geoJson ?? null });
242 }
243
244 if (request.method === "POST" && pathname === "/position-estimate") {
245 // Fabricated WiFi scans exercise the solver path end-to-end; the
246 // solver may not resolve unknown MACs, so surface the typed tag
247 // instead of failing the route.
248 const result = yield* Effect.result(
249 estimatePosition({
250 WiFiAccessPoints: [
251 { MacAddress: "A0:EC:F9:1E:32:C1", Rss: -66 },
252 { MacAddress: "A0:EC:F9:15:72:5E", Rss: -72 },
253 ],
254 }),
255 );
256 if (Result.isSuccess(result)) {
257 const geoJson = yield* decodeGeoJson(result.success.GeoJsonPayload);
258 return yield* HttpServerResponse.json({
259 ok: true,
260 geoJson: geoJson ?? null,
261 });
262 }
263 return yield* HttpServerResponse.json({
264 ok: false,
265 tag: result.failure._tag,
266 });
267 }
268
269 return yield* HttpServerResponse.json(
270 { error: "Not found", method: request.method, pathname },
271 { status: 404 },
272 );
273 }).pipe(
274 // Surface typed API errors AND defects as diagnosable 500s (the
275 // test's post helper retries 5xx through IAM propagation).
276 Effect.catchCause((cause) =>
277 Effect.succeed(
278 HttpServerResponse.text(`IoTWireless fixture error: ${String(Cause.squash(cause))}`, {
279 status: 500,
280 }),
281 ),
282 ),
283 ),
284 };
285 }).pipe(
286 Effect.provide(
287 Layer.provideMerge(
288 Layer.mergeAll(
289 IoTWireless.SendDataToWirelessDeviceHttp,
290 IoTWireless.ListQueuedMessagesHttp,
291 IoTWireless.DeleteQueuedMessagesHttp,
292 IoTWireless.GetWirelessDeviceStatisticsHttp,
293 IoTWireless.TestWirelessDeviceHttp,
294 IoTWireless.GetResourcePositionHttp,
295 IoTWireless.UpdateResourcePositionHttp,
296 IoTWireless.GetWirelessGatewayStatisticsHttp,
297 IoTWireless.GetServiceEndpointHttp,
298 IoTWireless.GetPositionEstimateHttp,
299 Lambda.WirelessDestinationEventSource,
300 AWS.SQS.QueueSinkHttp,
301 ),
302 Layer.mergeAll(AWS.SQS.SendMessageBatchHttp, ResultQueueLive),
303 ),
304 ),
305 ),
306 );