Live: performance tests e2e part (#43915)

* #41993: live perf tests e2e part

* #41993: added bash upgrade instructions

* #41993: remove custom feature toggle

* #41993: fix typo in 'integrationFolder'
This commit is contained in:
Artur Wierzbicki
2022-01-12 22:15:29 +04:00
committed by GitHub
parent 0c88b39162
commit e01ac44cfa
23 changed files with 1099 additions and 30 deletions
@@ -0,0 +1,136 @@
import CDP from 'chrome-remote-interface';
import Tracelib, { TraceEvent } from 'tracelib';
import { countBy, mean } from 'lodash';
import ProtocolProxyApi from 'devtools-protocol/types/protocol-proxy-api';
import { CollectedData, DataCollector, DataCollectorName } from './DataCollector';
type CDPDataCollectorDeps = {
port: number;
};
export class CDPDataCollector implements DataCollector {
private tracingCategories: string[];
private state: {
client?: CDP.Client;
tracingPromise?: Promise<CollectedData>;
traceEvents: TraceEvent[];
};
constructor(private deps: CDPDataCollectorDeps) {
this.state = this.getDefaultState();
this.tracingCategories = [
'disabled-by-default-v8.cpu_profile',
'disabled-by-default-v8.cpu_profiler',
'disabled-by-default-v8.cpu_profiler.hires',
'disabled-by-default-devtools.timeline.frame',
'disabled-by-default-devtools.timeline',
'disabled-by-default-devtools.timeline.inputs',
'disabled-by-default-devtools.timeline.stack',
'disabled-by-default-devtools.timeline.invalidationTracking',
'disabled-by-default-layout_shift.debug',
'disabled-by-default-cc.debug.scheduler.frames',
'disabled-by-default-blink.debug.display_lock',
];
}
getName = () => DataCollectorName.CDP;
private resetState = async () => {
if (this.state.client) {
await this.state.client.close();
}
this.state = this.getDefaultState();
};
private getDefaultState = () => ({
traceEvents: [],
});
// workaround for type declaration issues in cdp lib
private asApis = (
client: CDP.Client
): {
Profiler: ProtocolProxyApi.ProfilerApi;
Page: ProtocolProxyApi.PageApi;
Tracing: ProtocolProxyApi.TracingApi;
} => client;
private getClientApis = async () => this.asApis(await this.getClient());
private getClient = async () => {
if (this.state.client) {
return this.state.client;
}
const client = await CDP({ port: this.deps.port });
const { Profiler, Page } = this.asApis(client);
await Promise.all([Page.enable(), Profiler.enable(), Profiler.setSamplingInterval({ interval: 100 })]);
this.state.client = client;
return client;
};
start: DataCollector['start'] = async ({ id }) => {
if (this.state.tracingPromise) {
throw new Error(`collection in progress - can't start another one! ${id}`);
}
const { Tracing, Profiler } = await this.getClientApis();
await Promise.all([
Tracing.start({
bufferUsageReportingInterval: 1000,
traceConfig: {
includedCategories: this.tracingCategories,
},
}),
Profiler.start(),
]);
Tracing.on('dataCollected', ({ value: events }) => {
this.state.traceEvents.push(...events);
});
let resolveFn: (data: CollectedData) => void;
this.state.tracingPromise = new Promise<CollectedData>((resolve) => {
resolveFn = resolve;
});
Tracing.on('tracingComplete', ({ dataLossOccurred }) => {
const t = new Tracelib(this.state.traceEvents);
const eventCounts = countBy(this.state.traceEvents, (ev) => ev.name);
const fps = t.getFPS();
resolveFn({
eventCounts,
fps: mean(fps.values),
tracingDataLoss: dataLossOccurred ? 1 : 0,
warnings: t.getWarningCounts(),
});
});
};
stop: DataCollector['stop'] = async (req) => {
if (!this.state.tracingPromise) {
throw new Error(`collection was never started - there is nothing to stop!`);
}
const { Tracing, Profiler } = await this.getClientApis();
// TODO: capture profiler data
const [, , traceData] = await Promise.all([Profiler.stop(), Tracing.end(), this.state.tracingPromise]);
await this.resetState();
return traceData;
};
close: DataCollector['close'] = async () => {
await this.resetState();
};
}
@@ -0,0 +1,14 @@
export type CollectedData = Record<string, unknown>;
export enum DataCollectorName {
CDP = 'CDP',
}
type DataCollectorRequest = { id: string };
export type DataCollector<T extends CollectedData = CollectedData> = {
start: (input: DataCollectorRequest) => Promise<void>;
stop: (input: DataCollectorRequest) => Promise<T>;
getName: () => DataCollectorName;
close: () => Promise<void>;
};
@@ -0,0 +1,138 @@
import { CollectedData, DataCollectorName } from './DataCollector';
import { fromPairs } from 'lodash';
type Stats = {
sum: number;
min: number;
max: number;
count: number;
avg: number;
time: number;
};
export enum MeasurementName {
DataRenderDelay = 'DataRenderDelay',
}
type LivePerformanceAppStats = Record<MeasurementName, Stats[]>;
const isLivePerformanceAppStats = (data: CollectedData[]): data is LivePerformanceAppStats[] =>
data.some((st) => {
const stat = st?.[MeasurementName.DataRenderDelay];
return Array.isArray(stat) && Boolean(stat?.length);
});
type FormattedStats = {
total: {
count: number[];
avg: number[];
};
lastInterval: {
avg: number[];
min: number[];
max: number[];
count: number[];
};
};
export const formatAppStats = (allStats: CollectedData[]) => {
if (!isLivePerformanceAppStats(allStats)) {
return {};
}
const names = Object.keys(MeasurementName) as MeasurementName[];
return fromPairs(
names.map((name) => {
const statsForMeasurement = allStats.map((s) => s[name]);
const res: FormattedStats = {
total: {
count: [],
avg: [],
},
lastInterval: {
avg: [],
min: [],
max: [],
count: [],
},
};
statsForMeasurement.forEach((s) => {
const total = s.reduce(
(prev, next) => {
prev.count += next.count;
prev.avg += next.avg;
return prev;
},
{ count: 0, avg: 0 }
);
res.total.count.push(Math.round(total.count));
res.total.avg.push(Math.round(total.avg / s.length));
const lastInterval = s[s.length - 1];
res.lastInterval.avg.push(Math.round(lastInterval?.avg));
res.lastInterval.min.push(Math.round(lastInterval?.min));
res.lastInterval.max.push(Math.round(lastInterval?.max));
res.lastInterval.count.push(Math.round(lastInterval?.count));
});
return [name, res];
})
);
};
type CDPData = {
eventCounts: Record<string, unknown>;
fps: number;
tracingDataLoss: number;
warnings: Record<string, unknown>;
};
const isCDPData = (data: any[]): data is CDPData[] => data.every((d) => typeof d.eventCounts === 'object');
type FormattedCDPData = {
minorGC: number[];
majorGC: number[];
droppedFrames: number[];
fps: number[];
tracingDataLossOccurred: boolean;
longTaskWarnings: number[];
};
const emptyFormattedCDPData = (): FormattedCDPData => ({
minorGC: [],
majorGC: [],
droppedFrames: [],
fps: [],
tracingDataLossOccurred: false,
longTaskWarnings: [],
});
const formatCDPData = (data: any): FormattedCDPData => {
if (!isCDPData(data)) {
return emptyFormattedCDPData();
}
return data.reduce((acc, next) => {
acc.majorGC.push((next.eventCounts.MajorGC as number) ?? 0);
acc.minorGC.push((next.eventCounts.MinorGC as number) ?? 0);
acc.fps.push(Math.round(next.fps) ?? 0);
acc.tracingDataLossOccurred = acc.tracingDataLossOccurred || Boolean(next.tracingDataLoss);
acc.droppedFrames.push((next.eventCounts.DroppedFrame as number) ?? 0);
acc.longTaskWarnings.push((next.warnings.LongTask as number) ?? 0);
return acc;
}, emptyFormattedCDPData());
};
export const formatResults = (
results: Array<{ appStats: CollectedData; collectorsData: CollectedData }>
): CollectedData => {
return {
...formatAppStats(results.map(({ appStats }) => appStats)),
...formatCDPData(results.map(({ collectorsData }) => collectorsData[DataCollectorName.CDP])),
__raw: results,
};
};
@@ -0,0 +1,87 @@
import { CollectedData, DataCollector } from './DataCollector';
import { CDPDataCollector } from './CDPDataCollector';
import { fromPairs } from 'lodash';
import fs from 'fs';
import { formatResults } from './formatting';
const remoteDebuggingPortOptionPrefix = '--remote-debugging-port=';
const getOrAddRemoteDebuggingPort = (args: string[]) => {
const existing = args.find((arg) => arg.startsWith(remoteDebuggingPortOptionPrefix));
if (existing) {
return Number(existing.substring(remoteDebuggingPortOptionPrefix.length));
}
const port = 40000 + Math.round(Math.random() * 25000);
args.push(`${remoteDebuggingPortOptionPrefix}${port}`);
return port;
};
let collectors: DataCollector[] = [];
let results: Array<{ appStats: CollectedData; collectorsData: CollectedData }> = [];
const startBenchmarking = async ({ testName }: { testName: string }) => {
await Promise.all(collectors.map((coll) => coll.start({ id: testName })));
return true;
};
const stopBenchmarking = async ({ testName, appStats }: { testName: string; appStats: CollectedData }) => {
const data = await Promise.all(collectors.map(async (coll) => [coll.getName(), await coll.stop({ id: testName })]));
results.push({
collectorsData: fromPairs(data),
appStats: appStats,
});
return true;
};
const afterRun = async () => {
await Promise.all(collectors.map((coll) => coll.close()));
collectors = [];
results = [];
};
const afterSpec = (resultsFolder: string) => async (spec: { name: string }) => {
fs.writeFileSync(`${resultsFolder}/${spec.name}-${Date.now()}.json`, JSON.stringify(formatResults(results), null, 2));
results = [];
};
export const initialize: Cypress.PluginConfig = (on, config) => {
const resultsFolder = config.env['BENCHMARK_PLUGIN_RESULTS_FOLDER'];
if (!fs.existsSync(resultsFolder)) {
fs.mkdirSync(resultsFolder, { recursive: true });
console.log(`Created folder for benchmark results ${resultsFolder}`);
}
on('before:browser:launch', async (browser, options) => {
if (browser.family !== 'chromium' || browser.name === 'electron') {
throw new Error('benchmarking plugin requires chrome');
}
const { args } = options;
const port = getOrAddRemoteDebuggingPort(args);
collectors.push(new CDPDataCollector({ port }));
args.push('--start-fullscreen');
console.log(
`initialized benchmarking plugin with ${collectors.length} collectors: ${collectors
.map((col) => col.getName())
.join(', ')}`
);
return options;
});
on('task', {
startBenchmarking,
stopBenchmarking,
});
on('after:run', afterRun);
on('after:spec', afterSpec(resultsFolder));
};
@@ -0,0 +1,15 @@
type TraceEvent = {
name: string;
};
declare class Tracelib {
constructor(private events: TraceEvent[]) {}
getFPS: () => { times: number[]; values: number[] };
getWarningCounts: () => Record<string, number>;
}
declare module 'tracelib' {
export = Tracelib;
export { TraceEvent };
}