Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 29 additions & 47 deletions .github/scripts/cdn-template-smoke-test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {pageAssetUrls, primeCdnAssets} from './lib/cdn-asset-priming.mjs';
import {renderPage, renderUntilClean} from './lib/cdn-page-render.mjs';
import {resolvePublishedCdnVersion} from './lib/cdn-version.mjs';

const ROOT = path.resolve(
Expand Down Expand Up @@ -147,57 +148,38 @@ const server = http.createServer((req, res) => {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/`;

/** Load the page once and report everything that went wrong. */
async function render() {
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];

const browser = await chromium.launch();
try {
const page = await browser.newPage();
page.on('console', m => {
if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 300));
});
page.on('pageerror', e => pageErrors.push(String(e).slice(0, 300)));
page.on('requestfailed', r =>
failedRequests.push(`${r.url()} :: ${r.failure()?.errorText}`),
);
page.on('response', r => {
if (r.status() >= 400) failedRequests.push(`${r.status()} ${r.url()}`);
});

await page.goto(url, {waitUntil: 'networkidle', timeout: 90_000});
// A page that throws during render still reaches networkidle with an empty
// root, so the render itself has to be asserted, not just the error streams.
const button = await page
.getByRole('button')
.first()
.textContent({timeout: 15_000})
.catch(() => null);

return {consoleErrors, pageErrors, failedRequests, button};
} finally {
await browser.close();
}
}

// ── 5. Render, retrying once so a blip at a CDN is not a red build ───────────
let result;
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
result = await render();
const clean =
result.consoleErrors.length === 0 &&
result.pageErrors.length === 0 &&
result.failedRequests.length === 0 &&
result.button;
if (clean) break;
if (attempt < ATTEMPTS) console.log(` retry ${attempt} of ${ATTEMPTS - 1}`);
}
// Every attempt shares the one 90 s wait this step has always had, so the retry
// adds no time to it: this step can start with under two minutes of the
// smoke-test job's 15-minute limit left, and a page that hangs on both
// attempts still prints the report naming what hung before the job is stopped.
const RENDER_BUDGET_MS = 90_000;
const result = await renderUntilClean(
({budgetMs}) =>
renderPage(url, {launch: async () => chromium.launch(), budgetMs}),
{
attempts: ATTEMPTS,
deadline: Date.now() + RENDER_BUDGET_MS,
onRetry: (attempt, leftMs) =>
console.log(
` retry ${attempt} of ${ATTEMPTS - 1}, ${Math.round(leftMs / 1000)} s left`,
),
},
);
server.close();

// ── 6. Report ────────────────────────────────────────────────────────────────
console.log(`\n${PAGE} @ ${rendered}`);
if (result.timedOut) {
fail(
'the page never went idle, so its navigation timed out',
result.pendingRequests.length === 0
? ' no request was in flight when the wait gave up'
: result.pendingRequests
.map(entry => ` still in flight: ${entry}`)
.join('\n'),
);
}
for (const [label, entries] of [
['console error', result.consoleErrors],
['page error', result.pageErrors],
Expand All @@ -214,7 +196,7 @@ for (const [label, entries] of [
}
if (result.button) {
console.log(` ok rendered a button: "${result.button.trim()}"`);
} else {
} else if (!result.timedOut) {
fail('the page loaded but rendered no button');
}

Expand Down
81 changes: 81 additions & 0 deletions .github/scripts/lib/cdn-page-render.browser.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file cdn-page-render.browser.test.mjs
* @input A local page whose module request is never answered, and Chromium;
* run with ASTRYX_CDN_SMOKE_BROWSER=1 after `npx playwright install chromium`
* @output Real-browser proof that a page with a request that hangs never goes
* idle, and that renderPage reports that navigation timeout with the hung
* request instead of throwing
* @position The browser half of cdn-page-render.test.mjs, which runs the same
* rules against Playwright's events without a browser
*/

import http from 'node:http';
import {chromium} from 'playwright';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import {renderPage, renderUntilClean} from './cdn-page-render.mjs';

const PAGE =
'<!doctype html><button>Start</button>' +
'<script type="module" src="/stall.js"></script>';

describe.runIf(process.env.ASTRYX_CDN_SMOKE_BROWSER === '1')(
'renderPage in Chromium',
() => {
/** The module responses held open, so the page can never go idle. */
const held = [];
let server;
let url;

beforeAll(async () => {
server = http.createServer((req, res) => {
if (req.url === '/stall.js') {
held.push(res);
return;
}
res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});
res.end(PAGE);
});
await new Promise(resolve => {
server.listen(0, '127.0.0.1', resolve);
});
url = `http://127.0.0.1:${server.address().port}/`;
});

afterAll(async () => {
for (const res of held) {
res.destroy();
}
server.closeAllConnections();
await new Promise(resolve => {
server.close(resolve);
});
});

it('reports a page that never goes idle, naming the module that hung', async () => {
const result = await renderPage(url, {
launch: async () => chromium.launch(),
navigationTimeoutMs: 2_000,
});
expect(result.timedOut).toBe(true);
expect(result.pendingRequests).toEqual([`${url}stall.js`]);
});

it('fits both attempts at a page that never goes idle inside one deadline', async () => {
const started = Date.now();
const result = await renderUntilClean(
(attempt = {}) =>
renderPage(url, {
launch: async () => chromium.launch(),
budgetMs: attempt.budgetMs,
}),
{attempts: 2, deadline: Date.now() + 4_000},
);
// Two browser launches beside the 4 s the attempts share.
expect(Date.now() - started).toBeLessThan(8_000);
expect(result.timedOut).toBe(true);
expect(result.pendingRequests).toEqual([`${url}stall.js`]);
}, 20_000);
},
);
166 changes: 166 additions & 0 deletions .github/scripts/lib/cdn-page-render.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* Render the CDN starter page in a browser, and report what went wrong.
*
* One render loads the page until its network goes idle, then reads the first
* button: a page that throws while rendering still goes idle with an empty
* root, so the render itself is asserted, not only the error streams. A page
* with a request that never finishes never goes idle, so its navigation times
* out: that is an unclean render like any other, reported with the requests
* still in flight when the wait gave up, so the output names the asset that
* hung instead of ending the run on a stack trace. renderUntilClean retries
* an unclean render once, so a blip at a CDN is not a red build, and fits
* every attempt inside one deadline, so a page that hangs on each attempt
* still gets its report printed before the job running it is stopped.
*/

