The best way to control Claude Code, Codex and more from any computer or phone

main
ts 404 lines 16.4 KB
Raw
1 import * as CodeBuild from "@alchemy.run/aws/CodeBuild";
2 import * as IAM from "@alchemy.run/aws/IAM";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Logs from "@alchemy.run/aws/Logs";
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
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 export const FIXTURE_PROJECT_NAME = "alchemy-test-codebuild-bindings";
16 export const FIXTURE_REPORT_GROUP_NAME = "alchemy-test-codebuild-bindings-reports";
17
18 const buildspec = [
19 "version: 0.2",
20 "phases:",
21 " build:",
22 " commands:",
23 " - echo Hello from CodeBuild bindings fixture",
24 ].join("\n");
25
26 export class CodeBuildTestFunction extends Lambda.Function<Lambda.Function>()(
27 "CodeBuildTestFunction",
28 ) {}
29
30 /**
31 * Every route answers `{ …fields }` on success or `{ errorTag }` when the
32 * operation fails with a TYPED error — the test asserts the tag is a typed,
33 * non-authorization tag, which proves both the binding wiring and the IAM
34 * grant. An untyped error crashes into a 500 instead.
35 */
36 const errorTagged = <A, E extends { _tag: string }, R>(
37 effect: Effect.Effect<A, E, R>,
38 ): Effect.Effect<A | { errorTag: string }, never, R> =>
39 effect.pipe(
40 Effect.map((a): A | { errorTag: string } => a),
41 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
42 );
43
44 export default CodeBuildTestFunction.make(
45 {
46 main,
47 functionUrl: true,
48 // Build start/stop fan out SDK calls — AWS's 3s default intermittently
49 // times out under cold starts.
50 timeout: Duration.seconds(30),
51 },
52 Effect.gen(function* () {
53 const role = yield* IAM.Role("CodeBuildBindingsRole", {
54 assumeRolePolicyDocument: {
55 Version: "2012-10-17",
56 Statement: [
57 {
58 Effect: "Allow",
59 Principal: { Service: "codebuild.amazonaws.com" },
60 Action: ["sts:AssumeRole"],
61 },
62 ],
63 },
64 inlinePolicies: {
65 Logs: {
66 Version: "2012-10-17",
67 Statement: [
68 {
69 Effect: "Allow",
70 Action: ["logs:CreateLogStream", "logs:PutLogEvents"],
71 Resource: ["*"],
72 },
73 ],
74 },
75 },
76 });
77
78 // Own CodeBuild's deterministic log destination in the stack instead of
79 // allowing the service to create its implicit `/aws/codebuild/...` group.
80 // Project depends on this output, so destroy deletes the Project before
81 // the LogGroup; removing CreateLogGroup above prevents a late-finishing
82 // build from recreating it after the observed LogGroup deletion.
83 const buildLogs = yield* Logs.LogGroup("BindingsBuildLogs", {
84 logGroupName: `/aws/codebuild/${FIXTURE_PROJECT_NAME}`,
85 retention: "1 day",
86 });
87
88 const project = yield* CodeBuild.Project("BindingsProject", {
89 projectName: FIXTURE_PROJECT_NAME,
90 serviceRole: role.roleArn,
91 source: { type: "NO_SOURCE", buildspec },
92 environment: {
93 image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0",
94 computeType: "BUILD_GENERAL1_SMALL",
95 },
96 logsConfig: {
97 cloudWatchLogs: {
98 status: "ENABLED",
99 groupName: buildLogs.logGroupName,
100 },
101 s3Logs: { status: "DISABLED" },
102 },
103 });
104
105 const reportGroup = yield* CodeBuild.ReportGroup("BindingsReports", {
106 reportGroupName: FIXTURE_REPORT_GROUP_NAME,
107 type: "TEST",
108 });
109
110 // Build plane
111 const startBuild = yield* CodeBuild.StartBuild(project);
112 const batchGetBuilds = yield* CodeBuild.BatchGetBuilds(project);
113 const stopBuild = yield* CodeBuild.StopBuild(project);
114 const retryBuild = yield* CodeBuild.RetryBuild(project);
115 const listBuilds = yield* CodeBuild.ListBuildsForProject(project);
116 const batchDeleteBuilds = yield* CodeBuild.BatchDeleteBuilds(project);
117 const invalidateProjectCache = yield* CodeBuild.InvalidateProjectCache(project);
118 // Batch-build plane
119 const startBuildBatch = yield* CodeBuild.StartBuildBatch(project);
120 const stopBuildBatch = yield* CodeBuild.StopBuildBatch(project);
121 const retryBuildBatch = yield* CodeBuild.RetryBuildBatch(project);
122 const batchGetBuildBatches = yield* CodeBuild.BatchGetBuildBatches(project);
123 const listBuildBatches = yield* CodeBuild.ListBuildBatchesForProject(project);
124 const deleteBuildBatch = yield* CodeBuild.DeleteBuildBatch(project);
125 // Sandbox plane
126 const startSandbox = yield* CodeBuild.StartSandbox(project);
127 const stopSandbox = yield* CodeBuild.StopSandbox(project);
128 const batchGetSandboxes = yield* CodeBuild.BatchGetSandboxes(project);
129 const listSandboxes = yield* CodeBuild.ListSandboxesForProject(project);
130 const startCommandExecution = yield* CodeBuild.StartCommandExecution(project);
131 const batchGetCommandExecutions = yield* CodeBuild.BatchGetCommandExecutions(project);
132 const listCommandExecutions = yield* CodeBuild.ListCommandExecutionsForSandbox(project);
133 // Report plane
134 const listReports = yield* CodeBuild.ListReportsForReportGroup(reportGroup);
135 const batchGetReports = yield* CodeBuild.BatchGetReports(reportGroup);
136 const describeTestCases = yield* CodeBuild.DescribeTestCases(reportGroup);
137 const describeCodeCoverages = yield* CodeBuild.DescribeCodeCoverages(reportGroup);
138 const getReportGroupTrend = yield* CodeBuild.GetReportGroupTrend(reportGroup);
139 const deleteReport = yield* CodeBuild.DeleteReport(reportGroup);
140
141 // Deploy-time: creates the EventBridge rule (default bus, source
142 // aws.codebuild) targeting this Function. Runtime firing rides on the
143 // real builds the suite starts; the test verifies the rule deploys.
144 yield* CodeBuild.consumeBuildEvents({ kinds: ["state"] }, (events) =>
145 Stream.runForEach(events, (event) =>
146 Effect.log(
147 `codebuild event: ${event.detail["build-id"]} -> ${event.detail["build-status"]}`,
148 ),
149 ),
150 );
151
152 return {
153 fetch: Effect.gen(function* () {
154 const request = yield* HttpServerRequest;
155 const url = new URL(request.originalUrl);
156 const pathname = url.pathname;
157 const route = `${request.method} ${pathname}`;
158 const param = (name: string) => url.searchParams.get(name)!;
159
160 switch (route) {
161 // ---- build plane ----
162 case "POST /build/start": {
163 const result = yield* errorTagged(startBuild());
164 return yield* HttpServerResponse.json(
165 "errorTag" in result ? result : { buildId: result.build?.id },
166 );
167 }
168 case "GET /build/get": {
169 const result = yield* errorTagged(batchGetBuilds({ ids: [param("id")] }));
170 return yield* HttpServerResponse.json(
171 "errorTag" in result ? result : { status: result.builds?.[0]?.buildStatus },
172 );
173 }
174 case "GET /build/list": {
175 const result = yield* errorTagged(listBuilds());
176 return yield* HttpServerResponse.json(
177 "errorTag" in result ? result : { ids: result.ids ?? [] },
178 );
179 }
180 case "POST /build/stop": {
181 const body = (yield* request.json) as unknown as { id: string };
182 const result = yield* errorTagged(stopBuild({ id: body.id }));
183 return yield* HttpServerResponse.json(
184 "errorTag" in result ? result : { status: result.build?.buildStatus },
185 );
186 }
187 case "POST /build/retry": {
188 const body = (yield* request.json) as unknown as { id: string };
189 const result = yield* errorTagged(retryBuild({ id: body.id }));
190 return yield* HttpServerResponse.json(
191 "errorTag" in result ? result : { buildId: result.build?.id },
192 );
193 }
194 case "POST /build/delete": {
195 const body = (yield* request.json) as unknown as {
196 ids: string[];
197 };
198 const result = yield* errorTagged(batchDeleteBuilds({ ids: body.ids }));
199 return yield* HttpServerResponse.json(
200 "errorTag" in result
201 ? result
202 : {
203 deleted: result.buildsDeleted ?? [],
204 notDeleted: (result.buildsNotDeleted ?? []).map((b) => b.id),
205 },
206 );
207 }
208 case "POST /cache/invalidate": {
209 const result = yield* errorTagged(invalidateProjectCache());
210 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
211 }
212
213 // ---- batch-build plane ----
214 case "POST /batch/start": {
215 const result = yield* errorTagged(startBuildBatch());
216 return yield* HttpServerResponse.json(
217 "errorTag" in result ? result : { batchId: result.buildBatch?.id },
218 );
219 }
220 case "POST /batch/stop": {
221 const body = (yield* request.json) as unknown as { id: string };
222 const result = yield* errorTagged(stopBuildBatch({ id: body.id }));
223 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
224 }
225 case "POST /batch/retry": {
226 const body = (yield* request.json) as unknown as { id: string };
227 const result = yield* errorTagged(retryBuildBatch({ id: body.id }));
228 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
229 }
230 case "GET /batch/get": {
231 const result = yield* errorTagged(batchGetBuildBatches({ ids: [param("id")] }));
232 return yield* HttpServerResponse.json(
233 "errorTag" in result
234 ? result
235 : {
236 found: (result.buildBatches ?? []).map((b) => b.id),
237 notFound: result.buildBatchesNotFound ?? [],
238 },
239 );
240 }
241 case "GET /batch/list": {
242 const result = yield* errorTagged(listBuildBatches());
243 return yield* HttpServerResponse.json(
244 "errorTag" in result ? result : { ids: result.ids ?? [] },
245 );
246 }
247 case "POST /batch/delete": {
248 const body = (yield* request.json) as unknown as { id: string };
249 const result = yield* errorTagged(deleteBuildBatch({ id: body.id }));
250 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
251 }
252
253 // ---- sandbox plane ----
254 case "POST /sandbox/start": {
255 const result = yield* errorTagged(startSandbox());
256 return yield* HttpServerResponse.json(
257 "errorTag" in result ? result : { sandboxId: result.sandbox?.id },
258 );
259 }
260 case "POST /sandbox/stop": {
261 const body = (yield* request.json) as unknown as { id: string };
262 const result = yield* errorTagged(stopSandbox({ id: body.id }));
263 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
264 }
265 case "GET /sandbox/get": {
266 const result = yield* errorTagged(batchGetSandboxes({ ids: [param("id")] }));
267 return yield* HttpServerResponse.json(
268 "errorTag" in result
269 ? result
270 : {
271 statuses: (result.sandboxes ?? []).map((s) => s.status),
272 },
273 );
274 }
275 case "GET /sandbox/list": {
276 const result = yield* errorTagged(listSandboxes());
277 return yield* HttpServerResponse.json(
278 "errorTag" in result ? result : { ids: result.ids ?? [] },
279 );
280 }
281 case "POST /sandbox/command": {
282 const body = (yield* request.json) as unknown as {
283 sandboxId: string;
284 command: string;
285 };
286 const result = yield* errorTagged(
287 startCommandExecution({
288 sandboxId: body.sandboxId,
289 command: body.command,
290 }),
291 );
292 return yield* HttpServerResponse.json(
293 "errorTag" in result ? result : { commandId: result.commandExecution?.id },
294 );
295 }
296 case "GET /sandbox/command-get": {
297 const result = yield* errorTagged(
298 batchGetCommandExecutions({
299 sandboxId: param("sandboxId"),
300 commandExecutionIds: [param("commandId")],
301 }),
302 );
303 return yield* HttpServerResponse.json(
304 "errorTag" in result
305 ? result
306 : {
307 statuses: (result.commandExecutions ?? []).map((c) => c.status),
308 },
309 );
310 }
311 case "GET /sandbox/commands": {
312 const result = yield* errorTagged(
313 listCommandExecutions({ sandboxId: param("sandboxId") }),
314 );
315 return yield* HttpServerResponse.json(
316 "errorTag" in result
317 ? result
318 : {
319 count: (result.commandExecutions ?? []).length,
320 },
321 );
322 }
323
324 // ---- report plane ----
325 case "GET /reports/list": {
326 const result = yield* errorTagged(listReports());
327 return yield* HttpServerResponse.json(
328 "errorTag" in result ? result : { reports: result.reports ?? [] },
329 );
330 }
331 case "GET /reports/get": {
332 const result = yield* errorTagged(batchGetReports({ reportArns: [param("arn")] }));
333 return yield* HttpServerResponse.json(
334 "errorTag" in result
335 ? result
336 : {
337 found: (result.reports ?? []).map((r) => r.arn),
338 notFound: result.reportsNotFound ?? [],
339 },
340 );
341 }
342 case "GET /reports/test-cases": {
343 const result = yield* errorTagged(describeTestCases({ reportArn: param("arn") }));
344 return yield* HttpServerResponse.json(
345 "errorTag" in result ? result : { count: (result.testCases ?? []).length },
346 );
347 }
348 case "GET /reports/coverage": {
349 const result = yield* errorTagged(describeCodeCoverages({ reportArn: param("arn") }));
350 return yield* HttpServerResponse.json(
351 "errorTag" in result ? result : { count: (result.codeCoverages ?? []).length },
352 );
353 }
354 case "GET /reports/trend": {
355 const result = yield* errorTagged(getReportGroupTrend({ trendField: "DURATION" }));
356 return yield* HttpServerResponse.json(
357 "errorTag" in result ? result : { average: result.stats?.average },
358 );
359 }
360 case "POST /reports/delete": {
361 const body = (yield* request.json) as unknown as { arn: string };
362 const result = yield* errorTagged(deleteReport({ arn: body.arn }));
363 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
364 }
365
366 default:
367 return yield* HttpServerResponse.json({ error: "Not found", route }, { status: 404 });
368 }
369 }).pipe(Effect.orDie),
370 };
371 }).pipe(
372 Effect.provide(
373 Layer.mergeAll(
374 Lambda.EventSource,
375 CodeBuild.StartBuildHttp,
376 CodeBuild.BatchGetBuildsHttp,
377 CodeBuild.StopBuildHttp,
378 CodeBuild.RetryBuildHttp,
379 CodeBuild.ListBuildsForProjectHttp,
380 CodeBuild.BatchDeleteBuildsHttp,
381 CodeBuild.InvalidateProjectCacheHttp,
382 CodeBuild.StartBuildBatchHttp,
383 CodeBuild.StopBuildBatchHttp,
384 CodeBuild.RetryBuildBatchHttp,
385 CodeBuild.BatchGetBuildBatchesHttp,
386 CodeBuild.ListBuildBatchesForProjectHttp,
387 CodeBuild.DeleteBuildBatchHttp,
388 CodeBuild.StartSandboxHttp,
389 CodeBuild.StopSandboxHttp,
390 CodeBuild.BatchGetSandboxesHttp,
391 CodeBuild.ListSandboxesForProjectHttp,
392 CodeBuild.StartCommandExecutionHttp,
393 CodeBuild.BatchGetCommandExecutionsHttp,
394 CodeBuild.ListCommandExecutionsForSandboxHttp,
395 CodeBuild.ListReportsForReportGroupHttp,
396 CodeBuild.BatchGetReportsHttp,
397 CodeBuild.DescribeTestCasesHttp,
398 CodeBuild.DescribeCodeCoveragesHttp,
399 CodeBuild.GetReportGroupTrendHttp,
400 CodeBuild.DeleteReportHttp,
401 ),
402 ),
403 ),
404 );