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

main
ts 268 lines 9.79 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 eventbridge from "@distilled.cloud/aws/eventbridge";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Schedule from "effect/Schedule";
11 import GlueTestFunctionLive, { GlueTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "GlueBindings");
16
17 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
18 // over 60s on a fresh deploy.
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22 let functionArn: string;
23
24 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
25 readonly status: number;
26 readonly body: string;
27 }> {}
28
29 // The shared Lambda fixture occasionally answers a transient 5xx under load
30 // (cold re-init, IAM propagation on the freshly attached policy that the
31 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
32 // 4xx/assertion failure surfaces immediately.
33 const send = (request: HttpClientRequest.HttpClientRequest) =>
34 HttpClient.execute(request).pipe(
35 Effect.flatMap((response) =>
36 response.status >= 500
37 ? response.text.pipe(
38 Effect.flatMap((body) =>
39 Effect.fail(new TransientUpstream({ status: response.status, body })),
40 ),
41 )
42 : Effect.succeed(response),
43 ),
44 Effect.retry({
45 while: (e) => e._tag === "TransientUpstream",
46 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
47 }),
48 );
49
50 const getJson = (path: string) =>
51 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
52
53 const postJson = (path: string) =>
54 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
55
56 describe.sequential(
57 "Glue Bindings",
58 {
59 tags: [
60 "provider:aws",
61 "provider:aws:batch",
62 "provider:aws:glue",
63 "provider:aws:iam",
64 "provider:aws:lambda",
65 "provider:aws:s3",
66 "live",
67 ],
68 },
69 () => {
70 beforeAll(
71 Effect.gen(function* () {
72 yield* Effect.logInfo("Glue test setup: destroying previous resources");
73 yield* sharedStack.destroy();
74
75 yield* Effect.logInfo("Glue test setup: deploying fixture");
76 const attrs = yield* sharedStack.deploy(
77 Effect.gen(function* () {
78 return yield* GlueTestFunction;
79 }).pipe(Effect.provide(GlueTestFunctionLive)),
80 );
81
82 expect(attrs.functionUrl).toBeTruthy();
83 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
84 functionArn = attrs.functionArn;
85
86 const readinessUrl = `${baseUrl}/bindings`;
87 yield* Effect.logInfo(`Glue test setup: probing readiness at ${readinessUrl}`);
88 yield* HttpClient.get(readinessUrl).pipe(
89 Effect.flatMap((response) =>
90 response.status === 200
91 ? Effect.succeed(response)
92 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
93 ),
94 Effect.tapError((error) =>
95 Effect.logWarning(`Glue test setup: fixture not ready yet (${String(error)})`),
96 ),
97 Effect.retry({ schedule: readinessPolicy }),
98 );
99
100 // Glue's authorization layer caches IAM evaluations: a freshly created
101 // role + inline policy is denied (`AccessDeniedException`) by the Glue
102 // endpoint for ~3–5 minutes after `PutRolePolicy`, even though the
103 // policy is attached (verified via CloudTrail: policy attached
104 // 17:10:47Z, every glue:* call denied until exactly 17:15:50Z). Gate
105 // the suite on the first job-scoped call succeeding so the tests
106 // measure binding behavior, not IAM propagation.
107 yield* Effect.logInfo("Glue test setup: waiting for IAM propagation");
108 yield* HttpClient.get(`${baseUrl}/job-runs`).pipe(
109 Effect.flatMap((response) =>
110 response.status === 200
111 ? Effect.succeed(response)
112 : Effect.fail(new Error(`Glue IAM not propagated: ${response.status}`)),
113 ),
114 Effect.retry({
115 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(84)]),
116 }),
117 );
118 }),
119 { timeout: 900_000 },
120 );
121
122 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 300_000 });
123
124 describe("binding registration", () => {
125 test.provider("all twenty capabilities initialize in the runtime", () =>
126 Effect.gen(function* () {
127 const response = (yield* getJson("/bindings")) as { bound: string[] };
128 expect(response.bound).toHaveLength(20);
129 }),
130 );
131 });
132
133 describe("GetJobRuns", () => {
134 test.provider("lists the job's runs (injected job name)", () =>
135 Effect.gen(function* () {
136 const response = (yield* getJson("/job-runs")) as { count: number };
137 expect(response.count).toBeGreaterThanOrEqual(0);
138 }),
139 );
140 });
141
142 describe("GetJobBookmark / ResetJobBookmark", () => {
143 test.provider("both surface the typed missing-bookmark error", () =>
144 Effect.gen(function* () {
145 const response = (yield* getJson("/job-bookmark")) as { bookmark: string; reset: string };
146 expect(response.bookmark).toBe("none");
147 expect(response.reset).toBe("none");
148 }),
149 );
150 });
151
152 describe("StartJobRun / GetJobRun / BatchStopJobRun", () => {
153 test.provider(
154 "starts, reads, and stops a live run",
155 () =>
156 Effect.gen(function* () {
157 const response = (yield* postJson("/job-run")) as {
158 runId: string;
159 state: string;
160 stopSubmitted: number;
161 stopErrors: number;
162 };
163 expect(response.runId).toMatch(/^jr_/);
164 expect(response.state).toBeTruthy();
165 expect(response.stopSubmitted + response.stopErrors).toBe(1);
166 }),
167 { timeout: 120_000 },
168 );
169 });
170
171 describe("GetCrawler", () => {
172 test.provider("reads the bound crawler's live state", () =>
173 Effect.gen(function* () {
174 const response = (yield* getJson("/crawler")) as { name: string; state: string };
175 expect(response.name).toBeTruthy();
176 expect(["READY", "RUNNING", "STOPPING"]).toContain(response.state);
177 }),
178 );
179 });
180
181 describe("StartCrawler / StopCrawler", () => {
182 test.provider("stop on an idle crawler is the typed not-running", () =>
183 Effect.gen(function* () {
184 const response = (yield* postJson("/crawler-stop")) as { result: string };
185 expect(response.result).toBe("not-running");
186 }),
187 );
188
189 test.provider(
190 "starts a crawl and cancels it",
191 () =>
192 Effect.gen(function* () {
193 const response = (yield* postJson("/crawler-run")) as {
194 started: string;
195 stopped: string;
196 };
197 expect(["started", "already-running"]).toContain(response.started);
198 expect(["stopped", "stopping", "not-running"]).toContain(response.stopped);
199 }),
200 { timeout: 120_000 },
201 );
202 });
203
204 describe("GetTable / GetTables", () => {
205 test.provider("reads the bound table's schema and the database's tables", () =>
206 Effect.gen(function* () {
207 const response = (yield* getJson("/table")) as {
208 name: string;
209 columns: string[];
210 partitionKeys: string[];
211 tables: string[];
212 };
213 expect(response.columns).toEqual(["id", "amount"]);
214 expect(response.partitionKeys).toEqual(["dt"]);
215 expect(response.tables).toContain(response.name);
216 }),
217 );
218 });
219
220 describe("Partitions", () => {
221 test.provider(
222 "create, get, update, batch-create/update/get, list, batch-delete",
223 () =>
224 Effect.gen(function* () {
225 const response = (yield* postJson("/partitions")) as {
226 created: string[];
227 updatedParam: string;
228 batchErrors: number;
229 batchUpdateErrors: number;
230 bulkRead: number;
231 bulkUpdatedParams: number;
232 count: number;
233 batchDeleteErrors: number;
234 remaining: number;
235 };
236 expect(response.created).toEqual(["2026-01-01"]);
237 expect(response.updatedParam).toBe("true");
238 expect(response.batchErrors).toBe(0);
239 expect(response.batchUpdateErrors).toBe(0);
240 expect(response.bulkRead).toBe(3);
241 expect(response.bulkUpdatedParams).toBe(2);
242 expect(response.count).toBe(3);
243 expect(response.batchDeleteErrors).toBe(0);
244 expect(response.remaining).toBe(0);
245 }),
246 { timeout: 120_000 },
247 );
248 });
249
250 describe(
251 "consumeJobEvents / consumeCrawlerEvents",
252 { tags: ["provider:aws:eventbridge"] },
253 () => {
254 test.provider("the deploy created EventBridge rules targeting the function", () =>
255 Effect.gen(function* () {
256 // Out-of-band via distilled: the fixture's two consume* calls must
257 // have materialized as rules on the default bus with the Lambda as
258 // target.
259 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
260 TargetArn: functionArn,
261 });
262 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(2);
263 }),
264 );
265 },
266 );
267 },
268 );