The best way to control Claude Code, Codex and more from any computer or phone

main
ts 311 lines 11.2 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 Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import CostExplorerTestFunctionLive, { CostExplorerTestFunction } from "./handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "CostExplorerBindings");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy.
18 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
19
20 let baseUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // The shared Lambda fixture occasionally answers a transient 5xx under load
28 // (cold re-init, IAM propagation on the freshly attached policy that the
29 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
30 // 4xx/assertion failure surfaces immediately.
31 const send = (request: HttpClientRequest.HttpClientRequest) =>
32 HttpClient.execute(request).pipe(
33 Effect.flatMap((response) =>
34 response.status >= 500
35 ? response.text.pipe(
36 Effect.flatMap((body) =>
37 Effect.fail(new TransientUpstream({ status: response.status, body })),
38 ),
39 )
40 : Effect.succeed(response),
41 ),
42 Effect.retry({
43 while: (e) => e._tag === "TransientUpstream",
44 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
45 }),
46 );
47
48 const getJson = (path: string) =>
49 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
50
51 describe.sequential(
52 "CostExplorer Bindings",
53 { tags: ["provider:aws", "provider:aws:costexplorer", "provider:aws:lambda", "live"] },
54 () => {
55 beforeAll(
56 Effect.gen(function* () {
57 yield* Effect.logInfo("CostExplorer test setup: destroying previous resources");
58 yield* sharedStack.destroy();
59
60 yield* Effect.logInfo("CostExplorer test setup: deploying fixture");
61 const { functionUrl } = yield* sharedStack.deploy(
62 Effect.gen(function* () {
63 return yield* CostExplorerTestFunction;
64 }).pipe(Effect.provide(CostExplorerTestFunctionLive)),
65 );
66
67 expect(functionUrl).toBeTruthy();
68 baseUrl = functionUrl!.replace(/\/+$/, "");
69
70 const readinessUrl = `${baseUrl}/bindings`;
71 yield* Effect.logInfo(`CostExplorer test setup: probing readiness at ${readinessUrl}`);
72 yield* HttpClient.get(readinessUrl).pipe(
73 Effect.flatMap((response) =>
74 response.status === 200
75 ? Effect.succeed(response)
76 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
77 ),
78 Effect.tapError((error) =>
79 Effect.logWarning(`CostExplorer test setup: fixture not ready yet (${String(error)})`),
80 ),
81 Effect.retry({ schedule: readinessPolicy }),
82 );
83 }),
84 { timeout: 240_000 },
85 );
86
87 afterAll(sharedStack.destroy(), { timeout: 120_000 });
88
89 describe("binding registration", () => {
90 test.provider("all 31 capabilities initialize in the runtime", (_stack) =>
91 Effect.gen(function* () {
92 const response = yield* getJson("/bindings");
93 expect((response as any).bound).toHaveLength(31);
94 }),
95 );
96 });
97
98 describe("GetCostAndUsage", () => {
99 test.provider(
100 "queries last month's unblended cost",
101 (_stack) =>
102 Effect.gen(function* () {
103 const response = (yield* getJson("/cost-and-usage")) as any;
104 // A fresh account may legitimately have no ingested data yet — the
105 // typed DataUnavailableException tag is the accepted alternative.
106 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
107 if (response.tag === "Ok") {
108 expect(response.results).toBeGreaterThan(0);
109 expect(response.amount).not.toBeNull();
110 }
111 }),
112 { timeout: 60_000 },
113 );
114 });
115
116 describe("GetDimensionValues", () => {
117 test.provider(
118 "lists the SERVICE dimension values",
119 (_stack) =>
120 Effect.gen(function* () {
121 const response = (yield* getJson("/dimension-values")) as any;
122 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
123 if (response.tag === "Ok") {
124 expect(response.count).toBeGreaterThan(0);
125 }
126 }),
127 { timeout: 60_000 },
128 );
129 });
130
131 describe("GetTags", () => {
132 test.provider(
133 "lists cost allocation tag keys",
134 (_stack) =>
135 Effect.gen(function* () {
136 const response = (yield* getJson("/tag-keys")) as any;
137 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
138 expect(typeof response.count).toBe("number");
139 }),
140 { timeout: 60_000 },
141 );
142 });
143
144 describe("GetCostCategories", () => {
145 test.provider(
146 "lists cost category names (fixture category present after processing)",
147 (_stack) =>
148 Effect.gen(function* () {
149 const response = (yield* getJson("/cost-categories")) as any;
150 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
151 expect(Array.isArray(response.names)).toBe(true);
152 }),
153 { timeout: 60_000 },
154 );
155 });
156
157 describe("GetCostForecast", () => {
158 test.provider(
159 "forecasts next month's spend (or reports insufficient data, typed)",
160 (_stack) =>
161 Effect.gen(function* () {
162 const response = (yield* getJson("/forecast")) as any;
163 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
164 }),
165 { timeout: 60_000 },
166 );
167 });
168
169 describe("GetApproximateUsageRecords", () => {
170 test.provider(
171 "estimates usage record volume per service",
172 (_stack) =>
173 Effect.gen(function* () {
174 const response = (yield* getJson("/approximate-usage")) as any;
175 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
176 expect(typeof response.total).toBe("number");
177 }),
178 { timeout: 60_000 },
179 );
180 });
181
182 describe("GetRightsizingRecommendation", () => {
183 test.provider(
184 "returns EC2 rightsizing recommendations (or the typed opt-in rejection)",
185 (_stack) =>
186 Effect.gen(function* () {
187 const response = (yield* getJson("/rightsizing")) as any;
188 // Rightsizing is an opt-in Cost Explorer preference on the payer
189 // account; without the opt-in the API rejects with
190 // RightsizingRecommendationNotEnabled — the AccessDeniedException
191 // "opt-in only feature" rejection patched into distilled as a
192 // specific typed tag. Either outcome proves the binding + grant.
193 expect(["Ok", "RightsizingRecommendationNotEnabled"]).toContain(response.tag);
194 expect(response.count).toBeGreaterThanOrEqual(0);
195 }),
196 { timeout: 60_000 },
197 );
198 });
199
200 describe("GetReservationPurchaseRecommendation", () => {
201 test.provider(
202 "returns EC2 reservation purchase recommendations",
203 (_stack) =>
204 Effect.gen(function* () {
205 const response = (yield* getJson("/reservation-recommendation")) as any;
206 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
207 expect(response.count).toBeGreaterThanOrEqual(0);
208 }),
209 { timeout: 60_000 },
210 );
211 });
212
213 describe("GetSavingsPlansUtilization", () => {
214 test.provider(
215 "reads Savings Plans utilization (or typed data-unavailable)",
216 (_stack) =>
217 Effect.gen(function* () {
218 const response = (yield* getJson("/savings-plans-utilization")) as any;
219 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
220 }),
221 { timeout: 60_000 },
222 );
223 });
224
225 describe("ListSavingsPlansPurchaseRecommendationGeneration", () => {
226 test.provider(
227 "lists recent recommendation generations",
228 (_stack) =>
229 Effect.gen(function* () {
230 const response = (yield* getJson("/recommendation-generations")) as any;
231 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
232 expect(response.count).toBeGreaterThanOrEqual(0);
233 }),
234 { timeout: 60_000 },
235 );
236 });
237
238 describe("ListCommitmentPurchaseAnalyses", () => {
239 test.provider(
240 "lists commitment purchase analyses",
241 (_stack) =>
242 Effect.gen(function* () {
243 const response = (yield* getJson("/commitment-analyses")) as any;
244 expect(["Ok", "DataUnavailableException"]).toContain(response.tag);
245 expect(response.count).toBeGreaterThanOrEqual(0);
246 }),
247 { timeout: 60_000 },
248 );
249 });
250
251 describe("ListCostAllocationTags", () => {
252 test.provider(
253 "lists cost allocation tags",
254 (_stack) =>
255 Effect.gen(function* () {
256 const response = (yield* getJson("/allocation-tags")) as any;
257 expect(response.count).toBeGreaterThanOrEqual(0);
258 }),
259 { timeout: 60_000 },
260 );
261 });
262
263 describe("ListCostAllocationTagBackfillHistory", () => {
264 test.provider(
265 "lists backfill requests",
266 (_stack) =>
267 Effect.gen(function* () {
268 const response = (yield* getJson("/backfill-history")) as any;
269 expect(response.count).toBeGreaterThanOrEqual(0);
270 }),
271 { timeout: 60_000 },
272 );
273 });
274
275 describe("GetAnomalies", () => {
276 test.provider(
277 "lists the fixture monitor's anomalies (proving MonitorArn injection + the monitor-scoped grant)",
278 (_stack) =>
279 Effect.gen(function* () {
280 const response = (yield* getJson("/anomalies")) as any;
281 expect(response.count).toBeGreaterThanOrEqual(0);
282 }),
283 { timeout: 60_000 },
284 );
285 });
286
287 describe("ProvideAnomalyFeedback", () => {
288 test.provider(
289 "surfaces the typed ValidationException for a nonexistent anomaly (proving the grant)",
290 (_stack) =>
291 Effect.gen(function* () {
292 const response = (yield* getJson("/anomaly-feedback-invalid")) as any;
293 expect(response.tag).toBe("ValidationException");
294 }),
295 { timeout: 60_000 },
296 );
297 });
298
299 describe("ListCostCategoryResourceAssociations", () => {
300 test.provider(
301 "lists the fixture category's resource associations (proving CostCategoryArn injection)",
302 (_stack) =>
303 Effect.gen(function* () {
304 const response = (yield* getJson("/category-associations")) as any;
305 expect(response.count).toBeGreaterThanOrEqual(0);
306 }),
307 { timeout: 60_000 },
308 );
309 });
310 },
311 );