Debian Codegraph @

vendor/wikimedia/parsoid/bin/benchmark.js

raw
1 'use strict';
2
3 const fs = require('fs');
4 const yaml = require('js-yaml');
5 require('../core-upgrade.js');
6 const Promise = require('../lib/utils/promise.js');
7 const request = Promise.promisify(require('request'), true);
8
9 // Some semi-arbitrary list of titles
10 const sampleTitles = [
11 { wiki: 'enwiki', title: 'Main_Page', revid: 917272779 },
12 { wiki: 'enwiki', title: 'Skating', revid: 921619251 },
13 { wiki: 'enwiki', title: 'Hospet', revid: 913341503 },
14 { wiki: 'enwiki', title: 'Hampi', revid: 921528573 },
15 { wiki: 'enwiki', title: 'Berlin', revid: 921687210 },
16 { wiki: 'enwiki', title: 'Barack_Obama', revid: 921752860 },
17 { wiki: 'enwiki', title: 'Max_Planck_Institute_for_Physics', revid: 921775647 },
18 { wiki: 'enwiki', title: 'Architects & Engineers for 9/11 Truth', revid: 921775875 },
19 { wiki: 'itwiki', title: 'Luna', revid: 108284424 },
20 { wiki: 'itwiki', title: 'Metro', revid: 108262882 },
21 { wiki: 'frwiki', title: 'Mulholland_Drive', revid: 149562710 },
22 { wiki: 'frwiki', title: 'Metro', revid: 108262882 },
23 { wiki: 'frwiki', title: 'François_de_La_Tour_du_Pin', revid: 163623032 },
24 { wiki: 'frwiki', title: 'Jason_Bateman', revid: 163623075 },
25 { wiki: 'jawiki', title: '人類学', revid: 74657621 },
26 { wiki: 'jawiki', title: 'パレオ・インディアン', revid: 70817191 },
27 { wiki: 'mediawiki', title: 'Parsoid', revid: 3453996 },
28 { wiki: 'mediawiki', title: 'RESTBase', revid: 2962542 },
29 { wiki: 'mediawiki', title: 'VisualEditor', revid: 3408339 },
30 { wiki: 'dewikivoyage', title: 'Bengaluru', revid: 1224432 },
31 { wiki: 'dewikivoyage', title: 'Kopenhagen', revid: 1240570 },
32 { wiki: 'dewikivoyage', title: 'Stuttgart', revid: 1226146 },
33 { wiki: 'hiwiktionary', title: 'परिवर्णी', revid: 467616 },
34 { wiki: 'hiwiktionary', title: 'चीन', revid: 456648 },
35 { wiki: 'knwikisource', title: 'ಪಂಪಭಾರತ_ಪ್ರಥಮಾಶ್ವಾಸಂ', revid: 170413 },
36 ];
37
38 let outerConfig = {
39 // File with \n-separated json blobs with at least (wiki, title, oldId / revid) properties
40 // If domain is provided, it is used, if not wiki is treated as a prefix
41 // All other properties are ignored.
42 // If this property is null, sampleTitles above is used
43 testTitles: null, // '/tmp/logs',
44 mode: 'wt2html',
45 jsServer: {
46 baseURI: 'http://localhost:8142',
47 proxy: '',
48 },
49 phpServer: {
50 baseURI: 'http://DOMAIN/w/rest.php',
51 proxy: '', // 'http://parsoidtest1001.eqiad.wmnet:80',
52 },
53 maxOutstanding: 4,
54 maxRequests: 25,
55 verbose: true
56 };
57
58 const state = {
59 times: [],
60 numPendingRequests: 0,
61 outStanding: 0
62 };
63
64 function genFullUrls(config, domain, title, revid) {
65 let initRestFragment, restFragment;
66
67 switch (config.mode || 'wt2html') {
68 case 'wt2html':
69 restFragment = `${ domain }/v3/page/html/${ encodeURIComponent(title) }/${ revid }`;
70 break;
71 case 'wt2pb':
72 restFragment = `${ domain }/v3/page/pagebundle/${ encodeURIComponent(title) }/${ revid }`;
73 break;
74 case 'html2wt':
75 initRestFragment = `${ domain }/v3/page/html/${ encodeURIComponent(title) }/${ revid }`;
76 restFragment = `${ domain }/v3/transform/html/to/wikitext/${ encodeURIComponent(title) }/${ revid }`;
77 break;
78 case 'pb2wt':
79 initRestFragment = `${ domain }/v3/page/pagebundle/${ encodeURIComponent(title) }/${ revid }`;
80 restFragment = `${ domain }/v3/transform/pagebundle/to/wikitext/${ encodeURIComponent(title) }/${ revid }`;
81 break;
82 default:
83 console.log("Mode " + config.mode + " is not supported right now.");
84 process.exit(-1);
85 }
86 return {
87 js : `${ config.jsServer.baseURI }/${ restFragment }`,
88 php: `${ config.phpServer.baseURI.replace(/DOMAIN/, domain) }/${ restFragment }`,
89 init: initRestFragment ? `${ config.phpServer.baseURI.replace(/DOMAIN/, domain) }/${ initRestFragment }` : null,
90 jsTime: null,
91 phpTime: null,
92 };
93 }
94
95 function prefixToDomain(prefix) {
96 if (prefix === 'commonswiki') {
97 return 'commons.wikimedia.org';
98 }
99
100 if (prefix === 'metawiki') {
101 return 'meta.wikimedia.org';
102 }
103
104 if (prefix === 'wikidatawiki') {
105 return 'wikidata.org';
106 }
107
108 if (prefix === 'mediawiki' || prefix === 'mediawikiwiki') {
109 return 'www.mediawiki.org';
110 }
111
112 if (/wiki$/.test(prefix)) {
113 return prefix.replace(/wiki$/, '.wikipedia.org');
114 }
115
116 const project = [ 'wiktionary', 'wikisource', 'wikivoyage', 'wikibooks', 'wikiquote', 'wikinews', 'wikiversity' ].find(function(p) {
117 return prefix.endsWith(p);
118 });
119
120 return project ? `${ prefix.slice(0, Math.max(0, prefix.length - project.length)) }.${ project }.org` : null;
121 }
122
123 function contentFileName(url) {
124 // Hacky
125 const suffix = /.*v3\/(page|transform)\/pagebundle/.test(url) ? 'pb.json' : 'html';
126 const wiki = url.replace(/\/v3\/.*/, '').replace(/.*\//, '');
127 return '/tmp/' + wiki + "." + url.replace(/.*\//, '') + ".php." + suffix;
128 }
129
130 function fetchPageContent(url) {
131 const fileName = contentFileName(url);
132 return fs.existsSync(fileName) ? fs.readFileSync(fileName, 'utf8') : null;
133 }
134
135 function issueRequest(opts, url, finalizer) {
136 const config = opts.config;
137 const fromWT = opts.mode === 'wt2html' || opts.mode === 'wt2pb';
138 const httpOptions = {
139 method: fromWT ? 'GET' : 'POST',
140 headers: { 'User-Agent': 'Parsoid-Test' },
141 proxy: opts.proxy,
142 uri: fromWT ? url : url.replace(/\/\d+$/, ''), // strip oldid to suppress selser
143 };
144
145 if (!fromWT) {
146 httpOptions.headers['Content-Type'] = 'application/json';
147 const content = fetchPageContent(url);
148 if (!content) {
149 console.log("Aborting request! Content not found @ " + contentFileName(url));
150 // Abort
151 state.numPendingRequests--;
152 if (state.numPendingRequests === 0 && state.outStanding === 0) {
153 console.log('resolving after abort');
154 finalizer();
155 }
156 return;
157 }
158
159 if (opts.mode === 'pb2wt') {
160 const pb = JSON.parse(content);
161 httpOptions.body = {
162 html: pb.html.body,
163 original : {
164 'data-parsoid': pb['data-parsoid']
165 // non-selser mode, so don't need wikitext
166 },
167 };
168 } else {
169 httpOptions.body = {
170 'html': content
171 };
172 }
173 httpOptions.body = JSON.stringify(httpOptions.body);
174 }
175
176 const reqId = state.numPendingRequests;
177 if (config.verbose) {
178 console.log(`--> ID=${ reqId }; URL:${ url }; PENDING=${ state.numPendingRequests }; OUTSTANDING=${ state.outStanding }`);
179 }
180 state.numPendingRequests--;
181 state.outStanding++;
182 const startTime = process.hrtime();
183 return request(httpOptions)
184 .catch(function(error) {
185 console.log("errrorr!" + error);
186 })
187 .then(function(ret) {
188 state.outStanding--;
189 if (opts.type === 'init') {
190 fs.writeFileSync(contentFileName(url), ret[1]);
191 if (state.numPendingRequests === 0 && state.outStanding === 0) {
192 finalizer();
193 }
194 } else {
195 const endTime = process.hrtime();
196 const reqTime = Math.round((endTime[0] * 1e9 + endTime[1]) / 1e6 - (startTime[0] * 1e9 + startTime[1]) / 1e6);
197 if (config.verbose) {
198 console.log(`<-- ID=${ reqId }; URL:${ url }; TIME=${ reqTime }; STATUS: ${ ret[0].statusCode }; LEN: ${ ret[1].length }`);
199 }
200 if (!opts.results[reqId]) {
201 opts.results[reqId] = {
202 url: url,
203 };
204 }
205 opts.results[reqId][opts.type + 'Time'] = reqTime;
206 state.times.push(reqTime);
207 if (state.numPendingRequests === 0 && state.outStanding === 0) {
208 const res = state.times.reduce((stats, n) => {
209 stats.sum += n;
210 stats.min = n < stats.min ? n : stats.min;
211 stats.max = n > stats.max ? n : stats.max;
212 return stats;
213 }, { sum: 0, min: 1000000, max: 0 });
214 res.avg = res.sum / state.times.length;
215 res.median = state.times.sort((a, b) => a - b)[Math.floor(state.times.length / 2)];
216 console.log(`\n${ opts.type.toUpperCase() } STATS: ${ JSON.stringify(res) }`);
217 finalizer();
218 }
219 }
220 })
221 .catch(function(error) {
222 console.log("errrorr!" + error);
223 });
224 }
225
226 function computeRandomRequestStream(testUrls, config) {
227 const numReqs = config.maxRequests;
228 const reqs = [];
229 const n = testUrls.length;
230 for (let i = 0; i < numReqs; i++) {
231 // Pick a random url
232 reqs.push(testUrls[Math.floor(Math.random() * n)]);
233 }
234 return reqs;
235 }
236
237 function reset(config) {
238 state.times = [];
239 state.numPendingRequests = config.maxRequests;
240 state.outStanding = 0; // # outstanding reqs
241 }
242
243 function runTests(opts, finalizer) {
244 if (state.numPendingRequests > 0) {
245 if (state.outStanding < opts.config.maxOutstanding) {
246 const url = opts.reqs[opts.reqs.length - state.numPendingRequests][opts.type];
247 if (opts.type === 'js') {
248 opts.proxy = opts.config.jsServer.proxy || '';
249 } else { // 'php' or 'init' For init, content is always fetched from Parsoid/PHP
250 opts.proxy = opts.config.phpServer.proxy || '';
251 }
252 if (opts.type === 'init' && fs.existsSync(contentFileName(url))) {
253 // Content exists. Don't fetch.
254 state.numPendingRequests--;
255 if (state.numPendingRequests === 0 && state.outStanding === 0) {
256 finalizer();
257 return;
258 }
259 } else {
260 issueRequest(opts, url, finalizer);
261 }
262 }
263 setImmediate(() => runTests(opts, finalizer));
264 }
265 }
266
267 // Override default config
268 if (process.argv.length > 2) {
269 outerConfig = yaml.load(fs.readFileSync(process.argv[2], 'utf8'));
270 }
271
272 // CLI overrides config
273 if (process.argv.length > 3) {
274 outerConfig.maxOutstanding = parseInt(process.argv[3], 10);
275 }
276
277 // CLI overrides config
278 if (process.argv.length > 4) {
279 outerConfig.maxRequests = parseInt(process.argv[4], 10);
280 }
281
282 let testUrls;
283 if (outerConfig.testTitles) {
284 // Parse production logs and generate test urls
285 const logs = fs.readFileSync(outerConfig.testTitles, 'utf8');
286 const lines = logs.split(/\n/);
287 testUrls = [];
288 lines.forEach(function(l) {
289 if (l) {
290 const log = JSON.parse(l);
291 const domain = log.domain || prefixToDomain(log.wiki);
292 if (domain) {
293 testUrls.push(genFullUrls(outerConfig, domain, log.title, log.oldId || log.revid));
294 }
295 }
296 });
297 } else {
298 testUrls = [];
299 sampleTitles.forEach(function(t) {
300 testUrls.push(genFullUrls(outerConfig, t.domain || prefixToDomain(t.wiki), t.title, t.revid));
301 });
302 }
303
304 const reqStream = computeRandomRequestStream(testUrls, outerConfig);
305 const opts = {
306 config: outerConfig,
307 reqs: reqStream,
308 results: [],
309 };
310
311 let p;
312 if (/2wt$/.test(outerConfig.mode)) {
313 // Fetch pb / html as necessary and save to disk
314 // so we can run and benchmark pb2wt or html2wt after
315 p = new Promise(function(resolve, reject) {
316 opts.type = 'init';
317 opts.mode = outerConfig.mode === 'pb2wt' ? 'wt2pb' : 'wt2html';
318 console.log("--- Initialization ---");
319 reset(outerConfig);
320 runTests(opts, function() {
321 console.log("--- Initialization done---");
322 resolve();
323 });
324 });
325 } else {
326 p = Promise.resolve();
327 }
328
329 p.then(function() {
330 reset(outerConfig);
331 opts.type = 'js';
332 opts.mode = outerConfig.mode;
333 console.log("\n\n--- JS tests ---");
334 runTests(opts, function() {
335 console.log("\n\n--- PHP tests---");
336 reset(outerConfig);
337 opts.type = 'php';
338 opts.mode = outerConfig.mode;
339 runTests(opts, function() {
340 console.log("\n--- All done---\n");
341 let numJSFaster = 0;
342 let numPHPFaster = 0;
343 opts.results.forEach(function(r) {
344 if (r.jsTime < r.phpTime) {
345 numJSFaster++;
346 console.log(`For ${ r.url }, Parsoid/JS was faster than Parsoid/PHP (${ r.jsTime } vs. ${ r.phpTime })`);
347 } else {
348 numPHPFaster++;
349 }
350 });
351 console.log('\n# of reqs where Parsoid/JS was faster than Parsoid/PHP: ' + numJSFaster);
352 console.log('# of reqs where Parsoid/PHP was faster than Parsoid/JS: ' + numPHPFaster);
353 process.exit(0);
354 });
355 });
356 }).done();