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

main
ts 311 lines 11.9 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as SQS from "@alchemy.run/aws/SQS";
3 import * as Cause from "effect/Cause";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 // Shared Lambda fixture hosting every SQS message-plane binding, one HTTP
14 // route per operation (see test/AWS/DynamoDB/handler.ts for the pattern).
15 export class SQSTestFunction extends Lambda.Function<Lambda.Function>()("SQSTestFunction") {}
16
17 export default SQSTestFunction.make(
18 {
19 main,
20 functionUrl: true,
21 // The /receive route long-polls SQS (WaitTimeSeconds up to 2s); AWS's 3s
22 // default function timeout intermittently kills the invocation AFTER SQS
23 // has consumed the message server-side, trapping it invisible for the
24 // queue's 30s visibility window while the caller only sees a 500.
25 timeout: Duration.seconds(30),
26 },
27 Effect.gen(function* () {
28 // BindingsDLQ doubles as the redrive source for the message-move-task
29 // bindings; BindingsQueue's redrivePolicy is what makes it a valid DLQ.
30 const dlq = yield* SQS.Queue("BindingsDLQ");
31 const queue = yield* SQS.Queue("BindingsQueue", {
32 redrivePolicy: {
33 deadLetterTargetArn: dlq.queueArn,
34 // High enough that test polling (bounded re-receives) never trips a
35 // real redrive; the DLQ only receives messages sent to it directly.
36 maxReceiveCount: 1000,
37 },
38 });
39 // Dedicated source for MessageMoveTasks. Messages must have actually
40 // redriven from a source queue to be eligible for DLQ redrive; directly
41 // sending to the DLQ is not deterministic. Keep this separate from the
42 // shared binding queue because maxReceiveCount=1 would interfere with the
43 // receive/visibility tests below.
44 const moveSource = yield* SQS.Queue("BindingsMoveSource", {
45 redrivePolicy: {
46 deadLetterTargetArn: dlq.queueArn,
47 maxReceiveCount: 1,
48 },
49 });
50
51 const sendMessage = yield* SQS.SendMessage(queue);
52 const sendMessageBatch = yield* SQS.SendMessageBatch(queue);
53 const receiveMessage = yield* SQS.ReceiveMessage(queue);
54 const deleteMessage = yield* SQS.DeleteMessage(queue);
55 const deleteMessageBatch = yield* SQS.DeleteMessageBatch(queue);
56 const changeMessageVisibility = yield* SQS.ChangeMessageVisibility(queue);
57 const changeMessageVisibilityBatch = yield* SQS.ChangeMessageVisibilityBatch(queue);
58 const getQueueAttributes = yield* SQS.GetQueueAttributes(queue);
59 const purgeQueue = yield* SQS.PurgeQueue(queue);
60 const listDeadLetterSourceQueues = yield* SQS.ListDeadLetterSourceQueues(dlq);
61 const startMessageMoveTask = yield* SQS.StartMessageMoveTask(dlq, {
62 destination: moveSource,
63 });
64 const cancelMessageMoveTask = yield* SQS.CancelMessageMoveTask(dlq);
65 const listMessageMoveTasks = yield* SQS.ListMessageMoveTasks(dlq);
66 const queueUrl = yield* queue.queueUrl;
67 const dlqUrl = yield* dlq.queueUrl;
68 const moveSourceUrl = yield* moveSource.queueUrl;
69
70 return {
71 fetch: Effect.gen(function* () {
72 const request = yield* HttpServerRequest;
73 const url = new URL(request.originalUrl);
74 const pathname = url.pathname;
75
76 yield* Effect.logInfo(`Request: ${request.method} ${pathname}`);
77
78 if (request.method === "GET" && pathname === "/ready") {
79 return yield* HttpServerResponse.json({
80 ok: true,
81 queueUrl: yield* queueUrl,
82 dlqUrl: yield* dlqUrl,
83 moveSourceUrl: yield* moveSourceUrl,
84 });
85 }
86
87 if (request.method === "POST" && pathname === "/send") {
88 const body = (yield* request.json) as unknown as {
89 messageBody: string;
90 };
91 const result = yield* sendMessage({
92 MessageBody: body.messageBody,
93 });
94 return yield* HttpServerResponse.json({
95 messageId: result.MessageId,
96 });
97 }
98
99 if (request.method === "POST" && pathname === "/send-batch") {
100 const body = (yield* request.json) as unknown as {
101 entries: { id: string; messageBody: string }[];
102 };
103 const result = yield* sendMessageBatch({
104 Entries: body.entries.map((entry) => ({
105 Id: entry.id,
106 MessageBody: entry.messageBody,
107 })),
108 });
109 return yield* HttpServerResponse.json({
110 successful: (result.Successful ?? []).map((s) => ({
111 id: s.Id,
112 messageId: s.MessageId,
113 })),
114 failed: (result.Failed ?? []).map((f) => ({
115 id: f.Id,
116 code: f.Code,
117 })),
118 });
119 }
120
121 if (request.method === "POST" && pathname === "/receive") {
122 const body = (yield* request.json) as unknown as {
123 maxNumberOfMessages?: number;
124 waitTimeSeconds?: number;
125 visibilityTimeout?: number;
126 };
127 const result = yield* receiveMessage({
128 MaxNumberOfMessages: body.maxNumberOfMessages ?? 10,
129 WaitTimeSeconds: body.waitTimeSeconds ?? 2,
130 ...(body.visibilityTimeout !== undefined
131 ? { VisibilityTimeout: body.visibilityTimeout }
132 : {}),
133 });
134 return yield* HttpServerResponse.json({
135 messages: (result.Messages ?? []).map((message) => ({
136 messageId: message.MessageId,
137 body: message.Body,
138 receiptHandle: message.ReceiptHandle,
139 })),
140 });
141 }
142
143 if (request.method === "POST" && pathname === "/delete") {
144 const body = (yield* request.json) as unknown as {
145 receiptHandle: string;
146 };
147 yield* deleteMessage({ ReceiptHandle: body.receiptHandle });
148 return yield* HttpServerResponse.json({ success: true });
149 }
150
151 if (request.method === "POST" && pathname === "/delete-batch") {
152 const body = (yield* request.json) as unknown as {
153 entries: { id: string; receiptHandle: string }[];
154 };
155 const result = yield* deleteMessageBatch({
156 Entries: body.entries.map((entry) => ({
157 Id: entry.id,
158 ReceiptHandle: entry.receiptHandle,
159 })),
160 });
161 return yield* HttpServerResponse.json({
162 successful: (result.Successful ?? []).map((s) => s.Id),
163 failed: (result.Failed ?? []).map((f) => ({
164 id: f.Id,
165 code: f.Code,
166 })),
167 });
168 }
169
170 if (request.method === "POST" && pathname === "/change-visibility") {
171 const body = (yield* request.json) as unknown as {
172 receiptHandle: string;
173 visibilityTimeout: number;
174 };
175 yield* changeMessageVisibility({
176 ReceiptHandle: body.receiptHandle,
177 VisibilityTimeout: body.visibilityTimeout,
178 });
179 return yield* HttpServerResponse.json({ success: true });
180 }
181
182 if (request.method === "POST" && pathname === "/change-visibility-batch") {
183 const body = (yield* request.json) as unknown as {
184 entries: {
185 id: string;
186 receiptHandle: string;
187 visibilityTimeout: number;
188 }[];
189 };
190 const result = yield* changeMessageVisibilityBatch({
191 Entries: body.entries.map((entry) => ({
192 Id: entry.id,
193 ReceiptHandle: entry.receiptHandle,
194 VisibilityTimeout: entry.visibilityTimeout,
195 })),
196 });
197 return yield* HttpServerResponse.json({
198 successful: (result.Successful ?? []).map((s) => s.Id),
199 failed: (result.Failed ?? []).map((f) => ({
200 id: f.Id,
201 code: f.Code,
202 })),
203 });
204 }
205
206 if (request.method === "POST" && pathname === "/attributes") {
207 const body = (yield* request.json) as unknown as {
208 attributeNames?: string[];
209 };
210 const result = yield* getQueueAttributes({
211 AttributeNames: body.attributeNames ?? ["All"],
212 });
213 return yield* HttpServerResponse.json({
214 attributes: result.Attributes ?? {},
215 });
216 }
217
218 if (request.method === "POST" && pathname === "/purge") {
219 yield* purgeQueue();
220 return yield* HttpServerResponse.json({ success: true });
221 }
222
223 if (request.method === "POST" && pathname === "/dlq-sources") {
224 const result = yield* listDeadLetterSourceQueues();
225 return yield* HttpServerResponse.json({
226 queueUrls: result.queueUrls,
227 });
228 }
229
230 if (request.method === "POST" && pathname === "/move/start") {
231 const body = (yield* request.json) as unknown as {
232 maxNumberOfMessagesPerSecond?: number;
233 };
234 const result = yield* startMessageMoveTask({
235 ...(body.maxNumberOfMessagesPerSecond !== undefined
236 ? {
237 MaxNumberOfMessagesPerSecond: body.maxNumberOfMessagesPerSecond,
238 }
239 : {}),
240 });
241 return yield* HttpServerResponse.json({
242 taskHandle: result.TaskHandle,
243 });
244 }
245
246 if (request.method === "POST" && pathname === "/move/list") {
247 const result = yield* listMessageMoveTasks({ MaxResults: 10 });
248 return yield* HttpServerResponse.json({
249 tasks: (result.Results ?? []).map((task) => ({
250 taskHandle: task.TaskHandle,
251 status: task.Status,
252 moved: task.ApproximateNumberOfMessagesMoved,
253 })),
254 });
255 }
256
257 if (request.method === "POST" && pathname === "/move/cancel") {
258 const body = (yield* request.json) as unknown as {
259 taskHandle: string;
260 };
261 // A task that already finished is a benign race: SQS returns either
262 // ResourceNotFoundException or this exact typed validation message.
263 // Preserve every other InvalidParameterValueException as a failure.
264 const canceled = yield* cancelMessageMoveTask({
265 TaskHandle: body.taskHandle,
266 }).pipe(
267 Effect.map(() => true),
268 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)),
269 Effect.catchTag("InvalidParameterValueException", (error) =>
270 error.message === "Only active tasks can be cancelled."
271 ? Effect.succeed(false)
272 : Effect.fail(error),
273 ),
274 );
275 return yield* HttpServerResponse.json({ canceled });
276 }
277
278 return yield* HttpServerResponse.json(
279 { error: "Not found", method: request.method, pathname },
280 { status: 404 },
281 );
282 }).pipe(
283 // Lambda's default failure response is only "Internal Server Error",
284 // which hides the typed SQS rejection that made the route fail. This
285 // is a test-only handler: return the pretty Effect cause so the live
286 // test log identifies the exact capability/IAM/consistency failure.
287 Effect.catchCause((cause) =>
288 HttpServerResponse.json({ error: Cause.pretty(cause) }, { status: 500 }),
289 ),
290 ),
291 };
292 }).pipe(
293 Effect.provide(
294 Layer.mergeAll(
295 SQS.SendMessageHttp,
296 SQS.SendMessageBatchHttp,
297 SQS.ReceiveMessageHttp,
298 SQS.DeleteMessageHttp,
299 SQS.DeleteMessageBatchHttp,
300 SQS.ChangeMessageVisibilityHttp,
301 SQS.ChangeMessageVisibilityBatchHttp,
302 SQS.GetQueueAttributesHttp,
303 SQS.PurgeQueueHttp,
304 SQS.ListDeadLetterSourceQueuesHttp,
305 SQS.StartMessageMoveTaskHttp,
306 SQS.CancelMessageMoveTaskHttp,
307 SQS.ListMessageMoveTasksHttp,
308 ),
309 ),
310 ),
311 );