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 lambda from "@distilled.cloud/aws/lambda"; |
| 6 | import * as scheduler from "@distilled.cloud/aws/scheduler"; |
| 7 | import * as SQS from "@distilled.cloud/aws/sqs"; |
| 8 | import * as Alchemy from "alchemy"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 13 | import * as Schedule from "effect/Schedule"; |
| 14 | import SchedulerEnvFunctionLive, { SchedulerEnvFunction } from "./env-handler"; |
| 15 | import SchedulerTestFunctionLive, { SchedulerTestFunction } from "./handler"; |
| 16 | |
| 17 | const testOptions = { providers: AWS.providers() }; |
| 18 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 19 | const sharedStack = Core.scratchStack(testOptions, "SchedulerBindings"); |
| 20 | |
| 21 | // Every schedule the fixture mints at runtime carries this deterministic |
| 22 | // prefix so leftovers can be purged out-of-band before and after the suite. |
| 23 | const SCHEDULE_PREFIX = "alch-schedtest-"; |
| 24 | |
| 25 | // Lambda function URL cold-start (DNS, IAM propagation, init) can take well |
| 26 | // over 60s on a fresh deploy under parallel-suite load. |
| 27 | const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]); |
| 28 | |
| 29 | let baseUrl: string; |
| 30 | let sinkQueueUrl: string; |
| 31 | let cronQueueUrl: string; |
| 32 | |
| 33 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 34 | readonly status: number; |
| 35 | readonly body: string; |
| 36 | }> {} |
| 37 | |
| 38 | class MessageNotDelivered extends Data.TaggedError("MessageNotDelivered") {} |
| 39 | |
| 40 | class ScheduleStillExists extends Data.TaggedError("ScheduleStillExists") {} |
| 41 | |
| 42 | // The shared Lambda fixture occasionally answers a transient 5xx under |
| 43 | // parallel load (cold re-init, IAM propagation). Retry 5xx only; a genuine |
| 44 | // 4xx/assertion failure surfaces immediately. |
| 45 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 46 | HttpClient.execute(request).pipe( |
| 47 | Effect.flatMap((response) => |
| 48 | response.status >= 500 |
| 49 | ? response.text.pipe( |
| 50 | Effect.flatMap((body) => |
| 51 | Effect.fail(new TransientUpstream({ status: response.status, body })), |
| 52 | ), |
| 53 | ) |
| 54 | : Effect.succeed(response), |
| 55 | ), |
| 56 | Effect.retry({ |
| 57 | while: (e) => e._tag === "TransientUpstream", |
| 58 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]), |
| 59 | }), |
| 60 | ); |
| 61 | |
| 62 | // Out-of-band purge of runtime-minted schedules (default group, deterministic |
| 63 | // prefix) so a crashed previous run can't ConflictException this one. Wrapped |
| 64 | // in Core.withProviders because the distilled ops need the AWS environment |
| 65 | // (Credentials/Region) that test.provider bodies get implicitly but |
| 66 | // beforeAll/afterAll hooks do not. |
| 67 | const purgeTestSchedules = Core.withProviders( |
| 68 | Effect.gen(function* () { |
| 69 | const listed = yield* scheduler.listSchedules({ NamePrefix: SCHEDULE_PREFIX }); |
| 70 | const names = (listed.Schedules ?? []).flatMap((s) => (s.Name ? [s.Name] : [])); |
| 71 | if (names.length > 0) { |
| 72 | yield* Effect.logInfo( |
| 73 | `Scheduler test cleanup: deleting leftover schedules ${names.join(", ")}`, |
| 74 | ); |
| 75 | } |
| 76 | yield* Effect.forEach( |
| 77 | names, |
| 78 | (name) => |
| 79 | scheduler |
| 80 | .deleteSchedule({ Name: name }) |
| 81 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)), |
| 82 | { concurrency: 5 }, |
| 83 | ); |
| 84 | }), |
| 85 | testOptions, |
| 86 | "SchedulerBindingsPurge", |
| 87 | ); |
| 88 | |
| 89 | // Bounded poll until a message whose JSON body matches the predicate shows up |
| 90 | // on the queue; matched messages are deleted so re-polls stay clean. |
| 91 | const receiveMatching = ( |
| 92 | queueUrl: string, |
| 93 | matches: (body: any) => boolean, |
| 94 | options?: { times?: number }, |
| 95 | ) => |
| 96 | Effect.gen(function* () { |
| 97 | const result = yield* SQS.receiveMessage({ |
| 98 | QueueUrl: queueUrl, |
| 99 | MaxNumberOfMessages: 10, |
| 100 | WaitTimeSeconds: 5, |
| 101 | VisibilityTimeout: 15, |
| 102 | }); |
| 103 | const match = (result.Messages ?? []).find((message) => { |
| 104 | try { |
| 105 | return message.Body !== undefined && matches(JSON.parse(message.Body)); |
| 106 | } catch { |
| 107 | return false; |
| 108 | } |
| 109 | }); |
| 110 | if (!match?.ReceiptHandle) { |
| 111 | return yield* Effect.fail(new MessageNotDelivered()); |
| 112 | } |
| 113 | yield* SQS.deleteMessage({ QueueUrl: queueUrl, ReceiptHandle: match.ReceiptHandle }); |
| 114 | return JSON.parse(match.Body!) as any; |
| 115 | }).pipe( |
| 116 | Effect.retry({ |
| 117 | while: (error) => error._tag === "MessageNotDelivered", |
| 118 | schedule: Schedule.max([Schedule.fixed("1 seconds"), Schedule.recurs(options?.times ?? 12)]), |
| 119 | }), |
| 120 | ); |
| 121 | |
| 122 | // Typed wait-until-gone: retries while GetSchedule still succeeds. |
| 123 | const waitUntilScheduleGone = (name: string) => |
| 124 | Effect.gen(function* () { |
| 125 | const found = yield* scheduler |
| 126 | .getSchedule({ Name: name }) |
| 127 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined))); |
| 128 | if (found !== undefined) { |
| 129 | return yield* Effect.fail(new ScheduleStillExists()); |
| 130 | } |
| 131 | }).pipe( |
| 132 | Effect.retry({ |
| 133 | while: (error) => error._tag === "ScheduleStillExists", |
| 134 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(15)]), |
| 135 | }), |
| 136 | ); |
| 137 | |
| 138 | describe( |
| 139 | "Scheduler Bindings", |
| 140 | { |
| 141 | tags: [ |
| 142 | "provider:aws", |
| 143 | "provider:aws:iam", |
| 144 | "provider:aws:lambda", |
| 145 | "provider:aws:scheduler", |
| 146 | "provider:aws:sqs", |
| 147 | "live", |
| 148 | ], |
| 149 | }, |
| 150 | () => { |
| 151 | beforeAll( |
| 152 | Effect.gen(function* () { |
| 153 | yield* Effect.logInfo("Scheduler test setup: destroying previous resources"); |
| 154 | yield* sharedStack.destroy(); |
| 155 | yield* purgeTestSchedules; |
| 156 | |
| 157 | yield* Effect.logInfo("Scheduler test setup: deploying fixture"); |
| 158 | const { functionUrl } = yield* sharedStack.deploy( |
| 159 | Effect.gen(function* () { |
| 160 | return yield* SchedulerTestFunction; |
| 161 | }).pipe(Effect.provide(SchedulerTestFunctionLive)), |
| 162 | ); |
| 163 | |
| 164 | expect(functionUrl).toBeTruthy(); |
| 165 | baseUrl = functionUrl!.replace(/\/+$/, ""); |
| 166 | const readinessUrl = `${baseUrl}/info`; |
| 167 | |
| 168 | yield* Effect.logInfo(`Scheduler test setup: probing readiness at ${readinessUrl}`); |
| 169 | const info = yield* HttpClient.get(readinessUrl).pipe( |
| 170 | Effect.flatMap((response) => |
| 171 | response.status === 200 |
| 172 | ? (response.json as Effect.Effect<{ sinkQueueUrl?: string; cronQueueUrl?: string }>) |
| 173 | : Effect.fail(new Error(`Function not ready: ${response.status}`)), |
| 174 | ), |
| 175 | Effect.flatMap((body) => |
| 176 | body.sinkQueueUrl && body.cronQueueUrl |
| 177 | ? Effect.succeed(body as { sinkQueueUrl: string; cronQueueUrl: string }) |
| 178 | : Effect.fail(new Error("Function returned empty queue urls")), |
| 179 | ), |
| 180 | Effect.tapError((error) => |
| 181 | Effect.logWarning(`Scheduler test setup: fixture not ready yet (${String(error)})`), |
| 182 | ), |
| 183 | Effect.retry({ schedule: readinessPolicy }), |
| 184 | ); |
| 185 | sinkQueueUrl = info.sinkQueueUrl; |
| 186 | cronQueueUrl = info.cronQueueUrl; |
| 187 | }), |
| 188 | { timeout: 240_000 }, |
| 189 | ); |
| 190 | |
| 191 | afterAll( |
| 192 | Effect.gen(function* () { |
| 193 | // NO_DESTROY=1 keeps the deployment (and its log group) around while |
| 194 | // iterating locally — standard escape hatch, default is full cleanup. |
| 195 | if (process.env.NO_DESTROY) return; |
| 196 | // Leak guard: no runtime-minted schedules may outlive the suite. |
| 197 | yield* purgeTestSchedules; |
| 198 | yield* sharedStack.destroy(); |
| 199 | }), |
| 200 | { timeout: 120_000 }, |
| 201 | ); |
| 202 | |
| 203 | describe("CreateSchedule", () => { |
| 204 | test.provider( |
| 205 | "mints a one-shot at() schedule whose target fires (iam:PassRole end-to-end)", |
| 206 | (_stack) => |
| 207 | Effect.gen(function* () { |
| 208 | const name = `${SCHEDULE_PREFIX}oneshot`; |
| 209 | |
| 210 | const created = (yield* send( |
| 211 | HttpClientRequest.post(`${baseUrl}/schedules/${name}?delaySeconds=15`), |
| 212 | ).pipe(Effect.flatMap((r) => r.json))) as { scheduleArn: string; expression: string }; |
| 213 | |
| 214 | expect(created.scheduleArn).toContain(`:schedule/default/${name}`); |
| 215 | expect(created.expression).toMatch(/^at\(/); |
| 216 | |
| 217 | // Out-of-band: the schedule exists with the one-shot config the |
| 218 | // fixture requested. |
| 219 | const observed = yield* scheduler.getSchedule({ Name: name }); |
| 220 | expect(observed.Name).toBe(name); |
| 221 | expect(observed.ActionAfterCompletion).toBe("DELETE"); |
| 222 | expect(observed.Target?.RoleArn).toBeTruthy(); |
| 223 | |
| 224 | // The schedule fires ~15s after creation; the execution role (which |
| 225 | // the binding contributed iam:PassRole for) delivers the marker into |
| 226 | // the sink queue. Bounded: ~15s delay + poll ≤ ~75s. |
| 227 | const message = yield* receiveMatching(sinkQueueUrl, (body) => body.marker === name); |
| 228 | expect(message.marker).toBe(name); |
| 229 | |
| 230 | // ActionAfterCompletion=DELETE reaps the fired one-shot: typed |
| 231 | // wait-until-gone doubles as the no-leak proof. |
| 232 | yield* waitUntilScheduleGone(name); |
| 233 | }), |
| 234 | { timeout: 150_000 }, |
| 235 | ); |
| 236 | }); |
| 237 | |
| 238 | describe("GetSchedule", () => { |
| 239 | test.provider("reads a pending schedule through the binding", (_stack) => |
| 240 | Effect.gen(function* () { |
| 241 | const name = `${SCHEDULE_PREFIX}get`; |
| 242 | |
| 243 | yield* send(HttpClientRequest.post(`${baseUrl}/schedules/${name}?delaySeconds=900`)); |
| 244 | |
| 245 | const found = (yield* send(HttpClientRequest.get(`${baseUrl}/schedules/${name}`)).pipe( |
| 246 | Effect.flatMap((r) => r.json), |
| 247 | )) as { arn: string; name: string; state: string; expression: string }; |
| 248 | |
| 249 | expect(found.name).toBe(name); |
| 250 | expect(found.state).toBe("ENABLED"); |
| 251 | expect(found.expression).toMatch(/^at\(/); |
| 252 | |
| 253 | // cleanup via the DeleteSchedule binding route |
| 254 | const deleted = yield* send(HttpClientRequest.delete(`${baseUrl}/schedules/${name}`)); |
| 255 | expect(deleted.status).toBe(200); |
| 256 | }), |
| 257 | ); |
| 258 | |
| 259 | test.provider("surfaces the typed not-found as a 404", (_stack) => |
| 260 | Effect.gen(function* () { |
| 261 | const response = yield* send( |
| 262 | HttpClientRequest.get(`${baseUrl}/schedules/${SCHEDULE_PREFIX}missing`), |
| 263 | ); |
| 264 | expect(response.status).toBe(404); |
| 265 | }), |
| 266 | ); |
| 267 | }); |
| 268 | |
| 269 | describe("UpdateSchedule", () => { |
| 270 | test.provider( |
| 271 | "reschedules a pending schedule (full PUT + iam:PassRole)", |
| 272 | (_stack) => |
| 273 | Effect.gen(function* () { |
| 274 | const name = `${SCHEDULE_PREFIX}upd`; |
| 275 | |
| 276 | yield* send(HttpClientRequest.post(`${baseUrl}/schedules/${name}?delaySeconds=900`)); |
| 277 | |
| 278 | // Update: push the fire time out further and set a description. |
| 279 | const updated = (yield* send( |
| 280 | HttpClientRequest.put( |
| 281 | `${baseUrl}/schedules/${name}?delaySeconds=1800&description=rescheduled`, |
| 282 | ), |
| 283 | ).pipe(Effect.flatMap((r) => r.json))) as { scheduleArn: string; expression: string }; |
| 284 | expect(updated.scheduleArn).toContain(`:schedule/default/${name}`); |
| 285 | |
| 286 | // Out-of-band: the new expression and description landed. |
| 287 | const observed = yield* scheduler.getSchedule({ Name: name }); |
| 288 | expect(observed.ScheduleExpression).toBe(updated.expression); |
| 289 | expect(observed.Description).toBe("rescheduled"); |
| 290 | |
| 291 | // cleanup via the DeleteSchedule binding route |
| 292 | const deleted = yield* send(HttpClientRequest.delete(`${baseUrl}/schedules/${name}`)); |
| 293 | expect(deleted.status).toBe(200); |
| 294 | }), |
| 295 | { timeout: 120_000 }, |
| 296 | ); |
| 297 | |
| 298 | test.provider("surfaces the typed not-found as a 404", (_stack) => |
| 299 | Effect.gen(function* () { |
| 300 | const response = yield* send( |
| 301 | HttpClientRequest.put(`${baseUrl}/schedules/${SCHEDULE_PREFIX}missing-upd`), |
| 302 | ); |
| 303 | expect(response.status).toBe(404); |
| 304 | }), |
| 305 | ); |
| 306 | }); |
| 307 | |
| 308 | describe("ListSchedules", () => { |
| 309 | test.provider( |
| 310 | "lists runtime-minted schedules by prefix (default-group scoped)", |
| 311 | (_stack) => |
| 312 | Effect.gen(function* () { |
| 313 | const nameA = `${SCHEDULE_PREFIX}list-a`; |
| 314 | const nameB = `${SCHEDULE_PREFIX}list-b`; |
| 315 | |
| 316 | yield* send(HttpClientRequest.post(`${baseUrl}/schedules/${nameA}?delaySeconds=900`)); |
| 317 | yield* send(HttpClientRequest.post(`${baseUrl}/schedules/${nameB}?delaySeconds=900`)); |
| 318 | |
| 319 | const listed = (yield* send( |
| 320 | HttpClientRequest.get(`${baseUrl}/schedules?namePrefix=${SCHEDULE_PREFIX}list-`), |
| 321 | ).pipe(Effect.flatMap((r) => r.json))) as { |
| 322 | names: string[]; |
| 323 | error?: string; |
| 324 | message?: string; |
| 325 | }; |
| 326 | |
| 327 | // A typed failure inside the Lambda surfaces here with its tag. |
| 328 | expect(listed.error, listed.message).toBeUndefined(); |
| 329 | expect(listed.names).toContain(nameA); |
| 330 | expect(listed.names).toContain(nameB); |
| 331 | |
| 332 | // cleanup via the DeleteSchedule binding route |
| 333 | for (const name of [nameA, nameB]) { |
| 334 | const deleted = yield* send(HttpClientRequest.delete(`${baseUrl}/schedules/${name}`)); |
| 335 | expect(deleted.status).toBe(200); |
| 336 | } |
| 337 | }), |
| 338 | { timeout: 120_000 }, |
| 339 | ); |
| 340 | }); |
| 341 | |
| 342 | describe("DeleteSchedule", () => { |
| 343 | test.provider( |
| 344 | "deletes a pending schedule and reports not-found on repeat", |
| 345 | (_stack) => |
| 346 | Effect.gen(function* () { |
| 347 | const name = `${SCHEDULE_PREFIX}del`; |
| 348 | |
| 349 | yield* send(HttpClientRequest.post(`${baseUrl}/schedules/${name}?delaySeconds=900`)); |
| 350 | |
| 351 | // out-of-band: it exists before deletion |
| 352 | const observed = yield* scheduler.getSchedule({ Name: name }); |
| 353 | expect(observed.Name).toBe(name); |
| 354 | |
| 355 | const first = yield* send(HttpClientRequest.delete(`${baseUrl}/schedules/${name}`)); |
| 356 | expect(first.status).toBe(200); |
| 357 | expect(((yield* first.json) as any).deleted).toBe(true); |
| 358 | |
| 359 | // out-of-band typed wait-until-gone |
| 360 | yield* waitUntilScheduleGone(name); |
| 361 | |
| 362 | // idempotent repeat surfaces the typed ResourceNotFoundException |
| 363 | const second = yield* send(HttpClientRequest.delete(`${baseUrl}/schedules/${name}`)); |
| 364 | expect(second.status).toBe(404); |
| 365 | }), |
| 366 | { timeout: 120_000 }, |
| 367 | ); |
| 368 | }); |
| 369 | |
| 370 | describe("ScheduleEventSource", () => { |
| 371 | test.provider( |
| 372 | "the cron handler consumes its own scheduled invocations", |
| 373 | (_stack) => |
| 374 | Effect.gen(function* () { |
| 375 | // The fixture registered consumeSchedule(every("1 minute"), ...) at |
| 376 | // deploy time; the first fire lands within a minute of schedule |
| 377 | // creation (usually before the tests start), forwarded into the |
| 378 | // cron queue as the typed ScheduleEvent envelope. Bounded: long-poll |
| 379 | // ~90s to ride out one full rate window. |
| 380 | const event = yield* receiveMatching( |
| 381 | cronQueueUrl, |
| 382 | (body) => body.marker === "alch-schedtest-cron-fired", |
| 383 | { times: 15 }, |
| 384 | ); |
| 385 | |
| 386 | expect(event.scheduleArn).toContain(":schedule/default/"); |
| 387 | expect(event.scheduleId).toMatch(/^Scheduler[0-9a-f]{10}$/); |
| 388 | expect(event.scheduledTime).toBeTruthy(); |
| 389 | expect(event.executionId).toBeTruthy(); |
| 390 | }), |
| 391 | { timeout: 120_000 }, |
| 392 | ); |
| 393 | }); |
| 394 | }, |
| 395 | ); |
| 396 | |
| 397 | // #1842: `AWS.state()` builds the AWS environment outside the test's config, |
| 398 | // and the stack's providers reuse it. Its first resolution then runs while the |
| 399 | // function's init binds CreateSchedule, where every config key read is bound |
| 400 | // into the function's env — the deployer's profile or credentials included. |
| 401 | const withState = { providers: AWS.providers(), state: AWS.state() }; |
| 402 | const withStateHarness = Test.make(withState); |
| 403 | |
| 404 | const EnvStack = Alchemy.Stack( |
| 405 | "SchedulerBindingsEnv", |
| 406 | withState, |
| 407 | Effect.gen(function* () { |
| 408 | const fn = yield* SchedulerEnvFunction; |
| 409 | return { functionName: fn.functionName }; |
| 410 | }).pipe(Effect.provide(SchedulerEnvFunctionLive)), |
| 411 | ); |
| 412 | |
| 413 | describe( |
| 414 | "Scheduler Bindings with the S3 state store", |
| 415 | { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:scheduler", "live"] }, |
| 416 | () => { |
| 417 | const deployed = withStateHarness.beforeAll(withStateHarness.deploy(EnvStack), { |
| 418 | timeout: 120_000, |
| 419 | }); |
| 420 | withStateHarness.afterAll.skipIf(!!process.env.NO_DESTROY)(withStateHarness.destroy(EnvStack), { |
| 421 | timeout: 120_000, |
| 422 | }); |
| 423 | |
| 424 | withStateHarness.test( |
| 425 | "resolving the AWS environment in a function's init leaves its env clean", |
| 426 | Effect.gen(function* () { |
| 427 | const { functionName } = yield* deployed; |
| 428 | const config = yield* Core.withProviders( |
| 429 | lambda.getFunctionConfiguration({ FunctionName: functionName }), |
| 430 | withState, |
| 431 | "SchedulerBindingsEnv", |
| 432 | ); |
| 433 | const keys = Object.keys(config.Environment?.Variables ?? {}); |
| 434 | expect(keys.filter((key) => /^(AWS_|ALCHEMY_PROFILE$|CI$)/.test(key))).toEqual([]); |
| 435 | }), |
| 436 | { timeout: 180_000 }, |
| 437 | ); |
| 438 | }, |
| 439 | ); |