@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 218 lines 7.58 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Output from "alchemy/Output";
3 import * as Config from "effect/Config";
4 import * as ConfigProvider from "effect/ConfigProvider";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Layer from "effect/Layer";
10
11 /** The rules EventBridge manages on a global endpoint's bus, from the bus ARN. */
12 const managedRuleArnOf = (eventBusArn: string) =>
13 `${eventBusArn.replace(":event-bus/", ":rule/")}/GlobalEndpointManagedRule-*`;
14
15 const REPLICATION_PATH = "/eventbridge-replication/";
16
17 /** Roles on the replication path in the bus's account, from the bus ARN. */
18 const replicationRolesOf = (eventBusArn: string) =>
19 `arn:aws:iam::${eventBusArn.split(":")[4]}:role${REPLICATION_PATH}*`;
20
21 /** The failover region: any region other than the stack's. */
22 export const secondaryRegionOf = (region: string) =>
23 region === "us-east-1" ? "us-east-2" : "us-east-1";
24
25 /**
26 * A global endpoint over a same-named bus in the stack's region and in
27 * {@link secondaryRegionOf}, failing over on an always-healthy calculated
28 * health check. A rule on the primary bus routes the fixture's events to an
29 * SQS queue the test reads out-of-band.
30 */
31 export class EndpointInfra extends Context.Service<
32 EndpointInfra,
33 {
34 primary: AWS.EventBridge.EventBus;
35 secondary: AWS.EventBridge.EventBus;
36 endpoint: AWS.EventBridge.Endpoint;
37 queue: AWS.SQS.Queue;
38 }
39 >()("EventBridgeEndpointInfra") {}
40
41 export interface EndpointInfraOptions {
42 description: string;
43 replication: boolean;
44 }
45
46 export const EndpointInfraLive = (options: EndpointInfraOptions) =>
47 Layer.effect(
48 EndpointInfra,
49 Effect.gen(function* () {
50 // The region is configuration: report a missing one as a ConfigError.
51 const region = yield* (yield* AWS.Region).pipe(
52 Effect.mapError(
53 (e) =>
54 new Config.ConfigError(
55 e._tag === "SourceError" ? e : new ConfigProvider.SourceError({ message: e.message }),
56 ),
57 ),
58 );
59 const secondaryRegion = secondaryRegionOf(region);
60
61 const primary = yield* AWS.EventBridge.EventBus("PrimaryBus", {
62 forceDestroy: true,
63 });
64 // Both buses of a global endpoint must share a name.
65 const secondary = yield* AWS.EventBridge.EventBus("SecondaryBus", {
66 name: primary.eventBusName,
67 region: secondaryRegion,
68 forceDestroy: true,
69 });
70 // No children and a threshold of 0: always healthy, so events stay in
71 // the primary region.
72 const health = yield* AWS.Route53.HealthCheck("PrimaryHealth", {
73 type: "CALCULATED",
74 healthThreshold: 0,
75 childHealthChecks: [],
76 });
77 const role = yield* AWS.IAM.Role("ReplicationRole", {
78 path: REPLICATION_PATH,
79 assumeRolePolicyDocument: {
80 Version: "2012-10-17",
81 Statement: [
82 {
83 Effect: "Allow",
84 Principal: { Service: "events.amazonaws.com" },
85 Action: ["sts:AssumeRole"],
86 },
87 ],
88 },
89 inlinePolicies: {
90 Replicate: {
91 Version: "2012-10-17",
92 Statement: [
93 {
94 Effect: "Allow",
95 Action: ["events:PutEvents"],
96 Resource: [primary.eventBusArn, secondary.eventBusArn],
97 },
98 // EventBridge manages a replication rule on each bus.
99 {
100 Effect: "Allow",
101 Action: [
102 "events:PutRule",
103 "events:PutTargets",
104 "events:DeleteRule",
105 "events:RemoveTargets",
106 ],
107 Resource: [primary.eventBusArn, secondary.eventBusArn].map((arn) =>
108 arn.pipe(Output.map(managedRuleArnOf)),
109 ),
110 },
111 // EventBridge passes this role to its managed rules' targets;
112 // only roles on the replication path can be passed, and only
113 // to EventBridge.
114 {
115 Effect: "Allow",
116 Action: ["iam:PassRole"],
117 Resource: [primary.eventBusArn.pipe(Output.map(replicationRolesOf))],
118 Condition: { StringEquals: { "iam:PassedToService": "events.amazonaws.com" } },
119 },
120 ],
121 },
122 },
123 });
124 const endpoint = yield* AWS.EventBridge.Endpoint("GlobalEndpoint", {
125 description: options.description,
126 eventBuses: [primary.eventBusArn, secondary.eventBusArn],
127 failover: {
128 healthCheck: health.healthCheckId,
129 secondaryRegion,
130 },
131 replication: options.replication,
132 roleArn: role.roleArn,
133 });
134
135 // The delivery policy is a plain prop so the Queue never depends on
136 // the Rule (see sink-handler.ts).
137 const queue = yield* AWS.SQS.Queue("EndpointSinkQueue", {
138 policy: {
139 Version: "2012-10-17",
140 Statement: [
141 {
142 Effect: "Allow",
143 Principal: { Service: "events.amazonaws.com" },
144 Action: "sqs:SendMessage",
145 Resource: "*",
146 },
147 ],
148 },
149 });
150 yield* AWS.EventBridge.Rule("EndpointSinkRoute", {
151 eventBusName: primary.eventBusName,
152 eventPattern: { source: ["alchemy.test.endpoint"] },
153 targets: [{ Id: "EndpointSinkQueueTarget", Arn: queue.queueArn as any }],
154 });
155 return { primary, secondary, endpoint, queue };
156 }),
157 );
158
159 export class EndpointTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
160 "EndpointTestFunction",
161 ) {}
162
163 export const EndpointTestFunctionLive = (options: EndpointInfraOptions) =>
164 EndpointTestFunction.make(
165 {
166 main: import.meta.url,
167 functionUrl: true,
168 },
169 Effect.gen(function* () {
170 const { endpoint } = yield* EndpointInfra;
171 const putEvents = yield* AWS.EventBridge.PutEvents(endpoint);
172
173 return {
174 fetch: Effect.gen(function* () {
175 const request = yield* HttpServerRequest;
176 const pathname = new URL(request.originalUrl).pathname;
177
178 if (request.method === "GET" && pathname === "/health") {
179 return yield* HttpServerResponse.json({ ok: true });
180 }
181
182 if (request.method === "POST" && pathname === "/publish") {
183 const body = (yield* request.json) as unknown as { marker: string };
184 const result = yield* putEvents({
185 Entries: [
186 {
187 Source: "alchemy.test.endpoint",
188 DetailType: "EndpointEvent",
189 Detail: JSON.stringify({ marker: body.marker }),
190 },
191 ],
192 });
193 return yield* HttpServerResponse.json({
194 failedEntryCount: result.FailedEntryCount ?? 0,
195 entries: result.Entries ?? [],
196 });
197 }
198
199 return yield* HttpServerResponse.json(
200 { error: "Not found", method: request.method, pathname },
201 { status: 404 },
202 );
203 }).pipe(
204 Effect.catch((error) =>
205 Effect.succeed(
206 HttpServerResponse.text(`Internal server error: ${String(error)}`, {
207 status: 500,
208 }),
209 ),
210 ),
211 ),
212 };
213 }).pipe(
214 Effect.provide(Layer.mergeAll(EndpointInfraLive(options), AWS.EventBridge.PutEventsHttp)),
215 ),
216 );
217
218 export default EndpointTestFunctionLive({ description: "initial", replication: true });