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

main
ts 401 lines 14.6 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 SQS from "@distilled.cloud/aws/sqs";
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 Layer from "effect/Layer";
12 import * as Schedule from "effect/Schedule";
13 import EventBridgeTestFunctionLive, {
14 BusAndQueues,
15 BusAndQueuesLive,
16 EventBridgeTestFunction,
17 } from "./handler.ts";
18
19 const testOptions = { providers: AWS.providers() };
20 const { test, beforeAll, afterAll } = Test.make(testOptions);
21 const sharedStack = Core.scratchStack(testOptions, "EventBridgeBindings");
22
23 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
24 // over 60s on a fresh deploy under parallel-suite load. Budget ~150s.
25 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
26
27 let baseUrl: string;
28 let customQueueUrl: string;
29 let defaultQueueUrl: string;
30 let functionArn: string;
31
32 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
33 readonly status: number;
34 readonly body: string;
35 }> {}
36
37 // Retry transient 5xx from the fixture (cold re-init under parallel load);
38 // a genuine 4xx/assertion failure is surfaced immediately.
39 const send = (request: HttpClientRequest.HttpClientRequest) =>
40 HttpClient.execute(request).pipe(
41 Effect.flatMap((response) =>
42 response.status >= 500
43 ? response.text.pipe(
44 Effect.flatMap((body) =>
45 Effect.fail(new TransientUpstream({ status: response.status, body })),
46 ),
47 )
48 : Effect.succeed(response),
49 ),
50 Effect.retry({
51 while: (e) => e._tag === "TransientUpstream",
52 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
53 }),
54 );
55
56 class EventNotDelivered extends Data.TaggedError("EventNotDelivered") {}
57
58 interface DeliveredEvent {
59 source: string;
60 detailType: string;
61 detail: { marker: string };
62 }
63
64 // EventBridge rules on a freshly-created bus take a while to propagate; events
65 // published before the rule is active are silently dropped (EventBridge does
66 // not retro-deliver). So publish-then-poll in a bounded loop: each iteration
67 // re-publishes the marker event and long-polls the sink queue for it.
68 // Worst case ~= 18 * (publish + 5s long poll) ~= 95s, within the 120s test
69 // timeout.
70 const publishUntilReceived = Effect.fn(function* (route: string, queueUrl: string, marker: string) {
71 return yield* Effect.gen(function* () {
72 const publishResponse = yield* send(
73 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}${route}`), { marker }),
74 ).pipe(Effect.flatMap((r) => r.json));
75 expect(publishResponse).toHaveProperty("failedEntryCount", 0);
76
77 const result = yield* SQS.receiveMessage({
78 QueueUrl: queueUrl,
79 MaxNumberOfMessages: 10,
80 WaitTimeSeconds: 5,
81 });
82 const match = (result.Messages ?? [])
83 .flatMap((message) => (message.Body ? [JSON.parse(message.Body) as DeliveredEvent] : []))
84 .find((body) => body.detail?.marker === marker);
85 if (!match) {
86 yield* Effect.logInfo(
87 `EventBridge test: no matching event on ${route} yet (rule still propagating?)`,
88 );
89 return yield* Effect.fail(new EventNotDelivered());
90 }
91 return match;
92 }).pipe(
93 Effect.retry({
94 while: (e) => e._tag === "EventNotDelivered",
95 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(17)]),
96 }),
97 );
98 });
99
100 describe(
101 "EventBridge Bindings",
102 {
103 tags: [
104 "provider:aws",
105 "provider:aws:eventbridge",
106 "provider:aws:lambda",
107 "provider:aws:sqs",
108 "live",
109 ],
110 },
111 () => {
112 beforeAll(
113 Effect.gen(function* () {
114 yield* Effect.logInfo("EventBridge test setup: destroying previous resources");
115 yield* sharedStack.destroy();
116
117 yield* Effect.logInfo("EventBridge test setup: deploying fixture");
118 const { fn, custom, dflt } = yield* sharedStack.deploy(
119 Effect.gen(function* () {
120 const { customQueue, defaultQueue } = yield* BusAndQueues;
121 const fn = yield* EventBridgeTestFunction;
122 return { fn, custom: customQueue, dflt: defaultQueue };
123 }).pipe(Effect.provide(Layer.mergeAll(EventBridgeTestFunctionLive, BusAndQueuesLive))),
124 );
125
126 expect(fn.functionUrl).toBeTruthy();
127 baseUrl = fn.functionUrl!.replace(/\/+$/, "");
128 customQueueUrl = custom.queueUrl;
129 defaultQueueUrl = dflt.queueUrl;
130 functionArn = fn.functionArn;
131
132 yield* Effect.logInfo(`EventBridge test setup: probing readiness at ${baseUrl}/health`);
133 yield* HttpClient.get(`${baseUrl}/health`).pipe(
134 Effect.flatMap((response) =>
135 response.status === 200
136 ? Effect.succeed(response)
137 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
138 ),
139 Effect.tapError((error) =>
140 Effect.logWarning(`EventBridge test setup: fixture not ready yet (${String(error)})`),
141 ),
142 Effect.retry({ schedule: readinessPolicy }),
143 );
144 yield* Effect.logInfo("EventBridge test setup: fixture ready");
145 }),
146 { timeout: 240_000 },
147 );
148
149 afterAll.skipIf(!!process.env.NO_DESTROY)(
150 sharedStack.destroy().pipe(
151 // Typed wait-until-gone: the custom bus must be deleted after teardown.
152 // The raw afterAll context has no providers layer (only `test.provider`
153 // bodies do), so the out-of-band distilled call must be wrapped in
154 // `withProviders` to satisfy Credentials/HttpClient/Region.
155 Effect.andThen(
156 Core.withProviders(
157 eventbridge.describeEventBus({ Name: "alchemy-test-eb-bindings" }).pipe(
158 Effect.map(() => false),
159 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)),
160 Effect.repeat({
161 schedule: Schedule.spaced("2 seconds"),
162 until: (isGone): boolean => isGone,
163 times: 10,
164 }),
165 Effect.map((gone) => expect(gone).toBe(true)),
166 ),
167 testOptions,
168 "EventBridgeBindings",
169 ),
170 ),
171 ),
172 {
173 // Teardown deletes ~30 resources (invoke permissions, event-source
174 // rules, the Lambda fixture + role, ToggleRule, TestArchive, both
175 // sinks, then the buses). Each delete is bounded — the EventBus
176 // provider force-sweeps AWS's lingering managed archival rule — but
177 // the serial sum needs headroom on a slow AWS day.
178 timeout: 360_000,
179 },
180 );
181
182 describe("PutEvents", () => {
183 test.provider("publishes an event to the custom bus", (_stack) =>
184 Effect.gen(function* () {
185 const response = (yield* send(
186 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/publish-custom`), {
187 marker: "put-events-custom-direct",
188 }),
189 ).pipe(Effect.flatMap((r) => r.json))) as {
190 failedEntryCount: number;
191 entries: Array<{ EventId?: string }>;
192 };
193
194 expect(response.failedEntryCount).toBe(0);
195 expect(response.entries).toHaveLength(1);
196 expect(response.entries[0].EventId).toBeTruthy();
197 }),
198 );
199
200 test.provider("publishes an event to the default bus", (_stack) =>
201 Effect.gen(function* () {
202 const response = (yield* send(
203 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/publish-default`), {
204 marker: "put-events-default-direct",
205 }),
206 ).pipe(Effect.flatMap((r) => r.json))) as {
207 failedEntryCount: number;
208 entries: Array<{ EventId?: string }>;
209 };
210
211 expect(response.failedEntryCount).toBe(0);
212 expect(response.entries).toHaveLength(1);
213 expect(response.entries[0].EventId).toBeTruthy();
214 }),
215 );
216 });
217
218 describe("EnableRule / DisableRule / DescribeRule", () => {
219 test.provider(
220 "toggles the rule state and observes it via DescribeRule",
221 (_stack) =>
222 Effect.gen(function* () {
223 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/rule-toggle`)).pipe(
224 Effect.flatMap((r) => r.json),
225 )) as { afterDisable: string; afterEnable: string };
226
227 expect(response.afterDisable).toBe("DISABLED");
228 expect(response.afterEnable).toBe("ENABLED");
229 }),
230 { timeout: 60_000 },
231 );
232 });
233
234 describe("ListRuleNamesByTarget", () => {
235 test.provider(
236 "finds the consume-loop rule targeting the function",
237 (_stack) =>
238 Effect.gen(function* () {
239 const response = (yield* send(
240 HttpClientRequest.bodyJsonUnsafe(
241 HttpClientRequest.post(`${baseUrl}/rule-names-by-target`),
242 { targetArn: functionArn },
243 ),
244 ).pipe(Effect.flatMap((r) => r.json))) as { ruleNames: string[] };
245
246 // The default-bus consume loop's rule targets the Lambda.
247 expect(Array.isArray(response.ruleNames)).toBe(true);
248 expect(response.ruleNames.length).toBeGreaterThanOrEqual(1);
249 }),
250 { timeout: 60_000 },
251 );
252 });
253
254 describe("DescribeEventBus", () => {
255 test.provider("describes the bound custom bus", (_stack) =>
256 Effect.gen(function* () {
257 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/bus-info`)).pipe(
258 Effect.flatMap((r) => r.json),
259 )) as { name: string; arn: string };
260
261 expect(response.name).toBe("alchemy-test-eb-bindings");
262 expect(response.arn).toContain(":event-bus/alchemy-test-eb-bindings");
263 }),
264 );
265 });
266
267 describe("ListEventBuses", () => {
268 test.provider("enumerates account buses including the default", (_stack) =>
269 Effect.gen(function* () {
270 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/event-buses`)).pipe(
271 Effect.flatMap((r) => r.json),
272 )) as { names: string[] };
273
274 expect(response.names).toContain("default");
275 expect(response.names).toContain("alchemy-test-eb-bindings");
276 }),
277 );
278 });
279
280 describe("ListRules", () => {
281 test.provider("lists the rules on the bound custom bus", (_stack) =>
282 Effect.gen(function* () {
283 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/rules`)).pipe(
284 Effect.flatMap((r) => r.json),
285 )) as { ruleNames: string[] };
286
287 // The toggle rule and the custom-bus consume-loop rule live here.
288 expect(response.ruleNames).toContain("alchemy-test-eb-toggle");
289 expect(response.ruleNames.length).toBeGreaterThanOrEqual(2);
290 }),
291 );
292 });
293
294 describe("ListTargetsByRule", () => {
295 test.provider("lists the (empty) targets of the toggle rule", (_stack) =>
296 Effect.gen(function* () {
297 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/targets-by-rule`)).pipe(
298 Effect.flatMap((r) => r.json),
299 )) as { targetCount: number };
300
301 expect(response.targetCount).toBe(0);
302 }),
303 );
304 });
305
306 describe("TestEventPattern", () => {
307 test.provider("matches and rejects events against a pattern", (_stack) =>
308 Effect.gen(function* () {
309 const matching = (yield* send(
310 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/test-pattern`), {
311 source: "alchemy.test.pattern",
312 }),
313 ).pipe(Effect.flatMap((r) => r.json))) as { matches: boolean };
314 expect(matching.matches).toBe(true);
315
316 const nonMatching = (yield* send(
317 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/test-pattern`), {
318 source: "other.source",
319 }),
320 ).pipe(Effect.flatMap((r) => r.json))) as { matches: boolean };
321 expect(nonMatching.matches).toBe(false);
322 }),
323 );
324 });
325
326 describe("Replays", () => {
327 test.provider("ListReplays enumerates account replays", (_stack) =>
328 Effect.gen(function* () {
329 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/replays`)).pipe(
330 Effect.flatMap((r) => r.json),
331 )) as { count: number };
332
333 expect(typeof response.count).toBe("number");
334 expect(response.count).toBeGreaterThanOrEqual(0);
335 }),
336 );
337
338 test.provider(
339 "StartReplay/DescribeReplay/CancelReplay drive a replay of the archive",
340 (_stack) =>
341 Effect.gen(function* () {
342 const res = yield* send(
343 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/replay`), {}),
344 );
345 const bodyText = yield* res.text;
346 expect(res.status, bodyText).toBe(200);
347 const response = yield* Effect.sync(
348 () => JSON.parse(bodyText) as { state: string; cancel: string },
349 );
350
351 expect([
352 "STARTING",
353 "RUNNING",
354 "COMPLETED",
355 "CANCELLING",
356 "CANCELLED",
357 "FAILED",
358 ]).toContain(response.state);
359 expect(["cancelled", "not-cancellable"]).toContain(response.cancel);
360 }),
361 { timeout: 60_000 },
362 );
363 });
364
365 describe("EventSource", () => {
366 test.provider(
367 "consume loop receives custom-bus events",
368 (_stack) =>
369 Effect.gen(function* () {
370 const event = yield* publishUntilReceived(
371 "/publish-custom",
372 customQueueUrl,
373 "consume-loop-custom",
374 );
375
376 expect(event.source).toBe("alchemy.test.custom");
377 expect(event.detailType).toBe("TestEvent");
378 expect(event.detail.marker).toBe("consume-loop-custom");
379 }),
380 { timeout: 120_000 },
381 );
382
383 test.provider(
384 "consume loop receives default-bus events",
385 (_stack) =>
386 Effect.gen(function* () {
387 const event = yield* publishUntilReceived(
388 "/publish-default",
389 defaultQueueUrl,
390 "consume-loop-default",
391 );
392
393 expect(event.source).toBe("alchemy.test.default");
394 expect(event.detailType).toBe("TestEvent");
395 expect(event.detail.marker).toBe("consume-loop-default");
396 }),
397 { timeout: 120_000 },
398 );
399 });
400 },
401 );