@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 190 lines 7.03 KB
Raw
1 import * as Batch from "@alchemy.run/aws/Batch";
2 import * as IAM from "@alchemy.run/aws/IAM";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import type * as batch from "@distilled.cloud/aws/batch";
5 import * as Duration from "effect/Duration";
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 import * as Stream from "effect/Stream";
11 import path from "pathe";
12 import { BatchTestNetwork } from "./TestNetwork.ts";
13
14 const main = path.resolve(import.meta.dirname, "handler.ts");
15
16 export class BatchTestFunction extends Lambda.Function<Lambda.Function>()("BatchTestFunction") {}
17
18 export default BatchTestFunction.make(
19 {
20 main,
21 functionUrl: true,
22 // submit/describe fan out SDK calls — AWS's 3s default intermittently
23 // times out under cold starts.
24 timeout: Duration.seconds(30),
25 },
26 Effect.gen(function* () {
27 // The default run uses a managed Fargate CE so the SUCCEEDED round-trip in
28 // Bindings.test.ts can actually run a job. Under --fast (FAST=1) the
29 // capability tests only need jobs to reach RUNNABLE, so an unmanaged CE
30 // with no VPC resources is enough. Bindings.test.ts gates SUCCEEDED on the
31 // same predicate: an unmanaged CE has no instances, so jobs never leave RUNNABLE.
32 const fargate = !process.env.FAST;
33 const unmanagedServiceRole = fargate
34 ? undefined
35 : yield* IAM.Role("BatchServiceRole", {
36 assumeRolePolicyDocument: {
37 Version: "2012-10-17",
38 Statement: [
39 {
40 Effect: "Allow",
41 Principal: { Service: "batch.amazonaws.com" },
42 Action: ["sts:AssumeRole"],
43 },
44 ],
45 },
46 managedPolicyArns: ["arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole"],
47 });
48
49 const computeEnvironment = fargate
50 ? yield* Effect.gen(function* () {
51 const network = yield* BatchTestNetwork;
52 return yield* Batch.ComputeEnvironment("TestCE", {
53 subnets: network.subnetIds,
54 securityGroupIds: network.securityGroupIds,
55 });
56 })
57 : yield* Batch.ComputeEnvironment("TestCE", {
58 managementType: "UNMANAGED",
59 unmanagedvCpus: 4,
60 serviceRole: unmanagedServiceRole!.roleArn,
61 });
62 const queue = yield* Batch.JobQueue("TestQueue", {
63 computeEnvironments: [computeEnvironment.computeEnvironmentArn],
64 });
65 const executionRole = yield* IAM.Role("BatchExecutionRole", {
66 assumeRolePolicyDocument: {
67 Version: "2012-10-17",
68 Statement: [
69 {
70 Effect: "Allow",
71 Principal: { Service: "ecs-tasks.amazonaws.com" },
72 Action: ["sts:AssumeRole"],
73 },
74 ],
75 },
76 managedPolicyArns: ["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"],
77 });
78 const jobDefinition = yield* Batch.JobDefinition("EchoJob", {
79 image: "public.ecr.aws/docker/library/busybox:latest",
80 command: ["echo", "hello-from-batch"],
81 executionRoleArn: executionRole.roleArn,
82 platformCapabilities: fargate ? ["FARGATE"] : ["EC2"],
83 vcpus: fargate ? 0.25 : 1,
84 timeout: Duration.minutes(5),
85 });
86
87 const submitJob = yield* Batch.SubmitJob(queue, jobDefinition);
88 const describeJobs = yield* Batch.DescribeJobs(queue);
89 const terminateJob = yield* Batch.TerminateJob(queue);
90 const cancelJob = yield* Batch.CancelJob(queue);
91 const listJobs = yield* Batch.ListJobs(queue);
92 const getJobQueueSnapshot = yield* Batch.GetJobQueueSnapshot(queue);
93
94 // Deploy-time: creates the EventBridge rule (default bus, source
95 // aws.batch) targeting this Function. Runtime firing rides on real job
96 // submissions from the suite; the test verifies the rule deploys.
97 yield* Batch.consumeJobEvents({ kinds: ["job-state"] }, (events) =>
98 Stream.runForEach(events, (event) =>
99 Effect.log(`batch job event: ${event.detail.jobId} -> ${event.detail.status}`),
100 ),
101 );
102
103 return {
104 fetch: Effect.gen(function* () {
105 const request = yield* HttpServerRequest;
106 const url = new URL(request.originalUrl);
107 const pathname = url.pathname;
108
109 if (request.method === "POST" && pathname === "/submit") {
110 const body = (yield* request.json) as unknown as {
111 jobName: string;
112 };
113 const result = yield* submitJob({ jobName: body.jobName });
114 return yield* HttpServerResponse.json({
115 jobId: result.jobId,
116 jobName: result.jobName,
117 jobArn: result.jobArn,
118 });
119 }
120
121 if (request.method === "GET" && pathname === "/status") {
122 const jobId = url.searchParams.get("jobId")!;
123 const result = yield* describeJobs({ jobs: [jobId] });
124 const job = result.jobs?.[0];
125 return yield* HttpServerResponse.json({
126 status: job?.status,
127 statusReason: job?.statusReason,
128 jobQueue: job?.jobQueue,
129 });
130 }
131
132 if (request.method === "POST" && pathname === "/terminate") {
133 const body = (yield* request.json) as unknown as {
134 jobId: string;
135 reason: string;
136 };
137 yield* terminateJob({ jobId: body.jobId, reason: body.reason });
138 return yield* HttpServerResponse.json({ terminated: true });
139 }
140
141 if (request.method === "POST" && pathname === "/cancel") {
142 const body = (yield* request.json) as unknown as {
143 jobId: string;
144 reason: string;
145 };
146 yield* cancelJob({ jobId: body.jobId, reason: body.reason });
147 return yield* HttpServerResponse.json({ cancelled: true });
148 }
149
150 if (request.method === "GET" && pathname === "/jobs") {
151 const jobStatus = url.searchParams.get("jobStatus") ?? undefined;
152 const result = yield* listJobs(
153 jobStatus ? { jobStatus: jobStatus as batch.JobStatus } : {},
154 );
155 return yield* HttpServerResponse.json({
156 jobs: (result.jobSummaryList ?? []).map((job) => ({
157 jobId: job.jobId,
158 jobName: job.jobName,
159 status: job.status,
160 })),
161 });
162 }
163
164 if (request.method === "GET" && pathname === "/snapshot") {
165 const result = yield* getJobQueueSnapshot();
166 return yield* HttpServerResponse.json({
167 jobs: (result.frontOfQueue?.jobs ?? []).map((job) => job.jobArn),
168 });
169 }
170
171 return yield* HttpServerResponse.json(
172 { error: "Not found", method: request.method, pathname },
173 { status: 404 },
174 );
175 }).pipe(Effect.orDie),
176 };
177 }).pipe(
178 Effect.provide(
179 Layer.mergeAll(
180 Lambda.EventSource,
181 Batch.SubmitJobHttp,
182 Batch.DescribeJobsHttp,
183 Batch.TerminateJobHttp,
184 Batch.CancelJobHttp,
185 Batch.ListJobsHttp,
186 Batch.GetJobQueueSnapshotHttp,
187 ),
188 ),
189 ),
190 );