1import * as Alchemy from "alchemy";
2import * as GCP from "alchemy/GCP";
3import * as Test from "alchemy/Test/Bun";
4import { describe, expect } from "bun:test";
5import * as Console from "effect/Console";
6import * as Data from "effect/Data";
7import * as Effect from "effect/Effect";
8import * as Schedule from "effect/Schedule";
9import { spawnSync } from "node:child_process";
10import Stack from "../alchemy.run.ts";
11
12// A fresh Cloud Run revision can answer transient 404/5xx responses while
13// its URL starts serving. `Test.getWhenReady` retries through that
14// cold-start window until the site serves a real response.
15const { getWhenReady } = Test;
16
17class AssetNotReady extends Data.TaggedError("AssetNotReady")<{
18 body: string;
19}> {}
20
21// Retry until the body matches — the status alone can't distinguish a
22// cold start from a served page.
23const getBodyWhenReady = (url: string, expected: string) =>
24 Effect.gen(function* () {
25 const res = yield* getWhenReady(url);
26 expect(res.status).toBe(200);
27 const body = yield* res.text;
28 if (!body.includes(expected)) {
29 return yield* Effect.fail(new AssetNotReady({ body }));
30 }
31 return body;
32 }).pipe(
33 Effect.retry({
34 while: (error) => error instanceof AssetNotReady,
35 schedule: Schedule.max([
36 Schedule.min([
37 Schedule.exponential("500 millis"),
38 Schedule.spaced("3 seconds"),
39 ]),
40 Schedule.recurs(20),
41 ]),
42 }),
43 );
44
45const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
46 providers: GCP.providers(),
47 state: Alchemy.localState(),
48});
49
50// The image is built locally, so the whole suite needs Docker.
51const dockerAvailable =
52 spawnSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 }).status ===
53 0;
54
55describe.skipIf(!dockerAvailable)("gcp-website-astro", () => {
56 // The first deploy runs the Astro build, builds and pushes the image, and
57 // rolls out Cloud Run, so give the hook far more headroom than the default.
58 const stack = beforeAll(deploy(Stack).pipe(Effect.tap(Console.log)), {
59 timeout: 1_200_000,
60 });
61 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), {
62 timeout: 1_200_000,
63 });
64
65 const base = Effect.map(stack, ({ url }) => {
66 if (!url) throw new Error("expected the site to expose a Cloud Run url");
67 return String(url).replace(/\/+$/, "");
68 });
69
70 test(
71 "deploys and exposes a url",
72 Effect.gen(function* () {
73 const { url } = yield* stack;
74 expect(url).toBeString();
75 }),
76 { timeout: 180_000 },
77 );
78
79 test(
80 "serves the server-rendered home page",
81 Effect.gen(function* () {
82 const url = yield* base;
83 const res = yield* getWhenReady(url);
84 expect(res.status).toBe(200);
85 const html = yield* res.text;
86 // The `GREETING` env value from alchemy.run.ts, read via
87 // `process.env` in the page frontmatter — proves the container
88 // rendered it at request time.
89 expect(html).toContain("Hello from Astro on Cloud Run!");
90 expect(html).toContain("server-rendered on Cloud Run");
91 }),
92 { timeout: 180_000 },
93 );
94
95 test(
96 "serves the prerendered about page",
97 Effect.gen(function* () {
98 const url = yield* base;
99 const res = yield* getWhenReady(`${url}/about/`);
100 expect(res.status).toBe(200);
101 }),
102 { timeout: 180_000 },
103 );
104
105 test(
106 "compiles tailwind from astro.config.ts",
107 Effect.gen(function* () {
108 const url = yield* base;
109 // The utility class in the markup proves the page shipped with Tailwind
110 // classes; wait until the deployed HTML includes it.
111 const html = yield* getBodyWhenReady(url, "text-3xl");
112
113 // Astro either links an external compiled stylesheet or inlines small
114 // ones as a <style> block — accept both, but the compiled rule for the
115 // utility must be served either way. That rule only exists if the
116 // @tailwindcss/vite plugin from the project's own astro.config.ts ran.
117 const link = html.match(
118 /<link[^>]*rel="stylesheet"[^>]*href="([^"]+)"[^>]*>/,
119 );
120 if (link) {
121 const href = link[1]!;
122 const cssUrl = href.startsWith("http")
123 ? href
124 : `${url}${href.startsWith("/") ? "" : "/"}${href}`;
125 const css = yield* getBodyWhenReady(cssUrl, ".text-3xl");
126 expect(css).toContain(".text-3xl");
127 } else {
128 const style = html.match(/<style[^>]*>([\s\S]*?)<\/style>/);
129 expect(style).not.toBeNull();
130 expect(style![1]).toContain(".text-3xl");
131 }
132 }),
133 { timeout: 180_000 },
134 );
135
136 test(
137 "serves a static asset from public/",
138 Effect.gen(function* () {
139 const url = yield* base;
140 const body = yield* getBodyWhenReady(
141 `${url}/robots.txt`,
142 "User-agent: *",
143 );
144 expect(body).toContain("User-agent: *");
145 }),
146 { timeout: 180_000 },
147 );
148});