#!/usr/bin/env node // Measure the RAM and the response times of the optional features, each feature off and on. // The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started. // Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7//. import { existsSync } from "node:fs"; import { realpathSync } from "node:fs"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { fileURLToPath, pathToFileURL } from "node:url"; import { checkTarget, FEATURES, markdownTable, parseArguments, SCENARIOS, summarize, USAGE } from "./measure/core.mjs"; import { inspectPmBoards, prepareFixture } from "./measure/fixture.mjs"; import { startGiteaServer } from "./measure/giteaServer.mjs"; import { ACTIONS, TABLE } from "./measure/scenarios.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const IDLE_MS = 15000; const GC_SETTLE_MS = 5000; // Plugins load after the workbench shows. Each run waits this long after the start, so the action measures the feature and not the plugin load. const START_SETTLE_MS = 5000; const log = message => console.log(`[${new Date().toISOString().slice(11, 19)}] ${message}`); async function machine() { return { cpu: os.cpus()[0]?.model?.trim() ?? "unknown", cores: os.cpus().length, ramGB: os.totalmem() / 1024 ** 3, windows: `${os.version()} ${os.release()}`, node: process.version }; } /** Remove the data folders of the test identity. `checkTarget` made the paths from the test identifier. */ async function resetData(folders, identifier) { for (const folder of [folders.roaming, folders.local]) { if (path.win32.basename(folder) !== identifier) throw new Error(`Refusing to remove ${folder}.`); for (let attempt = 0; ; attempt++) { try { await rm(folder, { recursive: true, force: true }); break; } catch (error) { if (attempt >= 20) throw new Error(`Cannot reset ${folder}: ${error.message}`); await sleep(500); } } } } /** Write the folder grant and the settings of Background Slideshow before the first start. */ async function seedBackgroundPlugin(folders, backgrounds) { const id = TABLE.features.background.plugin.id; const folder = path.join(folders.roaming, "plugin-data", id); await mkdir(folder, { recursive: true }); const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"; await writeFile(path.join(folder, "folder-grants.json"), JSON.stringify({ schema: 1, grants: [{ id: grant, path: backgrounds }] }, null, 2)); await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" })); } /** * Write the `background` settings and the host folder file of the native Background before the first start * (src/lib/features/backgroundSettings.ts and src-tauri/src/backgrounds.rs). The settings file has no other section, * so the first start keeps it and migrates only the feature switches. */ async function seedBackgroundNative(folders, backgrounds) { await mkdir(folders.roaming, { recursive: true }); const background = { source: "folder", seconds: TABLE.features.background.seconds, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" }; await writeFile(path.join(folders.roaming, "settings.json"), JSON.stringify({ schema: 1, revision: 1, background }, null, 2) + "\n"); // The host accepts the folder only at its resolved path. await writeFile(path.join(folders.roaming, "background-folder.json"), JSON.stringify({ schema: 1, path: realpathSync.native(backgrounds) }, null, 2)); } /** The features that are on in the running app. */ async function readState(app, mode, invoke) { if (mode === "plugin") { const snapshot = await invoke(app.page, "plugins_snapshot"); return new Set(FEATURES.filter(feature => snapshot.plugins.some(row => row.manifest.id === TABLE.features[feature].plugin.id && row.enabled))); } const file = await invoke(app.page, "settings_read"); const section = file?.sections?.[TABLE.featuresSection] ?? {}; return new Set(FEATURES.filter(feature => section[TABLE.features[feature].nativeKey] === true)); } /** Turn on exactly the features in `enabled`, and turn off the others. */ async function applyState(app, mode, enabled, invoke) { if (mode === "plugin") { const snapshot = await invoke(app.page, "plugins_snapshot"); for (const row of snapshot.plugins) { const feature = FEATURES.find(item => TABLE.features[item].plugin.id === row.manifest.id); const want = feature ? enabled.has(feature) : false; if (row.enabled !== want) await invoke(app.page, "plugins_set_enabled", { id: row.manifest.id, enabled: want, hash: want ? row.hash : null }); } return; } const file = await invoke(app.page, "settings_read"); const value = { ...(file?.sections?.[TABLE.featuresSection] ?? {}) }; for (const feature of FEATURES) value[TABLE.features[feature].nativeKey] = enabled.has(feature); await invoke(app.page, "settings_write", { section: TABLE.featuresSection, value }); } const sameSet = (a, b) => a.size === b.size && [...a].every(item => b.has(item)); /** Install the plugins of `features` from the fake Gitea server. */ async function installPlugins(app, features, invoke) { const packages = features.map(feature => TABLE.features[feature].plugin); for (const item of packages) if (!existsSync(item.zip)) throw new Error(`No plugin ZIP at ${item.zip}.`); const server = await startGiteaServer(packages.map(item => ({ repo: item.repo, tag: item.tag, file: item.zip }))); try { for (const item of packages) { const rows = await invoke(app.page, "plugins_from_git", { url: server.repository(item.repo), tag: item.tag, token: null }); if (rows.length !== 1 || rows[0].error || !rows[0].token) throw new Error(`plugins_from_git for ${item.repo}: ${JSON.stringify(rows)}`); if (rows[0].manifest?.id !== item.id) throw new Error(`The ZIP of ${item.repo} has the ID ${rows[0].manifest?.id}, not ${item.id}.`); const results = await invoke(app.page, "plugins_install", { tokens: [rows[0].token], enabled: true }); if (results.some(result => result.error)) throw new Error(`plugins_install for ${item.id}: ${JSON.stringify(results)}`); log(`Installed ${item.id} from ${server.repository(item.repo)}.`); } } finally { await server.close(); } const snapshot = await invoke(app.page, "plugins_snapshot"); const missing = packages.filter(item => !snapshot.plugins.some(row => row.manifest.id === item.id && !row.error)); if (missing.length) throw new Error(`Plugins missing after the install: ${missing.map(item => item.id).join(", ")}.`); return snapshot.plugins.map(row => ({ id: row.manifest.id, version: row.manifest.version, hash: row.hash })); } export async function main(argv = process.argv.slice(2)) { if (argv.includes("--help")) { console.log(USAGE); return; } const options = parseArguments(argv); const exe = path.resolve(options.exe); const folders = checkTarget({ exe, identifier: options.identifier }); if (!existsSync(exe)) throw new Error(`No executable at ${exe}.`); // Load the app module after the refusals, so the refusals work without Playwright. const app = await import("./measure/app.mjs"); const output = path.join(repoRoot, "output", "phase-7", options.stage); await mkdir(output, { recursive: true }); const fixture = await prepareFixture({ fresh: options.freshFixture, log }); const pm = await inspectPmBoards(fixture.workspace); if (pm.checked && JSON.parse(pm.output).workspaces[0].boards.length !== 8) throw new Error("The Project Management fixture does not show 8 boards."); const reportPath = path.join(output, "memory.json"); const previous = options.only && existsSync(reportPath) ? JSON.parse(await readFile(reportPath, "utf8")) : null; const report = { stage: options.stage, mode: options.mode, build: exe, identifier: options.identifier, date: new Date().toISOString(), runs: options.runs, machine: await machine(), fixture, method: { idleMs: IDLE_MS, gcSettleMs: GC_SETTLE_MS, startSettleMs: START_SETTLE_MS, action: "Each run waits startSettleMs after the start, then starts the action. First need is the time from the start of the action to its ready condition.", memory: "Win32_Process PrivatePageCount and WorkingSetSize, summed over the descendants of the started process.", heap: "CDP Runtime.getHeapUsage usedSize of the main page after HeapProfiler.collectGarbage. Workers and other pages are not included.", start: `From the spawn to the visible tree row ${TABLE.knownRow}.`, longTasks: "PerformanceObserver longtask in the main page, from the start of the action to its end. For on-idle and base, over the idle wait.", }, plugins: previous?.plugins ?? null, setup: {}, rows: previous?.rows ?? [], notes: previous?.notes ?? [], }; const save = async () => { report.date = new Date().toISOString(); await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n"); await writeFile(path.join(output, "memory.md"), markdownTable(report)); }; const wanted = (feature, scenario) => !options.only || options.only.includes(feature === "base" ? "base" : `${feature}:${scenario}`); // The plan: base runs with every feature off, then each feature scenario with only that feature on. const plan = []; if (wanted("base") && !options.skipBase) for (let run = 1; run <= options.runs; run++) plan.push({ feature: "base", scenario: "base", run, enabled: new Set() }); const featurePlan = []; for (const feature of options.features) for (const scenario of SCENARIOS) if (wanted(feature, scenario)) for (let run = 1; run <= options.runs; run++) featurePlan.push({ feature, scenario, run, enabled: new Set([feature]) }); log(`Resetting ${folders.roaming} and ${folders.local}.`); await resetData(folders, options.identifier); if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds); if (options.mode === "native" && options.features.includes("background")) await seedBackgroundNative(folders, fixture.backgrounds); // The setup start opens the workspace. It also proves the test identity. let session = await app.launch({ exe, port: options.port }); try { if (!app.hasWebviewFolder(folders.local)) throw new Error(`${app.webviewFolder(folders.local)} does not exist. The executable does not use the identifier ${options.identifier}.`); const snapshot = await app.invoke(session.page, "plugins_snapshot"); if (!path.resolve(snapshot.root).toLowerCase().startsWith(path.resolve(folders.roaming).toLowerCase())) throw new Error(`The app data folder ${snapshot.root} is not in ${folders.roaming}.`); report.setup.identity = { webview: app.webviewFolder(folders.local), pluginRoot: snapshot.root }; await app.invoke(session.page, "workspace_open", { path: fixture.workspace }); await session.page.evaluate(layout => localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout)), TABLE.layout); await session.page.reload(); await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); if (options.mode === "native") await applyState(session, "native", new Set(), app.invoke); await app.clearViewState(session.page); } finally { await app.stop(session); } log("Setup done: workspace open, identity confirmed."); const rowFor = (feature, scenario) => { let row = report.rows.find(item => item.feature === feature && item.scenario === scenario); if (!row) { row = { feature, scenario, samples: [], median: null }; report.rows.push(row); } return row; }; for (const item of [...plan, ...featurePlan]) { const row = rowFor(item.feature, item.scenario); if (item.run === 1) { row.samples = []; row.median = null; delete row.reason; } } // Keep the row order stable: base first, then each feature in the order of FEATURES and SCENARIOS. const rank = row => row.feature === "base" ? -1 : FEATURES.indexOf(row.feature) * 10 + SCENARIOS.indexOf(row.scenario); report.rows.sort((a, b) => rank(a) - rank(b)); await save(); let installed = options.mode === "native"; const runAll = async list => { for (const [index, item] of list.entries()) { const next = list[index + 1]; const row = rowFor(item.feature, item.scenario); log(`${item.feature} ${item.scenario}, run ${item.run} of ${options.runs}.`); const sample = await measure(item, next, options.mode).catch(error => ({ run: item.run, error: String(error?.stack ?? error).split("\n").slice(0, 3).join(" | ") })); if (sample.error) log(` failed: ${sample.error}`); else log(` private ${sample.privateMB.toFixed(1)} MB, working set ${sample.workingSetMB.toFixed(1)} MB, heap ${sample.heapMB.toFixed(1)} MB, start ${Math.round(sample.startMs)} ms, first need ${sample.firstNeedMs === null ? "–" : Math.round(sample.firstNeedMs)} ms`); row.samples.push(sample); row.median = summarize(row.samples); if (row.median.failed === row.median.runs) row.reason = row.samples.find(item => item.error)?.error; else delete row.reason; await save(); } }; /** One measured run in a new app process. Before the stop, it prepares the feature state of `next`. */ async function measure(item, next, mode, retry = true) { const session = await app.launch({ exe, port: options.port }); const sample = { run: item.run, pid: session.pid, cdpMs: Math.round(session.cdpMs) }; let prepared = false; try { Object.assign(sample, await app.waitForWorkbench(session)); const state = await readState(session, mode, app.invoke); if (!sameSet(state, item.enabled)) { // A failed run can leave another state. Fix it and start again. if (!retry) throw new Error(`The feature state is ${[...state].join(",") || "none"}, not ${[...item.enabled].join(",") || "none"}.`); await applyState(session, mode, item.enabled, app.invoke); await app.clearViewState(session.page); prepared = true; await app.stop(session); return measure(item, next, mode, false); } await sleep(START_SETTLE_MS); await app.observeLongTasks(session.page); sample.firstNeedMs = null; if (item.scenario === "in-use" || item.scenario === "after-off") { const begin = performance.now(); sample.details = await ACTIONS[item.feature](session.page, { mode, log }) ?? null; sample.firstNeedMs = performance.now() - begin; if (item.scenario === "after-off") await applyState(session, mode, new Set(), app.invoke); const tasks = await app.collectLongTasks(session.page); await sleep(IDLE_MS); Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null }); } else { await sleep(IDLE_MS); const tasks = await app.collectLongTasks(session.page); Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null }); } Object.assign(sample, await app.readMemory(session, { settleMs: GC_SETTLE_MS })); return sample; } catch (error) { const shot = path.join(output, `failure-${item.feature}-${item.scenario}-${item.run}.png`); await session.page.screenshot({ path: shot }).catch(() => {}); throw error; } finally { if (!prepared) { try { await applyState(session, mode, next?.enabled ?? new Set(), app.invoke); await app.clearViewState(session.page); } catch (error) { log(` cleanup: ${error.message}`); } await app.stop(session); } } } await runAll(plan); if (featurePlan.length && !installed) { session = await app.launch({ exe, port: options.port }); try { await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); report.plugins = await installPlugins(session, options.features, app.invoke); await session.page.reload(); await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); await applyState(session, "plugin", featurePlan[0].enabled, app.invoke); await app.clearViewState(session.page); } finally { await app.stop(session); } installed = true; await save(); } await runAll(featurePlan); await save(); log(`Wrote ${reportPath} and ${path.join(output, "memory.md")}.`); } if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { main().catch(error => { console.error(error?.stack ?? String(error)); process.exitCode = 1; }); }