/
index.ts
224 lines (179 loc) · 6.67 KB
/
index.ts
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
import { appendFile, readdir } from 'fs/promises';
import Bun from 'bun';
import data, { rootDir } from './config';
import { Info } from './lib/types';
import { run, parseDefaultArgs, sortResults, find, validate } from './lib/utils';
import { existsSync, mkdirSync, rmSync } from 'fs';
import { render } from 'lib/utils/chart';
import { descript } from 'lib/description';
// Benchmark CLI
const tool = data.cli ||= 'bombardier';
const inTestMode = process.argv[2] === 'test';
// Destination file
const allResultsDir = `${rootDir}/results`,
subResultDir = `${allResultsDir}/main`;
const desFile = `${allResultsDir}/index.md`,
jsonResultFile = `${allResultsDir}/data.json`,
readmeFile = `${rootDir}/README.md`,
templateFile = `${rootDir}/README.template.md`,
debugFile = `${rootDir}/debug.log`;
// Prepare files
if (!inTestMode) {
await Bun.write(desFile, `Bun: ${Bun.version}\n`);
if (existsSync(debugFile)) rmSync(debugFile);
}
// Benchmark results
const results: number[] = [];
// Framework and test URLs
let frameworks = await readdir(`${rootDir}/src`);
if (data.include)
// @ts-ignore
frameworks = frameworks.filter(f => data.include.includes(f));
if (data.exclude)
// @ts-ignore
frameworks = frameworks.filter(f => !data.exclude.includes(f));
// URLs to test and benchmark
const urls = data.tests.map(v => {
const arr: any[] = [v.path, v.method || 'GET'];
if (v.bodyFile)
arr.push(v.bodyFile);
if (v.headers) {
const headerArr: string[] = []
for (const key in v.headers)
headerArr.push('--header', `${key}: ${v.headers[key]}`);
arr.push(headerArr);
}
arr.push(v.name);
return arr;
});
// Run scripts
if (!inTestMode) for (const script of data.scripts) {
const args = [
script.type || 'bun',
`${rootDir}/scripts/${script.file}`
] as [string, string];
console.log(args.join(' '));
Bun.spawnSync(args, {
stdout: 'inherit',
env: {
ROOT: rootDir,
DES: desFile
}
});
}
const failedFramework: string[] = [];
function cleanup(server: Bun.Subprocess) {
// Clean up
server.kill();
Bun.sleepSync(data.boot ?? 5000);
}
let frameworksDescription = '## Frameworks\n';
// Run benchmark
{
data.boot ||= 5000;
// Default arguments parsing
const defaultArgs = parseDefaultArgs(data);
// Run commands
const commands = urls.map(v => {
v = v.slice(0, -1);
const arr = [tool, ...defaultArgs, 'http://localhost:3000' + v[0], '--method', v[1]];
if (v[2])
arr.push('--body-file', v[2]);
if (v[3])
arr.push(...v[3]);
return arr;
});
// Search each framework
for (let i = 0; i < frameworks.length; ++i) {
const resultDir = `${subResultDir}/${frameworks[i]}`;
if (!existsSync(resultDir))
mkdirSync(resultDir);
Bun.gc(true);
const desDir = `${rootDir}/src/${frameworks[i]}`,
info = await find(desDir + '/package.json') as Info;
// Push to description
frameworksDescription += descript(frameworks[i], info);
// Check JS runtime
info.runtime ||= process.execPath;
// Check framework version
if (info.version) {
if (info.version === 'runtime') {
if (info.runtime.endsWith('bun'))
info.version = Bun.version;
if (info.runtime.endsWith('node'))
info.version = Bun.spawnSync([info.runtime, '--version']).stdout.toString().substring(1).replace('\n', '');
}
frameworks[i] += ' ' + info.version;
}
// Spawn process options
const spawnOpts = {
cwd: desDir,
stdout: 'inherit',
env: data.env
} as any;
// Build if a build script exists
if (info.build) Bun.spawnSync(info.build, spawnOpts);
// Start the server command args
info.main ||= 'index.ts';
const args = info.run || [info.runtime, `${desDir}/${info.main}`];
console.log(args.join(' '));
// Boot up
const server = Bun.spawn(args, spawnOpts);
console.log('Booting', frameworks[i] + '...');
Bun.sleepSync(data.boot);
try {
// Validate
console.log('Validating...');
if (!await validate(data.tests)) {
console.log('The server does not pass the tests! Skip to the next one!');
failedFramework.push(frameworks[i]);
cleanup(server);
continue;
}
Bun.gc(true);
Bun.sleepSync(data.boot);
// Only benchmark if not in test mode
if (inTestMode) {
cleanup(server);
continue;
}
// Benchmark
console.log('Benchmarking...');
results.push(...await run(commands as any, resultDir));
} catch (e) {
console.log(frameworks[i], 'Crashed!');
failedFramework.push(frameworks[i]);
await appendFile(debugFile, frameworks[i] + ':\n' + String(e) + '\n\n');
} finally {
if (!server.killed) cleanup(server);
}
}
}
if (inTestMode) {
console.log(frameworksDescription);
process.exit(0);
}
// Sort results
{
if (failedFramework.length > 0) {
console.log(`Frameworks that failed the test: ${failedFramework.join(', ')}.`);
console.log('These frameworks will not be included in the result!');
frameworks = frameworks.filter(v => !failedFramework.includes(v));
} else console.log('All frameworks passed the boot-up test!');
console.log('Sorting results...');
const tableResultString = sortResults(frameworks, urls.length, results),
resultTable = // Prepare table headers
'| Name | Average | '
+ urls.map(v => v.at(-1) ?? `${v[1]} \`${v[0]}\``).join(' | ') + ' |\n| '
// Split headers and results
+ ' :---: |'.repeat(urls.length + 2) + '\n'
// All results
+ tableResultString.full;
// Main result file
appendFile(desFile, resultTable);
// Write asynchronously
Bun.write(readmeFile, await Bun.file(templateFile).text() + '\n' + resultTable + '\n' + frameworksDescription);
Bun.write(jsonResultFile, JSON.stringify(tableResultString.json));
// Render the result chart
render(`${allResultsDir}/chart.png`, tableResultString.json);
}