@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 157 lines 6.04 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import type { CacheConnectionInfo } from "@alchemy.run/aws/ElastiCache";
3 import * as EC2 from "@distilled.cloud/aws/ec2";
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 { getDefaultVpc } from "../DefaultVpc.ts";
11 import { FixtureCache, FixtureCacheLive } from "./fixture-cache.ts";
12
13 export class ElastiCacheTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
14 "ElastiCacheTestFunction",
15 ) {}
16
17 /**
18 * Resolve the default VPC's default-for-AZ subnets and its DEFAULT security
19 * group for the fixture Lambda's VPC attachment.
20 *
21 * The default group is used on purpose (same rationale as the EFS Lambda
22 * mount test): its self-referencing ingress rule allows the Lambda ENI to
23 * reach the cache endpoint on 6379 (the serverless cache sits in the same
24 * default VPC + default SG by API default), and because the default group is
25 * never deleted, destroy avoids the ~20-minute Hyperplane ENI release that
26 * blocks deleting a security group that was attached to a Lambda.
27 *
28 * Runtime-guarded: the Lambda runtime re-executes this props effect on cold
29 * start, but VPC attachment is deploy-time-only configuration and the
30 * execution role has no ec2:Describe* permissions — return `undefined` there
31 * without touching the EC2 API.
32 */
33 const resolveFixtureVpc = Effect.gen(function* () {
34 if (globalThis.__ALCHEMY_RUNTIME__) {
35 return undefined;
36 }
37 const vpc = yield* getDefaultVpc;
38 const subnets = yield* EC2.describeSubnets({
39 Filters: [
40 { Name: "vpc-id", Values: [vpc.vpcId] },
41 { Name: "default-for-az", Values: ["true"] },
42 ],
43 });
44 const subnetIds = (subnets.Subnets ?? [])
45 .map((subnet) => subnet.SubnetId)
46 .filter((subnetId): subnetId is string => subnetId !== undefined)
47 .sort()
48 .slice(0, 2);
49 const groups = yield* EC2.describeSecurityGroups({
50 Filters: [
51 { Name: "vpc-id", Values: [vpc.vpcId] },
52 { Name: "group-name", Values: ["default"] },
53 ],
54 });
55 const securityGroupId = groups.SecurityGroups?.[0]?.GroupId;
56 if (subnetIds.length === 0 || securityGroupId === undefined) {
57 return yield* Effect.die(
58 new Error("default VPC is missing default-for-AZ subnets or its default security group"),
59 );
60 }
61 return { subnetIds, securityGroupIds: [securityGroupId] };
62 }).pipe(Effect.orDie);
63
64 /**
65 * SET then GET a key through the serverless cache with iovalkey. Serverless
66 * caches only accept TLS connections, so `tls` is always enabled from the
67 * binding's connection info. One client per request: connect, round-trip,
68 * disconnect — sockets must not be retained across invocations.
69 */
70 const cacheRoundtrip = (info: CacheConnectionInfo, value: string) =>
71 Effect.tryPromise({
72 try: async () => {
73 const client = new Valkey({
74 host: info.host,
75 port: info.port,
76 ...(info.tls ? { tls: {} } : {}),
77 connectTimeout: 10_000,
78 maxRetriesPerRequest: 2,
79 // Fail fast instead of reconnecting forever — the route must answer
80 // (or error) within the Lambda's 30s timeout.
81 retryStrategy: (times) => (times > 2 ? null : 500),
82 });
83 try {
84 await client.set("alchemy:elasticache:roundtrip", value);
85 return await client.get("alchemy:elasticache:roundtrip");
86 } finally {
87 client.disconnect();
88 }
89 },
90 catch: (cause) => new Error(`valkey roundtrip failed: ${String(cause)}`),
91 });
92
93 /**
94 * VPC-attached fixture Lambda exercising the full ElastiCache data plane:
95 *
96 * - `/connection` returns the endpoint the env-only Connect binding resolved
97 * from the injected environment.
98 * - `/roundtrip?value=...` SETs then GETs a key through the cache over TLS
99 * with iovalkey and returns the read-back value.
100 *
101 * The control-plane snapshot binding lives on a separate, non-VPC fixture
102 * (`snapshot-handler.ts`): this function's VPC has no route to the
103 * ElastiCache API.
104 */
105 export const ElastiCacheTestFunctionLive = ElastiCacheTestFunction.make(
106 Effect.gen(function* () {
107 const vpc = yield* resolveFixtureVpc;
108 return {
109 main: import.meta.url,
110 functionUrl: true,
111 timeout: Duration.seconds(30),
112 memorySize: 256,
113 ...(vpc === undefined ? {} : { vpc }),
114 };
115 }),
116 Effect.gen(function* () {
117 const { cache } = yield* FixtureCache;
118 const connection = yield* AWS.ElastiCache.Connect(cache);
119
120 return {
121 fetch: Effect.gen(function* () {
122 const request = yield* HttpServerRequest;
123 const url = new URL(request.originalUrl);
124 const pathname = url.pathname;
125
126 if (request.method === "GET" && pathname === "/ready") {
127 return yield* HttpServerResponse.json({ ok: true });
128 }
129
130 if (request.method === "GET" && pathname === "/connection") {
131 return yield* HttpServerResponse.json(yield* connection);
132 }
133
134 if (request.method === "GET" && pathname === "/roundtrip") {
135 const info = yield* connection;
136 const value = url.searchParams.get("value") ?? "hello-valkey";
137 return yield* cacheRoundtrip(info, value).pipe(
138 Effect.flatMap((read) => HttpServerResponse.json({ value: read })),
139 Effect.catch((error) =>
140 HttpServerResponse.json({ error: String(error) }, { status: 500 }),
141 ),
142 );
143 }
144
145 return yield* HttpServerResponse.json(
146 { error: "Not found", method: request.method, pathname },
147 { status: 404 },
148 );
149 }).pipe(Effect.orDie),
150 };
151 }).pipe(Effect.provide(Layer.mergeAll(AWS.ElastiCache.ConnectHttp, FixtureCacheLive))),
152 // Re-merge so the deploying Stack can `yield* FixtureCache` and expose the
153 // cache attributes as deploy-time outputs. Reusing the same
154 // `FixtureCacheLive` reference keeps it a single shared cache.
155 ).pipe(Layer.provideMerge(FixtureCacheLive));
156
157 export default ElastiCacheTestFunctionLive;