@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 169 lines 7.21 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 IAM from "@distilled.cloud/aws/iam";
5 import * as Lambda from "@distilled.cloud/aws/lambda";
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 Layer from "effect/Layer";
10 import * as Schedule from "effect/Schedule";
11 import KafkaTestFunctionLive, {
12 FixtureCluster,
13 FixtureClusterLive,
14 KafkaTestFunction,
15 } from "./kafka-handler.ts";
16
17 const { test } = Test.make({ providers: AWS.providers() });
18
19 // The MSK Serverless cluster this test provisions takes ~5-10 minutes to
20 // create and is metered while it exists, so the whole event-source e2e is
21 // skipped under `--fast`. It deploys a cluster + a Lambda that binds
22 // `consumeKafkaTopic`, then verifies the event source mapping was created and
23 // points at the cluster with the configured topic. (A full produce/consume
24 // roundtrip additionally requires a Kafka admin/producer with MSK IAM auth to
25 // create and write the topic, which is out of scope here.)
26 describe.sequential(
27 "AWS.Kafka.KafkaEventSource",
28 {
29 tags: ["provider:aws", "provider:aws:ec2", "provider:aws:kafka", "provider:aws:lambda", "live"],
30 },
31 () => {
32 test.provider.skipIf(!!process.env.FAST)(
33 "creates an event source mapping pointing a Lambda at the cluster topic",
34 (stack) =>
35 Effect.gen(function* () {
36 yield* stack.destroy();
37
38 const { cluster, fn } = yield* stack.deploy(
39 Effect.gen(function* () {
40 const { cluster } = yield* FixtureCluster;
41 const fn = yield* KafkaTestFunction;
42 return { cluster, fn };
43 // FixtureClusterLive is provided inside the Function's own impl,
44 // so the stack must provide it too to read the cluster outputs
45 // (the engine de-dupes the shared "FixtureCluster" declaration).
46 }).pipe(Effect.provide(Layer.mergeAll(KafkaTestFunctionLive, FixtureClusterLive))),
47 );
48
49 expect(cluster.clusterArn).toContain(":cluster/");
50
51 // Verify the event source mapping exists, targets the cluster, and
52 // carries the configured topic. MSK ESMs progress
53 // CREATING -> ENABLING -> ENABLED; assert it reached at least CREATING
54 // and never FAILED.
55 const mapping = yield* waitForMapping(fn.functionName, cluster.clusterArn);
56 expect(mapping.Topics).toEqual(["orders"]);
57 expect(mapping.State).not.toBe("Failed");
58
59 // The execution role may delete ENIs only in the cluster's subnets.
60 // Lambda's create-time check (no subnet in its request) passed, or
61 // the mapping wouldn't exist; a delete in another subnet is denied.
62 const [account, region] = [
63 cluster.clusterArn.split(":")[4],
64 cluster.clusterArn.split(":")[3],
65 ];
66 const subnetArn = (id: string) => `arn:aws:ec2:${region}:${account}:subnet/${id}`;
67 const deleteDecision = (subnet: string) =>
68 IAM.simulatePrincipalPolicy({
69 PolicySourceArn: fn.roleArn,
70 ActionNames: ["ec2:DeleteNetworkInterface"],
71 ResourceArns: [
72 `arn:aws:ec2:${region}:${account}:network-interface/eni-0123456789abcdef0`,
73 ],
74 ContextEntries: [
75 {
76 ContextKeyName: "ec2:Subnet",
77 ContextKeyType: "string",
78 ContextKeyValues: [subnet],
79 },
80 {
81 ContextKeyName: "aws:RequestedRegion",
82 ContextKeyType: "string",
83 ContextKeyValues: [region!],
84 },
85 ],
86 }).pipe(Effect.map((result) => result.EvaluationResults?.[0]?.EvalDecision));
87 expect(yield* deleteDecision(subnetArn(cluster.subnetIds[0]!))).toBe("allowed");
88 expect(yield* deleteDecision(subnetArn("subnet-0123456789abcdef0"))).not.toBe("allowed");
89
90 // Drive the control-plane bindings end-to-end through the deployed
91 // function URL: GetBootstrapBrokers, ConnectReadWrite (env-published
92 // endpoint), ListTopics, and the CreateTopic → DescribeTopic →
93 // DeleteTopic roundtrip.
94 const baseUrl = fn.functionUrl!.replace(/\/+$/, "");
95 const get = (path: string) =>
96 HttpClient.get(`${baseUrl}${path}`).pipe(
97 Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
98 Effect.flatMap((res) =>
99 res.status === 200
100 ? res.json
101 : res.text.pipe(
102 Effect.flatMap((body) =>
103 Effect.die(new Error(`GET ${path} -> ${res.status}: ${body}`)),
104 ),
105 ),
106 ),
107 );
108
109 const brokers = (yield* get("/brokers")) as { saslIam?: string };
110 expect(brokers.saslIam).toContain(":9098");
111
112 const connect = (yield* get("/connect")) as {
113 bootstrapServers: string;
114 brokers: string[];
115 clusterArn: string;
116 authentication: string;
117 };
118 expect(connect.authentication).toBe("iam");
119 expect(connect.bootstrapServers).toContain(":9098");
120 expect(connect.clusterArn).toBe(cluster.clusterArn);
121
122 const topics = (yield* get("/topics")) as { topics?: string[]; error?: string };
123 // MSK Serverless rejects the topic control plane with the typed
124 // `ServerlessUnsupported` ("Topic APIs are not supported on
125 // serverless clusters.") — either branch proves the grant works.
126 if (topics.error === undefined) {
127 expect(Array.isArray(topics.topics)).toBe(true);
128 } else {
129 expect(["BadRequestException", "ServerlessUnsupported"]).toContain(topics.error);
130 }
131
132 const roundtrip = (yield* get("/topics/roundtrip")) as {
133 created: boolean;
134 partitions?: number;
135 error?: string;
136 };
137 // Serverless clusters that don't support the topic control plane
138 // surface a typed BadRequestException — either branch proves the
139 // grant + ClusterArn injection (an IAM gap would be a 500).
140 if (roundtrip.created) {
141 expect(roundtrip.partitions).toBe(1);
142 } else {
143 expect(roundtrip.error).toBeDefined();
144 }
145
146 yield* stack.destroy();
147 }),
148 { timeout: 1_200_000 },
149 );
150 },
151 );
152
153 class MappingNotReady extends Data.TaggedError("MappingNotReady")<{}> {}
154
155 const waitForMapping = Effect.fn(function* (functionName: string, eventSourceArn: string) {
156 return yield* Lambda.listEventSourceMappings({
157 FunctionName: functionName,
158 EventSourceArn: eventSourceArn,
159 }).pipe(
160 Effect.flatMap((result) => {
161 const mapping = result.EventSourceMappings?.[0];
162 return mapping?.UUID ? Effect.succeed(mapping) : Effect.fail(new MappingNotReady());
163 }),
164 Effect.retry({
165 while: (e) => e._tag === "MappingNotReady",
166 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]),
167 }),
168 );
169 });