@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 251 lines 10.1 KB
Raw
1 import { resolve4 } from "node:dns/promises";
2 import * as AWS from "@alchemy.run/aws";
3 import { SecurityGroupRule, type SecurityGroupId } from "@alchemy.run/aws/EC2";
4 import type { SubnetId } from "@alchemy.run/aws/EC2/Subnet";
5 import {
6 Listener,
7 ListenerRule,
8 LoadBalancer,
9 TargetGroup,
10 TargetGroupAttachment,
11 } from "@alchemy.run/aws/ELBv2";
12 import { expect } from "@alchemy.run/test";
13 import * as Test from "@alchemy.run/test/Alchemy";
14 import * as EC2 from "@distilled.cloud/aws/ec2";
15 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
16 import * as Effect from "effect/Effect";
17 import * as HttpClient from "effect/http/HttpClient";
18 import { MinimumLogLevel } from "effect/References";
19 import * as Schedule from "effect/Schedule";
20 import { getDefaultVpc } from "../DefaultVpc.ts";
21 import { ApiTargetFunction, ApiTargetFunctionLive } from "./fixtures/api-handler.ts";
22 import { WebTargetFunction, WebTargetFunctionLive } from "./fixtures/web-handler.ts";
23
24 const { test } = Test.make({ providers: AWS.providers() });
25
26 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
27
28 // The flagship ELBv2 e2e: one internet-facing ALB routes two path patterns to
29 // two different Lambda targets (no VPC targets, no NAT — Lambda targets prove
30 // the rule routing end-to-end). A new ALB stays in `provisioning` with an
31 // unresolvable hostname for ~1-3 minutes, so the test waits for `active`
32 // before resolving DNS (~2.5 min end to end) and is skipped under --fast.
33 test.provider.skipIf(!!process.env.FAST)(
34 "ALB routes two paths to two Lambda targets",
35 (stack) =>
36 Effect.gen(function* () {
37 yield* stack.destroy();
38
39 const defaultVpc = yield* getDefaultVpc;
40
41 // Use the default VPC's EXISTING default subnets + default SG rather
42 // than creating our own. An ALB leaves ENIs that take minutes to
43 // release after deletion; a stack-managed subnet/SG cannot delete until
44 // those ENIs clear, which blew the whole test past its wall on
45 // teardown. Pre-existing, non-stack-managed network resources are never
46 // torn down, so teardown is just ALB + target groups + listener.
47 const subnetResult = yield* EC2.describeSubnets({
48 Filters: [
49 { Name: "vpc-id", Values: [defaultVpc.vpcId] },
50 { Name: "default-for-az", Values: ["true"] },
51 ],
52 });
53 const subnetIds = (subnetResult.Subnets ?? [])
54 .flatMap((s) => (s.SubnetId ? [s.SubnetId as SubnetId] : []))
55 .slice(0, 2);
56 expect(subnetIds.length).toBe(2);
57
58 const groupResult = yield* EC2.describeSecurityGroups({
59 Filters: [
60 { Name: "vpc-id", Values: [defaultVpc.vpcId] },
61 { Name: "group-name", Values: ["default"] },
62 ],
63 });
64 const defaultGroupId = groupResult.SecurityGroups?.[0]?.GroupId as SecurityGroupId;
65 expect(defaultGroupId).toBeTruthy();
66
67 const out = yield* stack.deploy(
68 Effect.gen(function* () {
69 const apiFn = yield* ApiTargetFunction.pipe(Effect.provide(ApiTargetFunctionLive));
70 const webFn = yield* WebTargetFunction.pipe(Effect.provide(WebTargetFunctionLive));
71
72 // Add one stack-owned ingress rule to the standing default SG. The
73 // ALB uses only pre-existing network containers, so teardown does
74 // not spend minutes waiting for ALB ENIs before deleting an SG.
75 yield* SecurityGroupRule("LtIngress", {
76 groupId: defaultGroupId,
77 type: "ingress",
78 ipProtocol: "tcp",
79 fromPort: 80,
80 toPort: 80,
81 cidrIpv4: "0.0.0.0/0",
82 description: "Alchemy ELBv2 Lambda-target e2e",
83 });
84
85 const lb = yield* LoadBalancer("LtLb", {
86 type: "application",
87 scheme: "internet-facing",
88 subnets: subnetIds,
89 securityGroups: [defaultGroupId],
90 });
91
92 const apiTg = yield* TargetGroup("LtApiTg", {
93 targetType: "lambda",
94 });
95 const webTg = yield* TargetGroup("LtWebTg", {
96 targetType: "lambda",
97 });
98
99 // ALB validates the invoke permission at registerTargets time, so
100 // each target group needs its Permission before the attachment
101 // (the attachment retries briefly while the permission propagates).
102 yield* AWS.Lambda.Permission("LtApiInvoke", {
103 action: "lambda:InvokeFunction",
104 functionName: apiFn.functionName,
105 principal: "elasticloadbalancing.amazonaws.com",
106 sourceArn: apiTg.targetGroupArn,
107 });
108 yield* AWS.Lambda.Permission("LtWebInvoke", {
109 action: "lambda:InvokeFunction",
110 functionName: webFn.functionName,
111 principal: "elasticloadbalancing.amazonaws.com",
112 sourceArn: webTg.targetGroupArn,
113 });
114
115 const apiAttachment = yield* TargetGroupAttachment("LtApiTarget", {
116 targetGroupArn: apiTg.targetGroupArn,
117 targetId: apiFn.functionArn,
118 });
119 const webAttachment = yield* TargetGroupAttachment("LtWebTarget", {
120 targetGroupArn: webTg.targetGroupArn,
121 targetId: webFn.functionArn,
122 });
123
124 const listener = yield* Listener("LtListener", {
125 loadBalancerArn: lb.loadBalancerArn,
126 port: 80,
127 protocol: "HTTP",
128 defaultActions: [
129 {
130 type: "fixedResponse",
131 statusCode: "404",
132 contentType: "text/plain",
133 messageBody: "no rule matched",
134 },
135 ],
136 });
137 yield* ListenerRule("LtApiRule", {
138 listenerArn: listener.listenerArn,
139 priority: 10,
140 conditions: [{ pathPattern: { values: ["/api/*"] } }],
141 actions: [
142 {
143 type: "forward",
144 targetGroups: [{ targetGroupArn: apiTg.targetGroupArn }],
145 },
146 ],
147 });
148 yield* ListenerRule("LtWebRule", {
149 listenerArn: listener.listenerArn,
150 priority: 20,
151 conditions: [{ pathPattern: { values: ["/web/*"] } }],
152 actions: [
153 {
154 type: "forward",
155 targetGroups: [{ targetGroupArn: webTg.targetGroupArn }],
156 },
157 ],
158 });
159
160 return {
161 dnsName: lb.dnsName,
162 loadBalancerArn: lb.loadBalancerArn,
163 apiTargetGroupArn: apiAttachment.targetGroupArn,
164 webTargetGroupArn: webAttachment.targetGroupArn,
165 apiFunctionArn: apiAttachment.targetId,
166 webFunctionArn: webAttachment.targetId,
167 };
168 }),
169 );
170
171 // Out-of-band: both Lambda targets are registered.
172 const apiHealth = yield* elbv2.describeTargetHealth({
173 TargetGroupArn: out.apiTargetGroupArn,
174 });
175 expect(
176 apiHealth.TargetHealthDescriptions?.some((d) => d.Target?.Id === out.apiFunctionArn),
177 ).toBe(true);
178 const webHealth = yield* elbv2.describeTargetHealth({
179 TargetGroupArn: out.webTargetGroupArn,
180 });
181 expect(
182 webHealth.TargetHealthDescriptions?.some((d) => d.Target?.Id === out.webFunctionArn),
183 ).toBe(true);
184
185 // A new ALB sits in `provisioning` (hostname not yet in DNS) for ~1-3
186 // minutes. Wait until AWS reports it `active` before touching DNS so a
187 // negative lookup is never cached (bounded: 18 × 10s).
188 yield* elbv2.describeLoadBalancers({ LoadBalancerArns: [out.loadBalancerArn] }).pipe(
189 Effect.flatMap((r) =>
190 r.LoadBalancers?.[0]?.State?.Code === "active"
191 ? Effect.void
192 : Effect.fail(new Error(`ALB ${out.dnsName} is not active yet`)),
193 ),
194 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 18 }),
195 );
196
197 // Resolve the newly-created ALB explicitly before the first HTTP
198 // request. Starting fetch while its hostname is still propagating can
199 // retain the negative DNS lookup for every retry in this process.
200 const [albAddress] = yield* Effect.tryPromise(() => resolve4(out.dnsName)).pipe(
201 Effect.flatMap((addresses) =>
202 addresses[0]
203 ? Effect.succeed(addresses)
204 : Effect.fail(new Error(`ALB ${out.dnsName} has no IPv4 address`)),
205 ),
206 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 8 }),
207 );
208
209 // Drive both paths through the public ALB address. Keep readiness under
210 // 50 seconds and probe both targets in parallel so one Lambda cold start
211 // does not serialize the other.
212 const getJson = (url: string) =>
213 HttpClient.get(url).pipe(
214 Effect.flatMap((response) =>
215 response.status === 200
216 ? response.json
217 : Effect.fail(new Error(`ALB returned ${response.status}`)),
218 ),
219 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 10 }),
220 );
221
222 const baseUrl = `http://${albAddress}`;
223 const [apiBody, webBody] = (yield* Effect.all(
224 [getJson(`${baseUrl}/api/hello`), getJson(`${baseUrl}/web/hello`)],
225 { concurrency: "unbounded" },
226 )) as [{ target: string; path: string }, { target: string; path: string }];
227 expect(apiBody.target).toBe("api");
228 expect(apiBody.path).toBe("/api/hello");
229 expect(webBody.target).toBe("web");
230 expect(webBody.path).toBe("/web/hello");
231
232 // Unmatched paths hit the listener's fixed-response default action.
233 const fallback = yield* HttpClient.get(`${baseUrl}/nope`);
234 expect(fallback.status).toBe(404);
235
236 yield* stack.destroy();
237
238 // Out-of-band: the target groups are gone after destroy.
239 const after = yield* elbv2
240 .describeTargetGroups({ TargetGroupArns: [out.apiTargetGroupArn] })
241 .pipe(
242 Effect.map((r) => r.TargetGroups?.length ?? 0),
243 Effect.catchTag("TargetGroupNotFoundException", () => Effect.succeed(0)),
244 );
245 expect(after).toBe(0);
246 }).pipe(logLevel),
247 {
248 tags: ["provider:aws", "provider:aws:ec2", "provider:aws:elbv2", "provider:aws:lambda", "live"],
249 timeout: 420_000,
250 },
251 );