/** Playwright's error for a navigation whose wait condition never came. */
function isTimeout(error) {
return error?.name === 'TimeoutError';
}

/**
* Load `url` once in a browser from `launch`, and collect its console errors,
* page errors and failed requests, and the first button's text (null when no
* button rendered). A navigation that times out comes back with `timedOut`
* and the URLs still in flight (`pendingRequests`, in request order); any
* other navigation error throws. With `budgetMs`, the whole attempt fits in
* it: the navigation waits no longer than the budget, and the button no
* longer than what is left of it.
*
* @param {string} url
* @param {{
* launch: () => Promise<import('playwright').Browser>,
* navigationTimeoutMs?: number,
* buttonTimeoutMs?: number,
* budgetMs?: number,
* now?: () => number,
* }} options
*/
export async function renderPage(
url,
{
launch,
navigationTimeoutMs = 90_000,
buttonTimeoutMs = 15_000,
budgetMs,
now = Date.now,
},
) {
const startedAt = now();
/**
* `limitMs`, cut to what is left of the budget. Never 0: Playwright reads a
* timeout of 0 as no timeout at all.
*/
const withinBudget = limitMs =>
budgetMs == null
? limitMs
: Math.max(1, Math.min(limitMs, budgetMs - (now() - startedAt)));
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
/** Requests the page made that have neither finished nor failed. */
const inFlight = new Set();

const browser = await launch();
try {
const page = await browser.newPage();
page.on('console', m => {
if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 300));
});
page.on('pageerror', e => pageErrors.push(String(e).slice(0, 300)));
page.on('request', r => inFlight.add(r));
page.on('requestfinished', r => inFlight.delete(r));
page.on('requestfailed', r => {
inFlight.delete(r);
failedRequests.push(`${r.url()} :: ${r.failure()?.errorText}`);
});
page.on('response', r => {
if (r.status() >= 400) failedRequests.push(`${r.status()} ${r.url()}`);
});

try {
await page.goto(url, {
waitUntil: 'networkidle',
timeout: withinBudget(navigationTimeoutMs),
});
} catch (error) {
if (!isTimeout(error)) {
throw error;
}
return {
consoleErrors,
pageErrors,
failedRequests,
timedOut: true,
pendingRequests: [...inFlight].map(r => r.url()),
button: null,
};
}
const button = await page
.getByRole('button')
.first()
.textContent({timeout: withinBudget(buttonTimeoutMs)})
.catch(() => null);

return {
consoleErrors,
pageErrors,
failedRequests,
timedOut: false,
pendingRequests: [],
button,
};
} finally {
await browser.close();
}
}

/** Whether a render went idle with nothing wrong and a button on the page. */
export function isCleanRender(result) {
return (
!result.timedOut &&
result.consoleErrors.length === 0 &&
result.pageErrors.length === 0 &&
result.failedRequests.length === 0 &&
Boolean(result.button)
);
}

/**
* Run `render` until one comes back clean, at most `attempts` times, and
* return the last result. With a `deadline` (in `now()`'s clock), each attempt
* is handed `budgetMs`, an equal share of the time left (so the retry gets
* whatever the first attempt left unused), and no attempt starts once the
* deadline has passed. `onRetry(attempt, leftMs)` hears each retry.
*
* @template {{timedOut: boolean, consoleErrors: string[], pageErrors: string[], failedRequests: string[], button: string | null}} R
* @param {(attempt: {budgetMs?: number}) => Promise<R>} render
* @param {{
* attempts?: number,
* deadline?: number,
* now?: () => number,
* onRetry?: (attempt: number, leftMs?: number) => void,
* }} [options]
* @returns {Promise<R>}
*/
export async function renderUntilClean(
render,
{attempts = 2, deadline, now = Date.now, onRetry} = {},
) {
const leftMs = () => (deadline == null ? undefined : deadline - now());
let result;
for (let attempt = 1; attempt <= attempts; attempt++) {
const left = leftMs();
result = await render({
budgetMs:
left == null ? undefined : Math.floor(left / (attempts - attempt + 1)),
});
if (isCleanRender(result) || attempt === attempts) break;
const remaining = leftMs();
if (remaining != null && remaining <= 0) break;
onRetry?.(attempt, remaining);
}
return result;
}
Loading
Loading