@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, 04:45 UTC

main
ts 341 lines 12.9 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Context from "effect/Context";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Layer from "effect/Layer";
7 import * as Result from "effect/Result";
8 import * as Stream from "effect/Stream";
9
10 export class EventBridgeTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
11 "EventBridgeTestFunction",
12 ) {}
13
14 /**
15 * Shared infrastructure for the EventBridge bindings fixture:
16 * - a custom event bus (PutEvents + consumeBusEvents against a named bus)
17 * - one SQS sink queue per consume loop (custom bus + default bus) so the
18 * test can observe delivered events out-of-band via `sqs.receiveMessage`
19 * - a target-less rule on the custom bus for the Enable/DisableRule toggles
20 * - an archive on the custom bus for the replay bindings
21 */
22 export class BusAndQueues extends Context.Service<
23 BusAndQueues,
24 {
25 bus: AWS.EventBridge.EventBus;
26 customQueue: AWS.SQS.Queue;
27 defaultQueue: AWS.SQS.Queue;
28 toggleRule: AWS.EventBridge.Rule;
29 archive: AWS.EventBridge.Archive;
30 }
31 >()("EventBridgeBusAndQueues") {}
32
33 export const BusAndQueuesLive = Layer.effect(
34 BusAndQueues,
35 Effect.gen(function* () {
36 const bus = yield* AWS.EventBridge.EventBus("TestBus", {
37 name: "alchemy-test-eb-bindings",
38 // A crashed run can leak event-source rules whose state rows are
39 // gone; without forceDestroy those orphans block deleteEventBus
40 // with EventBusHasRules forever.
41 forceDestroy: true,
42 });
43 const customQueue = yield* AWS.SQS.Queue("CustomBusSink");
44 const defaultQueue = yield* AWS.SQS.Queue("DefaultBusSink");
45 const toggleRule = yield* AWS.EventBridge.Rule("ToggleRule", {
46 name: "alchemy-test-eb-toggle",
47 eventBusName: bus.eventBusName,
48 eventPattern: { source: ["alchemy.test.toggle"] },
49 });
50 const archive = yield* AWS.EventBridge.Archive("TestArchive", {
51 name: "alchemy-test-eb-archive",
52 eventSourceArn: bus.eventBusArn,
53 retention: "1 day",
54 });
55 return { bus, customQueue, defaultQueue, toggleRule, archive };
56 }),
57 );
58
59 export default EventBridgeTestFunction.make(
60 {
61 main: import.meta.url,
62 functionUrl: true,
63 },
64 Effect.gen(function* () {
65 const { bus, customQueue, defaultQueue, toggleRule, archive } = yield* BusAndQueues;
66
67 const putEventsCustom = yield* AWS.EventBridge.PutEvents(bus);
68 const putEventsDefault = yield* AWS.EventBridge.PutEvents();
69 const customSink = yield* AWS.SQS.QueueSink(customQueue);
70 const defaultSink = yield* AWS.SQS.QueueSink(defaultQueue);
71 const enableRule = yield* AWS.EventBridge.EnableRule(toggleRule);
72 const disableRule = yield* AWS.EventBridge.DisableRule(toggleRule);
73 const describeToggleRule = yield* AWS.EventBridge.DescribeRule(toggleRule);
74 const listRuleNamesByTarget = yield* AWS.EventBridge.ListRuleNamesByTarget();
75 const startReplay = yield* AWS.EventBridge.StartReplay(archive);
76 const describeReplay = yield* AWS.EventBridge.DescribeReplay();
77 const cancelReplay = yield* AWS.EventBridge.CancelReplay();
78 const listReplays = yield* AWS.EventBridge.ListReplays();
79 const describeCustomBus = yield* AWS.EventBridge.DescribeEventBus(bus);
80 const listEventBuses = yield* AWS.EventBridge.ListEventBuses();
81 const listCustomBusRules = yield* AWS.EventBridge.ListRules(bus);
82 const listToggleRuleTargets = yield* AWS.EventBridge.ListTargetsByRule(toggleRule);
83 const testEventPattern = yield* AWS.EventBridge.TestEventPattern();
84
85 // Consume loop on the CUSTOM bus: matching events are forwarded to the
86 // custom sink queue where the test observes them out-of-band.
87 yield* AWS.EventBridge.consumeBusEvents(
88 bus,
89 { source: ["alchemy.test.custom"] },
90 (events: Stream.Stream<AWS.EventBridge.EventRecord>) =>
91 events.pipe(
92 Stream.map((event) => ({
93 MessageBody: JSON.stringify({
94 source: event.source,
95 detailType: event["detail-type"],
96 detail: event.detail,
97 }),
98 })),
99 Stream.run(customSink),
100 Effect.orDie,
101 ),
102 );
103
104 // Consume loop on the DEFAULT bus (no bus argument).
105 yield* AWS.EventBridge.consumeBusEvents(
106 { source: ["alchemy.test.default"] },
107 (events: Stream.Stream<AWS.EventBridge.EventRecord>) =>
108 events.pipe(
109 Stream.map((event) => ({
110 MessageBody: JSON.stringify({
111 source: event.source,
112 detailType: event["detail-type"],
113 detail: event.detail,
114 }),
115 })),
116 Stream.run(defaultSink),
117 Effect.orDie,
118 ),
119 );
120
121 return {
122 fetch: Effect.gen(function* () {
123 const request = yield* HttpServerRequest;
124 const url = new URL(request.originalUrl);
125 const pathname = url.pathname;
126
127 if (request.method === "GET" && pathname === "/health") {
128 return yield* HttpServerResponse.json({ ok: true });
129 }
130
131 if (request.method === "POST" && pathname === "/publish-custom") {
132 const body = (yield* request.json) as unknown as { marker: string };
133 const result = yield* putEventsCustom({
134 Entries: [
135 {
136 Source: "alchemy.test.custom",
137 DetailType: "TestEvent",
138 Detail: JSON.stringify({ marker: body.marker }),
139 },
140 ],
141 });
142 return yield* HttpServerResponse.json({
143 failedEntryCount: result.FailedEntryCount ?? 0,
144 entries: result.Entries ?? [],
145 });
146 }
147
148 if (request.method === "POST" && pathname === "/publish-default") {
149 const body = (yield* request.json) as unknown as { marker: string };
150 const result = yield* putEventsDefault({
151 Entries: [
152 {
153 Source: "alchemy.test.default",
154 DetailType: "TestEvent",
155 Detail: JSON.stringify({ marker: body.marker }),
156 },
157 ],
158 });
159 return yield* HttpServerResponse.json({
160 failedEntryCount: result.FailedEntryCount ?? 0,
161 entries: result.Entries ?? [],
162 });
163 }
164
165 if (request.method === "POST" && pathname === "/rule-toggle") {
166 // Disable, observe, re-enable, observe — exercises DisableRule,
167 // DescribeRule, and EnableRule end-to-end.
168 yield* disableRule();
169 const afterDisable = (yield* describeToggleRule()).State;
170 yield* enableRule();
171 const afterEnable = (yield* describeToggleRule()).State;
172 return yield* HttpServerResponse.json({ afterDisable, afterEnable });
173 }
174
175 if (request.method === "POST" && pathname === "/rule-names-by-target") {
176 const body = (yield* request.json) as unknown as {
177 targetArn: string;
178 };
179 const result = yield* listRuleNamesByTarget({
180 TargetArn: body.targetArn,
181 });
182 return yield* HttpServerResponse.json({
183 ruleNames: result.RuleNames ?? [],
184 });
185 }
186
187 if (request.method === "GET" && pathname === "/bus-info") {
188 // DescribeEventBus scoped to the bound custom bus.
189 const info = yield* describeCustomBus();
190 return yield* HttpServerResponse.json({
191 name: info.Name,
192 arn: info.Arn,
193 });
194 }
195
196 if (request.method === "GET" && pathname === "/event-buses") {
197 // ListEventBuses is account-level; the default bus always exists.
198 const result = yield* listEventBuses();
199 return yield* HttpServerResponse.json({
200 names: (result.EventBuses ?? []).flatMap((b) => (b.Name ? [b.Name] : [])),
201 });
202 }
203
204 if (request.method === "GET" && pathname === "/rules") {
205 // ListRules scoped to the bound custom bus — sees the toggle rule
206 // and the consume-loop rule.
207 const result = yield* listCustomBusRules();
208 return yield* HttpServerResponse.json({
209 ruleNames: (result.Rules ?? []).flatMap((r) => (r.Name ? [r.Name] : [])),
210 });
211 }
212
213 if (request.method === "GET" && pathname === "/targets-by-rule") {
214 // ListTargetsByRule scoped to the (target-less) toggle rule.
215 const result = yield* listToggleRuleTargets();
216 return yield* HttpServerResponse.json({
217 targetCount: (result.Targets ?? []).length,
218 });
219 }
220
221 if (request.method === "POST" && pathname === "/test-pattern") {
222 const body = (yield* request.json) as unknown as { source: string };
223 const event = JSON.stringify({
224 id: "1",
225 source: body.source,
226 "detail-type": "TestEvent",
227 account: "123456789012",
228 region: "us-east-1",
229 time: new Date().toISOString(),
230 detail: {},
231 });
232 const pattern = JSON.stringify({ source: ["alchemy.test.pattern"] });
233 const matching = yield* testEventPattern({
234 EventPattern: pattern,
235 Event: event,
236 });
237 return yield* HttpServerResponse.json({
238 matches: matching.Result ?? false,
239 });
240 }
241
242 if (request.method === "GET" && pathname === "/replays") {
243 const result = yield* listReplays();
244 return yield* HttpServerResponse.json({
245 count: (result.Replays ?? []).length,
246 });
247 }
248
249 if (request.method === "POST" && pathname === "/replay") {
250 const replayName = "alchemy-test-eb-replay";
251 // Replay an empty window from the recent past onto the archive's
252 // source bus (the binding's default destination). Replays cannot
253 // be deleted, so re-runs hit ResourceAlreadyExistsException —
254 // treated as success and observed via DescribeReplay below.
255 const now = Date.now();
256 const started = yield* Effect.result(
257 startReplay({
258 ReplayName: replayName,
259 EventStartTime: new Date(now - 10 * 60 * 1000),
260 EventEndTime: new Date(now - 5 * 60 * 1000),
261 }).pipe(
262 Effect.catchTag("ResourceAlreadyExistsException", () => Effect.succeed(undefined)),
263 ),
264 );
265 if (Result.isFailure(started)) {
266 return yield* HttpServerResponse.json(
267 {
268 error: "startReplay",
269 failure: JSON.stringify(started.failure),
270 },
271 { status: 400 },
272 );
273 }
274 const described = yield* Effect.result(describeReplay({ ReplayName: replayName }));
275 if (Result.isFailure(described)) {
276 return yield* HttpServerResponse.json(
277 {
278 error: "describeReplay",
279 failure: JSON.stringify(described.failure),
280 },
281 { status: 400 },
282 );
283 }
284 // Cancelling a finished replay fails with the typed
285 // IllegalStatusException — either outcome proves the binding.
286 const cancel = yield* Effect.result(
287 cancelReplay({ ReplayName: replayName }).pipe(
288 Effect.map(() => "cancelled" as const),
289 Effect.catchTag("IllegalStatusException", () =>
290 Effect.succeed("not-cancellable" as const),
291 ),
292 ),
293 );
294 if (Result.isFailure(cancel)) {
295 return yield* HttpServerResponse.json(
296 {
297 error: "cancelReplay",
298 failure: JSON.stringify(cancel.failure),
299 },
300 { status: 400 },
301 );
302 }
303 return yield* HttpServerResponse.json({
304 state: described.success.State,
305 cancel: cancel.success,
306 });
307 }
308
309 return yield* HttpServerResponse.json(
310 { error: "Not found", method: request.method, pathname },
311 { status: 404 },
312 );
313 }).pipe(Effect.orDie),
314 };
315 }).pipe(
316 Effect.provide(
317 Layer.provideMerge(
318 Layer.mergeAll(
319 AWS.Lambda.EventSource,
320 AWS.EventBridge.PutEventsHttp,
321 AWS.EventBridge.EnableRuleHttp,
322 AWS.EventBridge.DisableRuleHttp,
323 AWS.EventBridge.DescribeRuleHttp,
324 AWS.EventBridge.ListRuleNamesByTargetHttp,
325 AWS.EventBridge.StartReplayHttp,
326 AWS.EventBridge.DescribeReplayHttp,
327 AWS.EventBridge.CancelReplayHttp,
328 AWS.EventBridge.ListReplaysHttp,
329 AWS.EventBridge.DescribeEventBusHttp,
330 AWS.EventBridge.ListEventBusesHttp,
331 AWS.EventBridge.ListRulesHttp,
332 AWS.EventBridge.ListTargetsByRuleHttp,
333 AWS.EventBridge.TestEventPatternHttp,
334 AWS.SQS.QueueSinkHttp,
335 BusAndQueuesLive,
336 ),
337 Layer.mergeAll(AWS.SQS.SendMessageBatchHttp),
338 ),
339 ),
340 ),
341 );