The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as AWS from "@alchemy.run/aws"; |
| 2 | import { describe, expect } from "@alchemy.run/test"; |
| 3 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 4 | import * as Core from "@alchemy.run/test/Core"; |
| 5 | import * as amplify from "@distilled.cloud/aws/amplify"; |
| 6 | import * as eventbridge from "@distilled.cloud/aws/eventbridge"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import AmplifyTestFunctionLive, { AmplifyTestFunction } from "./fixtures/handler"; |
| 13 | import { makeAmplifyTestLease } from "./TestLease.ts"; |
| 14 | |
| 15 | const testOptions = { providers: AWS.providers() }; |
| 16 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 17 | const sharedStack = Core.scratchStack(testOptions, "AmplifyBindings"); |
| 18 | const testLease = makeAmplifyTestLease(); |
| 19 | |
| 20 | beforeAll(testLease.acquire, { timeout: 240_000 }); |
| 21 | afterAll(testLease.release); |
| 22 | |
| 23 | const branchName = "main"; |
| 24 | |
| 25 | // Minimal deployable site: a stored zip containing a single `index.html` |
| 26 | // ("hello amplify"). Generated once and checked in as a constant so the test |
| 27 | // never zips at runtime. |
| 28 | const SITE_ZIP_BASE64 = |
| 29 | "UEsDBBQAAAAAAAAAIVwZ1jYHJwAAACcAAAAKAAAAaW5kZXguaHRtbDxodG1sPjxib2R5PmhlbGxvIGFtcGxpZnk8L2JvZHk+PC9odG1sPlBLAQIUAxQAAAAAAAAAIVwZ1jYHJwAAACcAAAAKAAAAAAAAAAAAAACAAQAAAABpbmRleC5odG1sUEsFBgAAAAABAAEAOAAAAE8AAAAAAA=="; |
| 30 | |
| 31 | const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]); |
| 32 | |
| 33 | let baseUrl: string; |
| 34 | let appId: string; |
| 35 | |
| 36 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 37 | readonly status: number; |
| 38 | readonly body: string; |
| 39 | readonly message: string; |
| 40 | }> {} |
| 41 | |
| 42 | // Retry transient 5xx from the fixture (cold re-init under parallel-suite |
| 43 | // load); genuine 4xx surfaces immediately. |
| 44 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 45 | HttpClient.execute(request).pipe( |
| 46 | Effect.flatMap((response) => |
| 47 | response.status >= 500 |
| 48 | ? response.text.pipe( |
| 49 | Effect.flatMap((body) => |
| 50 | Effect.fail( |
| 51 | new TransientUpstream({ |
| 52 | status: response.status, |
| 53 | body, |
| 54 | message: `fixture returned ${response.status}: ${body}`, |
| 55 | }), |
| 56 | ), |
| 57 | ), |
| 58 | ) |
| 59 | : Effect.succeed(response), |
| 60 | ), |
| 61 | Effect.retry({ |
| 62 | while: (e) => e._tag === "TransientUpstream", |
| 63 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]), |
| 64 | }), |
| 65 | ); |
| 66 | |
| 67 | const postJson = (path: string, body: unknown) => |
| 68 | send( |
| 69 | HttpClientRequest.post(`${baseUrl}${path}`).pipe(HttpClientRequest.bodyJsonUnsafe(body)), |
| 70 | ).pipe(Effect.flatMap((response) => response.json)); |
| 71 | |
| 72 | const getJson = (path: string) => |
| 73 | send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe( |
| 74 | Effect.flatMap((response) => response.json), |
| 75 | ); |
| 76 | |
| 77 | const deploySite = (branchName: string) => |
| 78 | Effect.gen(function* () { |
| 79 | const staged = (yield* postJson("/deployments", { branchName })) as { |
| 80 | jobId: string; |
| 81 | zipUploadUrl: string; |
| 82 | }; |
| 83 | expect(staged.jobId).toBeTruthy(); |
| 84 | expect(staged.zipUploadUrl).toContain("https://"); |
| 85 | |
| 86 | const zipBytes = yield* Effect.sync(() => |
| 87 | Uint8Array.from(Buffer.from(SITE_ZIP_BASE64, "base64")), |
| 88 | ); |
| 89 | const upload = yield* HttpClient.execute( |
| 90 | HttpClientRequest.put(staged.zipUploadUrl).pipe( |
| 91 | HttpClientRequest.bodyUint8Array(zipBytes, "application/zip"), |
| 92 | ), |
| 93 | ); |
| 94 | expect(upload.status).toBe(200); |
| 95 | |
| 96 | const released = (yield* postJson("/deployments/start", { |
| 97 | branchName, |
| 98 | jobId: staged.jobId, |
| 99 | })) as { jobSummary: { jobId: string; status: string } }; |
| 100 | expect(released.jobSummary.jobId).toBe(staged.jobId); |
| 101 | |
| 102 | const settled = yield* getJson(`/job?branchName=${branchName}&jobId=${staged.jobId}`).pipe( |
| 103 | Effect.map((body) => body as { status: string; stepCount: number }), |
| 104 | Effect.repeat({ |
| 105 | schedule: Schedule.spaced("5 seconds"), |
| 106 | until: (job): boolean => |
| 107 | job.status === "SUCCEED" || job.status === "FAILED" || job.status === "CANCELLED", |
| 108 | times: 10, |
| 109 | }), |
| 110 | ); |
| 111 | expect(settled.status).toBe("SUCCEED"); |
| 112 | |
| 113 | return { ...staged, ...settled }; |
| 114 | }); |
| 115 | |
| 116 | describe.sequential( |
| 117 | "Amplify Bindings", |
| 118 | { tags: ["provider:aws", "provider:aws:amplify", "provider:aws:lambda", "live"] }, |
| 119 | () => { |
| 120 | beforeAll( |
| 121 | Effect.gen(function* () { |
| 122 | yield* sharedStack.destroy(); |
| 123 | |
| 124 | const { functionUrl } = yield* sharedStack.deploy( |
| 125 | Effect.gen(function* () { |
| 126 | return yield* AmplifyTestFunction; |
| 127 | }).pipe(Effect.provide(AmplifyTestFunctionLive)), |
| 128 | ); |
| 129 | |
| 130 | expect(functionUrl).toBeTruthy(); |
| 131 | baseUrl = functionUrl!.replace(/\/+$/, ""); |
| 132 | |
| 133 | yield* HttpClient.get(`${baseUrl}/ping`).pipe( |
| 134 | Effect.flatMap((response) => |
| 135 | response.status === 200 |
| 136 | ? Effect.succeed(response) |
| 137 | : Effect.fail(new Error(`Function not ready: ${response.status}`)), |
| 138 | ), |
| 139 | Effect.retry({ schedule: readinessPolicy }), |
| 140 | ); |
| 141 | |
| 142 | const meta = (yield* getJson("/meta")) as { appId: string }; |
| 143 | appId = meta.appId; |
| 144 | expect(appId).toBeTruthy(); |
| 145 | |
| 146 | // Manual-deploy branch (no repo needed) for the deployment bindings. |
| 147 | // The fixture app is freshly created above, so the branch never |
| 148 | // pre-exists; app deletion on destroy removes it. |
| 149 | // `beforeAll` doesn't run inside `test.provider`'s environment, so |
| 150 | // provide the AWS providers (Credentials/Region) explicitly for the |
| 151 | // out-of-band distilled call. |
| 152 | yield* Core.withProviders( |
| 153 | amplify.createBranch({ appId, branchName, enableAutoBuild: false }), |
| 154 | testOptions, |
| 155 | "AmplifyBindings", |
| 156 | ); |
| 157 | }), |
| 158 | { timeout: 240_000 }, |
| 159 | ); |
| 160 | |
| 161 | afterAll(sharedStack.destroy(), { timeout: 120_000 }); |
| 162 | |
| 163 | test( |
| 164 | "manual deployment lifecycle through the bindings", |
| 165 | Effect.gen(function* () { |
| 166 | // CreateDeployment, StartDeployment, and GetJob — stage the site, |
| 167 | // upload it through the pre-signed URL, release it, and wait for the |
| 168 | // deployment to settle. |
| 169 | const deployed = yield* deploySite(branchName); |
| 170 | |
| 171 | // ListJobs — the deployment shows up in the branch's job history. |
| 172 | const jobs = (yield* getJson(`/jobs?branchName=${branchName}`)) as { |
| 173 | jobSummaries: Array<{ jobId: string }>; |
| 174 | }; |
| 175 | expect(jobs.jobSummaries.map((j) => j.jobId)).toContain(deployed.jobId); |
| 176 | |
| 177 | // ListArtifacts — manual deploys typically produce none; the call |
| 178 | // itself (auth + wiring) is what's under test. |
| 179 | const artifacts = (yield* getJson( |
| 180 | `/artifacts?branchName=${branchName}&jobId=${deployed.jobId}`, |
| 181 | )) as { artifacts: Array<{ artifactId: string; artifactFileName: string }> }; |
| 182 | expect(Array.isArray(artifacts.artifacts)).toBe(true); |
| 183 | |
| 184 | // GetArtifactUrl — only exercisable when the job produced artifacts. |
| 185 | if (artifacts.artifacts.length > 0) { |
| 186 | const artifactUrl = (yield* getJson( |
| 187 | `/artifact-url?artifactId=${artifacts.artifacts[0].artifactId}`, |
| 188 | )) as { artifactUrl: string }; |
| 189 | expect(artifactUrl.artifactUrl).toContain("https://"); |
| 190 | } |
| 191 | |
| 192 | // StopJob — the job already settled, so the service rejects the stop |
| 193 | // with a typed tag; either outcome proves the binding + IAM wiring. |
| 194 | const stopped = (yield* postJson("/jobs/stop", { branchName, jobId: deployed.jobId })) as { |
| 195 | stopped: boolean; |
| 196 | errorTag?: string; |
| 197 | }; |
| 198 | if (!stopped.stopped) { |
| 199 | expect(stopped.errorTag).toBe("BadRequestException"); |
| 200 | } |
| 201 | |
| 202 | // DeleteJob correctly rejects the active hosted deployment with a typed |
| 203 | // BadRequestException. Deploy a successor, then prune the old job. |
| 204 | const activeDelete = (yield* postJson("/jobs/delete", { |
| 205 | branchName, |
| 206 | jobId: deployed.jobId, |
| 207 | })) as { deleted: boolean; errorTag?: string; message?: string }; |
| 208 | expect(activeDelete.deleted).toBe(false); |
| 209 | expect(activeDelete.errorTag).toBe("BadRequestException"); |
| 210 | expect(activeDelete.message).toContain("active job"); |
| 211 | |
| 212 | const successor = yield* deploySite(branchName); |
| 213 | expect(successor.jobId).not.toBe(deployed.jobId); |
| 214 | |
| 215 | // Amplify marks the superseded job deletable eventually — the successor |
| 216 | // can settle while the old job still reads "active" for a beat, so |
| 217 | // retry the delete until it lands (bounded). |
| 218 | const deleted = (yield* postJson("/jobs/delete", { |
| 219 | branchName, |
| 220 | jobId: deployed.jobId, |
| 221 | }).pipe( |
| 222 | Effect.repeat({ |
| 223 | schedule: Schedule.spaced("3 seconds"), |
| 224 | until: (r) => (r as { deleted: boolean }).deleted, |
| 225 | times: 10, |
| 226 | }), |
| 227 | )) as { deleted: boolean; errorTag?: string }; |
| 228 | expect(deleted.deleted).toBe(true); |
| 229 | |
| 230 | // Out-of-band: the job is gone from the branch history. |
| 231 | const remaining = yield* Core.withProviders( |
| 232 | amplify.listJobs({ appId, branchName }), |
| 233 | testOptions, |
| 234 | "AmplifyBindings", |
| 235 | ); |
| 236 | expect(remaining.jobSummaries.map((j) => j.jobId)).not.toContain(deployed.jobId); |
| 237 | }), |
| 238 | { timeout: 120_000, retry: 0 }, |
| 239 | ); |
| 240 | |
| 241 | test( |
| 242 | "startJob surfaces the typed rejection for a repo-less branch", |
| 243 | Effect.gen(function* () { |
| 244 | // RELEASE jobs need a connected Git repository; a manual-deploy branch |
| 245 | // rejects them with BadRequestException. Reaching that typed tag proves |
| 246 | // the binding executed against the service with the granted IAM. |
| 247 | const result = (yield* postJson("/jobs/start", { branchName, jobType: "RELEASE" })) as { |
| 248 | started: boolean; |
| 249 | errorTag?: string; |
| 250 | }; |
| 251 | expect(result.started).toBe(false); |
| 252 | expect(result.errorTag).toBe("BadRequestException"); |
| 253 | }), |
| 254 | { timeout: 60_000 }, |
| 255 | ); |
| 256 | |
| 257 | test( |
| 258 | "consumeDeploymentStatusChanges creates the EventBridge subscription", |
| 259 | Effect.gen(function* () { |
| 260 | // Deploy-time proof: the event source registered a rule on the default |
| 261 | // bus matching Amplify deployment status changes. (Actual delivery is |
| 262 | // recorded best-effort on the /events route — a different Lambda |
| 263 | // instance may serve it, so delivery is not hard-asserted here.) |
| 264 | const rules = yield* Core.withProviders( |
| 265 | eventbridge |
| 266 | .listRules({ NamePrefix: "AmplifyBindings" }) |
| 267 | .pipe(Effect.map((page) => page.Rules ?? [])), |
| 268 | testOptions, |
| 269 | "AmplifyBindings", |
| 270 | ); |
| 271 | const rule = rules.find( |
| 272 | (r): boolean => |
| 273 | typeof r.EventPattern === "string" && r.EventPattern.includes('"aws.amplify"'), |
| 274 | ); |
| 275 | expect(rule).toBeDefined(); |
| 276 | expect(rule!.EventPattern).toContain("Amplify Deployment Status Change"); |
| 277 | }), |
| 278 | { tags: ["provider:aws:eventbridge"], timeout: 60_000 }, |
| 279 | ); |
| 280 | |
| 281 | test( |
| 282 | "generateAccessLogs returns a pre-signed log URL for the default domain", |
| 283 | Effect.gen(function* () { |
| 284 | const meta = (yield* getJson("/meta")) as { defaultDomain: string }; |
| 285 | const result = (yield* postJson("/access-logs", { domainName: meta.defaultDomain })) as { |
| 286 | ok: boolean; |
| 287 | logUrl?: string; |
| 288 | errorTag?: string; |
| 289 | message?: string; |
| 290 | cause?: string; |
| 291 | }; |
| 292 | if (result.ok) { |
| 293 | expect(result.logUrl).toContain("https://"); |
| 294 | } else if (result.errorTag === "UnexpectedCause") { |
| 295 | return yield* Effect.fail( |
| 296 | new Error(result.cause ?? "GenerateAccessLogs failed unexpectedly"), |
| 297 | ); |
| 298 | } else { |
| 299 | // Some accounts gate access logs on the default domain — the typed |
| 300 | // tag still proves the binding + IAM wiring. |
| 301 | expect(["BadRequestException", "NotFoundException"]).toContain(result.errorTag); |
| 302 | } |
| 303 | }), |
| 304 | { timeout: 60_000, retry: 0 }, |
| 305 | ); |
| 306 | }, |
| 307 | ); |