@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, 04:45 UTC

main
ts 235 lines 8.87 KB
Raw
1 import * as DynamoDB from "@alchemy.run/aws/DynamoDB";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as S3 from "@alchemy.run/aws/S3";
4 import * as SNS from "@alchemy.run/aws/SNS";
5 import * as SQS from "@alchemy.run/aws/SQS";
6 import * as Config from "effect/Config";
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 Stream from "effect/Stream";
12 import { MARKER } from "./marker.ts";
13
14 /**
15 * Kitchen-sink dev-mode Lambda: one Function owning an S3 bucket, a
16 * DynamoDB table, an SQS queue, and an SNS topic, exercising each runtime
17 * binding AND each event-source glue resource (Subscription, Permission,
18 * EventSourceMapping) over HTTP routes so `alchemy dev` — and a live
19 * `alchemy deploy` — can be driven end-to-end from a test.
20 *
21 * Routes:
22 * - GET / → marker + env (Config-provided MY_VARIABLE)
23 * - GET /s3 → PutObject/GetObject roundtrip
24 * - GET /dynamo → PutItem/GetItem roundtrip
25 * - POST /queue/send → SendMessage over the binding
26 * - GET /queue/messages → reads what the queue consumer recorded
27 * - POST /topic/send → SNS Publish over the binding
28 * - GET /topic/messages → reads what the topic consumer recorded
29 * - POST /items → PutItem with a caller-chosen id (stream feed)
30 * - GET /changes → reads what the table-changes consumer recorded
31 *
32 * The consumers all run on this same Function:
33 * - `consumeQueueMessages` — the event-source-mapping poller invokes it
34 * with SQS batches
35 * - `consumeTopicNotifications` — creates the SNS.Subscription and the
36 * Lambda invoke Permission (the glue that must be local in dev mode)
37 * - `consumeTableChanges` — enables the table stream and creates the
38 * stream EventSourceMapping
39 * Each consumer records into the table under a distinct key prefix so every
40 * produce → deliver → consume path is observable over HTTP.
41 */
42 export default class ApiFunction extends Lambda.Function<ApiFunction>()(
43 "ApiFunction",
44 {
45 main: import.meta.url,
46 functionUrl: true,
47 // The default 128 MB runs this fixture at its ceiling (observed
48 // Max Memory Used: 127 MB live) — leave headroom for event batches.
49 memorySize: 512,
50 env: { MY_VARIABLE: "my-variable-abc123" },
51 },
52 Effect.gen(function* () {
53 // `/s3` writes into the bucket, so destroy must empty it first.
54 const bucket = yield* S3.Bucket("DevBucket", { forceDestroy: true });
55 const table = yield* DynamoDB.Table("MessagesTable", {
56 partitionKey: "id",
57 attributes: { id: "S" },
58 });
59 const queue = yield* SQS.Queue("DevQueue");
60 const topic = yield* SNS.Topic("DevTopic");
61
62 const getObject = yield* S3.GetObject(bucket);
63 const putObject = yield* S3.PutObject(bucket);
64 const getItem = yield* DynamoDB.GetItem(table);
65 const putItem = yield* DynamoDB.PutItem(table);
66 const sendMessage = yield* SQS.SendMessage(queue);
67 const publish = yield* SNS.Publish(topic);
68
69 // Consume produced messages and record them into the table so the
70 // test can observe the produce → deliver → consume roundtrip.
71 yield* SQS.consumeQueueMessages(
72 queue,
73 Effect.fn(function* (event) {
74 for (const record of event.Records) {
75 const parsed = JSON.parse(record.body) as { id: string };
76 yield* putItem({
77 Item: {
78 id: { S: `msg:${parsed.id}` },
79 body: { S: record.body },
80 },
81 });
82 }
83 }),
84 );
85
86 // Consume topic notifications. This is the SNS → Lambda glue: it
87 // creates the AWS.SNS.Subscription and the AWS.Lambda.Permission
88 // (lambda:InvokeFunction for sns.amazonaws.com) — the two resources
89 // that MUST resolve against the emulator in dev mode, since their
90 // props embed the local topic/function ARNs.
91 yield* SNS.consumeTopicNotifications(topic, (notifications) =>
92 notifications.pipe(
93 Stream.mapEffect((notification) => {
94 const parsed = JSON.parse(notification.Message) as { id: string };
95 return putItem({
96 Item: {
97 id: { S: `topic:${parsed.id}` },
98 body: { S: notification.Message },
99 },
100 });
101 }),
102 Stream.runDrain,
103 Effect.orDie,
104 ),
105 );
106
107 // Consume the table's change stream. This enables the DynamoDB stream
108 // on the table and creates the stream AWS.Lambda.EventSourceMapping.
109 // Only plain (un-prefixed) item ids are recorded, so the consumers'
110 // own `msg:`/`topic:`/`change:` writes never feed back into the stream.
111 // TRIM_HORIZON, not LATEST: on real AWS the poller starts reading from
112 // the stream TIP whenever it actually begins polling (minutes after
113 // mapping creation), so LATEST permanently skips records written in
114 // that window — a write shortly after deploy would never arrive.
115 yield* DynamoDB.consumeTableChanges(
116 table,
117 {
118 streamViewType: "NEW_AND_OLD_IMAGES",
119 startingPosition: "TRIM_HORIZON",
120 },
121 Effect.fn(function* (event) {
122 for (const record of event.Records) {
123 const id = record.dynamodb.Keys?.id?.S;
124 if (typeof id !== "string" || id.includes(":")) {
125 continue;
126 }
127 yield* putItem({
128 Item: {
129 id: { S: `change:${id}` },
130 body: { S: record.eventName ?? "UNKNOWN" },
131 },
132 });
133 }
134 }),
135 );
136
137 return {
138 fetch: Effect.gen(function* () {
139 const request = yield* HttpServerRequest;
140 const url = new URL(request.originalUrl);
141
142 if (url.pathname === "/") {
143 const variable = yield* Config.String("MY_VARIABLE");
144 return yield* HttpServerResponse.json({ marker: MARKER, variable });
145 }
146
147 if (url.pathname === "/s3") {
148 yield* putObject({ Key: "hello.txt", Body: "hello from s3" });
149 const object = yield* getObject({ Key: "hello.txt" });
150 const text = yield* (
151 object.Body?.pipe(Stream.decodeText, Stream.mkString) ?? Effect.succeed("")
152 );
153 return yield* HttpServerResponse.json({ text });
154 }
155
156 if (url.pathname === "/dynamo") {
157 yield* putItem({
158 Item: {
159 id: { S: "hello" },
160 content: { S: "hello from dynamo" },
161 },
162 });
163 const item = yield* getItem({ Key: { id: { S: "hello" } } });
164 return yield* HttpServerResponse.json({
165 text: item.Item?.content?.S ?? null,
166 });
167 }
168
169 if (url.pathname === "/queue/send" && request.method === "POST") {
170 const body = yield* request.text;
171 yield* sendMessage({ MessageBody: body });
172 return yield* HttpServerResponse.json({ sent: true });
173 }
174
175 if (url.pathname === "/queue/messages") {
176 const id = url.searchParams.get("id") ?? "";
177 const item = yield* getItem({ Key: { id: { S: `msg:${id}` } } });
178 return yield* HttpServerResponse.json({
179 body: item.Item?.body?.S ?? null,
180 });
181 }
182
183 if (url.pathname === "/topic/send" && request.method === "POST") {
184 const body = yield* request.text;
185 yield* publish({ Message: body });
186 return yield* HttpServerResponse.json({ published: true });
187 }
188
189 if (url.pathname === "/topic/messages") {
190 const id = url.searchParams.get("id") ?? "";
191 const item = yield* getItem({ Key: { id: { S: `topic:${id}` } } });
192 return yield* HttpServerResponse.json({
193 body: item.Item?.body?.S ?? null,
194 });
195 }
196
197 if (url.pathname === "/items" && request.method === "POST") {
198 const body = yield* request.text;
199 const parsed = JSON.parse(body) as { id: string };
200 yield* putItem({
201 Item: {
202 id: { S: parsed.id },
203 body: { S: body },
204 },
205 });
206 return yield* HttpServerResponse.json({ put: true });
207 }
208
209 if (url.pathname === "/changes") {
210 const id = url.searchParams.get("id") ?? "";
211 const item = yield* getItem({ Key: { id: { S: `change:${id}` } } });
212 return yield* HttpServerResponse.json({
213 body: item.Item?.body?.S ?? null,
214 });
215 }
216
217 return HttpServerResponse.text("Not found", { status: 404 });
218 }).pipe(Effect.orDie),
219 };
220 }).pipe(
221 Effect.provide(
222 Layer.mergeAll(
223 Lambda.QueueEventSource,
224 Lambda.TopicEventSource,
225 Lambda.TableEventSource,
226 S3.GetObjectHttp,
227 S3.PutObjectHttp,
228 DynamoDB.GetItemHttp,
229 DynamoDB.PutItemHttp,
230 SQS.SendMessageHttp,
231 SNS.PublishHttp,
232 ),
233 ),
234 ),
235 ) {}