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

main
ts 474 lines 18.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Context from "effect/Context";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 const formatError = (error: unknown) =>
14 typeof error === "object" && error !== null && "_tag" in error
15 ? { ok: false as const, error: (error as { _tag: string })._tag }
16 : { ok: false as const, error: `${error}` };
17
18 export class TopicAndQueue extends Context.Service<
19 TopicAndQueue,
20 {
21 topic: AWS.SNS.Topic;
22 queue: AWS.SQS.Queue;
23 subscription: AWS.SNS.Subscription;
24 subscriptionAttrsQueue: AWS.SQS.Queue;
25 queueSubscription: AWS.SNS.Subscription;
26 }
27 >()("TopicAndQueue") {}
28
29 export const TopicAndQueueLive = Layer.effect(
30 TopicAndQueue,
31 Effect.gen(function* () {
32 const topic = yield* AWS.SNS.Topic("TestTopic", {
33 attributes: {
34 DisplayName: "sns-test-topic",
35 },
36 });
37 const queue = yield* AWS.SQS.Queue("NotificationsQueue");
38 const subscriptionAttrsQueue = yield* AWS.SQS.Queue("SubscriptionAttrsQueue");
39 const queueSubscription = yield* AWS.SNS.Subscription("QueueFixtureSubscription", {
40 topicArn: topic.topicArn,
41 protocol: "sqs",
42 endpoint: subscriptionAttrsQueue.queueArn,
43 returnSubscriptionArn: true,
44 });
45 return {
46 topic,
47 queue,
48 // ConfirmSubscription only injects the parent TopicArn, so the existing
49 // queue subscription exercises that binding without a second Lambda.
50 subscription: queueSubscription,
51 subscriptionAttrsQueue,
52 queueSubscription,
53 };
54 }),
55 );
56
57 export class SNSApiFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()("SNSApiFunction") {}
58
59 export const SNSApiFunctionLive = SNSApiFunction.make(
60 {
61 main,
62 functionUrl: true,
63 // The sink's bounded partial-failure retry can sleep up to ~6s, which
64 // exceeds Lambda's 3s default timeout (see PATTERNS §7).
65 timeout: Duration.seconds(30),
66 env: {
67 DEBUG: "true",
68 },
69 },
70 Effect.gen(function* () {
71 const { topic, queue, subscription, queueSubscription } = yield* TopicAndQueue;
72
73 const publish = yield* AWS.SNS.Publish(topic);
74 const publishBatch = yield* AWS.SNS.PublishBatch(topic);
75 const getTopicAttributes = yield* AWS.SNS.GetTopicAttributes(topic);
76 const setTopicAttributes = yield* AWS.SNS.SetTopicAttributes(topic);
77 const addPermission = yield* AWS.SNS.AddPermission(topic);
78 const removePermission = yield* AWS.SNS.RemovePermission(topic);
79 const getDataProtectionPolicy = yield* AWS.SNS.GetDataProtectionPolicy(topic);
80 const putDataProtectionPolicy = yield* AWS.SNS.PutDataProtectionPolicy(topic);
81 const listTopics = yield* AWS.SNS.ListTopics();
82 const listSubscriptions = yield* AWS.SNS.ListSubscriptions();
83 const listSubscriptionsByTopic = yield* AWS.SNS.ListSubscriptionsByTopic(topic);
84 const listTagsForResource = yield* AWS.SNS.ListTagsForResource(topic);
85 const tagResource = yield* AWS.SNS.TagResource(topic);
86 const untagResource = yield* AWS.SNS.UntagResource(topic);
87 const getSubscriptionAttributes = yield* AWS.SNS.GetSubscriptionAttributes(queueSubscription);
88 const setSubscriptionAttributes = yield* AWS.SNS.SetSubscriptionAttributes(queueSubscription);
89 const confirmSubscription = yield* AWS.SNS.ConfirmSubscription(subscription);
90 const subscribeToTopic = yield* AWS.SNS.Subscribe(topic);
91 const unsubscribe = yield* AWS.SNS.Unsubscribe();
92 const publishSms = yield* AWS.SNS.PublishSms();
93 const checkIfPhoneNumberIsOptedOut = yield* AWS.SNS.CheckIfPhoneNumberIsOptedOut();
94 const optInPhoneNumber = yield* AWS.SNS.OptInPhoneNumber();
95 const listPhoneNumbersOptedOut = yield* AWS.SNS.ListPhoneNumbersOptedOut();
96 const getSmsAttributes = yield* AWS.SNS.GetSMSAttributes();
97 const setSmsAttributes = yield* AWS.SNS.SetSMSAttributes();
98 const listOriginationNumbers = yield* AWS.SNS.ListOriginationNumbers();
99 const getSandboxStatus = yield* AWS.SNS.GetSMSSandboxAccountStatus();
100 const listSandboxNumbers = yield* AWS.SNS.ListSMSSandboxPhoneNumbers();
101 const createSandboxNumber = yield* AWS.SNS.CreateSMSSandboxPhoneNumber();
102 const verifySandboxNumber = yield* AWS.SNS.VerifySMSSandboxPhoneNumber();
103 const deleteSandboxNumber = yield* AWS.SNS.DeleteSMSSandboxPhoneNumber();
104 const listPlatformApplications = yield* AWS.SNS.ListPlatformApplications();
105 const sink = yield* AWS.SNS.TopicSink(topic);
106 const QueueArn = yield* queue.queueArn;
107 const TopicArn = yield* topic.topicArn;
108 const accountId = TopicArn.pipe(Effect.map((topicArn) => topicArn.split(":")[4] ?? ""));
109
110 const queueSink = yield* AWS.SQS.QueueSink(queue);
111
112 yield* AWS.SNS.consumeTopicNotifications(topic, (stream) =>
113 stream.pipe(
114 Stream.map((notification) => ({
115 MessageBody: JSON.stringify({
116 topicArn: notification.TopicArn,
117 message: notification.Message,
118 subject: notification.Subject,
119 messageId: notification.MessageId,
120 }),
121 })),
122 Stream.run(queueSink),
123 Effect.orDie,
124 ),
125 );
126
127 return {
128 fetch: Effect.gen(function* () {
129 const request = yield* HttpServerRequest;
130 const url = new URL(request.originalUrl);
131 const pathname = url.pathname;
132
133 if (request.method === "GET" && pathname === "/ready") {
134 return yield* HttpServerResponse.json({ ok: true });
135 }
136
137 if (request.method === "POST" && pathname === "/publish") {
138 const body = (yield* request.json) as {
139 message: string;
140 subject?: string;
141 };
142 const response = yield* publish({
143 Message: body.message,
144 Subject: body.subject,
145 });
146 return yield* HttpServerResponse.json(response);
147 }
148
149 if (request.method === "POST" && pathname === "/publish-batch") {
150 const body = (yield* request.json) as { messages: string[] };
151 const response = yield* publishBatch({
152 PublishBatchRequestEntries: body.messages.map((message, index) => ({
153 Id: `${index}`,
154 Message: message,
155 })),
156 });
157 return yield* HttpServerResponse.json(response);
158 }
159
160 if (request.method === "POST" && pathname === "/sink") {
161 const body = (yield* request.json) as { messages: string[] };
162 yield* Stream.fromIterable(body.messages).pipe(
163 Stream.map((message) => ({ Message: message })),
164 Stream.run(sink),
165 );
166 return yield* HttpServerResponse.json({ ok: true });
167 }
168
169 if (request.method === "GET" && pathname === "/topic-attributes") {
170 return yield* HttpServerResponse.json(yield* getTopicAttributes());
171 }
172
173 if (request.method === "POST" && pathname === "/topic-attributes") {
174 const body = (yield* request.json) as {
175 name: string;
176 value?: string;
177 };
178 return yield* HttpServerResponse.json(
179 yield* setTopicAttributes({
180 AttributeName: body.name,
181 AttributeValue: body.value,
182 }),
183 );
184 }
185
186 if (request.method === "POST" && pathname === "/add-permission") {
187 const label = "FixturePublishPermission";
188 const response = yield* addPermission({
189 Label: label,
190 AWSAccountId: [yield* accountId],
191 ActionName: ["Publish"],
192 });
193 return yield* HttpServerResponse.json({ label, response });
194 }
195
196 if (request.method === "POST" && pathname === "/remove-permission") {
197 const response = yield* removePermission({
198 Label: "FixturePublishPermission",
199 });
200 return yield* HttpServerResponse.json(response);
201 }
202
203 if (request.method === "GET" && pathname === "/data-protection-policy") {
204 return yield* HttpServerResponse.json(
205 yield* getDataProtectionPolicy().pipe(
206 Effect.catch((error) => Effect.succeed(formatError(error))),
207 ),
208 );
209 }
210
211 if (request.method === "POST" && pathname === "/data-protection-policy") {
212 const body = (yield* request.json) as { policy: string };
213 const response = yield* putDataProtectionPolicy({
214 DataProtectionPolicy: body.policy,
215 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
216 return yield* HttpServerResponse.json(response);
217 }
218
219 if (request.method === "GET" && pathname === "/topics") {
220 return yield* HttpServerResponse.json(yield* listTopics());
221 }
222
223 if (request.method === "GET" && pathname === "/subscriptions") {
224 return yield* HttpServerResponse.json(yield* listSubscriptions());
225 }
226
227 if (request.method === "GET" && pathname === "/subscriptions-by-topic") {
228 return yield* HttpServerResponse.json(yield* listSubscriptionsByTopic());
229 }
230
231 if (request.method === "GET" && pathname === "/tags") {
232 return yield* HttpServerResponse.json(yield* listTagsForResource());
233 }
234
235 if (request.method === "POST" && pathname === "/tags") {
236 const body = (yield* request.json) as {
237 key: string;
238 value: string;
239 };
240 return yield* HttpServerResponse.json(
241 yield* tagResource({
242 Tags: [{ Key: body.key, Value: body.value }],
243 }),
244 );
245 }
246
247 if (request.method === "DELETE" && pathname === "/tags") {
248 const body = (yield* request.json) as { keys: string[] };
249 return yield* HttpServerResponse.json(
250 yield* untagResource({
251 TagKeys: body.keys,
252 }),
253 );
254 }
255
256 if (request.method === "GET" && pathname === "/subscription-attributes") {
257 return yield* HttpServerResponse.json(yield* getSubscriptionAttributes());
258 }
259
260 if (request.method === "POST" && pathname === "/subscription-attributes") {
261 const body = (yield* request.json) as {
262 name: string;
263 value?: string;
264 };
265 return yield* HttpServerResponse.json(
266 yield* setSubscriptionAttributes({
267 AttributeName: body.name,
268 AttributeValue: body.value,
269 }),
270 );
271 }
272
273 if (request.method === "POST" && pathname === "/subscribe-cycle") {
274 // Subscribe the (otherwise unsubscribed) notifications queue to the
275 // topic at runtime and immediately unsubscribe it — proves both the
276 // `Subscribe` and `Unsubscribe` bindings against the live API
277 // without leaving a subscription behind that would double-deliver
278 // later publishes.
279 const subscribed = yield* subscribeToTopic({
280 Protocol: "sqs",
281 Endpoint: yield* QueueArn,
282 ReturnSubscriptionArn: true,
283 });
284 if (!subscribed.SubscriptionArn) {
285 return yield* HttpServerResponse.json(
286 { ok: false, error: "no SubscriptionArn" },
287 { status: 500 },
288 );
289 }
290 yield* unsubscribe({ SubscriptionArn: subscribed.SubscriptionArn });
291 return yield* HttpServerResponse.json({
292 ok: true,
293 subscriptionArn: subscribed.SubscriptionArn,
294 });
295 }
296
297 if (request.method === "GET" && pathname === "/sms/attributes") {
298 return yield* HttpServerResponse.json(
299 yield* getSmsAttributes().pipe(
300 Effect.catch((error) => Effect.succeed(formatError(error))),
301 ),
302 );
303 }
304
305 if (request.method === "POST" && pathname === "/sms/attributes") {
306 const body = (yield* request.json) as { type: string };
307 return yield* HttpServerResponse.json(
308 yield* setSmsAttributes({
309 attributes: { DefaultSMSType: body.type },
310 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error)))),
311 );
312 }
313
314 if (request.method === "GET" && pathname === "/sms/opted-out") {
315 return yield* HttpServerResponse.json(
316 yield* listPhoneNumbersOptedOut().pipe(
317 Effect.catch((error) => Effect.succeed(formatError(error))),
318 ),
319 );
320 }
321
322 if (request.method === "POST" && pathname === "/sms/check-opt-out") {
323 const body = (yield* request.json) as { phoneNumber: string };
324 return yield* HttpServerResponse.json(
325 yield* checkIfPhoneNumberIsOptedOut({
326 phoneNumber: body.phoneNumber,
327 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error)))),
328 );
329 }
330
331 if (request.method === "POST" && pathname === "/sms/opt-in") {
332 const body = (yield* request.json) as { phoneNumber: string };
333 const response = yield* optInPhoneNumber({
334 phoneNumber: body.phoneNumber,
335 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
336 return yield* HttpServerResponse.json(response);
337 }
338
339 if (request.method === "GET" && pathname === "/sms/origination-numbers") {
340 return yield* HttpServerResponse.json(
341 yield* listOriginationNumbers().pipe(
342 Effect.catch((error) => Effect.succeed(formatError(error))),
343 ),
344 );
345 }
346
347 if (request.method === "GET" && pathname === "/sms/sandbox-status") {
348 return yield* HttpServerResponse.json(
349 yield* getSandboxStatus().pipe(
350 Effect.catch((error) => Effect.succeed(formatError(error))),
351 ),
352 );
353 }
354
355 if (request.method === "GET" && pathname === "/sms/sandbox-numbers") {
356 return yield* HttpServerResponse.json(
357 yield* listSandboxNumbers().pipe(
358 Effect.catch((error) => Effect.succeed(formatError(error))),
359 ),
360 );
361 }
362
363 if (request.method === "POST" && pathname === "/sms/sandbox-create") {
364 const body = (yield* request.json) as { phoneNumber: string };
365 const response = yield* createSandboxNumber({
366 PhoneNumber: body.phoneNumber,
367 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
368 return yield* HttpServerResponse.json(response);
369 }
370
371 if (request.method === "POST" && pathname === "/sms/sandbox-verify") {
372 const body = (yield* request.json) as {
373 phoneNumber: string;
374 otp: string;
375 };
376 const response = yield* verifySandboxNumber({
377 PhoneNumber: body.phoneNumber,
378 OneTimePassword: body.otp,
379 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
380 return yield* HttpServerResponse.json(response);
381 }
382
383 if (request.method === "POST" && pathname === "/sms/sandbox-delete") {
384 const body = (yield* request.json) as { phoneNumber: string };
385 const response = yield* deleteSandboxNumber({
386 PhoneNumber: body.phoneNumber,
387 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
388 return yield* HttpServerResponse.json(response);
389 }
390
391 if (request.method === "POST" && pathname === "/sms/publish") {
392 const body = (yield* request.json) as {
393 phoneNumber: string;
394 message: string;
395 };
396 const response = yield* publishSms({
397 PhoneNumber: body.phoneNumber,
398 Message: body.message,
399 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
400 return yield* HttpServerResponse.json(response);
401 }
402
403 if (request.method === "GET" && pathname === "/platform/applications") {
404 return yield* HttpServerResponse.json(
405 yield* listPlatformApplications().pipe(
406 Effect.catch((error) => Effect.succeed(formatError(error))),
407 ),
408 );
409 }
410
411 if (request.method === "POST" && pathname === "/confirm-subscription") {
412 const body = (yield* request.json) as { token: string };
413 const response = yield* confirmSubscription({
414 Token: body.token,
415 }).pipe(Effect.catch((error) => Effect.succeed(formatError(error))));
416 return yield* HttpServerResponse.json(response);
417 }
418
419 return yield* HttpServerResponse.json(
420 { error: "Not found", method: request.method, pathname },
421 { status: 404 },
422 );
423 }).pipe(Effect.orDie),
424 };
425 }).pipe(
426 Effect.provide(
427 Layer.provideMerge(
428 Layer.mergeAll(
429 TopicAndQueueLive,
430 AWS.Lambda.TopicEventSource,
431 AWS.SNS.TopicSinkHttp,
432 AWS.SQS.QueueSinkHttp,
433 ),
434 Layer.mergeAll(
435 AWS.SNS.AddPermissionHttp,
436 AWS.SNS.CheckIfPhoneNumberIsOptedOutHttp,
437 AWS.SNS.ConfirmSubscriptionHttp,
438 AWS.SNS.CreateSMSSandboxPhoneNumberHttp,
439 AWS.SNS.DeleteSMSSandboxPhoneNumberHttp,
440 AWS.SNS.GetSMSAttributesHttp,
441 AWS.SNS.GetSMSSandboxAccountStatusHttp,
442 AWS.SNS.ListOriginationNumbersHttp,
443 AWS.SNS.ListPhoneNumbersOptedOutHttp,
444 AWS.SNS.ListPlatformApplicationsHttp,
445 AWS.SNS.ListSMSSandboxPhoneNumbersHttp,
446 AWS.SNS.OptInPhoneNumberHttp,
447 AWS.SNS.PublishSmsHttp,
448 AWS.SNS.SetSMSAttributesHttp,
449 AWS.SNS.SubscribeHttp,
450 AWS.SNS.UnsubscribeHttp,
451 AWS.SNS.VerifySMSSandboxPhoneNumberHttp,
452 AWS.SNS.GetDataProtectionPolicyHttp,
453 AWS.SNS.GetSubscriptionAttributesHttp,
454 AWS.SNS.GetTopicAttributesHttp,
455 AWS.SNS.ListSubscriptionsByTopicHttp,
456 AWS.SNS.ListSubscriptionsHttp,
457 AWS.SNS.ListTagsForResourceHttp,
458 AWS.SNS.ListTopicsHttp,
459 AWS.SNS.PublishBatchHttp,
460 AWS.SNS.PublishHttp,
461 AWS.SNS.PutDataProtectionPolicyHttp,
462 AWS.SNS.RemovePermissionHttp,
463 AWS.SNS.SetSubscriptionAttributesHttp,
464 AWS.SNS.SetTopicAttributesHttp,
465 AWS.SNS.TagResourceHttp,
466 AWS.SNS.UntagResourceHttp,
467 AWS.SQS.SendMessageBatchHttp,
468 ),
469 ),
470 ),
471 ),
472 ).pipe(Layer.provideMerge(TopicAndQueueLive));
473
474 export default SNSApiFunctionLive;