@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 237 lines 8.88 KB
Raw
1 import * as EC2 from "@alchemy.run/aws/EC2";
2 import * as ECS from "@alchemy.run/aws/ECS";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class EcsBindingsTestFunction extends Lambda.Function<Lambda.Function>()(
14 "EcsBindingsTestFunction",
15 ) {}
16
17 // `ECS.Task` is a Platform; its static type doesn't surface the
18 // `ResourceClass.ref` that the runtime object carries (plain `Resource`
19 // classes like `ECS.Cluster` type it). Narrow it here.
20 const TaskRef = ECS.Task as unknown as {
21 ref: (id: string) => Effect.Effect<ECS.Task>;
22 };
23
24 /**
25 * Lambda fixture hosting the ECS task-control bindings:
26 * `RunTask`, `StopTask`, `DescribeTasks`, `ListTasks` — one HTTP route per
27 * operation.
28 *
29 * The cluster, one-shot task definition, and public subnet are deployed by
30 * the test's stack program (phase 1) and referenced here via
31 * `Resource.ref(...)`. Yielding them inline would re-execute their layers
32 * inside the Lambda runtime — and nesting a Platform resource (the ECS
33 * `Task`) under the Lambda bridge's intercepting ConfigProvider recurses
34 * config lookups until the sandbox OOMs. Refs resolve from stack state at
35 * deploy and from the injected environment at runtime.
36 */
37 export default EcsBindingsTestFunction.make(
38 {
39 main,
40 functionUrl: true,
41 timeout: Duration.seconds(30),
42 memorySize: 512,
43 },
44 Effect.gen(function* () {
45 const cluster = yield* ECS.Cluster.ref("EcsBindingsCluster");
46 const task = yield* TaskRef.ref("EcsBindingsOneShotTask");
47 const subnet = yield* EC2.Subnet.ref("EcsBindingsSubnet");
48
49 const runTask = yield* ECS.RunTask(cluster, task);
50 const stopTask = yield* ECS.StopTask(cluster);
51 const describeTasks = yield* ECS.DescribeTasks(cluster);
52 const listTasks = yield* ECS.ListTasks(cluster);
53 const describeServices = yield* ECS.DescribeServices(cluster);
54 const listServices = yield* ECS.ListServices(cluster);
55 const listContainerInstances = yield* ECS.ListContainerInstances(cluster);
56 const getTaskProtection = yield* ECS.GetTaskProtection(cluster);
57 const updateTaskProtection = yield* ECS.UpdateTaskProtection(cluster);
58
59 const SubnetId = yield* subnet.subnetId;
60 const ContainerName = yield* task.containerName;
61
62 return {
63 fetch: Effect.gen(function* () {
64 const request = yield* HttpServerRequest;
65 const url = new URL(request.originalUrl);
66 const pathname = url.pathname;
67
68 if (request.method === "POST" && pathname === "/run") {
69 const body = (yield* request.json) as unknown as {
70 command?: string[];
71 startedBy?: string;
72 };
73 const subnetId = yield* SubnetId;
74 const containerName = yield* ContainerName;
75 const response = yield* runTask({
76 launchType: "FARGATE",
77 count: 1,
78 startedBy: body.startedBy ?? "alchemy-ecs-bindings-test",
79 networkConfiguration: {
80 awsvpcConfiguration: {
81 subnets: [subnetId],
82 // No securityGroups: the VPC default security group applies
83 // (all egress allowed — enough to pull the image from ECR).
84 assignPublicIp: "ENABLED",
85 },
86 },
87 ...(body.command
88 ? {
89 overrides: {
90 containerOverrides: [{ name: containerName, command: body.command }],
91 },
92 }
93 : {}),
94 });
95 return yield* HttpServerResponse.json({
96 taskArn: response.tasks?.[0]?.taskArn,
97 lastStatus: response.tasks?.[0]?.lastStatus,
98 failures: response.failures,
99 });
100 }
101
102 if (request.method === "POST" && pathname === "/stop") {
103 const body = (yield* request.json) as unknown as {
104 taskArn: string;
105 reason?: string;
106 };
107 const response = yield* stopTask({
108 task: body.taskArn,
109 reason: body.reason,
110 });
111 return yield* HttpServerResponse.json({
112 taskArn: response.task?.taskArn,
113 lastStatus: response.task?.lastStatus,
114 desiredStatus: response.task?.desiredStatus,
115 });
116 }
117
118 if (request.method === "GET" && pathname === "/describe") {
119 const taskArn = url.searchParams.get("task");
120 if (!taskArn) {
121 return HttpServerResponse.text("Missing task", { status: 400 });
122 }
123 const response = yield* describeTasks({ tasks: [taskArn] });
124 return yield* HttpServerResponse.json({
125 tasks: response.tasks?.map((t) => ({
126 taskArn: t.taskArn,
127 lastStatus: t.lastStatus,
128 stoppedReason: t.stoppedReason,
129 startedBy: t.startedBy,
130 containers: t.containers?.map((c) => ({
131 name: c.name,
132 exitCode: c.exitCode,
133 lastStatus: c.lastStatus,
134 })),
135 })),
136 failures: response.failures,
137 });
138 }
139
140 if (request.method === "GET" && pathname === "/list") {
141 const desiredStatus = url.searchParams.get("status");
142 const startedBy = url.searchParams.get("startedBy");
143 const response = yield* listTasks({
144 ...(desiredStatus ? { desiredStatus: desiredStatus as "RUNNING" | "STOPPED" } : {}),
145 ...(startedBy ? { startedBy } : {}),
146 });
147 return yield* HttpServerResponse.json({
148 taskArns: response.taskArns ?? [],
149 });
150 }
151
152 if (request.method === "GET" && pathname === "/services") {
153 const response = yield* listServices({});
154 return yield* HttpServerResponse.json({
155 serviceArns: response.serviceArns ?? [],
156 });
157 }
158
159 if (request.method === "GET" && pathname === "/describe-services") {
160 const service = url.searchParams.get("service");
161 if (!service) {
162 return HttpServerResponse.text("Missing service", { status: 400 });
163 }
164 const response = yield* describeServices({ services: [service] });
165 return yield* HttpServerResponse.json({
166 services: response.services?.map((s) => ({
167 serviceName: s.serviceName,
168 status: s.status,
169 })),
170 failures: response.failures,
171 });
172 }
173
174 if (request.method === "GET" && pathname === "/container-instances") {
175 const response = yield* listContainerInstances({});
176 return yield* HttpServerResponse.json({
177 containerInstanceArns: response.containerInstanceArns ?? [],
178 });
179 }
180
181 if (request.method === "GET" && pathname === "/protection") {
182 const taskArn = url.searchParams.get("task");
183 if (!taskArn) {
184 return HttpServerResponse.text("Missing task", { status: 400 });
185 }
186 const response = yield* getTaskProtection({ tasks: [taskArn] }).pipe(
187 Effect.map((r) => ({
188 protectedTasks: r.protectedTasks,
189 failures: r.failures,
190 })),
191 Effect.catchTag(["InvalidParameterException", "ResourceNotFoundException"], (e) =>
192 Effect.succeed({ error: e._tag as string }),
193 ),
194 );
195 return yield* HttpServerResponse.json(response);
196 }
197
198 if (request.method === "POST" && pathname === "/protect") {
199 const body = (yield* request.json) as unknown as {
200 taskArn: string;
201 };
202 const response = yield* updateTaskProtection({
203 tasks: [body.taskArn],
204 protectionEnabled: true,
205 // Duration.Input → whole wire minutes via the central util.
206 expiresIn: "10 minutes",
207 }).pipe(
208 Effect.map((r) => ({
209 protectedTasks: r.protectedTasks,
210 failures: r.failures,
211 })),
212 Effect.catchTag(["InvalidParameterException", "ResourceNotFoundException"], (e) =>
213 Effect.succeed({ error: e._tag as string }),
214 ),
215 );
216 return yield* HttpServerResponse.json(response);
217 }
218
219 return yield* HttpServerResponse.json({ error: "Not found" }, { status: 404 });
220 }).pipe(Effect.orDie),
221 };
222 }).pipe(
223 Effect.provide(
224 Layer.mergeAll(
225 ECS.RunTaskHttp,
226 ECS.StopTaskHttp,
227 ECS.DescribeTasksHttp,
228 ECS.ListTasksHttp,
229 ECS.DescribeServicesHttp,
230 ECS.ListServicesHttp,
231 ECS.ListContainerInstancesHttp,
232 ECS.GetTaskProtectionHttp,
233 ECS.UpdateTaskProtectionHttp,
234 ),
235 ),
236 ),
237 );