@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, 04:45 UTC

main
ts 307 lines 11 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Project } from "@alchemy.run/aws/CodeBuild/Project";
3 import { normalizePolicyDocument, type PolicyDocument } from "@alchemy.run/aws/IAM/Policy";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as codebuild from "@distilled.cloud/aws/codebuild";
7 import * as sts from "@distilled.cloud/aws/sts";
8 import * as Provider from "alchemy/Provider";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 const projectName = "alchemy-test-codebuild-project";
16
17 const buildspec = [
18 "version: 0.2",
19 "phases:",
20 " build:",
21 " commands:",
22 " - echo Hello from CodeBuild",
23 ].join("\n");
24
25 const codebuildRole = (logical: string) =>
26 AWS.IAM.Role(logical, {
27 assumeRolePolicyDocument: {
28 Version: "2012-10-17",
29 Statement: [
30 {
31 Effect: "Allow",
32 Principal: { Service: "codebuild.amazonaws.com" },
33 Action: ["sts:AssumeRole"],
34 },
35 ],
36 },
37 inlinePolicies: {
38 Logs: {
39 Version: "2012-10-17",
40 Statement: [
41 {
42 Effect: "Allow",
43 Action: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
44 Resource: ["*"],
45 },
46 ],
47 },
48 },
49 });
50
51 const getProject = codebuild
52 .batchGetProjects({ names: [projectName] })
53 .pipe(Effect.map((res) => res.projects?.[0]));
54
55 class CodeBuildRoleNotReady extends Data.TaggedError("CodeBuildRoleNotReady")<{
56 readonly buildId: string;
57 readonly message: string;
58 }> {}
59
60 test.provider(
61 "lifecycle: create NO_SOURCE project, update, destroy",
62 (stack) =>
63 Effect.gen(function* () {
64 yield* stack.destroy();
65
66 // Create — a NO_SOURCE project with an inline buildspec. Defining a
67 // project is instant; no build is run.
68 const deployed = yield* stack.deploy(
69 Effect.gen(function* () {
70 const role = yield* codebuildRole("ProjectRole");
71 return yield* Project("LifecycleProject", {
72 projectName,
73 serviceRole: role.roleArn,
74 source: { type: "NO_SOURCE", buildspec },
75 environment: {
76 image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0",
77 computeType: "BUILD_GENERAL1_SMALL",
78 environmentVariables: [{ name: "STAGE", value: "dev" }],
79 },
80 });
81 }),
82 );
83 expect(deployed.projectArn).toContain(`project/${projectName}`);
84
85 // Out-of-band verification via distilled.
86 const created = yield* getProject;
87 expect(created?.name).toBe(projectName);
88 expect(created?.source?.type).toBe("NO_SOURCE");
89 expect(created?.environment?.computeType).toBe("BUILD_GENERAL1_SMALL");
90 expect(
91 created?.environment?.environmentVariables?.find((v) => v.name === "STAGE")?.value,
92 ).toBe("dev");
93
94 // Canonical list() coverage.
95 const provider = yield* Provider.findProvider(Project);
96 const all = yield* provider.list();
97 expect(all.some((p) => p.projectName === projectName)).toBe(true);
98
99 // Update — change an env var and timeout in place (no replacement),
100 // and attach a typed PolicyDocument resource policy sharing the
101 // project with this account's root principal.
102 const identity = yield* sts.getCallerIdentity({});
103 const resourcePolicy: PolicyDocument = {
104 Version: "2012-10-17",
105 Statement: [
106 {
107 Sid: "Share",
108 Effect: "Allow",
109 Principal: { AWS: `arn:aws:iam::${identity.Account}:root` },
110 Action: ["codebuild:BatchGetProjects"],
111 Resource: deployed.projectArn,
112 },
113 ],
114 };
115 const updateProject = Effect.gen(function* () {
116 const role = yield* codebuildRole("ProjectRole");
117 return yield* Project("LifecycleProject", {
118 projectName,
119 serviceRole: role.roleArn,
120 source: { type: "NO_SOURCE", buildspec },
121 environment: {
122 image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0",
123 computeType: "BUILD_GENERAL1_MEDIUM",
124 environmentVariables: [{ name: "STAGE", value: "prod" }],
125 },
126 timeout: "30 minutes",
127 resourcePolicy,
128 });
129 });
130 yield* stack.deploy(updateProject);
131 const updated = yield* getProject;
132 expect(updated?.environment?.computeType).toBe("BUILD_GENERAL1_MEDIUM");
133 expect(
134 updated?.environment?.environmentVariables?.find((v) => v.name === "STAGE")?.value,
135 ).toBe("prod");
136 expect(updated?.timeoutInMinutes).toBe(30);
137
138 // The PolicyDocument round-trips through the wire as a string that
139 // normalizes back to exactly the desired document.
140 const readPolicy = codebuild.getResourcePolicy({ resourceArn: deployed.projectArn }).pipe(
141 Effect.map((res) => res.policy),
142 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
143 );
144 const attached = yield* readPolicy;
145 expect(attached).toBeDefined();
146 expect(normalizePolicyDocument(attached!)).toBe(normalizePolicyDocument(resourcePolicy));
147
148 // Re-deploy the identical PolicyDocument — the drift comparison is on
149 // normalized documents, so this converges cleanly as a no-op and the
150 // policy is unchanged.
151 yield* stack.deploy(updateProject);
152 const afterRedeploy = yield* readPolicy;
153 expect(normalizePolicyDocument(afterRedeploy!)).toBe(normalizePolicyDocument(resourcePolicy));
154
155 // Drop the resourcePolicy prop — reconcile deletes the attached policy.
156 yield* stack.deploy(
157 Effect.gen(function* () {
158 const role = yield* codebuildRole("ProjectRole");
159 return yield* Project("LifecycleProject", {
160 projectName,
161 serviceRole: role.roleArn,
162 source: { type: "NO_SOURCE", buildspec },
163 environment: {
164 image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0",
165 computeType: "BUILD_GENERAL1_MEDIUM",
166 environmentVariables: [{ name: "STAGE", value: "prod" }],
167 },
168 timeout: "30 minutes",
169 });
170 }),
171 );
172 const afterRemoval = yield* readPolicy;
173 expect(afterRemoval === undefined || afterRemoval === "").toBe(true);
174
175 // Destroy — project is deleted; verify it is gone out-of-band.
176 yield* stack.destroy();
177 const after = yield* getProject;
178 expect(after).toBeUndefined();
179 }),
180 {
181 tags: ["provider:aws", "provider:aws:codebuild", "provider:aws:iam", "live"],
182 timeout: 300_000,
183 },
184 );
185
186 // Exercise the StartBuild + BatchGetBuilds path end-to-end against a
187 // NO_SOURCE project. Lambda compute keeps this within the regular test budget.
188 test.provider(
189 "NO_SOURCE build runs to SUCCEEDED",
190 (stack) => {
191 const buildIds: string[] = [];
192 return Effect.gen(function* () {
193 yield* stack.destroy();
194
195 const deployed = yield* stack.deploy(
196 Effect.gen(function* () {
197 const role = yield* codebuildRole("BuildRole");
198 return yield* Project("BuildProject", {
199 projectName: `${projectName}-run`,
200 serviceRole: role.roleArn,
201 source: { type: "NO_SOURCE", buildspec },
202 environment: {
203 image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0",
204 computeType: "BUILD_GENERAL1_SMALL",
205 },
206 // This smoke build does not consume its logs. Disabling both log
207 // destinations removes a race where CodeBuild assumes a freshly
208 // created role before its CloudWatch Logs policy has propagated.
209 logsConfig: {
210 cloudWatchLogs: { status: "DISABLED" },
211 s3Logs: { status: "DISABLED" },
212 },
213 });
214 }),
215 );
216
217 const configured = yield* codebuild.batchGetProjects({
218 names: [deployed.projectName],
219 });
220 expect(configured.projects?.[0]?.logsConfig?.cloudWatchLogs?.status).toBe("DISABLED");
221 expect(configured.projects?.[0]?.logsConfig?.s3Logs?.status).toBe("DISABLED");
222
223 const build = yield* Effect.gen(function* () {
224 const started = yield* codebuild.startBuild({
225 projectName: deployed.projectName,
226 });
227 const buildId = started.build?.id;
228 expect(buildId).toBeDefined();
229 buildIds.push(buildId!);
230
231 // Poll until the build reaches a terminal status. IN_QUEUE is not
232 // terminal; bound the total polling delay to 50 seconds.
233 const terminal = yield* codebuild.batchGetBuilds({ ids: [buildId!] }).pipe(
234 Effect.map((res) => res.builds?.[0]),
235 Effect.repeat({
236 schedule: Schedule.spaced("5 seconds"),
237 until: (b) => {
238 const status = b?.buildStatus;
239 return (
240 status === "SUCCEEDED" ||
241 status === "FAILED" ||
242 status === "FAULT" ||
243 status === "STOPPED" ||
244 status === "TIMED_OUT"
245 );
246 },
247 times: 10,
248 }),
249 );
250
251 // createProject validates the role but can return before the role's
252 // trust policy is usable by the CodeBuild data plane. Retry only this
253 // exact queued propagation failure. A buildspec/container failure is
254 // returned unchanged and must fail the SUCCEEDED assertion below.
255 const roleNotReady = terminal?.phases
256 ?.flatMap((phase) => phase.contexts ?? [])
257 .find(
258 (context) =>
259 context.statusCode === "ACCESS_DENIED" &&
260 context.message?.includes("Unable to assume role"),
261 );
262 if (terminal?.buildStatus === "FAILED" && roleNotReady) {
263 yield* Effect.logWarning(
264 `CodeBuild role not ready for ${buildId}: ${roleNotReady.message}`,
265 );
266 return yield* Effect.fail(
267 new CodeBuildRoleNotReady({
268 buildId: buildId!,
269 message: roleNotReady.message ?? "Unable to assume role",
270 }),
271 );
272 }
273 return terminal;
274 }).pipe(
275 Effect.retry({
276 while: (error) => error._tag === "CodeBuildRoleNotReady",
277 schedule: Schedule.spaced("3 seconds"),
278 times: 6,
279 }),
280 );
281 expect(build?.buildStatus).toBe("SUCCEEDED");
282
283 yield* stack.destroy();
284 const after = yield* codebuild.batchGetProjects({
285 names: [`${projectName}-run`],
286 });
287 expect(after.projects?.[0]).toBeUndefined();
288
289 return build;
290 }).pipe(
291 Effect.ensuring(
292 Effect.gen(function* () {
293 yield* Effect.forEach(
294 buildIds,
295 (buildId) => codebuild.stopBuild({ id: buildId }).pipe(Effect.ignore),
296 { concurrency: 2, discard: true },
297 );
298 yield* stack.destroy().pipe(Effect.ignore);
299 }),
300 ),
301 );
302 },
303 {
304 tags: ["provider:aws", "provider:aws:codebuild", "provider:aws:iam", "live"],
305 timeout: 120_000,
306 },
307 );