@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, 03:37 UTC

main
ts 1,612 lines 60.4 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as AWS from "@alchemy.run/aws";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Logs from "@distilled.cloud/aws/cloudwatch-logs";
6 import * as iam from "@distilled.cloud/aws/iam";
7 import * as Lambda from "@distilled.cloud/aws/lambda";
8 import { adopt } from "alchemy/AdoptPolicy";
9 import * as Drift from "alchemy/Drift";
10 import * as Output from "alchemy/Output";
11 import * as Provider from "alchemy/Provider";
12 import { State } from "alchemy/State";
13 import { zipCode } from "alchemy/Util/zip";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import * as HttpClient from "effect/http/HttpClient";
18 import * as Path from "effect/Path";
19 import * as Redacted from "effect/Redacted";
20 import * as Schedule from "effect/Schedule";
21 import * as Stream from "effect/Stream";
22 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
23 import { aliasFunction, AliasFunction } from "./fixtures/alias-handler.ts";
24 import { TestFunction, TestFunctionLive } from "./handler.ts";
25 import StreamingFunctionLive, { StreamingFunction } from "./streaming-handler.ts";
26
27 const asyncHandlerPath = fileURLToPath(new URL("./async-handler.ts", import.meta.url));
28 const namedHandlerPath = fileURLToPath(new URL("./named-handler.ts", import.meta.url));
29 const timeoutHandlerPath = fileURLToPath(new URL("./timeout-handler.ts", import.meta.url));
30 const externalPackageHandlerPath = fileURLToPath(
31 new URL("./external-package-handler.ts", import.meta.url),
32 );
33 const lockfilePinnedHandlerPath = (format: "npm" | "bun" | "pnpm" | "yarn") =>
34 fileURLToPath(new URL(`./fixtures/lockfile-pinning/${format}/handler.ts`, import.meta.url));
35
36 const { test } = Test.make({ providers: AWS.providers() });
37
38 test.provider(
39 "create, update, delete function",
40 (stack) =>
41 Effect.gen(function* () {
42 yield* stack.destroy();
43
44 const deploy = (marker: string) =>
45 stack.deploy(
46 Effect.gen(function* () {
47 const fn = yield* TestFunction;
48 yield* fn.bind`ReadinessMarker`({
49 env: { READINESS_MARKER: marker, CONFIG_FLAG: "true", CONFIG_PORT: "3000" },
50 });
51 return fn;
52 }).pipe(Effect.provide(TestFunctionLive)),
53 );
54
55 const { functionName, functionUrl, roleName } = yield* deploy("created");
56 yield* assertFunctionReady(functionName, "created");
57 // `Config.Boolean`/`Config.Number` decode JSON-looking env strings at runtime.
58 expect(yield* invokeHttpFunction(functionName, "/config")).toBe("true 3000");
59
60 const updated = yield* deploy("updated");
61 expect(updated.functionName).toBe(functionName);
62 yield* assertFunctionReady(updated.functionName, "updated");
63
64 expect(functionUrl).toBeTruthy();
65
66 const response = yield* HttpClient.get(functionUrl!).pipe(
67 Effect.flatMap((response) =>
68 response.status === 200
69 ? Effect.succeed(response)
70 : Effect.fail(new Error(`Function URL returned ${response.status}`)),
71 ),
72 Effect.tapError((error) => Effect.logError(error)),
73 Effect.retry({
74 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
75 }),
76 );
77
78 expect(response.status).toBe(200);
79 expect(yield* response.text).toBe("Hello, world!");
80
81 const invokePolicy = yield* getPolicyStatement(functionName, "FunctionURLAllowPublicInvoke");
82 expect(invokePolicy.Condition).toEqual({
83 Bool: {
84 "lambda:InvokedViaFunctionUrl": "true",
85 },
86 });
87
88 yield* stack.destroy();
89 yield* assertFunctionDeleted(functionName);
90 yield* assertRoleDeleted(roleName);
91
92 const recreated = yield* deploy("recreated");
93 yield* assertFunctionReady(recreated.functionName, "recreated");
94 yield* stack.destroy();
95 yield* assertFunctionDeleted(recreated.functionName);
96 yield* assertRoleDeleted(recreated.roleName);
97 }).pipe(
98 Effect.tap(() => stack.destroy()),
99 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
100 ),
101 {
102 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
103 timeout: 180_000,
104 },
105 );
106
107 // Pins the live diff's plan-time bundle hash. Dev mode (ALCHEMY_TEST_DEV=1)
108 // plans content-only changes as noop and hot-swaps them from the watch loop
109 // (covered by Function.local.test.ts), and the fixture's function-valued
110 // `build.external` cannot cross the dev sidecar's RPC boundary.
111 test.provider.skipIf(process.env.ALCHEMY_TEST_DEV === "1")(
112 "Effect-native function updates when its source changes",
113 (stack) =>
114 Effect.gen(function* () {
115 const fs = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 yield* stack.destroy();
118
119 // Work on a temp copy so editing the source never touches the
120 // checked-in fixture. The copy lives under packages/integration-tests/.tmp so its
121 // imports resolve exactly like the original's.
122 const fixtureDir = yield* cloneFixture(
123 yield* path.fromFileUrl(new URL("./fixtures/source-change", import.meta.url)),
124 {
125 prefix: "alchemy-lambda-source-change-",
126 tempRoot: yield* path.fromFileUrl(new URL("../../../.tmp", import.meta.url)),
127 },
128 );
129 const entry = path.join(fixtureDir, "function.ts");
130 const source = yield* fs.readFileString(entry);
131 const fixture = yield* Effect.promise(
132 () => import(entry) as Promise<typeof import("./fixtures/source-change/function.ts")>,
133 );
134 const declaration = fixture.SourceChangeFunction.pipe(
135 Effect.provide(fixture.SourceChangeFunctionLive),
136 );
137
138 const created = yield* Effect.gen(function* () {
139 const created = yield* stack.deploy(declaration);
140 expect(yield* invokeHttpFunction(created.functionName)).toBe("source-v1");
141
142 const unchanged = yield* stack.plan(declaration);
143 expect(unchanged.resources.SourceChangeFunction).toMatchObject({
144 action: "noop",
145 });
146
147 yield* fs.writeFileString(entry, source.replace('"source-v1"', '"source-v2"'));
148
149 const changed = yield* stack.plan(declaration);
150 expect(changed.resources.SourceChangeFunction).toMatchObject({
151 action: "update",
152 });
153
154 const updated = yield* stack.deploy(declaration);
155 expect(updated.functionName).toBe(created.functionName);
156 expect(yield* invokeHttpFunction(updated.functionName)).toBe("source-v2");
157 return created;
158 }).pipe(Effect.ensuring(fs.remove(fixtureDir, { recursive: true }).pipe(Effect.ignore)));
159
160 yield* stack.destroy();
161 yield* assertFunctionDeleted(created.functionName);
162 yield* assertRoleDeleted(created.roleName);
163 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
164 {
165 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
166 timeout: 120_000,
167 },
168 );
169
170 test.provider(
171 "async handler invokes the default export",
172 (stack) =>
173 Effect.gen(function* () {
174 yield* stack.destroy();
175
176 const fn = yield* stack.deploy(
177 AWS.Lambda.Function("AsyncHandlerFn", {
178 main: asyncHandlerPath,
179 functionUrl: false,
180 }),
181 );
182
183 const { Configuration } = yield* Lambda.getFunction({ FunctionName: fn.functionName });
184 expect(Configuration?.Handler).toBe("index.default");
185
186 const response = yield* Lambda.invoke({ FunctionName: fn.functionName, Payload: "{}" });
187 expect(response.FunctionError).toBeUndefined();
188 const payload = response.Payload
189 ? yield* response.Payload.pipe(Stream.decodeText(), Stream.mkString)
190 : "";
191 expect(JSON.parse(payload)).toEqual({ statusCode: 200, body: "ok" });
192
193 yield* stack.destroy();
194 yield* assertFunctionDeleted(fn.functionName);
195 yield* assertRoleDeleted(fn.roleName);
196 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
197 {
198 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
199 timeout: 120_000,
200 },
201 );
202
203 test.provider(
204 "async handler invokes the export named by `handler`",
205 (stack) =>
206 Effect.gen(function* () {
207 yield* stack.destroy();
208
209 const fn = yield* stack.deploy(
210 AWS.Lambda.Function("NamedHandlerFn", {
211 main: namedHandlerPath,
212 handler: "handler",
213 functionUrl: false,
214 }),
215 );
216
217 const { Configuration } = yield* Lambda.getFunction({ FunctionName: fn.functionName });
218 expect(Configuration?.Handler).toBe("index.handler");
219
220 const response = yield* Lambda.invoke({ FunctionName: fn.functionName, Payload: "{}" });
221 expect(response.FunctionError).toBeUndefined();
222 const payload = response.Payload
223 ? yield* response.Payload.pipe(Stream.decodeText(), Stream.mkString)
224 : "";
225 expect(JSON.parse(payload)).toEqual({ statusCode: 200, body: "named" });
226
227 yield* stack.destroy();
228 yield* assertFunctionDeleted(fn.functionName);
229 yield* assertRoleDeleted(fn.roleName);
230 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
231 {
232 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
233 timeout: 120_000,
234 },
235 );
236
237 test.provider(
238 "applies and updates the Lambda timeout",
239 (stack) =>
240 Effect.gen(function* () {
241 yield* stack.destroy();
242
243 const initial = yield* stack.deploy(
244 AWS.Lambda.Function("TimeoutFn", {
245 main: timeoutHandlerPath,
246 handler: "handler",
247 isExternal: true,
248 functionUrl: false,
249 timeout: Duration.seconds(15),
250 }),
251 );
252
253 const initialConfig = yield* Lambda.getFunction({
254 FunctionName: initial.functionName,
255 });
256 expect(initialConfig.Configuration?.Timeout).toBe(15);
257
258 yield* stack.deploy(
259 AWS.Lambda.Function("TimeoutFn", {
260 main: timeoutHandlerPath,
261 handler: "handler",
262 isExternal: true,
263 functionUrl: false,
264 timeout: Duration.seconds(45),
265 }),
266 );
267
268 const updatedConfig = yield* Lambda.getFunction({
269 FunctionName: initial.functionName,
270 }).pipe(
271 Effect.filterOrFail(
272 (c) => c.Configuration?.Timeout === 45,
273 () => new Error("Timeout update has not propagated yet"),
274 ),
275 Effect.retry({
276 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
277 }),
278 );
279 expect(updatedConfig.Configuration?.Timeout).toBe(45);
280
281 yield* stack.destroy();
282 yield* assertFunctionDeleted(initial.functionName);
283 }).pipe(
284 Effect.tap(() => stack.destroy()),
285 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
286 ),
287 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
288 );
289
290 // `logging.retention` makes Alchemy create the `/aws/lambda/<name>` log
291 // group up front (Lambda would only create it on first invoke, with no
292 // expiry) and keep its retention policy in sync; destroy reaps the group.
293 test.provider(
294 "applies, updates, and clears log retention",
295 (stack) =>
296 Effect.gen(function* () {
297 yield* stack.destroy();
298
299 const deployWith = (retention: "10 days" | "forever") =>
300 stack.deploy(
301 AWS.Lambda.Function("RetentionFn", {
302 main: timeoutHandlerPath,
303 handler: "handler",
304 isExternal: true,
305 functionUrl: false,
306 logging: { retention },
307 }),
308 );
309 const describeGroup = (name: string) =>
310 Logs.describeLogGroups({ logGroupNamePrefix: name }).pipe(
311 Effect.map((r) => (r.logGroups ?? []).find((g) => g.logGroupName === name)),
312 );
313
314 // Never invoked: the group exists only because Alchemy created it.
315 const fn = yield* deployWith("10 days");
316 const logGroupName = `/aws/lambda/${fn.functionName}`;
317 expect((yield* describeGroup(logGroupName))?.retentionInDays).toBe(14);
318
319 yield* deployWith("forever");
320 const cleared = yield* describeGroup(logGroupName);
321 expect(cleared).toBeDefined();
322 expect(cleared?.retentionInDays).toBeUndefined();
323
324 yield* stack.destroy();
325 yield* assertFunctionDeleted(fn.functionName);
326 expect(yield* describeGroup(logGroupName)).toBeUndefined();
327 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
328 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:logs", "live"], timeout: 360_000 },
329 );
330
331 // Alchemy owns `/aws/lambda/<name>`: the execution role keeps the managed
332 // AWSLambdaBasicExecutionRole but is denied logs:CreateLogGroup on its own
333 // group, so destroy deletes the group exactly once — Lambda's asynchronous
334 // flush of an invocation that ran right before the delete is dropped instead
335 // of silently recreating the group.
336 test.provider(
337 "destroy right after an invoke removes the log group for good",
338 (stack) =>
339 Effect.gen(function* () {
340 yield* stack.destroy();
341
342 const fn = yield* stack.deploy(
343 AWS.Lambda.Function("FlushFn", {
344 main: timeoutHandlerPath,
345 handler: "handler",
346 isExternal: true,
347 functionUrl: false,
348 }),
349 );
350 const logGroupName = `/aws/lambda/${fn.functionName}`;
351 const describeGroup = Logs.describeLogGroups({ logGroupNamePrefix: logGroupName }).pipe(
352 Effect.map((r) => (r.logGroups ?? []).find((g) => g.logGroupName === logGroupName)),
353 );
354
355 // Created by Alchemy before any invocation.
356 expect(yield* describeGroup).toBeDefined();
357
358 // The managed policy stays; an inline Deny scoped to this function's
359 // group overrides its logs:CreateLogGroup on *.
360 const attached = yield* iam.listAttachedRolePolicies({ RoleName: fn.roleName });
361 expect((attached.AttachedPolicies ?? []).map((p) => p.PolicyArn)).toEqual([
362 "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
363 ]);
364 const { PolicyDocument } = yield* iam.getRolePolicy({
365 RoleName: fn.roleName,
366 PolicyName: "AlchemyDenyLogGroupCreate",
367 });
368 const guard = JSON.parse(decodeURIComponent(PolicyDocument)) as {
369 Statement: { Effect: string; Action: string; Resource: string }[];
370 };
371 expect(guard.Statement).toHaveLength(1);
372 expect(guard.Statement[0]).toMatchObject({
373 Effect: "Deny",
374 Action: "logs:CreateLogGroup",
375 });
376 expect(guard.Statement[0]!.Resource).toMatch(
377 new RegExp(`:log-group:${logGroupName.replaceAll("/", "\\/")}:\\*$`),
378 );
379
380 // Invocations whose log batches are still in flight at delete time.
381 for (let i = 0; i < 3; i++) {
382 const response = yield* Lambda.invoke({ FunctionName: fn.functionName, Payload: "{}" });
383 expect(response.FunctionError).toBeUndefined();
384 }
385
386 const [elapsed] = yield* Effect.timed(stack.destroy());
387 yield* Effect.logInfo(`destroy took ${Duration.format(elapsed)}`);
388 // No flush window to wait out (previously ~40s+).
389 expect(Duration.toSeconds(elapsed)).toBeLessThan(30);
390 yield* assertFunctionDeleted(fn.functionName);
391 yield* assertRoleDeleted(fn.roleName);
392 expect(yield* describeGroup).toBeUndefined();
393
394 // Lambda flushes the final batches up to ~35s after the last invoke;
395 // the role could never create the group, so it stays gone.
396 yield* Effect.sleep("60 seconds");
397 expect(yield* describeGroup).toBeUndefined();
398 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
399 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:logs", "live"], timeout: 180_000 },
400 );
401
402 // Roles deployed by older Alchemy versions have no guard; the next deploy
403 // adds it (and creates the log group if Lambda never did).
404 test.provider(
405 "adds the log-group guard to an existing role on the next deploy",
406 (stack) =>
407 Effect.gen(function* () {
408 yield* stack.destroy();
409
410 const deploy = (marker: string) =>
411 stack.deploy(
412 AWS.Lambda.Function("LegacyRoleFn", {
413 main: timeoutHandlerPath,
414 handler: "handler",
415 isExternal: true,
416 functionUrl: false,
417 env: { MARKER: marker },
418 }),
419 );
420 const fn = yield* deploy("v1");
421 const logGroupName = `/aws/lambda/${fn.functionName}`;
422
423 // Recreate the pre-guard shape out-of-band.
424 yield* iam.deleteRolePolicy({
425 RoleName: fn.roleName,
426 PolicyName: "AlchemyDenyLogGroupCreate",
427 });
428 yield* Logs.deleteLogGroup({ logGroupName });
429
430 yield* deploy("v2");
431
432 const { PolicyNames } = yield* iam.listRolePolicies({ RoleName: fn.roleName });
433 expect(PolicyNames).toContain("AlchemyDenyLogGroupCreate");
434 const groups = yield* Logs.describeLogGroups({ logGroupNamePrefix: logGroupName });
435 expect((groups.logGroups ?? []).map((g) => g.logGroupName)).toContain(logGroupName);
436
437 yield* stack.destroy();
438 yield* assertFunctionDeleted(fn.functionName);
439 yield* assertRoleDeleted(fn.roleName);
440 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
441 { tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"], timeout: 120_000 },
442 );
443
444 test.provider(
445 "installs explicit external packages into the deployment artifact",
446 (stack) =>
447 Effect.gen(function* () {
448 yield* stack.destroy();
449
450 const { functionName, functionUrl } = yield* stack.deploy(
451 AWS.Lambda.Function("InstallFn", {
452 main: externalPackageHandlerPath,
453 handler: "handler",
454 isExternal: true,
455 functionUrl: true,
456 build: {
457 install: ["uuid"],
458 },
459 }),
460 );
461
462 const response = yield* HttpClient.get(functionUrl!).pipe(
463 Effect.flatMap((response) =>
464 response.status === 200
465 ? Effect.succeed(response)
466 : Effect.fail(new Error(`Function URL returned ${response.status}`)),
467 ),
468 Effect.retry({
469 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
470 }),
471 );
472
473 const body = JSON.parse(yield* response.text) as { id: string };
474 expect(body.id).toMatch(
475 /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
476 );
477
478 yield* stack.destroy();
479 yield* assertFunctionDeleted(functionName);
480 }).pipe(
481 Effect.tap(() => stack.destroy()),
482 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
483 ),
484 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
485 );
486
487 test.provider(
488 "installs external packages at the versions pinned by each lockfile format",
489 (stack) =>
490 Effect.gen(function* () {
491 yield* stack.destroy();
492
493 // Each fixture project declares make-dir@^3.0.0 but its lockfile pins
494 // make-dir@3.0.0 and its transitive semver@6.3.0 — both below the latest
495 // versions satisfying their ranges (3.1.0 / 6.3.1). Free npm resolution
496 // installs the newer versions, so the assertions below fail without
497 // lockfile pinning. Legacy binary bun.lockb has no live fixture because
498 // current Bun can only write the text format; its print-and-parse path
499 // is covered by the yarn-v1 unit fixtures.
500 const formats = ["npm", "bun", "pnpm", "yarn"] as const;
501 const pinnedFunction = (format: (typeof formats)[number]) =>
502 AWS.Lambda.Function(`LockfilePinnedFn-${format}`, {
503 main: lockfilePinnedHandlerPath(format),
504 handler: "handler",
505 isExternal: true,
506 functionUrl: true,
507 build: {
508 install: ["make-dir"],
509 },
510 });
511 const deployed = yield* stack.deploy(
512 Effect.all({
513 npm: pinnedFunction("npm"),
514 bun: pinnedFunction("bun"),
515 pnpm: pinnedFunction("pnpm"),
516 yarn: pinnedFunction("yarn"),
517 }),
518 );
519
520 for (const format of formats) {
521 const { functionUrl } = deployed[format];
522 const response = yield* HttpClient.get(functionUrl!).pipe(
523 Effect.flatMap((response) =>
524 response.status === 200
525 ? Effect.succeed(response)
526 : Effect.fail(new Error(`Function URL returned ${response.status}`)),
527 ),
528 Effect.retry({
529 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
530 }),
531 );
532
533 const body = JSON.parse(yield* response.text) as {
534 makeDir: string;
535 semver: string;
536 };
537 expect(body.makeDir, format).toBe("3.0.0");
538 expect(body.semver, format).toBe("6.3.0");
539 }
540
541 yield* stack.destroy();
542 yield* assertFunctionDeleted(deployed.npm.functionName);
543 }).pipe(
544 Effect.tap(() => stack.destroy()),
545 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
546 ),
547 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
548 );
549
550 test.provider(
551 "applies and updates the Lambda architecture",
552 (stack) =>
553 Effect.gen(function* () {
554 yield* stack.destroy();
555
556 const initial = yield* stack.deploy(
557 AWS.Lambda.Function("ArchitectureFn", {
558 main: timeoutHandlerPath,
559 handler: "handler",
560 isExternal: true,
561 functionUrl: false,
562 architecture: "arm64",
563 }),
564 );
565
566 yield* waitForArchitecture(initial.functionName, "arm64");
567
568 const updated = yield* stack.deploy(
569 AWS.Lambda.Function("ArchitectureFn", {
570 main: timeoutHandlerPath,
571 handler: "handler",
572 isExternal: true,
573 functionUrl: false,
574 }),
575 );
576
577 expect(updated.functionName).toBe(initial.functionName);
578 yield* waitForArchitecture(updated.functionName, "x86_64");
579
580 yield* stack.destroy();
581 yield* assertFunctionDeleted(initial.functionName);
582 }).pipe(
583 Effect.tap(() => stack.destroy()),
584 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
585 ),
586 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
587 );
588
589 test.provider(
590 "applies, updates, and removes reserved concurrency",
591 (stack) =>
592 Effect.gen(function* () {
593 yield* stack.destroy();
594
595 const initial = yield* stack.deploy(
596 AWS.Lambda.Function("ConcurrencyFn", {
597 main: timeoutHandlerPath,
598 handler: "handler",
599 isExternal: true,
600 functionUrl: false,
601 }),
602 );
603
604 expect(initial.reservedConcurrentExecutions).toBeUndefined();
605 yield* waitForReservedConcurrency(initial.functionName, undefined);
606
607 const updated = yield* stack.deploy(
608 AWS.Lambda.Function("ConcurrencyFn", {
609 main: timeoutHandlerPath,
610 handler: "handler",
611 isExternal: true,
612 functionUrl: false,
613 reservedConcurrentExecutions: 0,
614 }),
615 );
616
617 expect(updated.functionName).toBe(initial.functionName);
618 expect(updated.reservedConcurrentExecutions).toBe(0);
619 yield* waitForReservedConcurrency(updated.functionName, 0);
620
621 const removed = yield* stack.deploy(
622 AWS.Lambda.Function("ConcurrencyFn", {
623 main: timeoutHandlerPath,
624 handler: "handler",
625 isExternal: true,
626 functionUrl: false,
627 }),
628 );
629
630 expect(removed.functionName).toBe(initial.functionName);
631 expect(removed.reservedConcurrentExecutions).toBeUndefined();
632 yield* waitForReservedConcurrency(removed.functionName, undefined);
633
634 yield* stack.destroy();
635 yield* assertFunctionDeleted(initial.functionName);
636 }).pipe(
637 Effect.tap(() => stack.destroy()),
638 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
639 ),
640 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
641 );
642
643 // #2435: `read` must observe the live configuration, or an out-of-band
644 // memory/timeout change reads as `unchanged` and drift never repairs it.
645 test.provider(
646 "drift detects and repairs out-of-band memory and timeout changes",
647 (stack) =>
648 Effect.gen(function* () {
649 yield* stack.destroy();
650
651 const fn = yield* stack.deploy(
652 AWS.Lambda.Function("DriftFn", {
653 main: timeoutHandlerPath,
654 handler: "handler",
655 isExternal: true,
656 functionUrl: false,
657 memorySize: 128,
658 timeout: Duration.seconds(3),
659 }),
660 );
661 expect(fn.memorySize).toBe(128);
662 expect(fn.timeoutSeconds).toBe(3);
663
664 const detectDrift = () => Drift.detect(stack).pipe(Effect.provide(stack.state));
665 expect((yield* detectDrift()).resources.DriftFn?.action).toBe("unchanged");
666
667 yield* Lambda.updateFunctionConfiguration({
668 FunctionName: fn.functionName,
669 MemorySize: 256,
670 Timeout: 10,
671 }).pipe(
672 Effect.retry({
673 while: (e) => e._tag === "ResourceConflictException",
674 schedule: Schedule.exponential(500),
675 times: 8,
676 }),
677 );
678 yield* waitForConfiguration(fn.functionName, { memorySize: 256, timeout: 10 });
679
680 const drifted = (yield* detectDrift()).resources.DriftFn;
681 expect(drifted?.action).toBe("drifted");
682 expect(drifted?.attr).toMatchObject({ memorySize: 256, timeoutSeconds: 10 });
683
684 const repaired = yield* Drift.repair({ name: stack.name, stage: stack.stage }).pipe(
685 Effect.provide(stack.state),
686 );
687 expect(repaired.resources.DriftFn?.action).toBe("repaired");
688 yield* waitForConfiguration(fn.functionName, { memorySize: 128, timeout: 3 });
689 expect((yield* detectDrift()).resources.DriftFn?.action).toBe("unchanged");
690
691 yield* stack.destroy();
692 yield* assertFunctionDeleted(fn.functionName);
693 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
694 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 240_000 },
695 );
696
697 // `read` reports a function whose ownership tags were stripped as `Unowned`;
698 // drift repairs it anyway (state records it as ours). Repair must restore the
699 // configuration and the tags, not refuse on the missing tags.
700 test.provider(
701 "drift repairs a function whose ownership tags were stripped",
702 (stack) =>
703 Effect.gen(function* () {
704 yield* stack.destroy();
705
706 const fn = yield* stack.deploy(
707 AWS.Lambda.Function("DriftTagsFn", {
708 main: timeoutHandlerPath,
709 handler: "handler",
710 isExternal: true,
711 functionUrl: false,
712 memorySize: 128,
713 timeout: Duration.seconds(3),
714 }),
715 );
716 const before = yield* Lambda.getFunction({ FunctionName: fn.functionName });
717 const ownership = Object.keys(before.Tags ?? {}).filter((key) => key.startsWith("alchemy::"));
718 expect(ownership.length).toBeGreaterThan(0);
719
720 yield* Lambda.untagResource({ Resource: fn.functionArn, TagKeys: ownership });
721 yield* Lambda.updateFunctionConfiguration({
722 FunctionName: fn.functionName,
723 MemorySize: 256,
724 }).pipe(
725 Effect.retry({
726 while: (e) => e._tag === "ResourceConflictException",
727 schedule: Schedule.exponential(500),
728 times: 8,
729 }),
730 );
731 yield* waitForConfiguration(fn.functionName, { memorySize: 256, timeout: 3 });
732
733 const target = { name: stack.name, stage: stack.stage };
734 const detected = yield* Drift.detect(target).pipe(Effect.provide(stack.state));
735 expect(detected.resources.DriftTagsFn?.action).toBe("drifted");
736
737 const repaired = yield* Drift.repair(target).pipe(Effect.provide(stack.state));
738 expect(repaired.resources.DriftTagsFn?.action).toBe("repaired");
739 yield* waitForConfiguration(fn.functionName, { memorySize: 128, timeout: 3 });
740 const after = yield* Lambda.getFunction({ FunctionName: fn.functionName });
741 for (const key of ownership) expect(after.Tags?.[key]).toBe(before.Tags?.[key]);
742
743 yield* stack.destroy();
744 yield* assertFunctionDeleted(fn.functionName);
745 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
746 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 240_000 },
747 );
748
749 // #2659: `read` must observe every setting reconcile converges — environment,
750 // tracing, code, URL auth/CORS, log retention, execution-role policies — or
751 // an out-of-band change reads as `unchanged` and drift never repairs it.
752 test.provider(
753 "drift detects and repairs out-of-band configuration, code, URL and role changes",
754 (stack) =>
755 Effect.gen(function* () {
756 yield* stack.destroy();
757
758 const fn = yield* stack.deploy(
759 AWS.Lambda.Function("DriftConfigFn", {
760 main: timeoutHandlerPath,
761 handler: "handler",
762 isExternal: true,
763 functionUrl: { authType: "NONE" },
764 env: { DRIFT_MARKER: "declared" },
765 logging: { retention: "1 week" },
766 }),
767 );
768 const target = { name: stack.name, stage: stack.stage };
769 const detect = Drift.detect(target).pipe(
770 Effect.map((result) => result.resources.DriftConfigFn),
771 Effect.provide(stack.state),
772 );
773 expect((yield* detect)?.action).toBe("unchanged");
774 const deployed = yield* Lambda.getFunctionConfiguration({ FunctionName: fn.functionName });
775
776 const settled = Lambda.getFunctionConfiguration({ FunctionName: fn.functionName }).pipe(
777 Effect.repeat({
778 until: (config) => config.LastUpdateStatus === "Successful",
779 schedule: Schedule.spaced("1 second"),
780 times: 30,
781 }),
782 );
783 yield* Lambda.updateFunctionConfiguration({
784 FunctionName: fn.functionName,
785 Environment: {
786 Variables: { ...deployed.Environment?.Variables, DRIFT_MARKER: "out-of-band" },
787 },
788 TracingConfig: { Mode: "Active" },
789 }).pipe(
790 Effect.retry({
791 while: (e) => e._tag === "ResourceConflictException",
792 schedule: Schedule.exponential(500),
793 times: 8,
794 }),
795 );
796 yield* settled;
797 yield* Lambda.updateFunctionCode({
798 FunctionName: fn.functionName,
799 ZipFile: yield* zipCode("export const handler = async () => 'replaced';"),
800 }).pipe(
801 Effect.retry({
802 while: (e) => e._tag === "ResourceConflictException",
803 schedule: Schedule.exponential(500),
804 times: 8,
805 }),
806 );
807 yield* settled;
808 yield* Lambda.updateFunctionUrlConfig({
809 FunctionName: fn.functionName,
810 AuthType: "AWS_IAM",
811 Cors: { AllowOrigins: ["https://example.com"] },
812 }).pipe(
813 Effect.retry({
814 while: (e) => e._tag === "ResourceConflictException",
815 schedule: Schedule.exponential(500),
816 times: 8,
817 }),
818 );
819 yield* Logs.putRetentionPolicy({
820 logGroupName: `/aws/lambda/${fn.functionName}`,
821 retentionInDays: 30,
822 });
823 yield* iam.detachRolePolicy({
824 RoleName: fn.roleName,
825 PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
826 });
827
828 const drifted = yield* detect.pipe(
829 Effect.repeat({
830 until: (result) =>
831 result?.attr?.tracing === "Active" &&
832 result.attr.codeSha256 !== deployed.CodeSha256 &&
833 result.attr.functionUrlConfig?.authType === "AWS_IAM" &&
834 result.attr.logRetentionInDays === 30 &&
835 result.attr.executionRole?.managedPolicyArns.length === 0,
836 schedule: Schedule.spaced("2 seconds"),
837 times: 15,
838 }),
839 );
840 expect(drifted?.action).toBe("drifted");
841 expect(drifted?.attr?.environment?.DRIFT_MARKER).toBeDefined();
842 expect(drifted?.attr?.functionUrlConfig?.cors?.AllowOrigins).toEqual(["https://example.com"]);
843
844 const repaired = yield* Drift.repair(target).pipe(Effect.provide(stack.state));
845 expect(repaired.resources.DriftConfigFn?.action).toBe("repaired");
846 expect((yield* detect)?.action).toBe("unchanged");
847
848 const config = yield* Lambda.getFunctionConfiguration({ FunctionName: fn.functionName });
849 const marker = config.Environment?.Variables?.DRIFT_MARKER;
850 expect(Redacted.isRedacted(marker) ? Redacted.value(marker) : marker).toBe("declared");
851 expect(config.TracingConfig?.Mode).toBe("PassThrough");
852 expect(config.CodeSha256).toBe(deployed.CodeSha256);
853 const url = yield* Lambda.getFunctionUrlConfig({ FunctionName: fn.functionName });
854 expect(url.AuthType).toBe("NONE");
855 expect(url.Cors?.AllowOrigins ?? []).toEqual([]);
856 const groups = yield* Logs.describeLogGroups({
857 logGroupNamePrefix: `/aws/lambda/${fn.functionName}`,
858 });
859 expect(groups.logGroups?.[0]?.retentionInDays).toBe(7);
860 const attached = yield* iam.listAttachedRolePolicies({ RoleName: fn.roleName });
861 expect(attached.AttachedPolicies?.map((policy) => policy.PolicyArn)).toContain(
862 "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
863 );
864
865 yield* stack.destroy();
866 yield* assertFunctionDeleted(fn.functionName);
867 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
868 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 300_000 },
869 );
870
871 // #1536: drift recreates a deleted function without its bindings, then
872 // attaches them — the environment and IAM statements come back.
873 test.provider(
874 "drift repair recreates a deleted function and restores its bindings",
875 (stack) =>
876 Effect.gen(function* () {
877 yield* stack.destroy();
878
879 const fn = yield* stack.deploy(
880 Effect.gen(function* () {
881 const fn = yield* AWS.Lambda.Function("DriftBoundFn", {
882 main: timeoutHandlerPath,
883 handler: "handler",
884 isExternal: true,
885 functionUrl: false,
886 });
887 yield* fn.bind("DriftBinding", {
888 env: { DRIFT_MARKER: "bound" },
889 policyStatements: [
890 {
891 Sid: "DriftBinding",
892 Effect: "Allow",
893 Action: ["sqs:GetQueueUrl"],
894 Resource: ["*"],
895 },
896 ],
897 });
898 return fn;
899 }),
900 );
901
902 yield* Lambda.deleteFunction({ FunctionName: fn.functionName });
903 yield* assertFunctionDeleted(fn.functionName);
904
905 const target = { name: stack.name, stage: stack.stage };
906 const detected = yield* Drift.detect(target).pipe(Effect.provide(stack.state));
907 expect(detected.resources.DriftBoundFn?.action).toBe("missing");
908
909 const repaired = yield* Drift.repair(target).pipe(Effect.provide(stack.state));
910 expect(repaired.resources.DriftBoundFn?.action).toBe("recreated");
911
912 const config = yield* Lambda.getFunctionConfiguration({ FunctionName: fn.functionName });
913 const marker = config.Environment?.Variables?.DRIFT_MARKER;
914 expect(Redacted.isRedacted(marker) ? Redacted.value(marker) : marker).toBe("bound");
915 const policies = yield* iam.listRolePolicies({ RoleName: fn.roleName });
916 const documents = yield* Effect.all(
917 policies.PolicyNames.map((PolicyName) =>
918 iam.getRolePolicy({ RoleName: fn.roleName, PolicyName }),
919 ),
920 );
921 expect(
922 documents.some((doc) => decodeURIComponent(doc.PolicyDocument).includes("DriftBinding")),
923 ).toBe(true);
924 expect(
925 (yield* Drift.detect(target).pipe(Effect.provide(stack.state))).resources.DriftBoundFn
926 ?.action,
927 ).toBe("unchanged");
928
929 yield* stack.destroy();
930 yield* assertFunctionDeleted(fn.functionName);
931 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
932 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 240_000 },
933 );
934
935 // Canonical `list()` test (AWS account/region-scoped collection): deploy a
936 // real function, resolve the provider from context via the typed
937 // `Provider.findProvider`, call `list()`, and assert the deployed function
938 // appears in the exhaustively-paginated result.
939 test.provider(
940 "list enumerates the deployed function",
941 (stack) =>
942 Effect.gen(function* () {
943 yield* stack.destroy();
944
945 const deployed = yield* stack.deploy(
946 AWS.Lambda.Function("ListFn", {
947 main: timeoutHandlerPath,
948 handler: "handler",
949 isExternal: true,
950 functionUrl: false,
951 }),
952 );
953
954 const provider = yield* Provider.findProvider(AWS.Lambda.Function);
955 const all = yield* provider.list();
956
957 expect(all.some((f) => f.functionName === deployed.functionName)).toBe(true);
958
959 yield* stack.destroy();
960 yield* assertFunctionDeleted(deployed.functionName);
961 }).pipe(
962 Effect.tap(() => stack.destroy()),
963 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
964 ),
965 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 180_000 },
966 );
967
968 test.provider(
969 "streams an Effect HttpServerResponse through a RESPONSE_STREAM function URL",
970 (stack) =>
971 Effect.gen(function* () {
972 yield* stack.destroy();
973
974 const { functionName, functionUrl } = yield* stack.deploy(
975 Effect.gen(function* () {
976 return yield* StreamingFunction;
977 }).pipe(Effect.provide(StreamingFunctionLive)),
978 );
979 expect(functionUrl).toBeTruthy();
980
981 const response = yield* HttpClient.get(functionUrl!).pipe(
982 Effect.flatMap((response) =>
983 response.status === 200
984 ? Effect.succeed(response)
985 : Effect.fail(new Error(`Function URL returned ${response.status}`)),
986 ),
987 Effect.retry({
988 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
989 }),
990 );
991 expect(response.headers["content-type"]).toBe("text/event-stream");
992 expect(response.headers["x-streamed"]).toBe("true");
993 expect(response.headers["set-cookie"]).toContain("session=abc");
994
995 // Record when each event arrives: streamed events are ~2s apart, a
996 // buffered body arrives in one piece at the end.
997 const arrivals = yield* response.stream.pipe(
998 Stream.decodeText(),
999 Stream.mapEffect((text) =>
1000 Effect.map(
1001 Effect.clockWith((clock) => clock.currentTimeMillis),
1002 (at) => ({
1003 text,
1004 at,
1005 }),
1006 ),
1007 ),
1008 Stream.runCollect,
1009 );
1010 expect(arrivals.map((a) => a.text).join("")).toBe(
1011 "data: one\n\ndata: two\n\ndata: three\n\n",
1012 );
1013 expect(arrivals.length).toBeGreaterThanOrEqual(3);
1014 expect(arrivals[arrivals.length - 1]!.at - arrivals[0]!.at).toBeGreaterThanOrEqual(3_000);
1015
1016 yield* stack.destroy();
1017 yield* assertFunctionDeleted(functionName);
1018 }).pipe(
1019 Effect.tap(() => stack.destroy()),
1020 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
1021 ),
1022 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 180_000 },
1023 );
1024
1025 test.provider(
1026 "updates function URL auth to AWS_IAM",
1027 (stack) =>
1028 Effect.gen(function* () {
1029 yield* stack.destroy();
1030
1031 const initial = yield* stack.deploy(
1032 AWS.Lambda.Function("IamUrlFn", {
1033 main: timeoutHandlerPath,
1034 handler: "handler",
1035 isExternal: true,
1036 functionUrl: true,
1037 }),
1038 );
1039
1040 const invokePolicy = yield* getPolicyStatement(
1041 initial.functionName,
1042 "FunctionURLAllowPublicInvoke",
1043 );
1044 expect(invokePolicy.Condition).toEqual({
1045 Bool: {
1046 "lambda:InvokedViaFunctionUrl": "true",
1047 },
1048 });
1049
1050 const updated = yield* stack.deploy(
1051 AWS.Lambda.Function("IamUrlFn", {
1052 main: timeoutHandlerPath,
1053 handler: "handler",
1054 isExternal: true,
1055 functionUrl: {
1056 authType: "AWS_IAM",
1057 cors: {
1058 AllowHeaders: ["authorization", "content-type"],
1059 AllowMethods: ["GET", "POST"],
1060 AllowOrigins: ["https://example.com"],
1061 ExposeHeaders: ["x-request-id"],
1062 MaxAge: 300,
1063 },
1064 invokeMode: "RESPONSE_STREAM",
1065 },
1066 }),
1067 );
1068
1069 expect(updated.functionName).toBe(initial.functionName);
1070 expect(updated.functionUrl).toBeTruthy();
1071
1072 const config = yield* getFunctionUrlConfigWithAuth(updated.functionName, "AWS_IAM");
1073 expect(config.AuthType).toBe("AWS_IAM");
1074 expect(config.InvokeMode).toBe("RESPONSE_STREAM");
1075 expect(config.Cors).toEqual({
1076 AllowHeaders: ["authorization", "content-type"],
1077 AllowMethods: ["GET", "POST"],
1078 AllowOrigins: ["https://example.com"],
1079 ExposeHeaders: ["x-request-id"],
1080 MaxAge: 300,
1081 });
1082
1083 yield* waitForPolicyStatementAbsent(updated.functionName, "FunctionURLAllowPublicAccess");
1084 yield* waitForPolicyStatementAbsent(updated.functionName, "FunctionURLAllowPublicInvoke");
1085
1086 const response = yield* HttpClient.get(updated.functionUrl!).pipe(
1087 Effect.flatMap((response) =>
1088 response.status === 403
1089 ? Effect.succeed(response)
1090 : Effect.fail(new Error(`IAM Function URL returned ${response.status}`)),
1091 ),
1092 Effect.retry({
1093 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1094 }),
1095 );
1096 expect(response.status).toBe(403);
1097
1098 yield* stack.destroy();
1099 yield* assertFunctionDeleted(initial.functionName);
1100 }).pipe(
1101 Effect.tap(() => stack.destroy()),
1102 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
1103 ),
1104 { tags: ["provider:aws", "provider:aws:lambda", "live"], timeout: 360_000 },
1105 );
1106
1107 // `alias` publishes a version per deploy and routes every consumer through
1108 // the alias: the function URL and the event-source mapping target `:live`,
1109 // so moving the alias back to an earlier version rolls back without a
1110 // redeploy. Removing `alias` moves them back to the unqualified function.
1111 test.provider(
1112 "alias routes the function URL and event sources through the alias",
1113 (stack) =>
1114 Effect.gen(function* () {
1115 yield* stack.destroy();
1116
1117 const deploy = (alias: string | undefined, marker: string) =>
1118 stack.deploy(
1119 Effect.gen(function* () {
1120 const fn = yield* AliasFunction;
1121 yield* fn.bind`ReleaseMarker`({ env: { RELEASE_MARKER: marker } });
1122 return fn;
1123 }).pipe(Effect.provide(aliasFunction(alias))),
1124 );
1125
1126 const v1 = yield* deploy("live", "v1");
1127 const aliasArn = `${v1.functionArn}:live`;
1128 expect(v1.aliasName).toBe("live");
1129 expect(v1.qualifiedArn).toBe(aliasArn);
1130 expect(v1.version).toMatch(/^[1-9]\d*$/);
1131 yield* assertAlias(v1.functionName, "live", v1.version!);
1132 yield* assertUrlQualifier(v1.functionName, v1.functionUrl!, "live");
1133 expect(yield* eventSourceMappingTargets(v1.functionName)).toEqual([aliasArn]);
1134 yield* expectServes(`${v1.functionName}:live`, "v1");
1135
1136 // A new release advances the alias; consumers keep the same target.
1137 const v2 = yield* deploy("live", "v2");
1138 expect(v2.qualifiedArn).toBe(aliasArn);
1139 expect(v2.functionUrl).toBe(v1.functionUrl);
1140 expect(Number(v2.version)).toBeGreaterThan(Number(v1.version));
1141 yield* assertAlias(v2.functionName, "live", v2.version!);
1142 expect(yield* eventSourceMappingTargets(v2.functionName)).toEqual([aliasArn]);
1143 yield* expectServes(`${v2.functionName}:live`, "v2");
1144
1145 // Rollback is one UpdateAlias call: everything wired to the alias
1146 // serves v1 again.
1147 yield* Lambda.updateAlias({
1148 FunctionName: v2.functionName,
1149 Name: "live",
1150 FunctionVersion: v1.version!,
1151 });
1152 yield* expectServes(`${v2.functionName}:live`, "v1");
1153
1154 // Removing the alias moves the URL and mapping back to the function.
1155 const unaliased = yield* deploy(undefined, "v2");
1156 expect(unaliased.aliasName).toBeUndefined();
1157 expect(unaliased.qualifiedArn).toBe(unaliased.functionArn);
1158 yield* Lambda.getAlias({ FunctionName: unaliased.functionName, Name: "live" }).pipe(
1159 Effect.flatMap(() => Effect.fail(new Error("alias live still exists"))),
1160 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
1161 );
1162 yield* assertUrlQualifier(unaliased.functionName, unaliased.functionUrl!, undefined);
1163 expect(yield* eventSourceMappingTargets(unaliased.functionName)).toEqual([
1164 unaliased.functionArn,
1165 ]);
1166 yield* expectServes(unaliased.functionName, "v2");
1167
1168 yield* stack.destroy();
1169 yield* assertFunctionDeleted(unaliased.functionName);
1170 }).pipe(
1171 Effect.tap(() => stack.destroy()),
1172 Effect.onError(() => stack.destroy().pipe(Effect.ignore)),
1173 ),
1174 {
1175 tags: ["provider:aws", "provider:aws:lambda", "provider:aws:sqs", "live"],
1176 timeout: 360_000,
1177 },
1178 );
1179
1180 // Alias moves are eventually consistent: poll until the qualifier serves the
1181 // expected release.
1182 const expectServes = Effect.fn(function* (functionName: string, marker: string) {
1183 const body = yield* invokeHttpFunction(functionName).pipe(
1184 Effect.repeat({
1185 schedule: Schedule.spaced("1 second"),
1186 until: (body) => body === marker,
1187 times: 20,
1188 }),
1189 );
1190 expect(body).toBe(marker);
1191 });
1192
1193 const assertAlias = Effect.fn(function* (functionName: string, alias: string, version: string) {
1194 const observed = yield* Lambda.getAlias({ FunctionName: functionName, Name: alias });
1195 expect(observed.FunctionVersion).toBe(version);
1196 });
1197
1198 // The function URL lives on exactly one qualifier: the alias, or the
1199 // unqualified function when there is none.
1200 const assertUrlQualifier = Effect.fn(function* (
1201 functionName: string,
1202 functionUrl: string,
1203 qualifier: string | undefined,
1204 ) {
1205 const config = yield* Lambda.getFunctionUrlConfig({
1206 FunctionName: functionName,
1207 Qualifier: qualifier,
1208 });
1209 expect(config.FunctionUrl).toBe(functionUrl);
1210 expect(config.FunctionArn).toMatch(qualifier ? new RegExp(`:${qualifier}$`) : /:function:[^:]+$/);
1211 if (qualifier !== undefined) {
1212 const unqualified = yield* Lambda.getFunctionUrlConfig({ FunctionName: functionName }).pipe(
1213 Effect.map(() => "present" as const),
1214 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("absent" as const)),
1215 );
1216 expect(unqualified).toBe("absent");
1217 }
1218 });
1219
1220 // Function ARNs every event-source mapping on the function (any qualifier)
1221 // invokes.
1222 const eventSourceMappingTargets = Effect.fn(function* (functionName: string) {
1223 const mappings = yield* Lambda.listEventSourceMappings.items({}).pipe(
1224 Stream.filter((mapping) =>
1225 (mapping.FunctionArn ?? "").split(":").slice(6, 7).includes(functionName),
1226 ),
1227 Stream.runCollect,
1228 );
1229 return Array.from(mappings).map((mapping) => mapping.FunctionArn);
1230 });
1231
1232 const assertFunctionReady = Effect.fn(function* (functionName: string, marker: string) {
1233 // Deploy must finish configuration propagation; these checks never retry.
1234 const { Configuration } = yield* Lambda.getFunction({
1235 FunctionName: functionName,
1236 });
1237 expect(Configuration?.State).toBe("Active");
1238 expect(Configuration?.LastUpdateStatus).toBe("Successful");
1239 const observed = Configuration?.Environment?.Variables?.READINESS_MARKER;
1240 expect(Redacted.isRedacted(observed) ? Redacted.value(observed) : observed).toBe(marker);
1241
1242 expect(yield* invokeHttpFunction(functionName, "/readiness")).toBe(marker);
1243 });
1244
1245 const invokeHttpFunction = Effect.fn(function* (functionName: string, path = "/") {
1246 const response = yield* Lambda.invoke({
1247 FunctionName: functionName,
1248 Payload: JSON.stringify({
1249 version: "2.0",
1250 rawPath: path,
1251 rawQueryString: "",
1252 headers: { host: "localhost" },
1253 requestContext: {
1254 http: {
1255 method: "GET",
1256 path,
1257 protocol: "HTTP/1.1",
1258 sourceIp: "127.0.0.1",
1259 userAgent: "alchemy-test",
1260 },
1261 },
1262 isBase64Encoded: false,
1263 }),
1264 });
1265 expect(response.FunctionError).toBeUndefined();
1266 const payload = response.Payload
1267 ? yield* response.Payload.pipe(Stream.decodeText(), Stream.mkString)
1268 : "";
1269 const body = yield* Effect.try(() => JSON.parse(payload));
1270 expect(body.statusCode).toBe(200);
1271 return body.body as string;
1272 });
1273
1274 // A cycle precreates on unresolved props, before `read` can check ownership.
1275 // `observe` must refuse a foreign function at the precreate identity before
1276 // precreate's create-or-update overwrites it. The queue URL keeps the props
1277 // unresolved; the self-binding puts the function in a cycle.
1278 const cyclicFunction = (functionName: string, scoped?: boolean) =>
1279 Effect.gen(function* () {
1280 const queue = yield* AWS.SQS.Queue("CyclicQueue");
1281 const declaration = AWS.Lambda.Function("CyclicDifferent", {
1282 main: asyncHandlerPath,
1283 functionName,
1284 functionUrl: false,
1285 env: { QUEUE_URL: queue.queueUrl },
1286 });
1287 const fn = yield* scoped === undefined ? declaration : declaration.pipe(adopt(scoped));
1288 yield* fn.bind`Self`({ env: { SELF_NAME: fn.functionName } });
1289 return fn;
1290 });
1291
1292 /**
1293 * Deploys `CyclicOriginal`, then forgets it, leaving a function owned by
1294 * another logical id. Returns a step that remembers it again, so destroy
1295 * removes it — and its execution role — through normal stack cleanup.
1296 */
1297 const plantForeignFunction = Effect.fn(function* (stack: Test.ScratchStack) {
1298 yield* stack.destroy();
1299 const original = yield* stack.deploy(
1300 AWS.Lambda.Function("CyclicOriginal", { main: asyncHandlerPath, functionUrl: false }),
1301 );
1302 const key = { stack: stack.name, stage: stack.stage, fqn: "CyclicOriginal" };
1303 const row = yield* Effect.gen(function* () {
1304 const state = yield* yield* State;
1305 const value = yield* state.get(key);
1306 yield* state.delete(key);
1307 return value!;
1308 }).pipe(Effect.provide(stack.state));
1309 const restore = Effect.gen(function* () {
1310 const state = yield* yield* State;
1311 yield* state.set({ ...key, value: row });
1312 }).pipe(Effect.provide(stack.state));
1313 return { original, restore };
1314 });
1315
1316 for (const scoped of [undefined, false]) {
1317 test.provider(
1318 `a cyclic precreate refuses a foreign function (scoped adoption ${scoped})`,
1319 (stack) =>
1320 Effect.gen(function* () {
1321 const { original, restore } = yield* plantForeignFunction(stack);
1322 const before = yield* Lambda.getFunction({ FunctionName: original.functionName });
1323 const program = cyclicFunction(original.functionName, scoped);
1324 expect((yield* stack.plan(program)).resources.CyclicDifferent?.action).toBe("create");
1325 const error = yield* stack.deploy(program).pipe(Effect.flip);
1326 expect(error).toMatchObject({ _tag: "OwnedBySomeoneElse", logicalId: "CyclicDifferent" });
1327 // Neither the function's code nor its configuration changed.
1328 const after = yield* Lambda.getFunction({ FunctionName: original.functionName });
1329 expect(after.Configuration?.CodeSha256).toBe(before.Configuration?.CodeSha256);
1330 expect(after.Configuration?.LastModified).toBe(before.Configuration?.LastModified);
1331 expect(after.Tags).toEqual(before.Tags);
1332 yield* stack.destroy();
1333 yield* restore;
1334 yield* stack.destroy();
1335 yield* assertFunctionDeleted(original.functionName);
1336 yield* assertRoleDeleted(original.roleName);
1337 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
1338 {
1339 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
1340 timeout: 180_000,
1341 },
1342 );
1343 }
1344
1345 // Outside a cycle `read` refuses the foreign function at plan time; with
1346 // adoption, reconcile updates it from the adopted attributes. That update must
1347 // not re-check the tags the engine already admitted, and re-brands it.
1348 test.provider(
1349 "adopt(true) takes over a foreign function outside a cycle",
1350 (stack) =>
1351 Effect.gen(function* () {
1352 const { original, restore } = yield* plantForeignFunction(stack);
1353 const adopted = yield* stack.deploy(
1354 AWS.Lambda.Function("AdoptedFn", {
1355 main: asyncHandlerPath,
1356 functionName: original.functionName,
1357 functionUrl: false,
1358 }).pipe(adopt(true)),
1359 );
1360 expect(adopted.functionName).toBe(original.functionName);
1361 const { Tags } = yield* Lambda.getFunction({ FunctionName: original.functionName });
1362 expect(Tags?.["alchemy::id"]).toBe("AdoptedFn");
1363 yield* stack.destroy();
1364 yield* assertFunctionDeleted(original.functionName);
1365 yield* assertRoleDeleted(adopted.roleName);
1366 // The taken-over function's previous execution role is still `CyclicOriginal`'s.
1367 yield* restore;
1368 yield* stack.destroy();
1369 yield* assertRoleDeleted(original.roleName);
1370 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
1371 {
1372 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
1373 timeout: 180_000,
1374 },
1375 );
1376
1377 test.provider(
1378 "a cyclic precreate takes over a foreign function with adopt(true)",
1379 (stack) =>
1380 Effect.gen(function* () {
1381 const { original, restore } = yield* plantForeignFunction(stack);
1382 const adopted = yield* stack.deploy(cyclicFunction(original.functionName, true));
1383 expect(adopted.functionName).toBe(original.functionName);
1384 const { Tags } = yield* Lambda.getFunction({ FunctionName: original.functionName });
1385 expect(Tags?.["alchemy::id"]).toBe("CyclicDifferent");
1386 yield* stack.destroy();
1387 yield* assertFunctionDeleted(original.functionName);
1388 yield* assertRoleDeleted(adopted.roleName);
1389 // The taken-over function's previous execution role is still `CyclicOriginal`'s.
1390 yield* restore;
1391 yield* stack.destroy();
1392 yield* assertRoleDeleted(original.roleName);
1393 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
1394 {
1395 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
1396 timeout: 180_000,
1397 },
1398 );
1399
1400 // A cycle precreates before its peers reconcile, but a name from a resource
1401 // outside the cycle resolves first, so precreate names the function with it.
1402 test.provider(
1403 "a cyclic function precreates a name from a resource outside its cycle",
1404 (stack) =>
1405 Effect.gen(function* () {
1406 yield* stack.destroy();
1407 const { fn, queueName } = yield* stack.deploy(
1408 Effect.gen(function* () {
1409 const queue = yield* AWS.SQS.Queue("NamingQueue");
1410 const fn = yield* AWS.Lambda.Function("CyclicNamed", {
1411 main: asyncHandlerPath,
1412 functionName: queue.queueName.pipe(Output.map((name) => `${name.slice(-56)}-named`)),
1413 functionUrl: false,
1414 });
1415 yield* fn.bind`Self`({ env: { SELF_NAME: fn.functionName } });
1416 return { fn, queueName: queue.queueName };
1417 }),
1418 );
1419 expect(fn.functionName).toBe(`${queueName.slice(-56)}-named`);
1420 const live = yield* Lambda.getFunction({ FunctionName: fn.functionName });
1421 const selfName = live.Configuration?.Environment?.Variables?.SELF_NAME;
1422 expect(Redacted.isRedacted(selfName) ? Redacted.value(selfName) : selfName).toBe(
1423 fn.functionName,
1424 );
1425 yield* stack.destroy();
1426 yield* assertFunctionDeleted(fn.functionName);
1427 yield* assertRoleDeleted(fn.roleName);
1428 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
1429 {
1430 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "provider:aws:sqs", "live"],
1431 timeout: 180_000,
1432 },
1433 );
1434
1435 // A name derived from a peer in the function's own cycle is still unresolved
1436 // when the function precreates, so precreate refuses to guess one.
1437 test.provider(
1438 "a cyclic function refuses a name derived from a peer in its cycle",
1439 (stack) =>
1440 Effect.gen(function* () {
1441 yield* stack.destroy();
1442 const error = yield* stack
1443 .deploy(
1444 Effect.gen(function* () {
1445 const peer = yield* AWS.Lambda.Function("NamingPeer", {
1446 main: asyncHandlerPath,
1447 functionUrl: false,
1448 });
1449 const fn = yield* AWS.Lambda.Function("PeerNamed", {
1450 main: asyncHandlerPath,
1451 functionName: peer.functionName.pipe(
1452 Output.map((name) => `${name.slice(-56)}-named`),
1453 ),
1454 functionUrl: false,
1455 });
1456 yield* peer.bind`Named`({ env: { NAMED: fn.functionName } });
1457 return fn;
1458 }),
1459 )
1460 .pipe(Effect.flip);
1461 expect(error).toMatchObject({ _tag: "UnresolvedIdentity", logicalId: "PeerNamed" });
1462 yield* stack.destroy();
1463 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
1464 {
1465 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"],
1466 timeout: 180_000,
1467 },
1468 );
1469
1470 // Out-of-band proof that the trailing destroy actually removed the function
1471 // from the cloud (bounded retry to ride out delete propagation).
1472 const assertFunctionDeleted = Effect.fn(function* (functionName: string) {
1473 yield* Lambda.getFunction({ FunctionName: functionName }).pipe(
1474 Effect.flatMap(() => Effect.fail(new Error(`Function ${functionName} still exists`))),
1475 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
1476 Effect.retry({
1477 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
1478 }),
1479 );
1480 });
1481
1482 // Function cleanup owns its generated execution role. Verify the role is not
1483 // stranded when deletion also waits for Lambda's asynchronous log flush.
1484 const assertRoleDeleted = Effect.fn(function* (roleName: string) {
1485 yield* iam.getRole({ RoleName: roleName }).pipe(
1486 Effect.flatMap(() => Effect.fail(new Error(`Role ${roleName} still exists`))),
1487 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1488 Effect.retry({
1489 schedule: Schedule.spaced("1 second"),
1490 times: 8,
1491 }),
1492 );
1493 });
1494
1495 const getPolicyStatement = Effect.fn(function* (functionName: string, statementId: string) {
1496 return yield* findPolicyStatement(functionName, statementId).pipe(
1497 Effect.flatMap((statement) =>
1498 statement
1499 ? Effect.succeed(statement)
1500 : Effect.fail(new Error(`Policy statement ${statementId} not found`)),
1501 ),
1502 Effect.retry({
1503 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1504 }),
1505 );
1506 });
1507
1508 const waitForPolicyStatementAbsent = Effect.fn(function* (
1509 functionName: string,
1510 statementId: string,
1511 ) {
1512 yield* findPolicyStatement(functionName, statementId).pipe(
1513 Effect.flatMap((statement) =>
1514 statement
1515 ? Effect.fail(new Error(`Policy statement ${statementId} still exists`))
1516 : Effect.void,
1517 ),
1518 Effect.retry({
1519 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1520 }),
1521 );
1522 });
1523
1524 const findPolicyStatement = Effect.fn(function* (functionName: string, statementId: string) {
1525 return yield* Lambda.getPolicy({ FunctionName: functionName }).pipe(
1526 Effect.flatMap(({ Policy }) =>
1527 Effect.try({
1528 try: () => {
1529 const policy = JSON.parse(Policy ?? "{}") as {
1530 Statement?: Array<{
1531 Sid?: string;
1532 Condition?: unknown;
1533 }>;
1534 };
1535 return policy.Statement?.find((statement) => statement.Sid === statementId);
1536 },
1537 catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
1538 }),
1539 ),
1540 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
1541 );
1542 });
1543
1544 const getFunctionUrlConfigWithAuth = Effect.fn(function* (
1545 functionName: string,
1546 authType: Lambda.FunctionUrlAuthType,
1547 ) {
1548 return yield* Lambda.getFunctionUrlConfig({
1549 FunctionName: functionName,
1550 }).pipe(
1551 Effect.filterOrFail(
1552 (config) => config.AuthType === authType,
1553 () => new Error("Function URL auth has not propagated yet"),
1554 ),
1555 Effect.retry({
1556 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1557 }),
1558 );
1559 });
1560
1561 const waitForReservedConcurrency = Effect.fn(function* (
1562 functionName: string,
1563 expected: number | undefined,
1564 ) {
1565 return yield* Lambda.getFunctionConcurrency({
1566 FunctionName: functionName,
1567 }).pipe(
1568 Effect.map((config) => config.ReservedConcurrentExecutions),
1569 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
1570 Effect.filterOrFail(
1571 (actual) => actual === expected,
1572 () => new Error("Reserved concurrency update has not propagated yet"),
1573 ),
1574 Effect.retry({
1575 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1576 }),
1577 );
1578 });
1579
1580 const waitForConfiguration = Effect.fn(function* (
1581 functionName: string,
1582 expected: { memorySize: number; timeout: number },
1583 ) {
1584 return yield* Lambda.getFunctionConfiguration({ FunctionName: functionName }).pipe(
1585 Effect.filterOrFail(
1586 (config) =>
1587 config.MemorySize === expected.memorySize &&
1588 config.Timeout === expected.timeout &&
1589 config.LastUpdateStatus === "Successful",
1590 () => new Error("Lambda configuration update has not propagated yet"),
1591 ),
1592 Effect.retry({
1593 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1594 }),
1595 );
1596 });
1597
1598 const waitForArchitecture = Effect.fn(function* (
1599 functionName: string,
1600 expected: AWS.Lambda.FunctionArchitecture,
1601 ) {
1602 return yield* Lambda.getFunction({ FunctionName: functionName }).pipe(
1603 Effect.map((result) => result.Configuration?.Architectures),
1604 Effect.filterOrFail(
1605 (architectures) => architectures?.[0] === expected,
1606 () => new Error("Lambda architecture update has not propagated yet"),
1607 ),
1608 Effect.retry({
1609 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
1610 }),
1611 );
1612 });