@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 160 lines 6 KB
Raw
1 import * as net from "node:net";
2 import * as AWS from "@alchemy.run/aws";
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 Valkey from "iovalkey";
10 import { getProvisionedNetwork } from "./ProvisionedNetwork.ts";
11
12 export class ProvisionedCacheDataPlaneFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
13 "ProvisionedCacheDataPlaneFunction",
14 ) {}
15
16 const valkeyRoundtrip = (info: AWS.ElastiCache.ReplicationGroupConnectionInfo, value: string) =>
17 Effect.tryPromise({
18 try: async () => {
19 const client = new Valkey({
20 host: info.host,
21 port: info.port,
22 ...(info.tls ? { tls: {} } : {}),
23 connectTimeout: 10_000,
24 maxRetriesPerRequest: 2,
25 retryStrategy: (attempt) => (attempt > 2 ? null : 500),
26 });
27 try {
28 await client.set("alchemy:provisioned:valkey", value);
29 return await client.get("alchemy:provisioned:valkey");
30 } finally {
31 client.disconnect();
32 }
33 },
34 catch: (cause) => new Error(`Valkey roundtrip failed: ${String(cause)}`),
35 });
36
37 const memcachedRoundtrip = (endpoint: { address: string; port: number }, value: string) =>
38 Effect.tryPromise({
39 try: () =>
40 new Promise<string>((resolve, reject) => {
41 const socket = net.createConnection(endpoint.port, endpoint.address);
42 let response = "";
43 const key = "alchemy:provisioned:memcached";
44 const payload = `set ${key} 0 30 ${Buffer.byteLength(value)}\r\n${value}\r\nget ${key}\r\n`;
45 const fail = (error: Error) => {
46 socket.destroy();
47 reject(error);
48 };
49 socket.setTimeout(10_000, () => fail(new Error("Memcached timed out")));
50 socket.once("error", fail);
51 socket.on("data", (chunk) => {
52 response += chunk.toString();
53 if (!response.endsWith("END\r\n")) return;
54 socket.end();
55 const match = response.match(/VALUE [^\r]+\r\n([^\r]+)\r\nEND\r\n$/);
56 if (match?.[1] === undefined) {
57 reject(new Error(`Unexpected Memcached response: ${response}`));
58 return;
59 }
60 resolve(match[1]);
61 });
62 socket.once("connect", () => socket.write(payload));
63 }),
64 catch: (cause) => new Error(`Memcached roundtrip failed: ${String(cause)}`),
65 });
66
67 const ProvisionedCacheDataPlaneLive = ProvisionedCacheDataPlaneFunction.make(
68 Effect.succeed({
69 main: import.meta.url,
70 functionUrl: true,
71 timeout: Duration.seconds(30),
72 memorySize: 256,
73 }),
74 Effect.gen(function* () {
75 const net = yield* getProvisionedNetwork;
76 const lambdaSecurityGroup = yield* AWS.EC2.SecurityGroup("LambdaSecurityGroup", {
77 vpcId: net.vpcId,
78 description: "Provisioned ElastiCache data-plane test Lambda",
79 });
80 yield* AWS.EC2.SecurityGroupRule("ValkeyIngress", {
81 groupId: net.securityGroupId,
82 type: "ingress",
83 ipProtocol: "tcp",
84 fromPort: 6379,
85 toPort: 6379,
86 referencedGroupId: lambdaSecurityGroup.groupId,
87 });
88 yield* AWS.EC2.SecurityGroupRule("MemcachedIngress", {
89 groupId: net.securityGroupId,
90 type: "ingress",
91 ipProtocol: "tcp",
92 fromPort: 11211,
93 toPort: 11211,
94 referencedGroupId: lambdaSecurityGroup.groupId,
95 });
96 const valkey = yield* AWS.ElastiCache.ReplicationGroup("Valkey", {
97 description: "Alchemy provisioned Valkey data-plane test",
98 engine: "valkey",
99 nodeType: "cache.t4g.micro",
100 subnetGroupName: net.subnetGroupName,
101 securityGroupIds: [net.securityGroupId],
102 replicasPerNodeGroup: 0,
103 transitEncryptionEnabled: false,
104 });
105 const memcached = yield* AWS.ElastiCache.CacheCluster("Memcached", {
106 nodeType: "cache.t4g.micro",
107 subnetGroupName: net.subnetGroupName,
108 securityGroupIds: [net.securityGroupId],
109 numCacheNodes: 1,
110 });
111 const valkeyConnection = yield* AWS.ElastiCache.ConnectReplicationGroup(valkey, {
112 subnetIds: net.subnetIds,
113 securityGroupIds: [lambdaSecurityGroup.groupId],
114 });
115 const memcachedConnection = yield* AWS.ElastiCache.ConnectCacheCluster(memcached, {
116 subnetIds: net.subnetIds,
117 securityGroupIds: [lambdaSecurityGroup.groupId],
118 });
119
120 return {
121 fetch: Effect.gen(function* () {
122 const request = yield* HttpServerRequest;
123 const url = new URL(request.originalUrl);
124 const value = url.searchParams.get("value") ?? "hello-provisioned";
125 if (request.method === "GET" && url.pathname === "/connection") {
126 const [valkey, memcached] = yield* Effect.all([valkeyConnection, memcachedConnection]);
127 return yield* HttpServerResponse.json({ valkey, memcached });
128 }
129 if (request.method === "GET" && url.pathname === "/valkey") {
130 const info = yield* valkeyConnection;
131 const read = yield* valkeyRoundtrip(info, value);
132 return yield* HttpServerResponse.json({ value: read });
133 }
134 if (request.method === "GET" && url.pathname === "/memcached") {
135 const info = yield* memcachedConnection;
136 const endpoint = info.endpoints[0];
137 if (endpoint === undefined) {
138 return yield* Effect.fail(new Error("Memcached endpoint is unavailable"));
139 }
140 const read = yield* memcachedRoundtrip(endpoint, value);
141 return yield* HttpServerResponse.json({ value: read });
142 }
143 return yield* HttpServerResponse.json({ error: "Not found" }, { status: 404 });
144 }).pipe(
145 Effect.catchCause((cause) =>
146 HttpServerResponse.json({ error: Cause.pretty(cause) }, { status: 500 }),
147 ),
148 ),
149 };
150 }).pipe(
151 Effect.provide(
152 Layer.mergeAll(
153 AWS.ElastiCache.ConnectReplicationGroupHttp,
154 AWS.ElastiCache.ConnectCacheClusterHttp,
155 ),
156 ),
157 ),
158 );
159
160 export default ProvisionedCacheDataPlaneLive;