@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 292 lines 11 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Layer from "effect/Layer";
6 import * as Stream from "effect/Stream";
7 import path from "pathe";
8
9 const main = path.resolve(import.meta.dirname, "iot-bindings-handler.ts");
10
11 // The MQTT topic namespace this fixture publishes retained messages into.
12 export const TOPIC_FILTER = "alchemy/iot/bindings/*";
13 export const RETAINED_TOPIC = "alchemy/iot/bindings/retained";
14
15 // Exercises every IoT runtime binding from inside a deployed Lambda:
16 // device shadows + DescribeThing on a Thing resource, retained messages via
17 // Publish/GetRetainedMessage/ListRetainedMessages, DescribeEndpoint and
18 // ListThings at account level, and the MQTT connection-management data
19 // plane (GetConnection/ListSubscriptions/DeleteConnection/SendDirectMessage)
20 // against a client id filter.
21 export class IoTBindingsFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
22 "IoTBindingsFunction",
23 ) {}
24
25 export default IoTBindingsFunction.make(
26 {
27 main,
28 functionUrl: true,
29 },
30 Effect.gen(function* () {
31 const thing = yield* AWS.IoT.Thing("BindingsThing", {
32 attributes: { purpose: "bindings-test" },
33 });
34
35 // thing-scoped
36 const getShadow = yield* AWS.IoT.GetThingShadow(thing);
37 const updateShadow = yield* AWS.IoT.UpdateThingShadow(thing);
38 const deleteShadow = yield* AWS.IoT.DeleteThingShadow(thing);
39 const listShadows = yield* AWS.IoT.ListNamedShadowsForThing(thing);
40 const describeThing = yield* AWS.IoT.DescribeThing(thing);
41 // topic-scoped
42 const publish = yield* AWS.IoT.Publish(TOPIC_FILTER);
43 const getRetained = yield* AWS.IoT.GetRetainedMessage(TOPIC_FILTER);
44 // account-level
45 const listRetained = yield* AWS.IoT.ListRetainedMessages();
46 const describeEndpoint = yield* AWS.IoT.DescribeEndpoint();
47 const listThings = yield* AWS.IoT.ListThings();
48 // client-scoped
49 const getConnection = yield* AWS.IoT.GetConnection("alchemy-bindings-*");
50 const listSubscriptions = yield* AWS.IoT.ListSubscriptions("alchemy-bindings-*");
51 const deleteConnection = yield* AWS.IoT.DeleteConnection("alchemy-bindings-*");
52 const sendDirectMessage = yield* AWS.IoT.SendDirectMessage("alchemy-bindings-*");
53
54 const thingName = yield* thing.thingName;
55
56 const decodeShadowPayload = (payload: Stream.Stream<Uint8Array, Error> | undefined) =>
57 payload === undefined
58 ? Effect.succeed(undefined)
59 : Stream.mkString(Stream.decodeText(payload));
60
61 return {
62 fetch: Effect.gen(function* () {
63 const request = yield* HttpServerRequest;
64 const url = new URL(request.originalUrl);
65 const pathname = url.pathname;
66 const shadowName = url.searchParams.get("shadowName") ?? undefined;
67
68 if (request.method === "GET" && pathname === "/ready") {
69 // `updateFunctionConfiguration` (which delivers the accessor env
70 // vars) is eventually consistent: a sandbox that boots between the
71 // code update and the config update runs the REAL code with the
72 // STALE (pre-binding) env, and stays warm serving it. Report 503
73 // until the env is visible so the test's readiness retry keeps
74 // polling until Lambda retires the stale environment.
75 const resolvedThingName = yield* thingName;
76 if (!resolvedThingName) {
77 return yield* HttpServerResponse.json(
78 { ok: false, error: "binding env not yet propagated" },
79 { status: 503 },
80 );
81 }
82 return yield* HttpServerResponse.json({
83 ok: true,
84 thingName: resolvedThingName,
85 });
86 }
87
88 if (request.method === "POST" && pathname === "/shadow") {
89 const body = (yield* request.json) as {
90 shadowName?: string;
91 state: unknown;
92 };
93 const result = yield* updateShadow({
94 shadowName: body.shadowName,
95 payload: JSON.stringify({ state: body.state }),
96 });
97 const payload = yield* decodeShadowPayload(result.payload);
98 return yield* HttpServerResponse.json({ ok: true, payload });
99 }
100
101 if (request.method === "GET" && pathname === "/shadow") {
102 const result = yield* getShadow({ shadowName }).pipe(
103 Effect.map((r) => ({ found: true as const, payload: r.payload })),
104 Effect.catchTag("ResourceNotFoundException", () =>
105 Effect.succeed({ found: false as const, payload: undefined }),
106 ),
107 );
108 const payload = yield* decodeShadowPayload(result.payload);
109 return yield* HttpServerResponse.json({
110 found: result.found,
111 payload,
112 });
113 }
114
115 if (request.method === "GET" && pathname === "/shadow/list") {
116 const result = yield* listShadows();
117 return yield* HttpServerResponse.json({
118 results: result.results ?? [],
119 });
120 }
121
122 if (request.method === "DELETE" && pathname === "/shadow") {
123 yield* deleteShadow({ shadowName }).pipe(
124 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
125 );
126 return yield* HttpServerResponse.json({ ok: true });
127 }
128
129 if (request.method === "GET" && pathname === "/thing") {
130 const result = yield* describeThing();
131 return yield* HttpServerResponse.json({
132 thingName: result.thingName,
133 attributes: result.attributes ?? {},
134 });
135 }
136
137 if (request.method === "GET" && pathname === "/things") {
138 const result = yield* listThings();
139 return yield* HttpServerResponse.json({
140 thingNames: (result.things ?? []).map((t) => t.thingName),
141 });
142 }
143
144 if (request.method === "GET" && pathname === "/endpoint") {
145 const result = yield* describeEndpoint({
146 endpointType: "iot:Data-ATS",
147 });
148 return yield* HttpServerResponse.json({
149 endpointAddress: result.endpointAddress,
150 });
151 }
152
153 if (request.method === "POST" && pathname === "/retained") {
154 const body = (yield* request.json) as {
155 topic: string;
156 payload?: string;
157 };
158 // An empty retained payload clears the retained message.
159 yield* publish({
160 topic: body.topic,
161 retain: true,
162 qos: 1,
163 payload: body.payload,
164 });
165 return yield* HttpServerResponse.json({ ok: true });
166 }
167
168 if (request.method === "GET" && pathname === "/retained") {
169 const topic = url.searchParams.get("topic")!;
170 const result = yield* getRetained({ topic }).pipe(
171 Effect.map((r) => ({ found: true as const, payload: r.payload })),
172 Effect.catchTag("ResourceNotFoundException", () =>
173 Effect.succeed({ found: false as const, payload: undefined }),
174 ),
175 );
176 const payload = result.payload
177 ? yield* Effect.sync(() => new TextDecoder().decode(result.payload))
178 : undefined;
179 return yield* HttpServerResponse.json({
180 found: result.found,
181 payload,
182 });
183 }
184
185 if (request.method === "GET" && pathname === "/retained/list") {
186 const result = yield* listRetained();
187 return yield* HttpServerResponse.json({
188 topics: (result.retainedTopics ?? []).map((t) => t.topic),
189 });
190 }
191
192 if (request.method === "GET" && pathname === "/connection") {
193 const clientId = url.searchParams.get("clientId")!;
194 const result = yield* getConnection({ clientId }).pipe(
195 Effect.map((r) => ({
196 ok: true as const,
197 connected: r.connected ?? false,
198 })),
199 Effect.catchTag("ResourceNotFoundException", (e) =>
200 Effect.succeed({
201 ok: false as const,
202 tag: "ResourceNotFoundException",
203 message: e.message,
204 }),
205 ),
206 );
207 return yield* HttpServerResponse.json(result);
208 }
209
210 if (request.method === "GET" && pathname === "/subscriptions") {
211 const clientId = url.searchParams.get("clientId")!;
212 const result = yield* listSubscriptions({ clientId }).pipe(
213 Effect.map((r) => ({
214 ok: true as const,
215 subscriptions: r.subscriptions ?? [],
216 })),
217 Effect.catchTag("ResourceNotFoundException", (e) =>
218 Effect.succeed({
219 ok: false as const,
220 tag: "ResourceNotFoundException",
221 message: e.message,
222 }),
223 ),
224 );
225 return yield* HttpServerResponse.json(result);
226 }
227
228 if (request.method === "DELETE" && pathname === "/connection") {
229 const clientId = url.searchParams.get("clientId")!;
230 const result = yield* deleteConnection({ clientId }).pipe(
231 Effect.map(() => ({ ok: true as const })),
232 Effect.catchTag("ResourceNotFoundException", (e) =>
233 Effect.succeed({
234 ok: false as const,
235 tag: "ResourceNotFoundException",
236 message: e.message,
237 }),
238 ),
239 );
240 return yield* HttpServerResponse.json(result);
241 }
242
243 if (request.method === "POST" && pathname === "/direct") {
244 const body = (yield* request.json) as {
245 clientId: string;
246 topic: string;
247 payload?: string;
248 };
249 const result = yield* sendDirectMessage({
250 clientId: body.clientId,
251 topic: body.topic,
252 payload: body.payload,
253 }).pipe(
254 Effect.map(() => ({ ok: true as const })),
255 Effect.catchTag("ResourceNotFoundException", (e) =>
256 Effect.succeed({
257 ok: false as const,
258 tag: "ResourceNotFoundException",
259 message: e.message,
260 }),
261 ),
262 );
263 return yield* HttpServerResponse.json(result);
264 }
265
266 return yield* HttpServerResponse.json(
267 { error: "Not found", method: request.method, pathname },
268 { status: 404 },
269 );
270 }).pipe(Effect.orDie),
271 };
272 }).pipe(
273 Effect.provide(
274 Layer.mergeAll(
275 AWS.IoT.GetThingShadowHttp,
276 AWS.IoT.UpdateThingShadowHttp,
277 AWS.IoT.DeleteThingShadowHttp,
278 AWS.IoT.ListNamedShadowsForThingHttp,
279 AWS.IoT.DescribeThingHttp,
280 AWS.IoT.PublishHttp,
281 AWS.IoT.GetRetainedMessageHttp,
282 AWS.IoT.ListRetainedMessagesHttp,
283 AWS.IoT.DescribeEndpointHttp,
284 AWS.IoT.ListThingsHttp,
285 AWS.IoT.GetConnectionHttp,
286 AWS.IoT.ListSubscriptionsHttp,
287 AWS.IoT.DeleteConnectionHttp,
288 AWS.IoT.SendDirectMessageHttp,
289 ),
290 ),
291 ),
292 );