Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

test-examples.ts

430 lines13.9 KB

1import { preferLocalFlociImage } from "./floci-image.ts";
2​
3// `bun test:examples --profile testing` — the example suites read the
4// profile from `ALCHEMY_PROFILE` (`Test.make({ profile: process.env.ALCHEMY_PROFILE })`),
5// so translate the flag into the env every spawned `bun test` inherits.
6// Without this the flag was silently ignored and every suite ran against
7// the `default` profile, which only works when the shell already exports
8// `ALCHEMY_PROFILE`.
9{
10 const argv = process.argv.slice(2);
11 const index = argv.findIndex(
12 (arg) => arg === "--profile" || arg.startsWith("--profile="),
13 );
14 if (index !== -1) {
15 const arg = argv[index]!;
16 const profile = arg.includes("=")
17 ? arg.slice("--profile=".length)
18 : argv[index + 1];
19 if (profile === undefined || profile.startsWith("-")) {
20 console.error("--profile requires a value, e.g. --profile testing");
21 process.exit(2);
22 }
23 process.env.ALCHEMY_PROFILE = profile;
24 }
26​
27// The AWS examples run against the floci emulator: use the locally built
28// image when there is one so an emulator fix is testable before its
29// release image lands on GHCR.
30preferLocalFlociImage("test:examples");
31​
32const examples = [
33 "./examples/cloudflare-dev",
34 "./examples/cloudflare-worker",
35 "./examples/cloudflare-worker-async",
36 "./examples/cloudflare-website-tanstack-start",
37 "./examples/cloudflare-tanstack-start-solid",
38 "./examples/cloudflare-neon-drizzle",
39 "./examples/cloudflare-vue",
40 "./examples/cloudflare-website-solidstart",
41 "./examples/cloudflare-foldkit",
42 "./examples/cloudflare-foldkit-ssr",
43 "./examples/cloudflare-octane",
44 "./examples/cloudflare-website-astro",
45 "./examples/cloudflare-website-foldkit",
46 "./examples/cloudflare-website-nextjs",
47 "./examples/cloudflare-website-nuxt",
48 "./examples/cloudflare-website-react-router",
49 "./examples/cloudflare-website-sveltekit",
50 "./examples/cloudflare-website-vite",
51 "./examples/cloudflare-website-waku",
52 "./examples/cloudflare-website-vocs",
53 "./examples/aws-dev",
54 // "./examples/aws-ecs",
55 "./examples/aws-lambda",
56 // Cloudfront is too slow
57 // "./examples/aws-website-astro",
58 // "./examples/aws-website-foldkit",
59 // "./examples/aws-website-nextjs",
60 // "./examples/aws-website-nuxt",
61 // "./examples/aws-website-react-router",
62 // "./examples/aws-website-solidstart",
63 // "./examples/aws-website-sveltekit",
64 // "./examples/aws-website-tanstack-start",
65 // "./examples/aws-website-vite",
66 // "./examples/aws-website-waku",
67 "./examples/fly-app",
68 "./examples/fly-service",
69 "./examples/fly-website-vite",
70 "./examples/hetzner-website-vite",
71 // Railway examples are gated out of test:examples for now: repeated
72 // Railway platform outages (deployment queue backlogs, e.g. the
73 // 2026-08-28 "Deployments slow to start" incident) and general
74 // flakiness working with Railway's API make these suites too
75 // unreliable for CI. Run them from the example directory with
76 // `bun test` when Railway is healthy.
77 // "./examples/railway-project",
78 // "./examples/railway-service",
79 // "./examples/railway-website-vite",
80 // Card-app Website composites (same apps as the AWS/Cloudflare
81 // *-website-* examples). Commented so CI does not provision extra
82 // sites; run them from the example directory with `bun test`.
83 // "./examples/fly-website-astro",
84 // "./examples/fly-website-foldkit",
85 // "./examples/fly-website-nextjs",
86 // "./examples/fly-website-nuxt",
87 // "./examples/fly-website-react-router",
88 // "./examples/fly-website-solidstart",
89 // "./examples/fly-website-sveltekit",
90 // "./examples/fly-website-tanstack-start",
91 // "./examples/fly-website-waku",
92 // "./examples/fly-website-vocs",
93 // "./examples/hetzner-website-astro",
94 // "./examples/hetzner-website-foldkit",
95 // "./examples/hetzner-website-nextjs",
96 // "./examples/hetzner-website-nuxt",
97 // "./examples/hetzner-website-react-router",
98 // "./examples/hetzner-website-solidstart",
99 // "./examples/hetzner-website-sveltekit",
100 // "./examples/hetzner-website-tanstack-start",
101 // "./examples/hetzner-website-waku",
102 // "./examples/hetzner-website-vocs",
103 // "./examples/railway-website-astro",
104 // "./examples/railway-website-foldkit",
105 // "./examples/railway-website-nextjs",
106 // "./examples/railway-website-nuxt",
107 // "./examples/railway-website-react-router",
108 // "./examples/railway-website-solidstart",
109 // "./examples/railway-website-sveltekit",
110 // "./examples/railway-website-tanstack-start",
111 // "./examples/railway-website-waku",
112 // "./examples/railway-website-vocs",
113 "./examples/fly-sprite",
114 "./examples/fly-redis",
115 "./examples/fly-bucket",
116 "./examples/fly-postgres",
117] as const;
118​
119// The AWS examples share one floci emulator container (`alchemy-floci`):
120// two `alchemy dev` sessions ensuring it at the same time race to recreate
121// it on an image bump and hot-swap each other's Lambda code, so they run
122// one at a time. Everything else stays concurrent.
123const serialGroup = (example: string): string | undefined =>
124 example.startsWith("./examples/aws-") ? "floci" : undefined;
125​
126type CommandResult = {
127 label: string;
128 command: readonly string[];
129 exitCode: number | null;
130 stdout: string;
131 stderr: string;
132};
133​
134type Task = {
135 label: string;
136 command: readonly string[];
137 cwd?: string;
138 /** Tasks sharing a key run one at a time, in list order. */
139 serial?: string;
140};
141​
142type TaskState = Task & {
143 status: "pending" | "running" | "ok" | "failed";
144 startedAt?: number;
145 endedAt?: number;
146 exitCode?: number | null;
147};
148​
149const readStream = async (
150 stream: ReadableStream<Uint8Array>,
151): Promise<string> => new Response(stream).text();
152​
153const elapsedSeconds = (state: TaskState): string => {
154 if (state.startedAt === undefined) {
155 return "0s";
156 }
157 const endedAt = state.endedAt ?? performance.now();
158 return `${Math.round((endedAt - state.startedAt) / 1000)}s`;
159};
160​
161const makeStatusRenderer = (title: string, states: readonly TaskState[]) => {
162 const interactive = process.stdout.isTTY === true;
163 let renderedRows = 0;
164​
165 const taskLine = (state: TaskState) => {
166 const icon =
167 state.status === "ok"
168 ? "ok"
169 : state.status === "failed"
170 ? "failed"
171 : state.status;
172 const exit =
173 state.exitCode === undefined || state.exitCode === 0
174 ? ""
175 : ` exit ${state.exitCode ?? "signal"}`;
176 return ` ${icon.padEnd(7)} ${state.label} ${elapsedSeconds(state)}${exit}`;
177 };
178​
179 // Physical rows a line occupies once the terminal wraps it.
180 const rowsFor = (line: string) => {
181 const columns = process.stdout.columns || 80;
182 return Math.max(1, Math.ceil(line.length / columns));
183 };
184 const rowsForAll = (output: readonly string[]) =>
185 output.reduce((total, line) => total + rowsFor(line), 0);
186​
187 const fullLines = () => [title, ...states.map(taskLine)];
188​
189 // The in-place repaint moves the cursor up with `\x1b[NF`, which cannot
190 // climb above the top of the viewport: if a paint is taller than the
191 // terminal (or lines wrap), the write scrolls and every repaint leaks its
192 // topmost rows into scrollback. Keep each paint strictly shorter than the
193 // viewport by collapsing finished tasks into the header once space runs
194 // out (`+ 1` accounts for the cursor parking on the row below the paint).
195 const lines = () => {
196 const rows = process.stdout.rows || 24;
197 const full = fullLines();
198 if (rowsForAll(full) + 1 <= rows) {
199 return full;
200 }
201 const done = states.filter((state) => state.status === "ok").length;
202 const active = states.filter((state) => state.status !== "ok");
203 const header = `${title} (${done}/${states.length} ok)`;
204 const activeLines = active.map(taskLine);
205 let shown = activeLines.length;
206 const fits = (count: number) => {
207 const overflow = count < activeLines.length ? 1 : 0;
208 return (
209 rowsForAll([header, ...activeLines.slice(0, count)]) + overflow + 1 <=
210 rows
211 );
212 };
213 while (shown > 0 && !fits(shown)) {
214 shown--;
215 }
216 return shown === activeLines.length
217 ? [header, ...activeLines]
218 : [
219 header,
220 ...activeLines.slice(0, shown),
221 ` … ${activeLines.length - shown} more`,
222 ];
223 };
224​
225 return {
226 failure(result: CommandResult) {
227 if (interactive && renderedRows > 0) {
228 process.stdout.write(`\x1b[${renderedRows}F\x1b[J`);
229 renderedRows = 0;
230 }
231 const output = [
232 `\nFailed: ${result.label} (exit ${result.exitCode ?? "signal"}): ${result.command.join(" ")}`,
233 `--- ${result.label} stdout ---`,
234 result.stdout.trimEnd() || "(empty)",
235 `--- ${result.label} stderr ---`,
236 result.stderr.trimEnd() || "(empty)",
237 "",
238 ].join("\n");
239 // Use the TUI's stream so its next repaint starts below the logs.
240 (interactive ? process.stdout : process.stderr).write(output);
241 this.render();
242 },
243 render() {
244 if (!interactive) {
245 return;
246 }
247 if (renderedRows > 0) {
248 process.stdout.write(`\x1b[${renderedRows}F\x1b[J`);
249 }
250 const output = lines();
251 process.stdout.write(`${output.join("\n")}\n`);
252 renderedRows = rowsForAll(output);
253 },
254 finish() {
255 if (interactive && renderedRows > 0) {
256 process.stdout.write(`\x1b[${renderedRows}F\x1b[J`);
257 renderedRows = 0;
258 }
259 // Always end with the full table (the live view may be compacted).
260 for (const line of fullLines()) {
261 console.log(line);
262 }
263 },
264 };
265};
266​
267const run = async (
268 state: TaskState,
269 render: () => void,
270): Promise<CommandResult> => {
271 state.status = "running";
272 state.startedAt = performance.now();
273 render();
274​
275 const child = Bun.spawn([...state.command], {
276 cwd: state.cwd,
277 // Snapshot env at spawn time — `Bun.spawn` does not pick up later
278 // `process.env` mutations, and we want `ALCHEMY_PROFILE` (and friends)
279 // from the parent invocation.
280 env: { ...process.env },
281 stdout: "pipe",
282 stderr: "pipe",
283 stdin: "inherit",
284 });
285 const [exitCode, stdout, stderr] = await Promise.all([
286 child.exited,
287 readStream(child.stdout),
288 readStream(child.stderr),
289 ]);
290​
291 state.status = exitCode === 0 ? "ok" : "failed";
292 state.exitCode = exitCode;
293 state.endedAt = performance.now();
294 render();
295​
296 return {
297 label: state.label,
298 command: state.command,
299 exitCode,
300 stdout,
301 stderr,
302 };
303};
304​
305const runParallel = async (
306 title: string,
307 tasks: readonly Task[],
308 options?: { readonly concurrency?: number },
309): Promise<readonly CommandResult[]> => {
310 const states = tasks.map((task): TaskState => ({
311 ...task,
312 status: "pending",
313 }));
314 const renderer = makeStatusRenderer(title, states);
315 renderer.render();
316 const interval = setInterval(() => renderer.render(), 1000);
317 const chains = new Map<string, Promise<unknown>>();
318​
319 // At most `concurrency` tasks run at once; the rest wait for a slot.
320 const limit = options?.concurrency ?? Infinity;
321 let active = 0;
322 const waiting: Array<() => void> = [];
323 const acquire = () =>
324 new Promise<void>((resolve) => {
325 if (active < limit) {
326 active++;
327 resolve();
328 } else {
329 waiting.push(() => {
330 active++;
331 resolve();
332 });
333 }
334 });
335 const release = () => {
336 active--;
337 waiting.shift()?.();
338 };
339​
340 try {
341 return await Promise.all(
342 states.map((state) => {
343 const start = async () => {
344 await acquire();
345 try {
346 const result = await run(state, () => renderer.render());
347 if (result.exitCode !== 0) renderer.failure(result);
348 return result;
349 } finally {
350 release();
351 }
352 };
353 if (state.serial === undefined) return start();
354 const next = (chains.get(state.serial) ?? Promise.resolve()).then(
355 start,
356 start,
357 );
358 chains.set(state.serial, next);
359 return next;
360 }),
361 );
362 } finally {
363 clearInterval(interval);
364 renderer.finish();
365 }
366};
367​
368const testResults = await runParallel(
369 "Example tests",
370 examples.map((example) => ({
371 label: example,
372 // Run `bun test` IN the example directory. Concurrent
373 // `bun run --filter <workspace> test` all contend on bun's workspace
374 // graph (each sits in `openat` walking the monorepo) and none of them
375 // ever spawn the actual test process.
376 command: ["bun", "test"] as const,
377 cwd: example,
378 serial: serialGroup(example),
379 })),
380);
381const failedTests = testResults.filter((result) => result.exitCode !== 0);
382​
383if (failedTests.length > 0) {
384 console.error("\nFailed example tests:");
385 for (const failure of failedTests) {
386 const exit = failure.exitCode === null ? "signal" : failure.exitCode;
387 console.error(
388 `- ${failure.label} (exit ${exit}): ${failure.command.join(" ")}`,
389 );
390 }
391​
392 process.exit(1);
394​
395const cliResults = await runParallel(
396 "Example CLI lifecycle",
397 examples.map((example) => ({
398 label: `${example} CLI lifecycle`,
399 command: ["bun", "scripts/test-example-cli.ts", example],
400 serial: serialGroup(example),
401 })),
402 // Each `alchemy dev` session is a CLI, an exec child, sidecars, workerd
403 // and a bundler watch loop; 30 at once starve each other past the
404 // 4-minute readiness timeout.
405 { concurrency: 8 },
406);
407const failedCliTests = cliResults.filter((result) => result.exitCode !== 0);
408​
409if (failedCliTests.length > 0) {
410 console.error("\nFailed example CLI lifecycle tests:");
411 for (const failure of failedCliTests) {
412 const exit = failure.exitCode === null ? "signal" : failure.exitCode;
413 console.error(`- ${failure.label} (exit ${exit})`);
414 }
415 process.exit(1);
417​
418const [formatFailure] = await runParallel("Format", [
419 { label: "format", command: ["bun", "run", "format"] },
420]);
421if (formatFailure.exitCode !== 0) {
422 console.error("\nFormat failed:");
423 if (formatFailure.stdout.length > 0) {
424 console.error(formatFailure.stdout.trimEnd());
425 }
426 if (formatFailure.stderr.length > 0) {
427 console.error(formatFailure.stderr.trimEnd());
428 }
429 process.exit(formatFailure.exitCode ?? 1);