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
| 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 Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as HttpClient from "effect/http/HttpClient"; |
| 8 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import CodePipelineTestFunctionLive, { |
| 11 | APPROVAL_STAGE, |
| 12 | CodePipelineTestFunction, |
| 13 | SOURCE_ACTION, |
| 14 | SOURCE_STAGE, |
| 15 | } from "./handler"; |
| 16 | |
| 17 | const testOptions = { providers: AWS.providers() }; |
| 18 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 19 | const sharedStack = Core.scratchStack(testOptions, "CodePipelineBindings"); |
| 20 | |
| 21 | // A fresh Lambda role can remain unauthorized by CodePipeline after the |
| 22 | // function itself is active. |
| 23 | const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(90)]); |
| 24 | |
| 25 | let baseUrl: string; |
| 26 | |
| 27 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 28 | readonly status: number; |
| 29 | readonly body: string; |
| 30 | }> {} |
| 31 | |
| 32 | class PipelineReadinessError extends Data.TaggedError("PipelineReadinessError")<{ |
| 33 | readonly status: number; |
| 34 | readonly errorTag?: string; |
| 35 | readonly errorMessage?: string; |
| 36 | }> { |
| 37 | override get message() { |
| 38 | return `CodePipeline readiness failed (${this.errorTag ?? `HTTP ${this.status}`}): ${this.errorMessage ?? "no error details"}`; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Retry transient 5xx from the shared Lambda fixture (cold re-init, IAM |
| 43 | // propagation on the freshly attached codepipeline policy surfaced as a 500 |
| 44 | // by the handler's `Effect.orDie`). Genuine 4xx/assertion failures return |
| 45 | // immediately. |
| 46 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 47 | HttpClient.execute(request).pipe( |
| 48 | Effect.flatMap((response) => |
| 49 | response.status >= 500 |
| 50 | ? response.text.pipe( |
| 51 | Effect.flatMap((body) => |
| 52 | Effect.fail(new TransientUpstream({ status: response.status, body })), |
| 53 | ), |
| 54 | ) |
| 55 | : Effect.succeed(response), |
| 56 | ), |
| 57 | Effect.retry({ |
| 58 | while: (e) => e._tag === "TransientUpstream", |
| 59 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]), |
| 60 | }), |
| 61 | ); |
| 62 | |
| 63 | const getJson = (url: string) => |
| 64 | send(HttpClientRequest.get(url)).pipe(Effect.flatMap((r) => r.json)); |
| 65 | |
| 66 | const postJson = (url: string, body: unknown) => |
| 67 | send(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body))).pipe( |
| 68 | Effect.flatMap((r) => r.json), |
| 69 | ); |
| 70 | |
| 71 | const post = (url: string) => send(HttpClientRequest.post(url)).pipe(Effect.flatMap((r) => r.json)); |
| 72 | |
| 73 | /** |
| 74 | * A route answered with a typed error tag. The tag being present proves the |
| 75 | * binding produced a typed failure (untyped errors crash into a 500), and it |
| 76 | * not being an authorization tag proves the IAM grant covered the call. |
| 77 | */ |
| 78 | const expectTypedNonAuthz = (body: any) => { |
| 79 | expect(typeof body.errorTag).toBe("string"); |
| 80 | expect(body.errorTag).not.toBe("AccessDeniedException"); |
| 81 | }; |
| 82 | |
| 83 | /** A route that either succeeded or failed with a typed, authorized tag. */ |
| 84 | const expectAuthorized = (body: any) => { |
| 85 | if (body.errorTag !== undefined) expectTypedNonAuthz(body); |
| 86 | }; |
| 87 | |
| 88 | class ApprovalNotPending extends Data.TaggedError("ApprovalNotPending") {} |
| 89 | |
| 90 | class ExecutionNotVisible extends Data.TaggedError("ExecutionNotVisible") {} |
| 91 | |
| 92 | /** |
| 93 | * A freshly started execution is not immediately visible to |
| 94 | * GetPipelineExecution / ListPipelineExecutions (eventual consistency) — |
| 95 | * poll the route (bounded) until it stops answering not-found/absent. |
| 96 | */ |
| 97 | const untilExecutionVisible = <A, E, R>( |
| 98 | effect: Effect.Effect<A, E, R>, |
| 99 | visible: (body: A) => boolean, |
| 100 | ): Effect.Effect<A, E | ExecutionNotVisible, R> => |
| 101 | effect.pipe( |
| 102 | Effect.flatMap((body) => |
| 103 | visible(body) ? Effect.succeed(body) : Effect.fail(new ExecutionNotVisible()), |
| 104 | ), |
| 105 | Effect.retry({ |
| 106 | while: (e): boolean => e instanceof ExecutionNotVisible, |
| 107 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]), |
| 108 | }), |
| 109 | ); |
| 110 | |
| 111 | const FAKE_UUID = "00000000-0000-0000-0000-000000000000"; |
| 112 | |
| 113 | describe.sequential( |
| 114 | "CodePipeline Bindings", |
| 115 | { |
| 116 | tags: [ |
| 117 | "provider:aws", |
| 118 | "provider:aws:codepipeline", |
| 119 | "provider:aws:iam", |
| 120 | "provider:aws:lambda", |
| 121 | "provider:aws:s3", |
| 122 | "live", |
| 123 | ], |
| 124 | }, |
| 125 | () => { |
| 126 | beforeAll( |
| 127 | Effect.gen(function* () { |
| 128 | yield* Effect.logInfo("CodePipeline test setup: destroying previous"); |
| 129 | yield* sharedStack.destroy(); |
| 130 | |
| 131 | yield* Effect.logInfo("CodePipeline test setup: deploying fixture"); |
| 132 | const { functionUrl } = yield* sharedStack.deploy( |
| 133 | Effect.gen(function* () { |
| 134 | return yield* CodePipelineTestFunction; |
| 135 | }).pipe(Effect.provide(CodePipelineTestFunctionLive)), |
| 136 | ); |
| 137 | |
| 138 | expect(functionUrl).toBeTruthy(); |
| 139 | baseUrl = functionUrl!.replace(/\/+$/, ""); |
| 140 | const readinessUrl = `${baseUrl}/state`; |
| 141 | |
| 142 | yield* Effect.logInfo(`CodePipeline test setup: probing readiness at ${readinessUrl}`); |
| 143 | // Readiness requires an authorized downstream call, not just HTTP 200. |
| 144 | yield* HttpClient.get(readinessUrl).pipe( |
| 145 | Effect.flatMap((response) => |
| 146 | Effect.gen(function* () { |
| 147 | if (response.status !== 200) { |
| 148 | return yield* new PipelineReadinessError({ status: response.status }); |
| 149 | } |
| 150 | return yield* response.json; |
| 151 | }), |
| 152 | ), |
| 153 | Effect.flatMap((body) => { |
| 154 | const result = body as { errorTag?: string; errorMessage?: string }; |
| 155 | return result.errorTag === undefined |
| 156 | ? Effect.succeed(result) |
| 157 | : Effect.fail(new PipelineReadinessError({ status: 200, ...result })); |
| 158 | }), |
| 159 | Effect.tapError((error) => Effect.logWarning(String(error))), |
| 160 | Effect.retry({ schedule: readinessPolicy }), |
| 161 | ); |
| 162 | }), |
| 163 | { timeout: 300_000 }, |
| 164 | ); |
| 165 | |
| 166 | afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 240_000 }); |
| 167 | |
| 168 | describe("GetPipelineState + ListPipelineExecutions + ListActionExecutions + ListRuleExecutions", () => { |
| 169 | test.provider("reads the pipeline's state and histories", (_stack) => |
| 170 | Effect.gen(function* () { |
| 171 | const state = (yield* getJson(`${baseUrl}/state`)) as any; |
| 172 | expect(state.errorTag).toBeUndefined(); |
| 173 | expect(state.stageNames).toEqual([SOURCE_STAGE, APPROVAL_STAGE]); |
| 174 | |
| 175 | const executions = (yield* getJson(`${baseUrl}/executions`)) as any; |
| 176 | expect(executions.errorTag).toBeUndefined(); |
| 177 | expect(Array.isArray(executions.ids)).toBe(true); |
| 178 | |
| 179 | const actions = (yield* getJson(`${baseUrl}/actions`)) as any; |
| 180 | expect(actions.errorTag).toBeUndefined(); |
| 181 | |
| 182 | const rules = (yield* getJson(`${baseUrl}/rules`)) as any; |
| 183 | expectAuthorized(rules); |
| 184 | }), |
| 185 | ); |
| 186 | }); |
| 187 | |
| 188 | describe("StartPipelineExecution + GetPipelineExecution + PutApprovalResult + StopPipelineExecution", () => { |
| 189 | test.provider( |
| 190 | "runs an execution to the manual gate and approves it", |
| 191 | (_stack) => |
| 192 | Effect.gen(function* () { |
| 193 | // Seed the source object (S3.PutObject binding on the Lambda). |
| 194 | const uploaded = (yield* post(`${baseUrl}/source/upload`)) as any; |
| 195 | expect(uploaded.errorTag).toBeUndefined(); |
| 196 | |
| 197 | // Start an execution. |
| 198 | const started = (yield* post(`${baseUrl}/execution/start`)) as any; |
| 199 | expect(started.errorTag).toBeUndefined(); |
| 200 | const executionId = started.executionId as string; |
| 201 | expect(executionId).toBeTruthy(); |
| 202 | |
| 203 | // GetPipelineExecution sees it (eventual consistency — poll). |
| 204 | const got = (yield* untilExecutionVisible( |
| 205 | getJson(`${baseUrl}/execution/get?id=${encodeURIComponent(executionId)}`), |
| 206 | (body: any) => body.errorTag !== "PipelineExecutionNotFoundException", |
| 207 | )) as any; |
| 208 | expect(got.errorTag).toBeUndefined(); |
| 209 | expect(got.status).toBeTruthy(); |
| 210 | |
| 211 | // ListPipelineExecutions includes it (eventual consistency — poll). |
| 212 | const listed = (yield* untilExecutionVisible( |
| 213 | getJson(`${baseUrl}/executions`), |
| 214 | (body: any) => (body.ids ?? []).includes(executionId), |
| 215 | )) as any; |
| 216 | expect(listed.ids).toContain(executionId); |
| 217 | |
| 218 | // Wait (bounded) for the source stage to hand the execution to the |
| 219 | // manual-approval action, which exposes an approval token. |
| 220 | const token = yield* getJson(`${baseUrl}/state`).pipe( |
| 221 | Effect.flatMap((state: any) => |
| 222 | typeof state.approvalToken === "string" |
| 223 | ? Effect.succeed(state.approvalToken as string) |
| 224 | : Effect.fail(new ApprovalNotPending()), |
| 225 | ), |
| 226 | Effect.retry({ |
| 227 | while: (e): boolean => e._tag === "ApprovalNotPending", |
| 228 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(20)]), |
| 229 | }), |
| 230 | ); |
| 231 | |
| 232 | // ListActionExecutions shows the source action ran for this |
| 233 | // execution. |
| 234 | const actions = (yield* getJson( |
| 235 | `${baseUrl}/actions?executionId=${encodeURIComponent(executionId)}`, |
| 236 | )) as any; |
| 237 | expect(actions.errorTag).toBeUndefined(); |
| 238 | expect(actions.actions).toContain(SOURCE_ACTION); |
| 239 | |
| 240 | // Answer the approval. |
| 241 | const approved = (yield* postJson(`${baseUrl}/approval`, { |
| 242 | token, |
| 243 | status: "Approved", |
| 244 | })) as any; |
| 245 | expectAuthorized(approved); |
| 246 | |
| 247 | // StopPipelineExecution — the execution just completed via the |
| 248 | // approval, so a typed not-stoppable rejection is the expected |
| 249 | // proof of wiring (success is also fine if timing races). |
| 250 | const stopped = (yield* postJson(`${baseUrl}/execution/stop`, { |
| 251 | id: executionId, |
| 252 | abandon: true, |
| 253 | })) as any; |
| 254 | expectAuthorized(stopped); |
| 255 | }), |
| 256 | { timeout: 240_000 }, |
| 257 | ); |
| 258 | }); |
| 259 | |
| 260 | describe("DisableStageTransition + EnableStageTransition", () => { |
| 261 | test.provider("freezes and re-opens the approval stage", (_stack) => |
| 262 | Effect.gen(function* () { |
| 263 | const disabled = (yield* postJson(`${baseUrl}/transition/disable`, { |
| 264 | stageName: APPROVAL_STAGE, |
| 265 | })) as any; |
| 266 | expect(disabled.errorTag).toBeUndefined(); |
| 267 | |
| 268 | // GetPipelineState reflects the transition change eventually — poll |
| 269 | // (bounded) until the disabled transition is observed. |
| 270 | const frozen = (yield* untilExecutionVisible( |
| 271 | getJson(`${baseUrl}/state`), |
| 272 | (body: any) => body.inboundTransitionEnabled === false, |
| 273 | )) as any; |
| 274 | expect(frozen.inboundTransitionEnabled).toBe(false); |
| 275 | |
| 276 | const enabled = (yield* postJson(`${baseUrl}/transition/enable`, { |
| 277 | stageName: APPROVAL_STAGE, |
| 278 | })) as any; |
| 279 | expect(enabled.errorTag).toBeUndefined(); |
| 280 | |
| 281 | const open = (yield* untilExecutionVisible( |
| 282 | getJson(`${baseUrl}/state`), |
| 283 | (body: any) => body.inboundTransitionEnabled === true, |
| 284 | )) as any; |
| 285 | expect(open.inboundTransitionEnabled).toBe(true); |
| 286 | }), |
| 287 | ); |
| 288 | }); |
| 289 | |
| 290 | describe("RetryStageExecution + RollbackStage + OverrideStageCondition + PutActionRevision + ListDeployActionExecutionTargets", () => { |
| 291 | test.provider( |
| 292 | "stage operations answer typed for invalid targets", |
| 293 | (_stack) => |
| 294 | Effect.gen(function* () { |
| 295 | // Nothing failed — retrying is a typed StageNotRetryable / |
| 296 | // Conflict / NotLatestPipelineExecution rejection. |
| 297 | const retried = (yield* postJson(`${baseUrl}/stage/retry`, { |
| 298 | stageName: APPROVAL_STAGE, |
| 299 | executionId: FAKE_UUID, |
| 300 | })) as any; |
| 301 | expectTypedNonAuthz(retried); |
| 302 | |
| 303 | const rolledBack = (yield* postJson(`${baseUrl}/stage/rollback`, { |
| 304 | stageName: APPROVAL_STAGE, |
| 305 | targetExecutionId: FAKE_UUID, |
| 306 | })) as any; |
| 307 | expectTypedNonAuthz(rolledBack); |
| 308 | |
| 309 | // The fixture pipeline declares no stage conditions. |
| 310 | const overridden = (yield* postJson(`${baseUrl}/condition/override`, { |
| 311 | stageName: APPROVAL_STAGE, |
| 312 | executionId: FAKE_UUID, |
| 313 | })) as any; |
| 314 | expectTypedNonAuthz(overridden); |
| 315 | |
| 316 | // Unknown action name — typed ActionNotFoundException. |
| 317 | const revision = (yield* postJson(`${baseUrl}/action/revision`, { |
| 318 | actionName: "NoSuchAction", |
| 319 | revisionId: FAKE_UUID, |
| 320 | })) as any; |
| 321 | expectTypedNonAuthz(revision); |
| 322 | |
| 323 | // No deploy actions in the fixture — success-empty or a typed |
| 324 | // rejection both prove the wiring. |
| 325 | const targets = (yield* getJson( |
| 326 | `${baseUrl}/deploy-targets?actionExecutionId=${FAKE_UUID}`, |
| 327 | )) as any; |
| 328 | expectAuthorized(targets); |
| 329 | |
| 330 | // Approval with a fake token — typed InvalidApprovalToken / |
| 331 | // ApprovalAlreadyCompleted rejection. |
| 332 | const approval = (yield* postJson(`${baseUrl}/approval`, { |
| 333 | token: FAKE_UUID, |
| 334 | status: "Rejected", |
| 335 | })) as any; |
| 336 | expectTypedNonAuthz(approval); |
| 337 | }), |
| 338 | { timeout: 120_000 }, |
| 339 | ); |
| 340 | }); |
| 341 | |
| 342 | describe("GetJobDetails + PutJobSuccessResult + PutJobFailureResult + PollForJobs + AcknowledgeJob", () => { |
| 343 | test.provider("job-worker bindings answer typed for unknown jobs", (_stack) => |
| 344 | Effect.gen(function* () { |
| 345 | const details = (yield* getJson(`${baseUrl}/job/get?id=${FAKE_UUID}`)) as any; |
| 346 | expectAuthorized(details); |
| 347 | |
| 348 | const success = (yield* postJson(`${baseUrl}/job/success`, { jobId: FAKE_UUID })) as any; |
| 349 | expectTypedNonAuthz(success); |
| 350 | |
| 351 | const failure = (yield* postJson(`${baseUrl}/job/failure`, { jobId: FAKE_UUID })) as any; |
| 352 | expectTypedNonAuthz(failure); |
| 353 | |
| 354 | // No custom action type exists — typed ActionTypeNotFoundException. |
| 355 | const polled = (yield* post(`${baseUrl}/job/poll`)) as any; |
| 356 | expectTypedNonAuthz(polled); |
| 357 | |
| 358 | // Unknown job/nonce — typed JobNotFound / InvalidNonce rejection. |
| 359 | const acked = (yield* postJson(`${baseUrl}/job/ack`, { |
| 360 | jobId: FAKE_UUID, |
| 361 | nonce: FAKE_UUID, |
| 362 | })) as any; |
| 363 | expectTypedNonAuthz(acked); |
| 364 | }), |
| 365 | ); |
| 366 | }); |
| 367 | }, |
| 368 | ); |