@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 202 lines 7.18 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
5 import * as SQS from "@distilled.cloud/aws/sqs";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpBody from "effect/http/HttpBody";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as Schedule from "effect/Schedule";
11 import { BusSinkFunction, BusSinkFunctionLive } from "./sink-handler.ts";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 class FunctionNotReady extends Data.TaggedError("FunctionNotReady") {}
16
17 class SinkRequestFailed extends Data.TaggedError("SinkRequestFailed")<{
18 readonly status: number;
19 readonly body: string;
20 }> {}
21
22 class EventsNotDelivered extends Data.TaggedError("EventsNotDelivered")<{
23 readonly missing: number;
24 }> {}
25
26 const waitForFunctionReady = (url: string) =>
27 HttpClient.get(url).pipe(
28 Effect.flatMap((response) =>
29 response.status === 200
30 ? (response.json as Effect.Effect<{ queueUrl: string }>)
31 : Effect.fail(new FunctionNotReady()),
32 ),
33 // A freshly-deployed function can briefly serve a 200 before its captured
34 // env vars (the queue URL) have finished propagating, so treat a missing
35 // queueUrl as "not ready yet" and keep polling.
36 Effect.flatMap((json: any) =>
37 typeof json?.queueUrl === "string"
38 ? Effect.succeed({ queueUrl: json.queueUrl as string })
39 : Effect.fail(new FunctionNotReady()),
40 ),
41 Effect.retry({
42 while: (error) => error._tag === "FunctionNotReady",
43 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
44 }),
45 );
46
47 /** POST a marker batch to the fixture's /sink route; fail on non-200. */
48 const postSink = Effect.fn(function* (
49 baseUrl: string,
50 body: { markers: string[]; includeMalformed?: boolean },
51 ) {
52 const response = yield* HttpClient.post(`${baseUrl}/sink`, {
53 body: yield* HttpBody.json(body),
54 });
55 if (response.status !== 200) {
56 const text = yield* response.text;
57 return yield* Effect.fail(new SinkRequestFailed({ status: response.status, body: text }));
58 }
59 return (yield* response.json) as { ok: boolean; count: number };
60 });
61
62 /**
63 * Drain the routed queue, collecting `detail.marker` values into `received`,
64 * until every expected marker has been observed. Bounded — fails with
65 * `EventsNotDelivered` when the schedule is exhausted.
66 */
67 const waitForMarkers = Effect.fn(function* (queueUrl: string, expected: readonly string[]) {
68 const received = new Set<string>();
69 yield* Effect.gen(function* () {
70 const result = yield* SQS.receiveMessage({
71 QueueUrl: queueUrl,
72 MaxNumberOfMessages: 10,
73 WaitTimeSeconds: 2,
74 });
75 for (const message of result.Messages ?? []) {
76 if (message.Body) {
77 const event = JSON.parse(message.Body) as {
78 detail?: { marker?: string };
79 };
80 const marker = event.detail?.marker;
81 if (typeof marker === "string") {
82 received.add(marker);
83 }
84 }
85 if (message.ReceiptHandle) {
86 yield* SQS.deleteMessage({
87 QueueUrl: queueUrl,
88 ReceiptHandle: message.ReceiptHandle,
89 });
90 }
91 }
92 const missing = expected.filter((marker) => !received.has(marker));
93 if (missing.length > 0) {
94 return yield* Effect.fail(new EventsNotDelivered({ missing: missing.length }));
95 }
96 }).pipe(
97 Effect.retry({
98 while: (e) => e._tag === "EventsNotDelivered",
99 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
100 }),
101 );
102 return received;
103 });
104
105 /**
106 * EventBridge rules on a freshly-created bus take a while to propagate;
107 * events published before the rule is active are silently dropped (no
108 * retro-delivery). Publish-then-poll in a bounded loop: each iteration
109 * re-publishes the probe marker through the sink and long-polls the routed
110 * queue for it.
111 */
112 const probeUntilRouted = Effect.fn(function* (baseUrl: string, queueUrl: string, marker: string) {
113 yield* Effect.gen(function* () {
114 const response = yield* postSink(baseUrl, { markers: [marker] });
115 expect(response.ok).toBe(true);
116
117 const result = yield* SQS.receiveMessage({
118 QueueUrl: queueUrl,
119 MaxNumberOfMessages: 10,
120 WaitTimeSeconds: 5,
121 });
122 const match = (result.Messages ?? []).some((message) =>
123 message.Body ? message.Body.includes(marker) : false,
124 );
125 if (!match) {
126 yield* Effect.logInfo("BusSink test: probe event not routed yet (rule still propagating?)");
127 return yield* Effect.fail(new EventsNotDelivered({ missing: 1 }));
128 }
129 }).pipe(
130 Effect.retry({
131 while: (e) => e._tag === "EventsNotDelivered",
132 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(17)]),
133 }),
134 );
135 });
136
137 test.provider(
138 "BusSink streams entries through a deployed Lambda to EventBridge",
139 (stack) =>
140 Effect.gen(function* () {
141 // Leading destroy: reconcile away any partial deployment left behind by
142 // a previous crashed run (physical names are deterministic constants).
143 yield* stack.destroy();
144
145 const fn = yield* stack.deploy(BusSinkFunction.pipe(Effect.provide(BusSinkFunctionLive)));
146 const baseUrl = fn.functionUrl!.replace(/\/+$/, "");
147
148 const { queueUrl } = yield* waitForFunctionReady(`${baseUrl}/ready`);
149
150 // Prove the bus -> queue rule is active before asserting on batches.
151 yield* probeUntilRouted(baseUrl, queueUrl, "bussink-probe");
152
153 // 25 entries > the PutEvents limit of 10, so the batched sink must
154 // split the chunk into 3 sequential API calls (10 + 10 + 5).
155 const markers = Array.from({ length: 25 }, (_, i) => `bussink-${i}-${crypto.randomUUID()}`);
156 const response = yield* postSink(baseUrl, { markers });
157 expect(response.ok).toBe(true);
158 expect(response.count).toBe(markers.length);
159
160 yield* waitForMarkers(queueUrl, markers);
161
162 // Partial failure: one entry with malformed Detail is rejected
163 // per-entry (ErrorCode: MalformedDetail). The sink must drop it and
164 // deliver the rest without failing the batch.
165 const partialMarkers = Array.from(
166 { length: 3 },
167 (_, i) => `bussink-partial-${i}-${crypto.randomUUID()}`,
168 );
169 const partial = yield* postSink(baseUrl, {
170 markers: partialMarkers,
171 includeMalformed: true,
172 });
173 expect(partial.ok).toBe(true);
174 expect(partial.count).toBe(partialMarkers.length + 1);
175
176 yield* waitForMarkers(queueUrl, partialMarkers);
177
178 yield* stack.destroy();
179
180 // Typed wait-until-gone: the sink's event bus must be deleted.
181 const gone = yield* eventbridge.describeEventBus({ Name: "alchemy-test-eb-bus-sink" }).pipe(
182 Effect.map(() => false),
183 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)),
184 Effect.repeat({
185 schedule: Schedule.spaced("2 seconds"),
186 until: (isGone): boolean => isGone,
187 times: 10,
188 }),
189 );
190 expect(gone).toBe(true);
191 }),
192 {
193 tags: [
194 "provider:aws",
195 "provider:aws:eventbridge",
196 "provider:aws:lambda",
197 "provider:aws:sqs",
198 "live",
199 ],
200 timeout: 240_000,
201 },
202 );