Skip to content
62 changes: 49 additions & 13 deletions scripts/screenshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,28 @@ import {
loadScreenshotScenario,
type ScreenshotScenario,
} from "./screenshots/scenario.ts";
import { waitForHealthy } from "./screenshots/server.ts";
import { findAvailablePort } from "./stripe-mock.ts";
import {
startWithFailureCleanup,
waitForHealthy,
} from "./screenshots/server.ts";
import {
findAvailablePort,
startStripeMock,
stripeMockEnv,
} from "./stripe-mock.ts";

const ROOT = dirname(dirname(fromFileUrl(import.meta.url)));
const DB_KEY = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=";
const USERNAME = "screenshots";
const PASSWORD = "screenshots-password";
const STRIPE_KEY = "sk_test_mock";
const TIMEOUT_MS = 60_000;
const RETRY_MS = 200;
const MOBILE_VIEWPORT = { height: 844, width: 390 };

interface AppServer {
baseUrl: string;
enableStripe: () => Promise<void>;
stop: () => Promise<void>;
}

Expand Down Expand Up @@ -111,18 +120,20 @@ const SCENES: Record<ScreenshotName, Scene> = {
users: { path: at("/admin/users") },
};

const startServer = async (): Promise<AppServer> => {
const build = await runDeno(["task", "build:static"], ROOT);
if (!build.success) throw new Error("Could not build static assets.");
const startAppServer = async (
stripeMock: Awaited<ReturnType<typeof startStripeMock>>,
): Promise<AppServer> => {
const tempDir = await Deno.makeTempDir({ prefix: "tickets-screenshots-" });
const port = findAvailablePort();
const baseUrl = `http://127.0.0.1:${port}`;
const dbUrl = `file:${join(tempDir, "screenshots.db")}`;
const child = denoCommand(["run", "-A", "src/index.ts"], {
cwd: ROOT,
env: {
...Deno.env.toObject(),
...stripeMockEnv(stripeMock.port),
DB_ENCRYPTION_KEY: DB_KEY,
DB_URL: `file:${join(tempDir, "screenshots.db")}`,
DB_URL: dbUrl,
PORT: String(port),
},
stderr: "inherit",
Expand All @@ -138,12 +149,23 @@ const startServer = async (): Promise<AppServer> => {
if (healthy) {
return {
baseUrl,
enableStripe: async () => {
Deno.env.set("DB_ENCRYPTION_KEY", DB_KEY);
Deno.env.set("DB_URL", dbUrl);
const { settings } = await import("#shared/db/settings.ts");
await settings.update.stripe.activate({
secretKey: STRIPE_KEY,
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
webhookEndpointId: "we_screenshots",
webhookSecret: "whsec_screenshots",
});
},
stop: async () => {
try {
child.kill("SIGTERM");
await child.status;
} finally {
await removeTree(tempDir);
await stripeMock.stop();
}
},
};
Expand All @@ -154,6 +176,16 @@ const startServer = async (): Promise<AppServer> => {
throw new Error("The screenshot app did not start within 60 seconds.");
};

const startServer = async (): Promise<AppServer> => {
const build = await runDeno(["task", "build:static"], ROOT);
if (!build.success) throw new Error("Could not build static assets.");
const stripeMock = await startStripeMock();
return await startWithFailureCleanup(
() => startAppServer(stripeMock),
stripeMock.stop,
);
};

const submit = async (page: Page, formSelector: string): Promise<void> => {
const form = page.locator(formSelector);
await Promise.all([
Expand Down Expand Up @@ -184,13 +216,15 @@ const setupAdmin = async (
await page.goto(`${baseUrl}/admin/settings`);
await page.locator('[name="business_email"]').fill("hello@example.com");
await submit(page, 'form[action="/admin/settings/business-email"]');
await page.goto(`${baseUrl}/admin/settings`);
await page.locator('[name="payment_provider"][value="none"]').check();
await submit(page, 'form[action="/admin/settings/payment-provider"]');
};

const setupApp = async (page: Page, baseUrl: string): Promise<SceneContext> => {
const setupApp = async (
page: Page,
server: AppServer,
): Promise<SceneContext> => {
const { baseUrl } = server;
await setupAdmin(page, baseUrl);
await server.enableStripe();
await page.goto(`${baseUrl}/admin/seeds`);
await page.locator('[name="listing_count"]').fill("5");
await page.locator('[name="attendees_per_listing"]').fill("8");
Expand Down Expand Up @@ -346,10 +380,12 @@ const capturePreparedPage = async (
const captureScenario = async (
scenario: ScreenshotScenario,
page: Page,
baseUrl: string,
server: AppServer,
outputDir: string,
): Promise<void> => {
const { baseUrl } = server;
await setupAdmin(page, baseUrl, scenario.setupUsername);
await server.enableStripe();
await applyTheme(
page,
baseUrl,
Expand Down Expand Up @@ -421,10 +457,10 @@ const main = async (): Promise<void> => {
const page = await context.newPage();
page.setDefaultTimeout(TIMEOUT_MS);
if (scenario) {
await captureScenario(scenario, page, server.baseUrl, outputDir);
await captureScenario(scenario, page, server, outputDir);
return;
}
const sceneContext = await setupApp(page, server.baseUrl);
const sceneContext = await setupApp(page, server);
for (const theme of options.themes) {
const themeDir = join(outputDir, theme);
await Deno.mkdir(themeDir, { recursive: true });
Expand Down
13 changes: 13 additions & 0 deletions scripts/screenshots/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
import { type CleanupTask, failAfterCleanups } from "../cleanup.ts";

export const startWithFailureCleanup = async <T>(
start: () => Promise<T>,
cleanup: CleanupTask,
): Promise<T> => {
try {
return await start();
} catch (error) {
return await failAfterCleanups(error, [cleanup]);
}
};

export const waitForHealthy = async (
request: () => Promise<Response>,
wait: () => Promise<void>,
Expand Down
3 changes: 2 additions & 1 deletion src/ui/static/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -1193,7 +1193,8 @@ label > input[type="number"] {
}

label > select[name="quantity"],
label > select[name^="quantity_"] {
label > select[name^="quantity_"],
label > select[name^="child_qty_"] {
width: 8ch;
flex: 0 0 auto;
}
Expand Down
34 changes: 33 additions & 1 deletion test/scripts/screenshots-server.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { expect } from "@std/expect";
import { describe, it } from "@std/testing/bdd";
import { waitForHealthy } from "../../scripts/screenshots/server.ts";
import {
startWithFailureCleanup,
waitForHealthy,
} from "../../scripts/screenshots/server.ts";

const expectOneRetry = async (
request: () => Promise<Response>,
Expand All @@ -19,6 +22,35 @@ const expectOneRetry = async (
};

describe("screenshot server", () => {
it("stops an acquired resource when startup fails", async () => {
const startupError = new Error("startup failed");
let stops = 0;

await expect(
startWithFailureCleanup(
() => Promise.reject(startupError),
() => {
stops += 1;
},
),
).rejects.toBe(startupError);
expect(stops).toBe(1);
});

it("leaves an acquired resource running after successful startup", async () => {
let stops = 0;

expect(
await startWithFailureCleanup(
() => Promise.resolve("running"),
() => {
stops += 1;
},
),
).toBe("running");
expect(stops).toBe(0);
});

it("waits before retrying a non-OK response", async () => {
const responses = [
new Response("Starting", { status: 503 }),
Expand Down