summaryrefslogtreecommitdiff
path: root/preact/benches/scripts/deopts.js
blob: 990a6cc8ba028bb8ba42d5ad23d6cea67b69d649 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import * as path from 'path';
import { mkdir } from 'fs/promises';
import { spawn } from 'child_process';
import { Transform } from 'stream';
import escapeRe from 'escape-string-regexp';
import stripAnsi from 'strip-ansi';
import { pool } from '@kristoferbaxter/async';
import {
	globSrc,
	benchesRoot,
	getPkgBinPath,
	resultsPath,
	IS_CI
} from './utils.js';
import { generateConfig } from './config.js';
import { defaultBenchOptions } from './bench.js';

export const defaultDeoptsOptions = {
	framework: 'preact-local',
	timeout: 5,
	open: IS_CI ? false : true
};

const getResultDir = (benchmark, framework) =>
	resultsPath('v8-deopt-viewer', benchmark, framework);

/**
 * @param {string} pkgName
 * @param {string[]} args
 * @param {"pipe" | "inherit"} [stdio]
 * @returns {Promise<import('child_process').ChildProcess>}
 */
async function runPackage(pkgName, args, stdio) {
	const binPath = await getPkgBinPath(pkgName);
	args.unshift(binPath);

	return spawn(process.execPath, args, { stdio });
}

/**
 * @param {import('child_process').ChildProcess} childProcess
 */
async function onExit(childProcess) {
	return new Promise((resolve, reject) => {
		childProcess.once('exit', (code, signal) => {
			if (code === 0 || signal == 'SIGINT') {
				resolve();
			} else {
				reject(new Error('Exit with error code: ' + code));
			}
		});

		childProcess.once('error', err => {
			reject(err);
		});
	});
}

/**
 * @typedef {{ benchName: string; framework: string; url: string; }} TachURL
 * @param {import('child_process').ChildProcess} tachProcess
 * @param {import('./config').ConfigData} tachConfig
 * @param {number} timeoutMs
 * @returns {Promise<TachURL[]>}
 */
async function getTachometerURLs(tachProcess, tachConfig, timeoutMs = 60e3) {
	return new Promise(async (resolve, reject) => {
		let timeout;
		if (timeoutMs > 0) {
			timeout = setTimeout(() => {
				reject(
					new Error(
						'Timed out waiting for Tachometer to get set up. Did it output a URL?'
					)
				);
			}, timeoutMs);
		}

		// Look for lines like:
		// many_updates [@preact]
		// http://127.0.0.1:56536/src/many_updates.html
		const benchesToSearch = tachConfig.config.benchmarks.map(bench => ({
			benchName: bench.name,
			framework: bench.packageVersions.label,
			regex: new RegExp(
				escapeRe(`${bench.name} [@${bench.packageVersions.label}]`) +
					`\\s+(http:\\/\\/.*)`,
				'im'
			),
			url: null
		}));

		/** @type {TachURL[]} */
		const results = [];
		let output = '';
		tachProcess.stdout.on('data', function onStdOutChunk(chunk) {
			output += stripAnsi(chunk.toString('utf8'));

			for (let bench of benchesToSearch) {
				if (bench.url) {
					continue;
				}

				let match = output.match(bench.regex);
				if (match) {
					bench.url = match[1];
					results.push(bench);
				}
			}

			if (results.length == benchesToSearch.length) {
				// All URLs found, removeEventListener
				tachProcess.off('data', onStdOutChunk);

				clearTimeout(timeout);
				resolve(results);
			}
		});
	});
}

function createPrefixTransform(prefix) {
	return new Transform({
		transform(chunk, encoding, callback) {
			try {
				// @ts-ignore
				chunk = encoding == 'buffer' ? chunk.toString() : chunk;
				const lines = chunk.split('\n');

				for (let line of lines) {
					if (line) {
						line = `[${prefix}] ${line}`;
						this.push(line + '\n');
					}
				}

				callback();
			} catch (error) {
				return callback(error);
			}
		}
	});
}

/**
 * @param {TachURL} tachURL
 * @param {DeoptOptions} options
 */
async function runV8DeoptViewer(tachURL, options) {
	const deoptOutputDir = getResultDir(tachURL.benchName, tachURL.framework);
	await mkdir(deoptOutputDir, { recursive: true });

	const deoptArgs = [
		tachURL.url,
		'-o',
		deoptOutputDir,
		'-t',
		(options.timeout * 1000).toString()
	];

	if (options.open) {
		deoptArgs.push('--open');
	}

	const deoptProcess = await runPackage('v8-deopt-viewer', deoptArgs);
	deoptProcess.stdout
		.pipe(createPrefixTransform(tachURL.framework))
		.pipe(process.stdout);
	deoptProcess.stderr
		.pipe(createPrefixTransform(tachURL.framework))
		.pipe(process.stderr);

	await onExit(deoptProcess);
}

/**
 * @param {string} benchGlob
 * @param {DeoptOptions} options
 */
export async function runDeopts(benchGlob, options) {
	// TODO:
	// * Handle multiple benchmarks

	const frameworks = options.framework;
	if (!benchGlob) {
		benchGlob = 'many_updates.html';
	}

	const benchesToRun = await globSrc(benchGlob);
	if (benchesToRun.length > 1) {
		console.error('Matched multiple benchmarks. Only running the first one.');
	}

	const benchPath = benchesRoot('src', benchesToRun[0]);
	const tachConfig = await generateConfig(benchPath, {
		...defaultBenchOptions,
		...defaultDeoptsOptions,
		framework: frameworks
	});

	console.log('Benchmarks running:', benchPath);
	console.log('Frameworks running:', frameworks);

	/** @type {Promise<void>} */
	let onTachExit;
	/** @type {import('child_process').ChildProcess} */
	let tachProcess;
	try {
		// Run tachometer in manual mode with generated config
		const tachArgs = ['--config', tachConfig.configPath, '--manual'];
		tachProcess = await runPackage('tachometer', tachArgs);
		tachProcess.stdout.pipe(process.stdout);
		tachProcess.stderr.pipe(process.stderr);
		onTachExit = onExit(tachProcess);

		// Parse URL from tachometer stdout
		const tachURLs = await getTachometerURLs(tachProcess, tachConfig);

		// Run v8-deopt-viewer against tachometer URL
		console.log();
		await pool(tachURLs, tachURL =>
			runV8DeoptViewer(tachURL, {
				...options,
				open: options.open && tachURLs.length == 1
			})
		);

		if (tachURLs.length > 1) {
			const rootResultDir = getResultDir('', '');
			console.log(`\nOpen your browser to ${rootResultDir} to view results.`);

			if (options.open) {
				// TODO: Figure out how to open a directory in the user's default browser
			}
		}
	} finally {
		if (tachProcess) {
			tachProcess.kill('SIGINT');

			// Log a message is Tachometer takes a while to close
			let logMsg = () => console.log('Waiting for Tachometer to exit...');
			let t = setTimeout(logMsg, 2e3);

			try {
				await onTachExit;
			} catch (error) {
				console.error('Error waiting for Tachometer to exit:', error);
			} finally {
				clearTimeout(t);
			}
		}
	}
}