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

main
ts 289 lines 12.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Index, View } from "@alchemy.run/aws/ResourceExplorer";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as re2 from "@distilled.cloud/aws/resource-explorer-2";
6 import * as Provider from "alchemy/Provider";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as Schedule from "effect/Schedule";
10 import ResourceExplorerTestFunctionLive, { ResourceExplorerTestFunction } from "./handler.ts";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 // `GetIndex` keeps returning the most recent index long after deletion
15 // (State DELETED), so both NotFound and DELETING/DELETED mean "no index".
16 const getLiveIndex = re2.getIndex({}).pipe(
17 Effect.map((r): re2.GetIndexOutput | undefined =>
18 r.State === "DELETED" || r.State === "DELETING" ? undefined : r,
19 ),
20 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
21 );
22
23 // The index is an account/region singleton (capture-and-restore): these
24 // tests only run destructively when the region has no index, or when the
25 // existing one carries Alchemy tags (i.e. a leftover from a crashed
26 // previous run of this same suite). A user-owned index is never touched.
27 const foreignIndexExists = Effect.gen(function* () {
28 const live = yield* getLiveIndex;
29 return (
30 live !== undefined && !Object.keys(live.Tags ?? {}).some((key) => key.startsWith("alchemy::"))
31 );
32 });
33
34 const waitForIndexGone = re2.getIndex({}).pipe(
35 Effect.map((r): string | undefined => r.State),
36 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
37 Effect.repeat({
38 schedule: Schedule.spaced("3 seconds"),
39 until: (state) => state === undefined || state === "DELETED" || state === "DELETING",
40 times: 20,
41 }),
42 );
43
44 const waitForIndexActive = re2.getIndex({}).pipe(
45 Effect.repeat({
46 schedule: Schedule.spaced("3 seconds"),
47 until: (r) => r.State === "ACTIVE",
48 times: 30,
49 }),
50 );
51
52 const getViewSafe = (viewArn: string) =>
53 re2.getView({ ViewArn: viewArn }).pipe(
54 Effect.map((r): re2.GetViewOutput | undefined => r),
55 // Resource Explorer's "view not found" is the typed UnauthorizedException
56 Effect.catchTag(["UnauthorizedException", "ResourceNotFoundException"], () =>
57 Effect.succeed(undefined),
58 ),
59 );
60
61 const waitForViewGone = (viewArn: string) =>
62 getViewSafe(viewArn).pipe(
63 Effect.repeat({
64 schedule: Schedule.spaced("2 seconds"),
65 until: (view) => view === undefined,
66 times: 10,
67 }),
68 );
69
70 // The Resource Explorer index is an account/region singleton, so every
71 // test in this file mutates the same underlying cloud state — run them
72 // strictly one at a time (vitest runs tests in a file concurrently by
73 // default).
74 describe.sequential(
75 "ResourceExplorer",
76 { tags: ["provider:aws", "provider:aws:resourceexplorer", "live"] },
77 () => {
78 test.provider(
79 "index lifecycle: create LOCAL, sync tags, promote to AGGREGATOR, destroy",
80 (stack) =>
81 Effect.gen(function* () {
82 if (yield* foreignIndexExists) {
83 yield* Effect.logInfo(
84 "a foreign Resource Explorer index exists — skipping destructive index lifecycle test",
85 );
86 return;
87 }
88 yield* stack.destroy();
89
90 const make = (props: { type?: "LOCAL" | "AGGREGATOR"; tags?: Record<string, string> }) =>
91 Effect.gen(function* () {
92 const index = yield* Index("Explorer", props);
93 return { index };
94 });
95
96 // Create — LOCAL index, engine waits for ACTIVE.
97 const { index } = yield* stack.deploy(make({ tags: { purpose: "alchemy-re2-test" } }));
98 expect(index.indexArn).toContain(":index/");
99 expect(index.indexType).toBe("LOCAL");
100 expect(index.indexState).toBe("ACTIVE");
101
102 // Out-of-band verification: live state + internal & user tags.
103 const live = yield* re2.getIndex({});
104 expect(live.Arn).toBe(index.indexArn);
105 expect(live.State).toBe("ACTIVE");
106 expect(live.Tags?.purpose).toBe("alchemy-re2-test");
107 expect(live.Tags?.["alchemy::id"]).toBe("Explorer");
108
109 // Canonical list() coverage — the singleton is reported.
110 const provider = yield* Provider.findProvider(Index);
111 const all = yield* provider.list();
112 expect(all.map((i) => i.indexArn)).toContain(index.indexArn);
113
114 // Update — tag sync (add one, drop one) without replacement.
115 const { index: retagged } = yield* stack.deploy(make({ tags: { team: "platform" } }));
116 expect(retagged.indexArn).toBe(index.indexArn);
117 const afterTags = yield* re2.getIndex({});
118 expect(afterTags.Tags?.team).toBe("platform");
119 expect(afterTags.Tags?.purpose).toBeUndefined();
120 expect(afterTags.Tags?.["alchemy::id"]).toBe("Explorer");
121
122 // Update — promote to AGGREGATOR in place (single-region account:
123 // replication settles quickly). GATED: promoting and then deleting
124 // the aggregator index starts an account-wide 24h cool-down on
125 // UpdateIndexType (`ServiceQuotaExceededException`, Name
126 // "COOL_DOWN_PERIOD"), so the promotion leg cannot run on every CI
127 // pass — set AWS_TEST_RE2_AGGREGATOR=1 on a cooled-down account.
128 if (process.env.AWS_TEST_RE2_AGGREGATOR) {
129 const { index: promoted } = yield* stack.deploy(
130 make({ type: "AGGREGATOR", tags: { team: "platform" } }),
131 );
132 expect(promoted.indexArn).toBe(index.indexArn);
133 expect(promoted.indexType).toBe("AGGREGATOR");
134
135 // Let the async promotion settle before deleting.
136 const settled = yield* waitForIndexActive;
137 expect(settled.Type).toBe("AGGREGATOR");
138 }
139
140 // Destroy — Resource Explorer is turned off for the region.
141 yield* stack.destroy();
142 const gone = yield* waitForIndexGone;
143 expect(["DELETED", "DELETING", undefined]).toContain(gone);
144 }),
145 { timeout: 240_000 },
146 );
147
148 test.provider(
149 "view lifecycle: single-shot deploy with index, update filters, replace on rename",
150 (stack) =>
151 Effect.gen(function* () {
152 if (yield* foreignIndexExists) {
153 yield* Effect.logInfo(
154 "a foreign Resource Explorer index exists — skipping destructive view lifecycle test",
155 );
156 return;
157 }
158 yield* stack.destroy();
159
160 const make = (props: {
161 viewName?: string;
162 filterString?: string;
163 includedProperties?: string[];
164 }) =>
165 Effect.gen(function* () {
166 // Index + View in ONE deploy: the view provider retries
167 // through the index's provisioning window.
168 const index = yield* Index("Explorer", {});
169 const view = yield* View("TestView", props);
170 return { index, view };
171 });
172
173 // Create — filtered view with tags included in results.
174 const { index, view } = yield* stack.deploy(
175 make({ filterString: "service:s3", includedProperties: ["tags"] }),
176 );
177 expect(index.indexState).toBe("ACTIVE");
178 expect(view.viewArn).toContain(":view/");
179 expect(view.scope).toBeDefined();
180
181 const observed = yield* re2.getView({ ViewArn: view.viewArn });
182 expect(observed.View?.Filters?.FilterString).toBe("service:s3");
183 expect(observed.View?.IncludedProperties).toEqual([{ Name: "tags" }]);
184 expect(observed.Tags?.["alchemy::id"]).toBe("TestView");
185
186 // Update — change the filter and clear included properties
187 // (UpdateView replaces both).
188 const { view: updated } = yield* stack.deploy(make({ filterString: "service:sqs" }));
189 expect(updated.viewArn).toBe(view.viewArn);
190 const afterUpdate = yield* re2.getView({ ViewArn: view.viewArn });
191 expect(afterUpdate.View?.Filters?.FilterString).toBe("service:sqs");
192 expect(afterUpdate.View?.IncludedProperties ?? []).toEqual([]);
193
194 // Canonical list() coverage.
195 const provider = yield* Provider.findProvider(View);
196 const all = yield* provider.list();
197 expect(all.map((v) => v.viewArn)).toContain(view.viewArn);
198
199 // Replace — an explicit rename replaces the view (the index stays
200 // deployed across the replacement).
201 const { view: renamed } = yield* stack.deploy(
202 make({ viewName: "alchemy-re2-renamed-view", filterString: "service:sqs" }),
203 );
204 expect(renamed.viewArn).not.toBe(view.viewArn);
205 expect(renamed.viewName).toBe("alchemy-re2-renamed-view");
206 // Old view is gone after the replacement completes.
207 const oldView = yield* waitForViewGone(view.viewArn);
208 expect(oldView).toBeUndefined();
209
210 // Destroy — the view and the index are removed.
211 yield* stack.destroy();
212 const goneView = yield* waitForViewGone(renamed.viewArn);
213 expect(goneView).toBeUndefined();
214 const goneIndex = yield* waitForIndexGone;
215 expect(["DELETED", "DELETING", undefined]).toContain(goneIndex);
216 }),
217 { timeout: 240_000 },
218 );
219
220 describe("Bindings", { tags: ["provider:aws:lambda"] }, () => {
221 test.provider(
222 "deployed Lambda exercises Search, ListResources and ListSupportedResourceTypes",
223 (stack) =>
224 Effect.gen(function* () {
225 if (yield* foreignIndexExists) {
226 yield* Effect.logInfo(
227 "a foreign Resource Explorer index exists — skipping search binding test",
228 );
229 return;
230 }
231 yield* stack.destroy();
232
233 const { functionUrl } = yield* stack.deploy(
234 Effect.gen(function* () {
235 return yield* ResourceExplorerTestFunction;
236 }).pipe(Effect.provide(ResourceExplorerTestFunctionLive)),
237 );
238 expect(functionUrl).toBeTruthy();
239 const baseUrl = functionUrl!.replace(/\/+$/, "");
240
241 const client = yield* HttpClient.HttpClient;
242 // Fresh function URLs take a few seconds to start serving; 403/
243 // 5xx during that window are transient.
244 const response = yield* client.get(`${baseUrl}/search?q=service:s3`).pipe(
245 Effect.flatMap((res) =>
246 res.status === 200
247 ? Effect.succeed(res)
248 : Effect.fail(new Error(`status ${res.status}`)),
249 ),
250 Effect.retry({
251 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(40)]),
252 }),
253 );
254 const body = (yield* response.json) as {
255 viewArn: string;
256 totalResources: number;
257 complete: boolean;
258 resources: string[];
259 };
260 // A brand-new index may not have indexed anything yet — assert
261 // the search round-trip itself, not its contents.
262 expect(body.viewArn).toContain(":view/");
263 expect(typeof body.totalResources).toBe("number");
264 expect(Array.isArray(body.resources)).toBe(true);
265
266 // ListResources — structured-filter enumeration through the same
267 // view (a brand-new index may be empty; assert the round-trip).
268 const listRes = yield* client.get(`${baseUrl}/resources?filter=service:s3`);
269 expect(listRes.status).toBe(200);
270 const listBody = (yield* listRes.json) as { viewArn: string; resources: string[] };
271 expect(listBody.viewArn).toContain(":view/");
272 expect(Array.isArray(listBody.resources)).toBe(true);
273
274 // ListSupportedResourceTypes — account-level discovery; always
275 // returns a non-empty catalog.
276 const typesRes = yield* client.get(`${baseUrl}/types`);
277 expect(typesRes.status).toBe(200);
278 const typesBody = (yield* typesRes.json) as { resourceTypes: string[] };
279 expect(typesBody.resourceTypes.length).toBeGreaterThan(0);
280
281 yield* stack.destroy();
282 const goneIndex = yield* waitForIndexGone;
283 expect(["DELETED", "DELETING", undefined]).toContain(goneIndex);
284 }),
285 { timeout: 300_000 },
286 );
287 });
288 },
289 );