The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as AWS from "@alchemy.run/aws"; |
| 2 | import * as EC2 from "@distilled.cloud/aws/ec2"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 6 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { getDefaultVpc } from "../DefaultVpc.ts"; |
| 10 | |
| 11 | export class KafkaTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()( |
| 12 | "KafkaTestFunction", |
| 13 | ) {} |
| 14 | |
| 15 | export class FixtureCluster extends Context.Service< |
| 16 | FixtureCluster, |
| 17 | { cluster: AWS.Kafka.ServerlessCluster } |
| 18 | >()("FixtureCluster") {} |
| 19 | |
| 20 | /** |
| 21 | * Resolve two default-for-AZ subnets from the account's default VPC — MSK |
| 22 | * requires at least two subnets in distinct AZs. Runtime-guarded: the Lambda |
| 23 | * runtime re-executes this props effect on cold start with no ec2:Describe* |
| 24 | * permission, so return an empty list there (VPC config is deploy-time only). |
| 25 | */ |
| 26 | const resolveSubnets = Effect.gen(function* () { |
| 27 | if (globalThis.__ALCHEMY_RUNTIME__) return [] as string[]; |
| 28 | const vpc = yield* getDefaultVpc; |
| 29 | const subnets = yield* EC2.describeSubnets({ |
| 30 | Filters: [ |
| 31 | { Name: "vpc-id", Values: [vpc.vpcId] }, |
| 32 | { Name: "default-for-az", Values: ["true"] }, |
| 33 | ], |
| 34 | }); |
| 35 | const byAz = new Map<string, string>(); |
| 36 | for (const s of subnets.Subnets ?? []) { |
| 37 | if (s.AvailabilityZone && s.SubnetId && !byAz.has(s.AvailabilityZone)) { |
| 38 | byAz.set(s.AvailabilityZone, s.SubnetId); |
| 39 | } |
| 40 | } |
| 41 | return [...byAz.values()].slice(0, 3); |
| 42 | }).pipe( |
| 43 | // Deploy-time lookup only; a failure here is a fixture defect, not a typed |
| 44 | // error the Function impl contract can carry. |
| 45 | Effect.orDie, |
| 46 | ); |
| 47 | |
| 48 | export const FixtureClusterLive = Layer.effect( |
| 49 | FixtureCluster, |
| 50 | Effect.gen(function* () { |
| 51 | const subnetIds = yield* resolveSubnets; |
| 52 | const cluster = yield* AWS.Kafka.ServerlessCluster("FixtureCluster", { |
| 53 | subnetIds, |
| 54 | tags: { fixture: "kafka-serverless" }, |
| 55 | }); |
| 56 | return { cluster }; |
| 57 | }), |
| 58 | ); |
| 59 | |
| 60 | export default KafkaTestFunction.make( |
| 61 | { main: import.meta.url, functionUrl: true }, |
| 62 | Effect.gen(function* () { |
| 63 | const { cluster } = yield* FixtureCluster; |
| 64 | |
| 65 | // Wire the "orders" topic to this function. At deploy time this grants MSK |
| 66 | // IAM-auth actions and creates the event source mapping; at runtime it |
| 67 | // registers the record handler below. |
| 68 | yield* AWS.Kafka.consumeKafkaTopic( |
| 69 | cluster, |
| 70 | { topics: ["orders"], consumerGroupId: "alchemy-fixture" }, |
| 71 | (records) => records.pipe(Stream.runForEach((r) => Effect.log(r.value))), |
| 72 | ); |
| 73 | |
| 74 | // Cluster-scoped control-plane bindings (grant + ClusterArn injection). |
| 75 | const getBootstrapBrokers = yield* AWS.Kafka.GetBootstrapBrokers(cluster); |
| 76 | const listTopics = yield* AWS.Kafka.ListTopics(cluster); |
| 77 | const createTopic = yield* AWS.Kafka.CreateTopic(cluster); |
| 78 | const describeTopic = yield* AWS.Kafka.DescribeTopic(cluster); |
| 79 | const deleteTopic = yield* AWS.Kafka.DeleteTopic(cluster); |
| 80 | // Data-plane connection descriptor (env-published bootstrap endpoint). |
| 81 | const connect = yield* AWS.Kafka.ConnectReadWrite(cluster); |
| 82 | |
| 83 | const ClusterArn = cluster.clusterArn; |
| 84 | |
| 85 | return { |
| 86 | fetch: Effect.gen(function* () { |
| 87 | const request = yield* HttpServerRequest; |
| 88 | const url = new URL(request.originalUrl ?? request.url, "http://x"); |
| 89 | if (url.pathname === "/cluster") { |
| 90 | const clusterArn = yield* ClusterArn; |
| 91 | return yield* HttpServerResponse.json({ clusterArn }); |
| 92 | } |
| 93 | if (url.pathname === "/brokers") { |
| 94 | const brokers = yield* getBootstrapBrokers(); |
| 95 | return yield* HttpServerResponse.json({ |
| 96 | saslIam: brokers.BootstrapBrokerStringSaslIam, |
| 97 | }); |
| 98 | } |
| 99 | if (url.pathname === "/connect") { |
| 100 | const info = yield* connect; |
| 101 | return yield* HttpServerResponse.json(info); |
| 102 | } |
| 103 | if (url.pathname === "/topics") { |
| 104 | // Like the roundtrip below, a typed rejection (topic APIs are not |
| 105 | // supported on serverless clusters: `ServerlessUnsupported`) is |
| 106 | // surfaced rather than thrown — an IAM gap is still a 500. |
| 107 | const result = yield* listTopics().pipe( |
| 108 | Effect.map((page) => ({ |
| 109 | topics: (page.Topics ?? []).map((t) => t.TopicName), |
| 110 | })), |
| 111 | Effect.catchTag(["BadRequestException", "ServerlessUnsupported"], (e) => |
| 112 | Effect.succeed({ error: e._tag }), |
| 113 | ), |
| 114 | // Any other failure is a real defect (e.g. an IAM gap): report it |
| 115 | // as a 500 whose body names the error so the test shows it. |
| 116 | Effect.catch((e) => |
| 117 | Effect.succeed({ |
| 118 | failed: true, |
| 119 | error: e._tag, |
| 120 | message: String(e), |
| 121 | detail: e._tag === "UnknownAwsError" ? e.errorTag : undefined, |
| 122 | }), |
| 123 | ), |
| 124 | ); |
| 125 | return yield* HttpServerResponse.json(result, { |
| 126 | status: "failed" in result ? 500 : 200, |
| 127 | }); |
| 128 | } |
| 129 | if (url.pathname === "/topics/roundtrip") { |
| 130 | // Create → describe → delete a probe topic through the MSK topic |
| 131 | // control plane. Typed 400s are surfaced (not thrown) so the test |
| 132 | // can distinguish "grant works, cluster type unsupported" from an |
| 133 | // IAM failure (which dies as a 500). |
| 134 | const outcome = yield* createTopic({ |
| 135 | TopicName: "alchemy-probe", |
| 136 | PartitionCount: 1, |
| 137 | }).pipe( |
| 138 | Effect.flatMap(() => |
| 139 | describeTopic({ TopicName: "alchemy-probe" }).pipe( |
| 140 | Effect.map((d) => ({ |
| 141 | created: true, |
| 142 | partitions: d.PartitionCount, |
| 143 | })), |
| 144 | ), |
| 145 | ), |
| 146 | Effect.tap(() => |
| 147 | deleteTopic({ TopicName: "alchemy-probe" }).pipe( |
| 148 | Effect.catchTag("NotFoundException", () => Effect.void), |
| 149 | ), |
| 150 | ), |
| 151 | Effect.catchTag( |
| 152 | ["BadRequestException", "ServerlessUnsupported", "TopicExistsException"], |
| 153 | (e) => Effect.succeed({ created: false, error: e._tag }), |
| 154 | ), |
| 155 | ); |
| 156 | return yield* HttpServerResponse.json(outcome); |
| 157 | } |
| 158 | return HttpServerResponse.text("ok"); |
| 159 | }).pipe(Effect.orDie), |
| 160 | }; |
| 161 | }).pipe( |
| 162 | Effect.provide( |
| 163 | Layer.provideMerge( |
| 164 | Layer.mergeAll( |
| 165 | AWS.Lambda.KafkaEventSource, |
| 166 | AWS.Kafka.GetBootstrapBrokersHttp, |
| 167 | AWS.Kafka.ListTopicsHttp, |
| 168 | AWS.Kafka.CreateTopicHttp, |
| 169 | AWS.Kafka.DescribeTopicHttp, |
| 170 | AWS.Kafka.DeleteTopicHttp, |
| 171 | AWS.Kafka.ConnectReadWriteHttp, |
| 172 | ), |
| 173 | FixtureClusterLive, |
| 174 | ), |
| 175 | ), |
| 176 | ), |
| 177 | // Re-merge so the deploying Stack can `yield* FixtureCluster` and expose the |
| 178 | // cluster attributes as deploy-time outputs. Reusing the same |
| 179 | // `FixtureClusterLive` reference keeps it a single shared cluster. |
| 180 | ).pipe(Layer.provideMerge(FixtureClusterLive)); |