playwright-soak
Version:
Catch memory leaks in Playwright tests. Repeat a user flow a few hundred times, force GC, and fail the test if DOM nodes, listeners or heap keep piling up.
277 lines (271 loc) • 9.99 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
attachCDP: () => attachCDP,
calibrateTypingCost: () => calibrateTypingCost,
checkLeaks: () => checkLeaks,
expectNoLeak: () => expectNoLeak,
formatSoak: () => formatSoak,
getPageMetrics: () => getPageMetrics,
heapHalves: () => heapHalves,
metricHalves: () => metricHalves,
metricStretches: () => metricStretches,
soak: () => soak
});
module.exports = __toCommonJS(index_exports);
// src/metrics.ts
async function attachCDP(page) {
const client = await page.context().newCDPSession(page);
await client.send("Performance.enable");
return client;
}
async function getPageMetrics(client) {
await client.send("HeapProfiler.collectGarbage");
await client.send("HeapProfiler.collectGarbage");
const { metrics } = await client.send("Performance.getMetrics");
const m = Object.fromEntries(metrics.map((i) => [i.name, i.value]));
return {
heap: m.JSHeapUsedSize,
nodes: m.Nodes,
listeners: m.JSEventListeners,
documents: m.Documents
};
}
// src/soak.ts
async function soak({
client,
flow,
iterations = 200,
warmup = 5,
sampleEvery = Math.max(1, Math.floor(iterations / 8))
}) {
for (let i = 0; i < warmup; i++) {
await runFlow(flow, i, "warmup", warmup);
}
const baseline = await getPageMetrics(client);
const samples = [];
for (let i = 0; i < iterations; i++) {
await runFlow(flow, i, "iteration", iterations);
if ((i + 1) % sampleEvery === 0 && i + 1 < iterations) {
samples.push({ iteration: i + 1, metrics: await getPageMetrics(client) });
}
}
const after = await getPageMetrics(client);
samples.push({ iteration: iterations, metrics: after });
return { baseline, after, samples, iterations, warmup };
}
async function runFlow(flow, index, phase, total) {
try {
await flow(index);
} catch (cause) {
throw new Error(
`playwright-soak: flow threw on ${phase} ${index + 1} of ${total}` + (phase === "iteration" ? " (warmup rounds ran before this, so page state is not fresh)" : ""),
{ cause }
);
}
}
function metricStretches(r, metric) {
const readings = [{ iteration: 0, metrics: r.baseline }, ...r.samples];
return readings.slice(1).map((reading, i) => ({
from: readings[i].iteration,
to: reading.iteration,
delta: reading.metrics[metric] - readings[i].metrics[metric]
}));
}
function metricHalves(r, metric) {
const half = r.iterations / 2;
const mid = r.samples.reduce(
(best, s) => Math.abs(s.iteration - half) < Math.abs(best.iteration - half) ? s : best
);
if (mid === r.samples[r.samples.length - 1]) return void 0;
return {
first: mid.metrics[metric] - r.baseline[metric],
second: r.after[metric] - mid.metrics[metric],
midIteration: mid.iteration
};
}
function heapHalves(r) {
return metricHalves(r, "heap");
}
// src/assert.ts
var mb = (bytes) => `${(bytes / 1024 / 1024).toFixed(2)}MB`;
function accumulates(result, metric) {
const stretches = metricStretches(result, metric);
if (stretches.length < 2) return true;
const total = stretches.reduce((sum, s) => sum + s.delta, 0);
const largest = Math.max(...stretches.map((s) => s.delta));
return largest * 2 < total;
}
var shape = (halves) => halves ? `, +${halves.first} then +${halves.second} across the halves, split @${halves.midIteration}` : "";
function checkLeaks(result, thresholds = {}) {
const {
nodes = 100,
listeners = 0,
documents = 0,
typingCost = 0,
heapRatio = 0.5,
heapNoise = 256 * 1024
} = thresholds;
const findings = [];
const { baseline, after, iterations } = result;
const counter = (metric, allowance, describe) => {
const growth = after[metric] - baseline[metric];
if (growth <= allowance) return;
if (!accumulates(result, metric)) return;
const halves2 = metricHalves(result, metric);
findings.push({
metric,
growth,
perIteration: growth / iterations,
halves: halves2,
message: describe(growth, halves2)
});
};
const typingAllowance = Math.ceil(typingCost * iterations * 1.1);
const nodeBudget = nodes + typingAllowance;
counter(
"nodes",
// Historically a `>=` boundary, kept so a flow that lands exactly on the
// budget is treated as spent rather than clear.
nodeBudget - 1,
(growth, halves2) => `DOM nodes accumulated: +${growth} over ${iterations} iterations (${(growth / iterations).toFixed(2)}/iteration${shape(halves2)}), budget ${nodeBudget}${typingCost ? ` (${nodes} + ${typingAllowance} for typing)` : ""}`
);
counter(
"listeners",
listeners,
(growth, halves2) => `event listeners accumulated: +${growth} over ${iterations} iterations (${(growth / iterations).toFixed(2)}/iteration${shape(halves2)}), allowed ${listeners}`
);
counter(
"documents",
documents,
(growth, halves2) => `documents accumulated: +${growth} over ${iterations} iterations${shape(halves2)}, allowed ${documents}`
);
const halves = metricHalves(result, "heap");
if (halves) {
const allowed = Math.max(halves.first * heapRatio, heapNoise);
if (halves.second > allowed) {
const growth = after.heap - baseline.heap;
findings.push({
metric: "heap",
growth,
perIteration: growth / iterations,
halves,
message: `heap grew as fast in the second half as the first (${mb(halves.first)} then ${mb(halves.second)}, split @${halves.midIteration}), which is a linear climb rather than a settling one; allowed ${mb(allowed)}`
});
}
}
return findings;
}
function expectNoLeak(result, thresholds = {}) {
const findings = checkLeaks(result, thresholds);
if (!findings.length) return;
throw new Error(
`playwright-soak: leak detected over ${result.iterations} iterations
` + findings.map((f) => ` - ${f.message}`).join("\n")
);
}
// src/format.ts
var mb2 = (bytes) => `${(bytes / 1024 / 1024).toFixed(2)}MB`;
var signed = (n) => n >= 0 ? `+${n}` : String(n);
var COUNTERS = [
["nodes", "nodes"],
["listeners", "listeners"],
["documents", "docs"]
];
var spark = (stretches) => stretches.map((s) => s.delta > 0 ? "+" : s.delta < 0 ? "-" : "\xB7").join("");
function stretchLines(r) {
return COUNTERS.flatMap(([metric, label]) => {
const stretches = metricStretches(r, metric);
if (stretches.length < 2) return [];
const total = stretches.reduce((sum, s) => sum + s.delta, 0);
if (total <= 0) return [];
const largest = Math.max(...stretches.map((s) => s.delta));
const share = Math.round(largest / total * 100);
return [
` ${label.padEnd(9)} ${spark(stretches)} ${signed(total)} total, biggest stretch ${share}% of it (${share < 50 ? "spread out, so accumulating" : "concentrated, so a step"})`
];
});
}
function formatSoak(name, r, extra) {
const d = {
heap: r.after.heap - r.baseline.heap,
nodes: r.after.nodes - r.baseline.nodes,
listeners: r.after.listeners - r.baseline.listeners,
documents: r.after.documents - r.baseline.documents
};
const row = (label, m) => ` ${label} heap ${mb2(m.heap).padStart(8)} nodes ${String(m.nodes).padStart(6)} listeners ${String(m.listeners).padStart(5)} docs ${m.documents}`;
const lines = [
`
[soak] ${name} \u2014 ${r.iterations} iterations`,
row("base ", r.baseline),
...r.samples.map(
(s) => row(`@${String(s.iteration).padStart(5)}`, s.metrics)
),
` delta heap ${d.heap >= 0 ? "+" : ""}${mb2(d.heap)} nodes ${signed(d.nodes)} listeners ${signed(d.listeners)} docs ${signed(d.documents)}`,
` per-iteration heap ${(d.heap / r.iterations / 1024).toFixed(2)}KB nodes ${(d.nodes / r.iterations).toFixed(2)} listeners ${(d.listeners / r.iterations).toFixed(3)}`
];
const halves = heapHalves(r);
if (halves) {
lines.push(
` heap halves 1st ${mb2(halves.first)} 2nd ${mb2(halves.second)} (split @${halves.midIteration}; a settling curve has 2nd well under 1st)`
);
}
lines.push(...stretchLines(r));
if (extra?.typingCost) {
lines.push(
` browser typing cost ${extra.typingCost.toFixed(2)} nodes/round (budgeted for)`
);
}
return lines.join("\n");
}
// src/typing.ts
async function calibrateTypingCost(page, client, gesture, rounds = 20) {
await page.evaluate(() => {
const input = document.createElement("input");
input.setAttribute("data-playwright-soak-control", "");
document.body.appendChild(input);
});
const control = page.locator("[data-playwright-soak-control]");
await gesture(control);
const before = await getPageMetrics(client);
for (let i = 0; i < rounds; i++) {
await gesture(control);
}
const after = await getPageMetrics(client);
await page.evaluate(() => {
document.querySelector("[data-playwright-soak-control]")?.remove();
});
return Math.max(0, (after.nodes - before.nodes) / rounds);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
attachCDP,
calibrateTypingCost,
checkLeaks,
expectNoLeak,
formatSoak,
getPageMetrics,
heapHalves,
metricHalves,
metricStretches,
soak
});
//# sourceMappingURL=index.cjs.map