Open History to see the last commit
1/**
2 * True `alchemy dev` end-to-end for the Job app — the regression test for
3 * the dev-mode apply failure where the SNS→Lambda glue resources
4 * (AWS.SNS.Subscription and the AWS.Lambda.Permission behind
5 * `consumeTopicNotifications`) were created against REAL AWS with floci
6 * ARNs and died with `InvalidParameterException: Invalid parameter:
7 * TopicArn` / `ResourceNotFoundException: Function not found`.
8 *
9 * This stack is also the mixed-mode case: the DynamoDB table, SQS queue,
10 * SNS topic, Lambda function, event source mapping, subscription, and
11 * permission are all local (floci), while the mode-agnostic CloudWatch
12 * Dashboard + Alarm deploy live — so the run needs AWS credentials, and a
13 * green apply proves local glue and live mode-agnostic resources coexist.
14 *
15 * Mirrored from examples/aws-dev/test/dev.test.ts (which owns the broader
16 * per-binding + hot-reload coverage); this suite drives the real app:
17 * POST a job over the emulator-served Function URL, read it back, and let
18 * the notification publish ride the local Subscription.
19 */
20import { afterAll, expect, test } from "bun:test";
21import { spawn, spawnSync } from "node:child_process";
22import * as path from "node:path";
23
24const root = path.resolve(import.meta.dirname, "..");
25// Spawn the CLI entry directly (not through `bun run` / the cli.js
26// launcher) so signals hit the actual CLI process, whose scope teardown
27// kills the exec child and the provider sidecars.
28const alchemyBin = path.join(
29 root,
30 "node_modules",
31 "alchemy",
32 "bin",
33 "alchemy.ts",
34);
35// Isolated stage so this suite never fights integ.test.ts (same stack
36// name) over state rows.
37const STAGE = "dev-cli-test";
38
39// The whole suite needs docker (floci runs as a container).
40const dockerAvailable =
41 spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0;
42
43let proc: ReturnType<typeof spawn> | undefined;
44let output = "";
45
46const pump = (stream: NodeJS.ReadableStream) => {
47 stream.on("data", (chunk: Buffer) => {
48 const text = chunk.toString();
49 output += text;
50 if (process.env.DEBUG) process.stderr.write(text);
51 });
52};
53
54/** Bounded poll for a (possibly async) producer to yield a value. */
55const pollUntil = async <T>(
56 what: string,
57 f: () => T | undefined | Promise<T | undefined>,
58 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
59): Promise<T> => {
60 for (let i = 0; i < tries; i++) {
61 const value = await f();
62 if (value !== undefined) return value;
63 await Bun.sleep(delayMs);
64 }
65 throw new Error(
66 `Timed out waiting for ${what}.\n--- alchemy dev output (tail) ---\n${output.slice(-4000)}`,
67 );
68};
69
70/** Fetch with retries — the emulator's URL proxy takes a moment to serve. */
71const fetchOk = async (
72 url: string | URL,
73 init?: RequestInit,
74 { tries = 20, delayMs = 500 }: { tries?: number; delayMs?: number } = {},
75) => {
76 let last: Response | undefined;
77 for (let i = 0; i < tries; i++) {
78 try {
79 last = await fetch(url, init);
80 if (last.ok) return last;
81 } catch {
82 // proxy not listening yet
83 }
84 await Bun.sleep(delayMs);
85 }
86 throw new Error(
87 `${init?.method ?? "GET"} ${url} never returned 2xx (last status: ${last?.status})`,
88 );
89};
90
91/** Extract a stack-output URL the CLI prints on stdout. */
92const outputUrl = (key: string) =>
93 output.match(new RegExp(`\\b${key}:\\s*['"]?(http[^\\s'",]+)`))?.[1];
94
95afterAll(async () => {
96 if (proc?.pid) {
97 // Ctrl-C semantics: signal the whole PROCESS GROUP (the CLI, its
98 // `--watch` exec child, and the provider sidecars).
99 const killGroup = (signal: NodeJS.Signals) => {
100 try {
101 process.kill(-proc!.pid!, signal);
102 } catch {
103 // group already gone
104 }
105 };
106 const exited = new Promise((resolve) => proc!.once("exit", resolve));
107 killGroup("SIGINT");
108 await Promise.race([exited, Bun.sleep(15_000)]);
109 if (proc.exitCode === null && proc.signalCode === null) {
110 killGroup("SIGKILL");
111 await Promise.race([exited, Bun.sleep(5_000)]);
112 }
113 }
114 if (!process.env.NO_DESTROY && dockerAvailable) {
115 const destroyed = spawnSync(
116 "bun",
117 [alchemyBin, "destroy", "--stage", STAGE, "--yes"],
118 {
119 cwd: root,
120 stdio: "inherit",
121 timeout: 120_000,
122 },
123 );
124 if (destroyed.status !== 0) {
125 throw new Error(
126 `alchemy destroy exited ${destroyed.status} — local teardown must succeed`,
127 );
128 }
129 }
130}, 180_000);
131
132test.skipIf(!dockerAvailable)(
133 "alchemy dev applies the mixed local/live Job stack and serves jobs",
134 async () => {
135 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
136 cwd: root,
137 // Own process group, so teardown can deliver Ctrl-C to the whole
138 // tree the way a terminal would.
139 detached: true,
140 stdio: ["ignore", "pipe", "pipe"],
141 });
142 pump(proc.stdout!);
143 pump(proc.stderr!);
144
145 // The first dev deploy may pull the floci image and provision the
146 // local data plane before printing stack outputs.
147 const url = await pollUntil(
148 "url in stack outputs",
149 () => outputUrl("url"),
150 { tries: 300, delayMs: 1000 },
151 );
152
153 // Dev identity: the function URL is served locally, not by AWS
154 // (e.g. http://<id>.lambda-url.us-east-1.localhost:<port>/). The port
155 // is whatever the emulator bound — never hard-code it, only the URL
156 // captured from the CLI's stdout is authoritative.
157 expect(new URL(url).hostname).toEndWith("localhost");
158 expect(url).not.toContain("amazonaws.com");
159
160 // The bug failed the APPLY itself: Subscription/Permission creation
161 // against real AWS with floci ARNs. Outputs printing means apply
162 // succeeded, but pin the failure banner too so a partial apply that
163 // still prints outputs can never sneak past.
164 expect(output).not.toContain("apply failed");
165
166 const api = new URL(url);
167 api.search = "";
168
169 // POST a job: stores it in the local table AND publishes the
170 // job.created notification over the local topic — which only works
171 // when the Subscription + invoke Permission were created on floci.
172 const content = `hello from alchemy dev ${crypto.randomUUID()}`;
173 const created = (await (
174 await fetchOk(api, {
175 method: "POST",
176 headers: { "content-type": "text/plain" },
177 body: content,
178 })
179 ).json()) as { jobId: string };
180 expect(created.jobId).toBeString();
181
182 // Read it back through the local DynamoDB storage.
183 const job = (await (
184 await fetchOk(new URL(`/?jobId=${created.jobId}`, api))
185 ).json()) as { id: string; content: string };
186 expect(job.id).toBe(created.jobId);
187 expect(job.content).toBe(content);
188 },
189 { timeout: 600_000 },
190);