Files
RuneStone/scripts/measure/app.mjs
T
2026-11-16 04:21:21 -07:00

146 lines
7.3 KiB
JavaScript

// Start the test build, attach to its WebView2 through CDP, read the metrics, and stop only the started process tree.
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { playwright } from "../../tests/smoke/_harness/index.mjs";
import { processTree } from "./core.mjs";
import { listProcesses, stopTree } from "./processes.mjs";
import { TABLE } from "./scenarios.mjs";
const isMainPage = page => { try { const url = new URL(page.url()); return url.pathname === "/" && !url.search && url.protocol.startsWith("http"); } catch { return false; } };
async function cdpResponds(port) {
try {
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
return response.ok;
} catch { return false; }
}
/** Call a Rust command from the page. */
export function invoke(page, command, args = {}) {
return page.evaluate(([command, args]) => window.__TAURI_INTERNALS__.invoke(command, args), [command, args]);
}
/**
* Start `exe` with remote debugging on `port` and attach to its main page.
* Refuse when another program already answers on the port, because the tool must not drive a foreign browser.
*/
export async function launch({ exe, port, timeout = 90000 }) {
if (await cdpResponds(port)) throw new Error(`Port ${port} already answers CDP requests. Stop that program or choose another --port.`);
const env = { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}`, NO_PROXY: "127.0.0.1,localhost", no_proxy: "127.0.0.1,localhost" };
const started = performance.now();
const startedAt = Date.now();
const child = spawn(exe, [], { env, cwd: path.dirname(exe), stdio: "ignore", windowsHide: false });
let exited = null;
child.on("exit", code => { exited = code ?? -1; });
child.on("error", error => { exited = String(error); });
await new Promise(resolve => child.once("spawn", resolve).once("error", resolve));
const app = { child, pid: child.pid, started, startedAt, browser: null, page: null, cdpMs: null };
if (!app.pid) throw new Error(`Cannot start ${exe}: ${exited}`);
try {
const { chromium } = playwright();
while (!app.browser) {
if (exited !== null) throw new Error(`The app stopped during the start (exit ${exited}).`);
if (performance.now() - started > timeout) throw new Error("CDP did not answer during the start.");
if (await cdpResponds(port)) app.browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 10000 });
else await sleep(50);
}
app.cdpMs = performance.now() - started;
while (!app.page) {
if (performance.now() - started > timeout) throw new Error("The main window page did not open.");
app.page = app.browser.contexts().flatMap(context => context.pages()).find(isMainPage) ?? null;
if (!app.page) await sleep(50);
}
app.page.setDefaultTimeout(30000);
return app;
} catch (error) {
await stop(app);
throw error;
}
}
/** Wait for the known tree row. Return the start time in milliseconds from the spawn, and page timing values. */
export async function waitForWorkbench(app, timeout = 60000) {
await app.page.locator(TABLE.knownRow).waitFor({ state: "visible", timeout });
const startMs = performance.now() - app.started;
const timing = await app.page.evaluate(() => ({ timeOrigin: performance.timeOrigin, domContentLoaded: performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ?? null, tabs: document.querySelectorAll('[role="tab"]').length }));
return { startMs, navigationMs: timing.timeOrigin - app.startedAt, domContentLoadedMs: timing.domContentLoaded === null ? null : timing.timeOrigin + timing.domContentLoaded - app.startedAt, tabsAtStart: timing.tabs };
}
/** Start a long task observer in the page. */
export function observeLongTasks(page) {
return page.evaluate(() => {
const state = { count: 0, max: 0 };
const record = entries => { for (const entry of entries) { state.count++; state.max = Math.max(state.max, entry.duration); } };
const observer = new PerformanceObserver(list => record(list.getEntries()));
observer.observe({ type: "longtask" });
window.__rsLongTasks = { state, observer, record };
});
}
/** Stop the long task observer. Return the count and the longest duration. */
export function collectLongTasks(page) {
return page.evaluate(() => {
const tasks = window.__rsLongTasks;
if (!tasks) return null;
tasks.record(tasks.observer.takeRecords());
tasks.observer.disconnect();
return { count: tasks.state.count, maxMs: Math.round(tasks.state.max) };
});
}
/** Collect garbage in the main page, wait, and read the heap and the process tree. */
export async function readMemory(app, { settleMs = 5000 } = {}) {
const cdp = await app.page.context().newCDPSession(app.page);
try {
await cdp.send("HeapProfiler.collectGarbage");
await sleep(settleMs);
const heap = await cdp.send("Runtime.getHeapUsage");
const tree = processTree(await listProcesses(), app.pid);
return {
heapMB: heap.usedSize / 1048576,
heapTotalMB: heap.totalSize / 1048576,
privateMB: tree.privateBytes / 1048576,
workingSetMB: tree.workingSet / 1048576,
processCount: tree.count,
processNames: tree.names,
processes: tree.processes.map(item => ({ pid: item.ProcessId, parent: item.ParentProcessId, name: item.Name, privateMB: +(item.PrivatePageCount / 1048576).toFixed(1), workingSetMB: +(item.WorkingSetSize / 1048576).toFixed(1), created: item.Created })),
};
} finally { await cdp.detach().catch(() => {}); }
}
/**
* Clear the open tabs and the layout in the page storage, so the next start restores no tab and shows the file tree.
* Chromium writes local storage to disk after a delay, so the function waits before it returns.
*/
export async function clearViewState(page, flushMs = 6000) {
await page.evaluate(layout => {
for (const key of Object.keys(localStorage)) if (key.startsWith("runestone.document-session.")) localStorage.removeItem(key);
localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout));
}, TABLE.layout);
await sleep(flushMs);
}
/** Stop the started process tree and make sure that none of its processes remain. */
export async function stop(app) {
if (!app?.pid) return { stopped: false };
const before = processTree(await listProcesses().catch(() => []), app.pid).processes;
const result = await stopTree(app.pid);
await app.browser?.close().catch(() => {});
for (let attempt = 0; attempt < 50; attempt++) {
const now = await listProcesses().catch(() => []);
const left = before.filter(item => now.some(other => other.ProcessId === item.ProcessId && other.Created === item.Created));
if (!left.length) return { ...result, remaining: [] };
if (attempt === 10) for (const item of left) await stopTree(item.ProcessId);
await sleep(200);
}
throw new Error(`Processes of the stopped app remain: ${before.map(item => item.ProcessId).join(", ")}.`);
}
/** The WebView2 folder of the test identity. It exists after the first start of a build with that identifier. */
export function webviewFolder(localData) {
return path.join(localData, "EBWebView");
}
export const hasWebviewFolder = localData => existsSync(webviewFolder(localData));