@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 214 lines 8.75 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as aas from "@distilled.cloud/aws/application-auto-scaling";
6 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Result from "effect/Result";
12 import * as Schedule from "effect/Schedule";
13 import ApplicationAutoScalingTestFunctionLive, {
14 ApplicationAutoScalingTestFunction,
15 } from "./handler";
16
17 const testOptions = { providers: AWS.providers() };
18 const { test, beforeAll, afterAll } = Test.make(testOptions);
19 const sharedStack = Core.scratchStack(testOptions, "ApplicationAutoScalingBindings");
20
21 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
22 // over 60s on a fresh deploy under parallel-suite load.
23 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
24
25 let baseUrl: string;
26
27 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
28 readonly status: number;
29 readonly body: string;
30 }> {}
31
32 // The shared Lambda fixture occasionally answers a transient 5xx under
33 // full-suite parallel load (cold re-init, IAM propagation on the freshly
34 // attached policy that the handler's `Effect.orDie` surfaces as a 500).
35 // Retry only 5xx; a genuine 4xx/assertion failure surfaces immediately.
36 const send = (request: HttpClientRequest.HttpClientRequest) =>
37 HttpClient.execute(request).pipe(
38 Effect.flatMap((response) =>
39 response.status >= 500
40 ? response.text.pipe(
41 Effect.flatMap((body) =>
42 Effect.fail(new TransientUpstream({ status: response.status, body })),
43 ),
44 )
45 : Effect.succeed(response),
46 ),
47 Effect.retry({
48 while: (e) => e._tag === "TransientUpstream",
49 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
50 }),
51 );
52
53 describe.sequential(
54 "ApplicationAutoScaling Bindings",
55 {
56 tags: [
57 "provider:aws",
58 "provider:aws:applicationautoscaling",
59 "provider:aws:dynamodb",
60 "provider:aws:lambda",
61 "live",
62 ],
63 },
64 () => {
65 beforeAll(
66 Effect.gen(function* () {
67 yield* Effect.logInfo("ApplicationAutoScaling test setup: destroying previous resources");
68 yield* sharedStack.destroy();
69
70 yield* Effect.logInfo("ApplicationAutoScaling test setup: deploying fixture");
71 const { functionUrl } = yield* sharedStack.deploy(
72 Effect.gen(function* () {
73 return yield* ApplicationAutoScalingTestFunction;
74 }).pipe(Effect.provide(ApplicationAutoScalingTestFunctionLive)),
75 );
76
77 expect(functionUrl).toBeTruthy();
78 baseUrl = functionUrl!.replace(/\/+$/, "");
79
80 const readinessUrl = `${baseUrl}/bindings`;
81 yield* Effect.logInfo(
82 `ApplicationAutoScaling test setup: probing readiness at ${readinessUrl}`,
83 );
84 yield* HttpClient.get(readinessUrl).pipe(
85 Effect.flatMap((response) =>
86 response.status === 200
87 ? Effect.succeed(response)
88 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
89 ),
90 Effect.tapError((error) =>
91 Effect.logWarning(
92 `ApplicationAutoScaling test setup: fixture not ready yet (${String(error)})`,
93 ),
94 ),
95 Effect.retry({ schedule: readinessPolicy }),
96 );
97 }),
98 { timeout: 240_000 },
99 );
100
101 afterAll(sharedStack.destroy(), { timeout: 120_000 });
102
103 describe("binding registration", () => {
104 test.provider("both capabilities initialize in the runtime", (_stack) =>
105 Effect.gen(function* () {
106 const response = yield* send(HttpClientRequest.get(`${baseUrl}/bindings`)).pipe(
107 Effect.flatMap((r) => r.json),
108 );
109 expect((response as any).bound).toEqual([
110 "describeScalingActivities",
111 "getPredictiveScalingForecast",
112 ]);
113 }),
114 );
115 });
116
117 describe("DescribeScalingActivities", () => {
118 test.provider("lists the fixture target's scaling activities", (_stack) =>
119 Effect.gen(function* () {
120 const response = yield* send(HttpClientRequest.get(`${baseUrl}/scaling-activities`)).pipe(
121 Effect.flatMap((r) => r.json),
122 );
123 // A fresh target typically has zero activities — assert the call
124 // round-trips with a well-formed page (the identity triple was
125 // injected and the IAM grant works).
126 expect(typeof (response as any).count).toBe("number");
127 }),
128 );
129 });
130
131 describe("ScalingActivityEventSource", { tags: ["provider:aws:eventbridge"] }, () => {
132 test.provider(
133 "consumeScalingActivityEvents created the EventBridge rule",
134 (_stack) =>
135 Effect.gen(function* () {
136 // The rule's physical name starts with the stack name but the
137 // 64-char rule-name budget truncates the long
138 // `BindingsTarget-ScalingActivityEvents` logical id, so scope by
139 // NamePrefix and match on the rule's event pattern instead
140 // (bounded manual pagination).
141 let rule: eventbridge.Rule | undefined;
142 let nextToken: string | undefined;
143 for (let page = 0; page < 10 && !rule; page++) {
144 const result = yield* eventbridge.listRules({
145 NamePrefix: "ApplicationAutoScalingBindings",
146 NextToken: nextToken,
147 });
148 rule = (result.Rules ?? []).find((candidate) =>
149 candidate.EventPattern?.includes("aws.application-autoscaling"),
150 );
151 nextToken = result.NextToken;
152 if (!nextToken) break;
153 }
154 expect(rule).toBeDefined();
155 expect(rule?.EventPattern).toContain("aws.application-autoscaling");
156 expect(rule?.EventPattern).toContain(
157 "Application Auto Scaling Scaling Activity State Change",
158 );
159 }),
160 { timeout: 60_000 },
161 );
162 });
163
164 describe("GetPredictiveScalingForecast", () => {
165 // Ungated probe (runs in the test process, which resolves distilled from
166 // patched `src/` via the bun export condition): predictive scaling
167 // exists only for ECS services, and for a dynamodb-namespace target the
168 // live API answers with the typed PredictiveScalingForecastNotSupported
169 // — a distilled synthetic error carved out of AccessDeniedException
170 // "GetPredictiveScalingForecast is not supported.". The namespace check
171 // runs before any existence check, so the probe needs no live target.
172 test.provider(
173 "distilled patch: non-ECS namespace surfaces the typed not-supported tag",
174 (_stack) =>
175 Effect.gen(function* () {
176 const result = yield* Effect.result(
177 aas.getPredictiveScalingForecast({
178 ServiceNamespace: "dynamodb",
179 ResourceId: "table/alchemy-probe-nonexistent",
180 ScalableDimension: "dynamodb:table:ReadCapacityUnits",
181 PolicyName: "alchemy-probe-nonexistent",
182 StartTime: new Date("2030-01-01T00:00:00Z"),
183 EndTime: new Date("2030-01-01T12:00:00Z"),
184 }),
185 );
186 expect(Result.isFailure(result)).toBe(true);
187 if (Result.isFailure(result)) {
188 expect(result.failure._tag).toBe("PredictiveScalingForecastNotSupported");
189 }
190 }),
191 );
192
193 // End-to-end through the deployed Lambda: the fixture's policy is on the
194 // dynamodb namespace, so the call is rejected with the platform
195 // not-supported error. An IAM gap would ALSO surface as an
196 // AccessDeniedException — the probe above plus the CLI-verified message
197 // ("GetPredictiveScalingForecast is not supported.") pin the platform
198 // behavior; here we accept either the synthetic tag (patched distilled
199 // in the bundle) or its base wire tag (the deployed bundle resolves
200 // distilled's built `lib/`, which only picks up the patch after the
201 // coordinator rebuilds distilled).
202 test.provider("runtime binding surfaces the typed rejection through the Lambda", (_stack) =>
203 Effect.gen(function* () {
204 const response = yield* send(HttpClientRequest.get(`${baseUrl}/forecast`)).pipe(
205 Effect.flatMap((r) => r.json),
206 );
207 expect(["PredictiveScalingForecastNotSupported", "AccessDeniedException"]).toContain(
208 (response as any).tag,
209 );
210 }),
211 );
212 });
213 },
214 );