@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 276 lines 10.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import {
3 AutoScalingGroup,
4 consumeInstanceEvents,
5 DescribeAutoScalingGroup,
6 DescribeAutoScalingGroupHttp,
7 DescribeScalingActivities,
8 DescribeScalingActivitiesHttp,
9 ExecutePolicy,
10 ExecutePolicyHttp,
11 InstanceRefresh,
12 InstanceRefreshHttp,
13 LaunchTemplate,
14 SetDesiredCapacity,
15 SetDesiredCapacityHttp,
16 SetInstanceHealth,
17 SetInstanceHealthHttp,
18 SetInstanceProtection,
19 SetInstanceProtectionHttp,
20 Standby,
21 StandbyHttp,
22 TerminateInstanceInAutoScalingGroup,
23 TerminateInstanceInAutoScalingGroupHttp,
24 } from "@alchemy.run/aws/AutoScaling";
25 import { amazonLinux2023 } from "@alchemy.run/aws/EC2";
26 import * as Output from "alchemy/Output";
27 import * as Context from "effect/Context";
28 import * as Duration from "effect/Duration";
29 import * as Effect from "effect/Effect";
30 import { HttpServerRequest } from "effect/http/HttpServerRequest";
31 import * as HttpServerResponse from "effect/http/HttpServerResponse";
32 import * as Layer from "effect/Layer";
33 import * as Stream from "effect/Stream";
34 import { getAutoScalingTestSubnetId } from "../TestNetwork.ts";
35
36 export const bindingsAsgName = "alchemy-test-asg-bindings-asg";
37
38 /** A well-formed instance id that does not exist — probes reach the service
39 * (proving credentials + IAM) and come back as a typed `ValidationError`. */
40 const bogusInstanceId = "i-00000000000000000";
41
42 export class AsgBindingsFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
43 "AsgBindingsFunction",
44 ) {}
45
46 /**
47 * Shared fleet for the bindings E2E: a launch template + Auto Scaling Group
48 * sized to zero (no instances launch). Subnet/AMI are `Output`s resolved at
49 * deploy time only, so this composition is safe to re-execute inside the
50 * deployed Lambda without runtime guards.
51 */
52 export class BindingsFleet extends Context.Service<BindingsFleet, { group: AutoScalingGroup }>()(
53 "AutoScalingBindingsFleet",
54 ) {}
55
56 export const BindingsFleetLive = Layer.effect(
57 BindingsFleet,
58 Effect.gen(function* () {
59 const imageId = amazonLinux2023();
60 const subnetId = Output.fromEffect(getAutoScalingTestSubnetId.pipe(Effect.orDie));
61
62 const template = yield* LaunchTemplate("BindingsTemplate", {
63 imageId,
64 instanceType: "t3.micro",
65 });
66 const group = yield* AutoScalingGroup("BindingsGroup", {
67 autoScalingGroupName: bindingsAsgName,
68 launchTemplate: template,
69 subnetIds: [subnetId],
70 minSize: 0,
71 maxSize: 0,
72 desiredCapacity: 0,
73 });
74 return { group };
75 }),
76 );
77
78 export default AsgBindingsFunction.make(
79 {
80 main: import.meta.url,
81 functionUrl: true,
82 // The AWS defaults (128 MB / 3s) are too tight for the AutoScaling
83 // client: cold routes time out at exactly 3s (the function URL turns
84 // that into a 502) with memory pegged at 127/128 MB.
85 timeout: Duration.seconds(30),
86 memorySize: 512,
87 },
88 Effect.gen(function* () {
89 const { group } = yield* BindingsFleet;
90
91 const describeGroup = yield* DescribeAutoScalingGroup(group);
92 const describeActivities = yield* DescribeScalingActivities(group);
93 const setDesiredCapacity = yield* SetDesiredCapacity(group);
94 const executePolicy = yield* ExecutePolicy(group);
95 const setInstanceHealth = yield* SetInstanceHealth(group);
96 const setInstanceProtection = yield* SetInstanceProtection(group);
97 const terminateInstance = yield* TerminateInstanceInAutoScalingGroup(group);
98 const standby = yield* Standby(group);
99 const refresh = yield* InstanceRefresh(group);
100
101 // Subscribe to completed launch/terminate scaling activities (creates the
102 // EventBridge rule at deploy time).
103 yield* consumeInstanceEvents(group, {}, (events) =>
104 Stream.runForEach(events, (event) =>
105 Effect.log(
106 `${event["detail-type"]}: ${event.detail.EC2InstanceId} in ${event.detail.AutoScalingGroupName}`,
107 ),
108 ),
109 );
110
111 return {
112 fetch: Effect.gen(function* () {
113 const request = yield* HttpServerRequest;
114 const pathname = new URL(request.originalUrl).pathname;
115
116 if (request.method === "GET" && pathname === "/health") {
117 return yield* HttpServerResponse.json({ ok: true });
118 }
119
120 if (request.method === "GET" && pathname === "/describe") {
121 const result = yield* describeGroup().pipe(Effect.result);
122 return yield* HttpServerResponse.json({
123 ok: result._tag === "Success",
124 tag: result._tag === "Failure" ? result.failure._tag : "Success",
125 name: result._tag === "Success" ? result.success?.AutoScalingGroupName : undefined,
126 maxSize: result._tag === "Success" ? result.success?.MaxSize : undefined,
127 });
128 }
129
130 if (request.method === "GET" && pathname === "/activities") {
131 const result = yield* describeActivities({ MaxRecords: 10 }).pipe(Effect.result);
132 return yield* HttpServerResponse.json({
133 ok: result._tag === "Success",
134 tag: result._tag === "Failure" ? result.failure._tag : "Success",
135 count: result._tag === "Success" ? (result.success.Activities ?? []).length : undefined,
136 });
137 }
138
139 if (request.method === "POST" && pathname === "/set-desired") {
140 const result = yield* setDesiredCapacity({
141 DesiredCapacity: 0,
142 }).pipe(Effect.result);
143 return yield* HttpServerResponse.json({
144 ok: result._tag === "Success",
145 tag: result._tag === "Failure" ? result.failure._tag : "Success",
146 });
147 }
148
149 // Executes a policy that doesn't exist: AWS rejects it with a typed
150 // `ValidationError` rather than AccessDenied, proving the IAM policy
151 // the binding attached is correct.
152 if (request.method === "POST" && pathname === "/execute-policy") {
153 const result = yield* executePolicy({
154 PolicyName: "alchemy-test-bogus-policy",
155 }).pipe(Effect.result);
156 return yield* HttpServerResponse.json({
157 ok: result._tag === "Success",
158 tag: result._tag === "Failure" ? result.failure._tag : "Success",
159 });
160 }
161
162 // Instance-scoped operation: the request carries no group name, so
163 // EC2 Auto Scaling resolves the instance's owning group for
164 // resource-level authorization. A bogus instance resolves to nothing,
165 // which the (correct, least-privilege) group-scoped grant denies.
166 if (request.method === "POST" && pathname === "/set-health") {
167 const result = yield* setInstanceHealth({
168 InstanceId: bogusInstanceId,
169 HealthStatus: "Unhealthy",
170 }).pipe(Effect.result);
171 return yield* HttpServerResponse.json({
172 ok: result._tag === "Success",
173 tag: result._tag === "Failure" ? result.failure._tag : "Success",
174 });
175 }
176
177 if (request.method === "POST" && pathname === "/set-protection") {
178 const result = yield* setInstanceProtection({
179 InstanceIds: [bogusInstanceId],
180 ProtectedFromScaleIn: true,
181 }).pipe(Effect.result);
182 return yield* HttpServerResponse.json({
183 ok: result._tag === "Success",
184 tag: result._tag === "Failure" ? result.failure._tag : "Success",
185 });
186 }
187
188 // Instance-scoped like /set-health above — see that comment.
189 if (request.method === "POST" && pathname === "/terminate") {
190 const result = yield* terminateInstance({
191 InstanceId: bogusInstanceId,
192 ShouldDecrementDesiredCapacity: false,
193 }).pipe(Effect.result);
194 return yield* HttpServerResponse.json({
195 ok: result._tag === "Success",
196 tag: result._tag === "Failure" ? result.failure._tag : "Success",
197 });
198 }
199
200 if (request.method === "POST" && pathname === "/standby-enter") {
201 const result = yield* standby
202 .enter({
203 InstanceIds: [bogusInstanceId],
204 ShouldDecrementDesiredCapacity: true,
205 })
206 .pipe(Effect.result);
207 return yield* HttpServerResponse.json({
208 ok: result._tag === "Success",
209 tag: result._tag === "Failure" ? result.failure._tag : "Success",
210 });
211 }
212
213 if (request.method === "POST" && pathname === "/standby-exit") {
214 const result = yield* standby
215 .exit({ InstanceIds: [bogusInstanceId] })
216 .pipe(Effect.result);
217 return yield* HttpServerResponse.json({
218 ok: result._tag === "Success",
219 tag: result._tag === "Failure" ? result.failure._tag : "Success",
220 });
221 }
222
223 // Full instance-refresh cycle on the zero-instance fleet: start
224 // succeeds (and completes immediately with nothing to replace),
225 // describe lists it, cancel tolerates the already-finished refresh.
226 if (request.method === "POST" && pathname === "/refresh") {
227 const started = yield* refresh.start().pipe(Effect.result);
228 const startTag = started._tag === "Failure" ? started.failure._tag : "Success";
229
230 const described = yield* refresh.describe().pipe(Effect.result);
231 const describeOk = described._tag === "Success";
232 const describeCount =
233 described._tag === "Success"
234 ? (described.success.InstanceRefreshes ?? []).length
235 : undefined;
236
237 const cancelled = yield* refresh.cancel().pipe(
238 Effect.catchTag("ActiveInstanceRefreshNotFoundFault", () =>
239 Effect.succeed({ InstanceRefreshId: undefined }),
240 ),
241 Effect.result,
242 );
243 const cancelTag = cancelled._tag === "Failure" ? cancelled.failure._tag : "Success";
244
245 return yield* HttpServerResponse.json({
246 startTag,
247 describeOk,
248 describeCount,
249 cancelTag,
250 });
251 }
252
253 return yield* HttpServerResponse.json(
254 { error: "Not found", method: request.method, pathname },
255 { status: 404 },
256 );
257 }).pipe(Effect.orDie),
258 };
259 }).pipe(
260 Effect.provide(
261 Layer.mergeAll(
262 AWS.Lambda.EventSource,
263 DescribeAutoScalingGroupHttp,
264 DescribeScalingActivitiesHttp,
265 SetDesiredCapacityHttp,
266 ExecutePolicyHttp,
267 SetInstanceHealthHttp,
268 SetInstanceProtectionHttp,
269 TerminateInstanceInAutoScalingGroupHttp,
270 StandbyHttp,
271 InstanceRefreshHttp,
272 BindingsFleetLive,
273 ),
274 ),
275 ),
276 );