@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 262 lines 10.7 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Cluster } from "@alchemy.run/aws/ECS/Cluster";
3 import { Service } from "@alchemy.run/aws/ECS/Service";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as aas from "@distilled.cloud/aws/application-auto-scaling";
7 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
8 import * as ec2 from "@distilled.cloud/aws/ec2";
9 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as Redacted from "effect/Redacted";
14 import * as Schedule from "effect/Schedule";
15 import { getDefaultVpcNetwork } from "../DefaultVpc.ts";
16
17 const { test } = Test.make({ providers: AWS.providers() });
18
19 class RouteMismatch extends Data.TaggedError("RouteMismatch")<{
20 readonly path: string;
21 readonly status: number;
22 readonly body: string;
23 }> {}
24
25 // The container compares its secret-sourced env vars against the KNOWN seed
26 // values and serves PRESENCE booleans (never the values) plus a /health
27 // route via busybox httpd.
28 //
29 // NOTE: an Effect-native fixture (`main:` + `{ fetch }`) would be the
30 // preferred shape here, but the Platform class form with Effect-valued
31 // props (needed to reference the cluster/parameter/secret) currently OOMs
32 // during construction — a pre-existing Platform.ts bug independent of the
33 // props under test. The external `image:` form covers the same Phase-2
34 // surface: `secrets`, `loadBalancer.health`, `scaling`, and
35 // `logging.retention` are all provider/composition-level features.
36 const SERVE_SCRIPT = [
37 "mkdir -p /www",
38 `if [ "$PHASE2_PARAM" = "phase2-parameter-value" ] && [ "$PHASE2_SECRET" = "phase2-secret-value" ]; then echo '{"param":true,"secret":true}' > /www/secrets; else echo '{"param":false,"secret":false}' > /www/secrets; fi`,
39 "echo ok > /www/health",
40 "exec httpd -f -p 3000 -h /www",
41 ].join(" && ");
42
43 // Phase-2 kitchen sink: one service exercising `secrets` (SSM parameter +
44 // Secrets Manager secret injected via valueFrom), `loadBalancer.health`
45 // (per-TG override to /health), `scaling` (CPU + ALB request-count target
46 // tracking; asserted by describing the scalable target + policies, NOT by
47 // waiting for a scale event), and `logging.retention` — with a live HTTP
48 // round-trip over the owned ALB proving the container runs, the health
49 // override passes, and the secrets arrived (presence only).
50 //
51 // Requires a local Docker daemon (the `image:` source mirrors into ECR).
52 test.provider.skipIf(!!process.env.FAST)(
53 "phase2 service wires secrets, health overrides, scaling, and log retention",
54 (stack) =>
55 Effect.gen(function* () {
56 yield* stack.destroy();
57 const net = yield* getDefaultVpcNetwork;
58 const client = yield* HttpClient.HttpClient;
59
60 // Only the per-AZ default subnets: concurrent suites create extra
61 // subnets, and an ALB rejects two subnets in one AZ.
62 const azSubnets = yield* ec2
63 .describeSubnets({
64 Filters: [
65 { Name: "vpc-id", Values: [net.vpcId] },
66 { Name: "default-for-az", Values: ["true"] },
67 ],
68 })
69 .pipe(
70 Effect.map((r) => (r.Subnets ?? []).flatMap((s) => (s.SubnetId ? [s.SubnetId] : []))),
71 );
72
73 const deployed = yield* stack.deploy(
74 Effect.gen(function* () {
75 const cluster = yield* Cluster("Phase2Cluster", {
76 clusterName: "alchemy-test-ecs-phase2",
77 });
78 const parameter = yield* AWS.SSM.Parameter("Phase2Param", {
79 value: "phase2-parameter-value",
80 });
81 const secret = yield* AWS.SecretsManager.Secret("Phase2Secret", {
82 secretString: Redacted.make("phase2-secret-value"),
83 });
84 const service = yield* Service("Phase2Api", {
85 cluster,
86 image: "busybox:stable",
87 command: ["sh", "-c", SERVE_SCRIPT],
88 port: 3000,
89 desiredCount: 1,
90 // Run on ARM64 so the locally-cached (Apple Silicon) busybox the
91 // mirror pushes matches the Fargate runtime architecture.
92 runtimePlatform: {
93 cpuArchitecture: "ARM64",
94 operatingSystemFamily: "LINUX",
95 },
96 vpcId: net.vpcId as string,
97 subnets: azSubnets,
98 // Default-VPC public subnets: tasks need a public IP to pull
99 // the mirrored image from ECR without a NAT.
100 assignPublicIp: true,
101 loadBalancer: {
102 rules: [{ listen: "80/http" }],
103 health: {
104 "3000/http": {
105 path: "/health",
106 interval: "15 seconds",
107 successCodes: "200",
108 },
109 },
110 },
111 scaling: {
112 min: 1,
113 max: 2,
114 cpuUtilization: 70,
115 requestCount: 500,
116 scaleInCooldown: "2 minutes",
117 },
118 secrets: {
119 PHASE2_PARAM: parameter.parameterArn,
120 PHASE2_SECRET: secret.secretArn,
121 },
122 logging: { retention: "3 days" },
123 });
124 return {
125 url: service.url.as<string>(),
126 serviceName: service.serviceName.as<string>(),
127 clusterArn: service.clusterArn.as<string>(),
128 loadBalancerArn: service.loadBalancerArn.as<string>(),
129 targetGroupArn: service.targetGroupArn.as<string>(),
130 logGroupName: service.logGroupName.as<string>(),
131 };
132 }),
133 );
134
135 expect(deployed.url).toMatch(/^http:\/\//);
136
137 // ── live round-trip: /health (the overridden TG path) + /secrets ──
138 const fetchRoute = (path: string) =>
139 client
140 .get(`${deployed.url}${path}`)
141 .pipe(
142 Effect.flatMap((res) => Effect.map(res.text, (body) => ({ status: res.status, body }))),
143 );
144 const awaitRoute = (path: string, predicate: (body: string) => boolean) =>
145 fetchRoute(path).pipe(
146 Effect.flatMap(({ status, body }) =>
147 status === 200 && predicate(body)
148 ? Effect.succeed(body)
149 : Effect.fail(new RouteMismatch({ path, status, body })),
150 ),
151 // ALB provisioning (~2 min) + image mirror + Fargate start.
152 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 60 }),
153 );
154
155 yield* awaitRoute("/health", (body) => body.includes("ok"));
156 const secretsBody = yield* awaitRoute("/secrets", (body) => body.includes("true"));
157 const seen = JSON.parse(secretsBody) as {
158 param: boolean;
159 secret: boolean;
160 };
161 expect(seen.param).toBe(true);
162 expect(seen.secret).toBe(true);
163 // The secret VALUES never leave the container.
164 expect(secretsBody).not.toContain("phase2-parameter-value");
165 expect(secretsBody).not.toContain("phase2-secret-value");
166
167 // ── per-TG health override landed on the composed target group ────
168 const targetGroups = yield* elbv2.describeTargetGroups({
169 TargetGroupArns: [deployed.targetGroupArn],
170 });
171 const targetGroup = targetGroups.TargetGroups?.[0];
172 expect(targetGroup?.HealthCheckPath).toBe("/health");
173 expect(targetGroup?.HealthCheckIntervalSeconds).toBe(15);
174 expect(targetGroup?.Matcher?.HttpCode).toBe("200");
175
176 // ── scaling: scalable target (min/max) + one policy per metric ────
177 const resourceId = `service/alchemy-test-ecs-phase2/${deployed.serviceName}`;
178 const targets = yield* aas.describeScalableTargets({
179 ServiceNamespace: "ecs",
180 ResourceIds: [resourceId],
181 });
182 const scalableTarget = targets.ScalableTargets?.[0];
183 expect(scalableTarget?.MinCapacity).toBe(1);
184 expect(scalableTarget?.MaxCapacity).toBe(2);
185
186 const policies = yield* aas.describeScalingPolicies({
187 ServiceNamespace: "ecs",
188 ResourceId: resourceId,
189 });
190 const trackingConfigs = (policies.ScalingPolicies ?? []).map(
191 (policy) => policy.TargetTrackingScalingPolicyConfiguration,
192 );
193 expect(trackingConfigs.length).toBe(2);
194 const cpuPolicy = trackingConfigs.find(
195 (config) =>
196 config?.PredefinedMetricSpecification?.PredefinedMetricType ===
197 "ECSServiceAverageCPUUtilization",
198 );
199 expect(cpuPolicy?.TargetValue).toBe(70);
200 expect(cpuPolicy?.ScaleInCooldown).toBe(120);
201 const requestPolicy = trackingConfigs.find(
202 (config) =>
203 config?.PredefinedMetricSpecification?.PredefinedMetricType ===
204 "ALBRequestCountPerTarget",
205 );
206 expect(requestPolicy?.TargetValue).toBe(500);
207 // ResourceLabel = app/{lb-name}/{lb-id}/targetgroup/{tg-name}/{tg-id}.
208 const expectedLabel = `${deployed.loadBalancerArn.slice(
209 deployed.loadBalancerArn.indexOf("loadbalancer/") + "loadbalancer/".length,
210 )}/${deployed.targetGroupArn.slice(deployed.targetGroupArn.indexOf("targetgroup/"))}`;
211 expect(requestPolicy?.PredefinedMetricSpecification?.ResourceLabel).toBe(expectedLabel);
212
213 // ── logging.retention on the auto-created log group ───────────────
214 const logGroups = yield* logs.describeLogGroups({
215 logGroupNamePrefix: deployed.logGroupName,
216 });
217 const logGroup = (logGroups.logGroups ?? []).find(
218 (group) => group.logGroupName === deployed.logGroupName,
219 );
220 expect(logGroup?.retentionInDays).toBe(3);
221
222 // ── destroy + zero-orphan proofs ──────────────────────────────────
223 yield* stack.destroy();
224
225 const targetsAfter = yield* aas.describeScalableTargets({
226 ServiceNamespace: "ecs",
227 ResourceIds: [resourceId],
228 });
229 expect((targetsAfter.ScalableTargets ?? []).length).toBe(0);
230
231 const lbGone = yield* elbv2
232 .describeLoadBalancers({
233 LoadBalancerArns: [deployed.loadBalancerArn],
234 })
235 .pipe(
236 Effect.map((r) => (r.LoadBalancers ?? []).length === 0),
237 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.succeed(true)),
238 );
239 expect(lbGone).toBe(true);
240
241 const logGroupsAfter = yield* logs.describeLogGroups({
242 logGroupNamePrefix: deployed.logGroupName,
243 });
244 expect(
245 (logGroupsAfter.logGroups ?? []).some(
246 (group) => group.logGroupName === deployed.logGroupName,
247 ),
248 ).toBe(false);
249 }),
250 {
251 tags: [
252 "provider:aws",
253 "provider:aws:applicationautoscaling",
254 "provider:aws:ec2",
255 "provider:aws:ecs",
256 "provider:aws:secretsmanager",
257 "provider:aws:ssm",
258 "live",
259 ],
260 timeout: 900_000,
261 },
262 );