@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 271 lines 10.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import type { SubnetId } from "@alchemy.run/aws/EC2/Subnet";
3 import {
4 DeregisterTargets,
5 DeregisterTargetsHttp,
6 DescribeCapacityReservation,
7 DescribeCapacityReservationHttp,
8 DescribeTargetHealth,
9 DescribeTargetHealthHttp,
10 GetTrustStoreCaCertificatesBundle,
11 GetTrustStoreCaCertificatesBundleHttp,
12 GetTrustStoreRevocationContent,
13 GetTrustStoreRevocationContentHttp,
14 LoadBalancer,
15 ModifyCapacityReservation,
16 ModifyCapacityReservationHttp,
17 RegisterTargets,
18 RegisterTargetsHttp,
19 TargetGroup,
20 TrustStore,
21 } from "@alchemy.run/aws/ELBv2";
22 import { Bucket } from "@alchemy.run/aws/S3";
23 import * as ec2 from "@distilled.cloud/aws/ec2";
24 import * as Context from "effect/Context";
25 import * as Effect from "effect/Effect";
26 import { HttpServerRequest } from "effect/http/HttpServerRequest";
27 import * as HttpServerResponse from "effect/http/HttpServerResponse";
28 import * as Layer from "effect/Layer";
29
30 /**
31 * An RFC1918 IP outside the default VPC's CIDR. RegisterTargets accepts
32 * out-of-VPC private addresses when `AvailabilityZone: "all"` is specified —
33 * no live target is needed (this TG isn't attached to a listener, so the
34 * health state is `unused`).
35 */
36 export const testTargetIp = "192.168.100.10";
37
38 /** S3 key of the trust store's CA bundle (uploaded out-of-band by the test). */
39 export const bundleKey = "ca-bundle.pem";
40
41 // A self-signed CA certificate generated once and checked in (never created
42 // at test time, per the fixture convention). X.509 v3 with basicConstraints
43 // CA:TRUE + keyCertSign — ELBv2 trust stores reject v1 certs.
44 export const CA_BUNDLE_PEM = `-----BEGIN CERTIFICATE-----
45 MIIC2jCCAcKgAwIBAgIJAJyM/Dvd55qtMA0GCSqGSIb3DQEBCwUAMBoxGDAWBgNV
46 BAMMD2FsY2hlbXktdGVzdC1jYTAeFw0yNjA2MTcwNjA5MDlaFw0zNjA2MTQwNjA5
47 MDlaMBoxGDAWBgNVBAMMD2FsY2hlbXktdGVzdC1jYTCCASIwDQYJKoZIhvcNAQEB
48 BQADggEPADCCAQoCggEBANgo7XPCQMpyecXg2SCj6Tn6R1snlmhSA1vKGQnHoQBS
49 QA11DMpv+iFRT9s1d3izaGA4GEcxfrXOsmUBkzYIHJIYakCWdr6qcUXs6lS2uhnZ
50 qcyR0CamDtHTqAxRKEK+QPaISoxyD3BIwQqE0I8yNzV3/6osIE513e+7tp9E+J04
51 dBhyG5goSwR3ueqs53gQioYVp/fgLKo4MqFcsA3p7anEE9hyeq1Q/lGAXxQwZmXT
52 3kQli/JjMoF8OfccpA3aBx9Y2aDTCU8HXTscVYmPSHbnTGkTARGBwnag+Jwq5Uni
53 YvM2OeDUPwvszgpi3JgiblZQhZQAy4/MeNhmE8qgIa8CAwEAAaMjMCEwDwYDVR0T
54 AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggEBAJnp
55 el0xBbL/eQY87evhy0o+ZTHMVCdI9Uc+kDK0XPMi4hc5OfjWNIy8u5/s33kPkNYS
56 Y5Jhm5KtGtMb9kXioCWjSi0aREA8zijGrXn1jC+0rksMQmJka63bKsJ4TjFaHMcc
57 m/xt25xX1Ssp/gWr9YX3MzbPhcn57Uu9OTtzf13F6CMv1XtRS1RKFYtkLZrhvzBR
58 WPdos3xvn3D0Fjd5H5AgVKTkeb2YPhINfN4jyzn3J09teKZpNN/qHTAQewIh2FnO
59 MeplcuT3eQVUZNTBelvUE7VKHe11AUc8TkvVMS/XOFeN6OHAJtq08EegbTcjwz9Z
60 lyGGetkNMmdhGRV6AlY=
61 -----END CERTIFICATE-----
62 `;
63
64 export class ElbBindingsFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
65 "ElbBindingsFunction",
66 ) {}
67
68 /**
69 * Shared fleet for the bindings E2E: an unattached `ip` target group (targets
70 * register/deregister without a listener) plus an internal ALB for the
71 * capacity-reservation bindings. VPC/subnets are resolved only at deploy
72 * time — at runtime the resources resolve to references, so the lookups are
73 * guarded off inside the deployed Lambda.
74 */
75 export class BindingsFleet extends Context.Service<
76 BindingsFleet,
77 {
78 targetGroup: TargetGroup;
79 loadBalancer: LoadBalancer;
80 trustStore: TrustStore;
81 }
82 >()("ELBv2BindingsFleet") {}
83
84 export const BindingsFleetLive = Layer.effect(
85 BindingsFleet,
86 Effect.gen(function* () {
87 const isDeploy = !globalThis.__ALCHEMY_RUNTIME__;
88 const vpcId = isDeploy
89 ? yield* ec2
90 .describeVpcs({
91 Filters: [{ Name: "isDefault", Values: ["true"] }],
92 })
93 .pipe(
94 Effect.map((r) => r.Vpcs?.[0]?.VpcId ?? "vpc-0"),
95 // Deploy-time lookup only; a failure here is a fixture defect, not
96 // a typed error the Function impl contract can carry.
97 Effect.orDie,
98 )
99 : "vpc-0";
100 const subnetIds = isDeploy
101 ? yield* ec2
102 .describeSubnets({
103 Filters: [
104 { Name: "vpc-id", Values: [vpcId] },
105 { Name: "default-for-az", Values: ["true"] },
106 ],
107 })
108 .pipe(
109 Effect.map((r) =>
110 (r.Subnets ?? [])
111 .flatMap((s) => (s.SubnetId ? [s.SubnetId as SubnetId] : []))
112 .slice(0, 2),
113 ),
114 Effect.orDie,
115 )
116 : (["subnet-0", "subnet-1"] as SubnetId[]);
117
118 const targetGroup = yield* TargetGroup("ElbBindingsTg", {
119 vpcId,
120 port: 80,
121 protocol: "HTTP",
122 targetType: "ip",
123 });
124 const loadBalancer = yield* LoadBalancer("ElbBindingsLb", {
125 type: "application",
126 scheme: "internal",
127 subnets: subnetIds,
128 });
129 // The CA bundle object is uploaded out-of-band by the test between the
130 // bucket-only phase-1 deploy and the full fixture deploy (there is no
131 // declarative S3 object resource yet).
132 const bucket = yield* Bucket("ElbBindingsBundleBucket", {
133 forceDestroy: true,
134 });
135 const trustStore = yield* TrustStore("ElbBindingsTrustStore", {
136 caCertificatesBundleS3Bucket: bucket.bucketName,
137 caCertificatesBundleS3Key: bundleKey,
138 });
139 return { targetGroup, loadBalancer, trustStore };
140 }),
141 );
142
143 export default ElbBindingsFunction.make(
144 {
145 main: import.meta.url,
146 functionUrl: true,
147 },
148 Effect.gen(function* () {
149 const { targetGroup, loadBalancer, trustStore } = yield* BindingsFleet;
150
151 const registerTargets = yield* RegisterTargets(targetGroup);
152 const deregisterTargets = yield* DeregisterTargets(targetGroup);
153 const describeTargetHealth = yield* DescribeTargetHealth(targetGroup);
154 const describeCapacityReservation = yield* DescribeCapacityReservation(loadBalancer);
155 const modifyCapacityReservation = yield* ModifyCapacityReservation(loadBalancer);
156 const getCaCertificatesBundle = yield* GetTrustStoreCaCertificatesBundle(trustStore);
157 const getRevocationContent = yield* GetTrustStoreRevocationContent(trustStore);
158
159 return {
160 fetch: Effect.gen(function* () {
161 const request = yield* HttpServerRequest;
162 const pathname = new URL(request.originalUrl).pathname;
163
164 if (request.method === "GET" && pathname === "/health") {
165 return yield* HttpServerResponse.json({ ok: true });
166 }
167
168 if (request.method === "POST" && pathname === "/register") {
169 const result = yield* registerTargets({
170 Targets: [{ Id: testTargetIp, Port: 80, AvailabilityZone: "all" }],
171 }).pipe(Effect.result);
172 return yield* HttpServerResponse.json({
173 ok: result._tag === "Success",
174 tag: result._tag === "Failure" ? result.failure._tag : "Success",
175 message: result._tag === "Failure" ? String(result.failure) : undefined,
176 });
177 }
178
179 if (request.method === "GET" && pathname === "/target-health") {
180 const result = yield* describeTargetHealth({}).pipe(Effect.result);
181 return yield* HttpServerResponse.json({
182 ok: result._tag === "Success",
183 tag: result._tag === "Failure" ? result.failure._tag : "Success",
184 targets:
185 result._tag === "Success"
186 ? (result.success.TargetHealthDescriptions ?? []).map((d) => ({
187 id: d.Target?.Id,
188 state: d.TargetHealth?.State,
189 }))
190 : undefined,
191 });
192 }
193
194 if (request.method === "POST" && pathname === "/deregister") {
195 const result = yield* deregisterTargets({
196 Targets: [{ Id: testTargetIp, Port: 80, AvailabilityZone: "all" }],
197 }).pipe(Effect.result);
198 return yield* HttpServerResponse.json({
199 ok: result._tag === "Success",
200 tag: result._tag === "Failure" ? result.failure._tag : "Success",
201 });
202 }
203
204 if (request.method === "GET" && pathname === "/capacity") {
205 const result = yield* describeCapacityReservation().pipe(Effect.result);
206 return yield* HttpServerResponse.json({
207 ok: result._tag === "Success",
208 tag: result._tag === "Failure" ? result.failure._tag : "Success",
209 states:
210 result._tag === "Success"
211 ? (result.success.CapacityReservationState ?? []).map((s) => s.State)
212 : undefined,
213 });
214 }
215
216 // Resets a reservation that was never set — a no-op that proves the
217 // write grant end-to-end without reserving billable LCUs.
218 if (request.method === "POST" && pathname === "/capacity-reset") {
219 const result = yield* modifyCapacityReservation({
220 ResetCapacityReservation: true,
221 }).pipe(Effect.result);
222 return yield* HttpServerResponse.json({
223 ok: result._tag === "Success",
224 tag: result._tag === "Failure" ? result.failure._tag : "Success",
225 });
226 }
227
228 if (request.method === "GET" && pathname === "/truststore-bundle") {
229 const result = yield* getCaCertificatesBundle().pipe(Effect.result);
230 return yield* HttpServerResponse.json({
231 ok: result._tag === "Success",
232 tag: result._tag === "Failure" ? result.failure._tag : "Success",
233 // A presigned S3 URL, valid for ten minutes.
234 location: result._tag === "Success" ? result.success.Location : undefined,
235 });
236 }
237
238 // Queries a revocation id that was never added — proves the IAM grant
239 // and that the miss surfaces as the typed tag, without needing a CRL
240 // fixture.
241 if (request.method === "GET" && pathname === "/truststore-revocation-missing") {
242 const result = yield* getRevocationContent({
243 RevocationId: 424242,
244 }).pipe(Effect.result);
245 return yield* HttpServerResponse.json({
246 ok: result._tag === "Success",
247 tag: result._tag === "Failure" ? result.failure._tag : "Success",
248 });
249 }
250
251 return yield* HttpServerResponse.json(
252 { error: "Not found", method: request.method, pathname },
253 { status: 404 },
254 );
255 }).pipe(Effect.orDie),
256 };
257 }).pipe(
258 Effect.provide(
259 Layer.mergeAll(
260 RegisterTargetsHttp,
261 DeregisterTargetsHttp,
262 DescribeTargetHealthHttp,
263 DescribeCapacityReservationHttp,
264 ModifyCapacityReservationHttp,
265 GetTrustStoreCaCertificatesBundleHttp,
266 GetTrustStoreRevocationContentHttp,
267 BindingsFleetLive,
268 ),
269 ),
270 ),
271 );