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

main
ts 91 lines 2.76 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Console from "effect/Console";
3 import * as Context from "effect/Context";
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 * as Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "sink-handler.ts");
13
14 export class TestQueue extends Context.Service<TestQueue, { queue: AWS.SQS.Queue }>()(
15 "TestQueue",
16 ) {}
17
18 export const TestQueueLive = Layer.effect(
19 TestQueue,
20 Effect.gen(function* () {
21 const queue = yield* AWS.SQS.Queue("QueueSinkQueue");
22 return { queue };
23 }),
24 );
25
26 export class QueueSinkFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
27 "QueueSinkFunction",
28 ) {}
29
30 export const QueueSinkFunctionLive = QueueSinkFunction.make(
31 {
32 main,
33 functionUrl: true,
34 // The sink's bounded partial-failure retry can sleep up to ~6s, which
35 // exceeds Lambda's 3s default timeout (see PATTERNS §7).
36 timeout: Duration.seconds(30),
37 },
38 Effect.gen(function* () {
39 const { queue } = yield* TestQueue;
40 const sink = yield* AWS.SQS.QueueSink(queue);
41 const queueUrl = yield* queue.queueUrl;
42
43 return {
44 fetch: Effect.gen(function* () {
45 const request = yield* HttpServerRequest;
46 yield* Console.log(request);
47 const pathname = new URL(request.originalUrl).pathname;
48
49 if (request.method === "GET" && pathname === "/ready") {
50 return yield* HttpServerResponse.json({
51 ok: true,
52 queueUrl: yield* queueUrl,
53 });
54 }
55
56 if (request.method === "POST" && pathname === "/sink") {
57 const body = (yield* request.json) as { messages: string[] };
58
59 yield* Stream.fromIterable(body.messages).pipe(
60 Stream.map((message) => ({ MessageBody: message })),
61 Stream.run(sink),
62 );
63
64 return yield* HttpServerResponse.json({
65 ok: true,
66 count: body.messages.length,
67 });
68 }
69
70 return yield* HttpServerResponse.json(
71 { error: "Not found", method: request.method, pathname },
72 { status: 404 },
73 );
74 }).pipe(
75 Effect.tapError(Console.log),
76 Effect.tap(Console.log),
77 Effect.catch(() =>
78 Effect.succeed(HttpServerResponse.text("Internal server error", { status: 500 })),
79 ),
80 ),
81 };
82 }).pipe(
83 Effect.provide(
84 Layer.provideMerge(
85 Layer.mergeAll(TestQueueLive, AWS.SQS.QueueSinkHttp),
86 Layer.mergeAll(AWS.SQS.SendMessageBatchHttp),
87 ),
88 ),
89 ),
90 );
91 export default QueueSinkFunctionLive;