|
| 1 | +const fs = require('node:fs/promises'); |
| 2 | +const { setTimeout: delay } = require('node:timers/promises'); |
| 3 | +const path = require('node:path'); |
| 4 | +const { spawn } = require('node:child_process'); |
| 5 | +const assert = require('node:assert'); |
| 6 | +const autocannon = require('autocannon'); |
| 7 | + |
| 8 | +const runner = { |
| 9 | + autocannon: (opts) => { |
| 10 | + return autocannon({ |
| 11 | + url: `http://localhost:${opts.http.serverPort}`, |
| 12 | + connections: 100, |
| 13 | + pipelining: 1, |
| 14 | + duration: 10 * opts.http.routes.length, |
| 15 | + requests: opts.http.routes, |
| 16 | + }) |
| 17 | + }, |
| 18 | +} |
| 19 | + |
| 20 | +const parser = { |
| 21 | + autocannon: (settings, result) => { |
| 22 | + return { |
| 23 | + name: settings.name, |
| 24 | + method: 'autocannon', |
| 25 | + http: { |
| 26 | + totalReq: asNumber(result.requests), |
| 27 | + duration: result.duration, |
| 28 | + errors: result.errors, |
| 29 | + } |
| 30 | + }; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +const ALLOWED_BENCHMARKER = ['autocannon', 'benchmarkjs']; |
| 35 | + |
| 36 | +function asNumber (stat) { |
| 37 | + const result = Object.create(null) |
| 38 | + for (const k of Object.keys(stat)) { |
| 39 | + result[k] = stat[k].toLocaleString(undefined, { |
| 40 | + // to show all digits |
| 41 | + maximumFractionDigits: 20 |
| 42 | + }) |
| 43 | + } |
| 44 | + return result |
| 45 | +} |
| 46 | + |
| 47 | +function spawnServer(settings) { |
| 48 | + const server = spawn( |
| 49 | + process.execPath, |
| 50 | + [settings.http.server], |
| 51 | + { stdio: 'inherit' }, |
| 52 | + ); |
| 53 | + return server; |
| 54 | +} |
| 55 | + |
| 56 | +async function runBenchmark(settings) { |
| 57 | + assert.ok(settings.http.server, 'HTTP Benchmark must have a server to be spawned'); |
| 58 | + assert.ok(ALLOWED_BENCHMARKER.includes(settings.benchmarker), 'Invalid settings.benchmarker'); |
| 59 | + |
| 60 | + let server = undefined; |
| 61 | + if (settings.type === 'http') { |
| 62 | + server = spawnServer(settings); |
| 63 | + // TODO: replace this workaround to use IPC to know when server is up |
| 64 | + await delay(1000); |
| 65 | + } |
| 66 | + |
| 67 | + const benchRunner = runner[settings.benchmarker]; |
| 68 | + const benchParser = parser[settings.benchmarker]; |
| 69 | + const results = await benchRunner(settings); |
| 70 | + if (server) { |
| 71 | + server.kill('SIGINT'); |
| 72 | + } |
| 73 | + return benchParser(settings, results); |
| 74 | +} |
| 75 | + |
| 76 | +async function main() { |
| 77 | + const files = await fs.readdir(path.join(__dirname, './src')); |
| 78 | + for (const file of files) { |
| 79 | + if (file.match(/.*-benchmark\.js$/)) { |
| 80 | + const bench = require(path.join(__dirname, './src/', file)); |
| 81 | + console.log(bench.name, 'results', await runBenchmark(bench)); |
| 82 | + } |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +main(); |
0 commit comments