Skip to content

Commit fcf4d7f

Browse files
authored
fix(ci): the CDN smoke test retries a page that never goes idle and names the request that hung (#8733)
fix(ci): the CDN smoke test retries a page that never goes idle and names the request that hung Co-authored-by: vjeux <vjeux@users.noreply.github.com>
1 parent dbb2d52 commit fcf4d7f

4 files changed

Lines changed: 663 additions & 47 deletions

File tree

‎.github/scripts/cdn-template-smoke-test.mjs‎

Lines changed: 40 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ import * as os from 'node:os';
3030
import * as path from 'node:path';
3131
import {fileURLToPath} from 'node:url';
3232
import {pageAssetUrls, primeCdnAssets} from './lib/cdn-asset-priming.mjs';
33+
import {
34+
renderPage,
35+
renderUntilClean,
36+
uncleanFindings,
37+
} from './lib/cdn-page-render.mjs';
3338
import {resolvePublishedCdnVersion} from './lib/cdn-version.mjs';
3439

3540
const ROOT = path.resolve(
@@ -147,57 +152,45 @@ const server = http.createServer((req, res) => {
147152
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
148153
const url = `http://127.0.0.1:${server.address().port}/`;
149154

150-
/** Load the page once and report everything that went wrong. */
151-
async function render() {
152-
const consoleErrors = [];
153-
const pageErrors = [];
154-
const failedRequests = [];
155-
156-
const browser = await chromium.launch();
157-
try {
158-
const page = await browser.newPage();
159-
page.on('console', m => {
160-
if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 300));
161-
});
162-
page.on('pageerror', e => pageErrors.push(String(e).slice(0, 300)));
163-
page.on('requestfailed', r =>
164-
failedRequests.push(`${r.url()} :: ${r.failure()?.errorText}`),
165-
);
166-
page.on('response', r => {
167-
if (r.status() >= 400) failedRequests.push(`${r.status()} ${r.url()}`);
168-
});
169-
170-
await page.goto(url, {waitUntil: 'networkidle', timeout: 90_000});
171-
// A page that throws during render still reaches networkidle with an empty
172-
// root, so the render itself has to be asserted, not just the error streams.
173-
const button = await page
174-
.getByRole('button')
175-
.first()
176-
.textContent({timeout: 15_000})
177-
.catch(() => null);
178-
179-
return {consoleErrors, pageErrors, failedRequests, button};
180-
} finally {
181-
await browser.close();
182-
}
183-
}
184-
185155
// ── 5. Render, retrying once so a blip at a CDN is not a red build ───────────
186-
let result;
187-
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
188-
result = await render();
189-
const clean =
190-
result.consoleErrors.length === 0 &&
191-
result.pageErrors.length === 0 &&
192-
result.failedRequests.length === 0 &&
193-
result.button;
194-
if (clean) break;
195-
if (attempt < ATTEMPTS) console.log(` retry ${attempt} of ${ATTEMPTS - 1}`);
196-
}
156+
// Every attempt shares the one 90 s wait this step has always had, so the retry
157+
// adds no time to it: this step can start with under two minutes of the
158+
// smoke-test job's 15-minute limit left, and a page that hangs on both
159+
// attempts still prints the report naming what hung before the job is stopped.
160+
const RENDER_BUDGET_MS = 90_000;
161+
const result = await renderUntilClean(
162+
({budgetMs}) =>
163+
renderPage(url, {launch: async () => chromium.launch(), budgetMs}),
164+
{
165+
attempts: ATTEMPTS,
166+
deadline: Date.now() + RENDER_BUDGET_MS,
167+
// The attempt a retry replaces is printed in full: a CDN blip that clears
168+
// on the retry still shows in the log, rather than vanishing behind a
169+
// green run.
170+
onRetry: (attempt, leftMs, discarded) => {
171+
console.log(
172+
` retry ${attempt} of ${ATTEMPTS - 1}, ${Math.round(leftMs / 1000)} s left, after:`,
173+
);
174+
for (const finding of uncleanFindings(discarded)) {
175+
console.log(` ${finding}`);
176+
}
177+
},
178+
},
179+
);
197180
server.close();
198181

199182
// ── 6. Report ────────────────────────────────────────────────────────────────
200183
console.log(`\n${PAGE} @ ${rendered}`);
184+
if (result.timedOut) {
185+
fail(
186+
'the page never went idle, so its navigation timed out',
187+
result.pendingRequests.length === 0
188+
? ' no request was in flight when the wait gave up'
189+
: result.pendingRequests
190+
.map(entry => ` still in flight: ${entry}`)
191+
.join('\n'),
192+
);
193+
}
201194
for (const [label, entries] of [
202195
['console error', result.consoleErrors],
203196
['page error', result.pageErrors],
@@ -214,7 +207,7 @@ for (const [label, entries] of [
214207
}
215208
if (result.button) {
216209
console.log(` ok rendered a button: "${result.button.trim()}"`);
217-
} else {
210+
} else if (!result.timedOut) {
218211
fail('the page loaded but rendered no button');
219212
}
220213

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file cdn-page-render.browser.test.mjs
5+
* @input A local page whose module request is never answered, and Chromium;
6+
* run with ASTRYX_CDN_SMOKE_BROWSER=1 after `npx playwright install chromium`
7+
* @output Real-browser proof that a page with a request that hangs never goes
8+
* idle, and that renderPage reports that navigation timeout with the hung
9+
* request instead of throwing
10+
* @position The browser half of cdn-page-render.test.mjs, which runs the same
11+
* rules against Playwright's events without a browser
12+
*/
13+
14+
import http from 'node:http';
15+
import {chromium} from 'playwright';
16+
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
17+
import {renderPage, renderUntilClean} from './cdn-page-render.mjs';
18+
19+
const PAGE =
20+
'<!doctype html><button>Start</button>' +
21+
'<script type="module" src="/stall.js"></script>';
22+
23+
describe.runIf(process.env.ASTRYX_CDN_SMOKE_BROWSER === '1')(
24+
'renderPage in Chromium',
25+
() => {
26+
/** The module responses held open, so the page can never go idle. */
27+
const held = [];
28+
let server;
29+
let url;
30+
31+
beforeAll(async () => {
32+
server = http.createServer((req, res) => {
33+
if (req.url === '/stall.js') {
34+
held.push(res);
35+
return;
36+
}
37+
res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});
38+
res.end(PAGE);
39+
});
40+
await new Promise(resolve => {
41+
server.listen(0, '127.0.0.1', resolve);
42+
});
43+
url = `http://127.0.0.1:${server.address().port}/`;
44+
});
45+
46+
afterAll(async () => {
47+
for (const res of held) {
48+
res.destroy();
49+
}
50+
server.closeAllConnections();
51+
await new Promise(resolve => {
52+
server.close(resolve);
53+
});
54+
});
55+
56+
it('reports a page that never goes idle, naming the module that hung', async () => {
57+
const result = await renderPage(url, {
58+
launch: async () => chromium.launch(),
59+
navigationTimeoutMs: 2_000,
60+
});
61+
expect(result.timedOut).toBe(true);
62+
expect(result.pendingRequests).toEqual([`${url}stall.js`]);
63+
});
64+
65+
it('fits both attempts at a page that never goes idle inside one deadline', async () => {
66+
const started = Date.now();
67+
const result = await renderUntilClean(
68+
(attempt = {}) =>
69+
renderPage(url, {
70+
launch: async () => chromium.launch(),
71+
budgetMs: attempt.budgetMs,
72+
}),
73+
{attempts: 2, deadline: Date.now() + 4_000},
74+
);
75+
// Two browser launches beside the 4 s the attempts share.
76+
expect(Date.now() - started).toBeLessThan(8_000);
77+
expect(result.timedOut).toBe(true);
78+
expect(result.pendingRequests).toEqual([`${url}stall.js`]);
79+
}, 20_000);
80+
},
81+
);
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* Render the CDN starter page in a browser, and report what went wrong.
5+
*
6+
* One render loads the page until its network goes idle, then reads the first
7+
* button: a page that throws while rendering still goes idle with an empty
8+
* root, so the render itself is asserted, not only the error streams. A page
9+
* with a request that never finishes never goes idle, so its navigation times
10+
* out: that is an unclean render like any other, reported with the requests
11+
* still in flight when the wait gave up, so the output names the asset that
12+
* hung instead of ending the run on a stack trace. renderUntilClean retries
13+
* an unclean render once, so a blip at a CDN is not a red build, and fits
14+
* every attempt inside one deadline, so a page that hangs on each attempt
15+
* still gets its report printed before the job running it is stopped. It
16+
* hands every retry the attempt it discards, and uncleanFindings names what
17+
* made that attempt unclean, so a blip that clears on the retry still shows
18+
* in the log. Only an expected absence (a wait that ran out) becomes a value;
19+
* every other error throws.
20+
*/
21+
22+
/** Playwright's error for a navigation whose wait condition never came. */
23+
function isTimeout(error) {
24+
return error?.name === 'TimeoutError';
25+
}
26+
27+
/**
28+
* Load `url` once in a browser from `launch`, and collect its console errors,
29+
* page errors and failed requests, and the first button's text (null when no
30+
* button rendered). A navigation that times out comes back with `timedOut`
31+
* and the URLs still in flight (`pendingRequests`, in request order); any
32+
* other navigation error throws. With `budgetMs`, the whole attempt fits in
33+
* it: the navigation waits no longer than the budget, and the button no
34+
* longer than what is left of it.
35+
*
36+
* @param {string} url
37+
* @param {{
38+
* launch: () => Promise<import('playwright').Browser>,
39+
* navigationTimeoutMs?: number,
40+
* buttonTimeoutMs?: number,
41+
* budgetMs?: number,
42+
* now?: () => number,
43+
* }} options
44+
*/
45+
export async function renderPage(
46+
url,
47+
{
48+
launch,
49+
navigationTimeoutMs = 90_000,
50+
buttonTimeoutMs = 15_000,
51+
budgetMs,
52+
now = Date.now,
53+
},
54+
) {
55+
const startedAt = now();
56+
/**
57+
* `limitMs`, cut to what is left of the budget. Never 0: Playwright reads a
58+
* timeout of 0 as no timeout at all.
59+
*/
60+
const withinBudget = limitMs =>
61+
budgetMs == null
62+
? limitMs
63+
: Math.max(1, Math.min(limitMs, budgetMs - (now() - startedAt)));
64+
const consoleErrors = [];
65+
const pageErrors = [];
66+
const failedRequests = [];
67+
/** Requests the page made that have neither finished nor failed. */
68+
const inFlight = new Set();
69+
70+
const browser = await launch();
71+
try {
72+
const page = await browser.newPage();
73+
page.on('console', m => {
74+
if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 300));
75+
});
76+
page.on('pageerror', e => pageErrors.push(String(e).slice(0, 300)));
77+
page.on('request', r => inFlight.add(r));
78+
page.on('requestfinished', r => inFlight.delete(r));
79+
page.on('requestfailed', r => {
80+
inFlight.delete(r);
81+
failedRequests.push(`${r.url()} :: ${r.failure()?.errorText}`);
82+
});
83+
page.on('response', r => {
84+
if (r.status() >= 400) failedRequests.push(`${r.status()} ${r.url()}`);
85+
});
86+
87+
try {
88+
await page.goto(url, {
89+
waitUntil: 'networkidle',
90+
timeout: withinBudget(navigationTimeoutMs),
91+
});
92+
} catch (error) {
93+
if (!isTimeout(error)) {
94+
throw error;
95+
}
96+
return {
97+
consoleErrors,
98+
pageErrors,
99+
failedRequests,
100+
timedOut: true,
101+
pendingRequests: [...inFlight].map(r => r.url()),
102+
button: null,
103+
};
104+
}
105+
let button;
106+
try {
107+
button = await page
108+
.getByRole('button')
109+
.first()
110+
.textContent({timeout: withinBudget(buttonTimeoutMs)});
111+
} catch (error) {
112+
if (!isTimeout(error)) {
113+
throw error;
114+
}
115+
// No button within the wait: the page rendered nothing to press.
116+
button = null;
117+
}
118+
119+
return {
120+
consoleErrors,
121+
pageErrors,
122+
failedRequests,
123+
timedOut: false,
124+
pendingRequests: [],
125+
button,
126+
};
127+
} finally {
128+
await browser.close();
129+
}
130+
}
131+
132+
/**
133+
* Everything that made `result` unclean, one line each: the timeout and the
134+
* requests still in flight, each console error, page error and failed
135+
* request, and a missing button on a page that finished loading. Empty for a
136+
* clean render.
137+
*/
138+
export function uncleanFindings(result) {
139+
return [
140+
...(result.timedOut ? ['navigation timed out'] : []),
141+
...result.pendingRequests.map(url => `still in flight: ${url}`),
142+
...result.consoleErrors.map(entry => `console error: ${entry}`),
143+
...result.pageErrors.map(entry => `page error: ${entry}`),
144+
...result.failedRequests.map(entry => `failed request: ${entry}`),
145+
...(!result.timedOut && !result.button ? ['rendered no button'] : []),
146+
];
147+
}
148+
149+
/** Whether a render went idle with nothing wrong and a button on the page. */
150+
export function isCleanRender(result) {
151+
return (
152+
!result.timedOut &&
153+
result.consoleErrors.length === 0 &&
154+
result.pageErrors.length === 0 &&
155+
result.failedRequests.length === 0 &&
156+
Boolean(result.button)
157+
);
158+
}
159+
160+
/**
161+
* Run `render` until one comes back clean, at most `attempts` times, and
162+
* return the last result. With a `deadline` (in `now()`'s clock), each attempt
163+
* is handed `budgetMs`, an equal share of the time left (so the retry gets
164+
* whatever the first attempt left unused), and no attempt starts once the
165+
* deadline has passed. `onRetry(attempt, leftMs, discarded)` hears each
166+
* retry, with the unclean attempt it replaces.
167+
*
168+
* @template {{timedOut: boolean, consoleErrors: string[], pageErrors: string[], failedRequests: string[], button: string | null}} R
169+
* @param {(attempt: {budgetMs?: number}) => Promise<R>} render
170+
* @param {{
171+
* attempts?: number,
172+
* deadline?: number,
173+
* now?: () => number,
174+
* onRetry?: (attempt: number, leftMs: number | undefined, discarded: R) => void,
175+
* }} [options]
176+
* @returns {Promise<R>}
177+
*/
178+
export async function renderUntilClean(
179+
render,
180+
{attempts = 2, deadline, now = Date.now, onRetry} = {},
181+
) {
182+
const leftMs = () => (deadline == null ? undefined : deadline - now());
183+
let result;
184+
for (let attempt = 1; attempt <= attempts; attempt++) {
185+
const left = leftMs();
186+
result = await render({
187+
budgetMs:
188+
left == null ? undefined : Math.floor(left / (attempts - attempt + 1)),
189+
});
190+
if (isCleanRender(result) || attempt === attempts) break;
191+
const remaining = leftMs();
192+
if (remaining != null && remaining <= 0) break;
193+
onRetry?.(attempt, remaining, result);
194+
}
195+
return result;
196+
}

0 commit comments

Comments
 (0)