-
Notifications
You must be signed in to change notification settings - Fork 38
/
bench.ts
374 lines (299 loc) · 8.16 KB
/
bench.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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import {
readdirSync,
mkdirSync,
existsSync,
lstatSync,
readFileSync,
writeFileSync
} from 'fs'
import killPort from 'kill-port'
import { $, pathToFileURL } from 'bun'
const whitelists = <string[]>['node/elysia', 'node/express', 'node/fastify', 'node/h3', 'node/hono']
// ? Not working
const blacklists = [
// Not booting up in test
'node/adonis/index',
// Not setting content-type header for some reason
'node/nest/index',
// 'Not booting up in test'
'node/hapi',
// Body: Result not match
'bun/xirelta',
// Crash
'bun/bagel',
// Crash
'bun/bunrest',
// Doesn't work properly
'bun/colston',
// Crash on 0.6.2
'bun/zarf',
// Crash due to invalid npm version requirement of uWebSockets
'deno/byte',
// Crash
'bun/fastify',
// failed to parse body in benchmark
'bun/byte'
] as const
const time = 10
const commands = [
`bombardier --fasthttp -c 500 -d ${time}s http://127.0.0.1:3000/`,
`bombardier --fasthttp -c 500 -d ${time}s http://127.0.0.1:3000/id/1?name=bun`,
`bombardier --fasthttp -c 500 -d ${time}s -m POST -H 'Content-Type:application/json' -f ./scripts/body.json http://127.0.0.1:3000/json`
] as const
const runtimeCommand = {
node: 'node',
deno: 'deno run --allow-net --allow-env',
bun: 'bun'
} as const
const catchNumber = /Reqs\/sec\s+(\d+[.|,]\d+)/m
const format = (value: string | number) =>
Intl.NumberFormat('en-US').format(+value)
const sleep = (s = 1) => new Promise((resolve) => setTimeout(resolve, s * 1000))
const secToMin = (seconds: number) =>
Math.floor(seconds / 60) +
':' +
(seconds % 60 < 10 ? '0' : '') +
(seconds % 60)
// Fetch with retry
const retryFetch = (
url: string,
options?: RequestInit,
time = 0,
resolveEnd?: Function,
rejectEnd?: Function
) => {
return new Promise<Response>((resolve, reject) => {
fetch(url, options)
.then((a) => {
if (resolveEnd) resolveEnd(a)
resolve(a)
})
.catch((e) => {
if (time > 7) {
if (rejectEnd) rejectEnd(e)
return reject(e)
}
setTimeout(
() => retryFetch(url, options, time + 1, resolve, reject),
200
)
})
})
}
const test = async () => {
try {
const index = await retryFetch('http://127.0.0.1:3000/')
if ((await index.text()) !== 'Hi')
throw new Error('Index: Result not match')
if (!index.headers.get('Content-Type')?.includes('text/plain'))
throw new Error('Index: Content-Type not match')
const query = await retryFetch('http://127.0.0.1:3000/id/1?name=bun')
if ((await query.text()) !== '1 bun')
throw new Error('Query: Result not match')
if (!query.headers.get('Content-Type')?.includes('text/plain'))
throw new Error('Query: Content-Type not match')
if (!query.headers.get('X-Powered-By')?.includes('benchmark'))
throw new Error('Query: X-Powered-By not match')
const body = await retryFetch('http://127.0.0.1:3000/json', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
hello: 'world'
})
})
if ((await body.text()) !== JSON.stringify({ hello: 'world' }))
throw new Error('Body: Result not match')
if (!body.headers.get('Content-Type')?.includes('application/json'))
throw new Error('Body: Content-Type not match')
} catch (error) {
throw error
}
}
const spawn = (target: string, title = true) => {
let [runtime, framework, index] = target.split('/') as [
keyof typeof runtimeCommand,
string,
string
]
if (index) framework += '/index'
const name = framework.replace('/index', '')
if (title) {
console.log('\n', name)
console.log(' >', runtime, framework, '\n')
}
const file = existsSync(`./src/${runtime}/${framework}.ts`)
? `src/${runtime}/${framework}.ts`
: `src/${runtime}/${framework}.js`
const server = Bun.spawn({
cmd: [...runtimeCommand[runtime].split(" "), file],
env: {
...Bun.env,
NODE_ENV: 'production'
}
})
return async () => {
await server.kill()
await sleep(0.3)
try {
await fetch('http://127.0.0.1:3000')
await sleep(0.6)
await fetch('http://127.0.0.1:3000')
await killPort(3000)
} catch {
// Empty
}
}
}
try {
if (lstatSync('results').isDirectory()) rimraf.sync('results')
} catch {}
await Bun.$`rm -rf ./results`
mkdirSync('results')
writeFileSync('results/results.md', '')
const resultFile = Bun.file('results/results.md')
const result = resultFile.writer()
const main = async () => {
try {
await fetch('http://127.0.0.1:3000')
await killPort(3000)
} catch {
// Empty
}
const runtimes = <string[]>[]
let frameworks = readdirSync('src')
.flatMap((runtime) => {
if (!lstatSync(`src/${runtime}`).isDirectory()) return
if (!existsSync(`results/${runtime}`))
mkdirSync(`results/${runtime}`)
return readdirSync(`src/${runtime}`)
.filter(
(a) =>
a.endsWith('.ts') ||
a.endsWith('.js') ||
!a.includes('.')
)
.map((a) =>
a.includes('.')
? `${runtime}/` + a.replace(/.(j|t)s$/, '')
: `${runtime}/${a}/index`
)
.filter(
(a) =>
!blacklists.includes(a as (typeof blacklists)[number])
)
})
.filter((x) => x)
.sort()
// Overwrite test here
frameworks = whitelists?.length ? whitelists : frameworks
console.log(`${frameworks.length} frameworks`)
for (const framework of frameworks) console.log(`- ${framework}`)
console.log('\nTest:')
for (const target of frameworks) {
const kill = spawn(target!, false)
let [runtime, framework] = target!.split('/')
await sleep(0.1)
if (runtimes.includes(runtime)) {
const folder = `results/${runtime}`
if (!lstatSync(folder).isDirectory()) rimraf(folder)
}
try {
const kill = await test()
console.log(`✅ ${framework} (${runtime})`)
} catch (error) {
console.log(`❌ ${framework} (${runtime})`)
console.log(' ', (error as Error)?.message || error)
frameworks.splice(frameworks.indexOf(target!), 1)
} finally {
await kill()
}
}
const estimateTime = frameworks.length * (commands.length * time + 1)
console.log()
console.log(`${frameworks.length} frameworks`)
for (const framework of frameworks) console.log(`- ${framework}`)
console.log(`\nEstimate time: ${secToMin(estimateTime)} min`)
// process.exit()
result.write(
`
| Framework | Runtime | Average | Ping | Query | Body |
| ---------------- | ------- | ------- | ---------- | ---------- | ---------- |
`
)
for (const target of frameworks) {
const kill = spawn(target!)
let [runtime, framework, index] = target!.split('/') as [
keyof typeof runtimeCommand,
string,
string
]
const name = framework.replace('/index', '')
const frameworkResultFile = Bun.file(`results/${runtime}/${name}.txt`)
const frameworkResult = frameworkResultFile.writer()
result.write(`| ${name} | ${runtime} `)
// Wait .3 second for server to bootup
await sleep(0.4)
let content = ''
const total = []
for (const command of commands) {
frameworkResult.write(`${command}\n`)
console.log(command)
const res = await Bun.spawn({
cmd: command.split(' '),
env: Bun.env
})
const stdout = await new Response(res.stdout).text()
console.log(stdout)
const results = catchNumber.exec(stdout)
if (!results?.[1]) continue
content += `| ${format(results[1])} `
total.push(toNumber(results[1]))
frameworkResult.write(results + '\n')
}
content =
`| ${format(
total.reduce((a, b) => +a + +b, 0) / commands.length
)} ` +
content +
'|\n'
result.write(content)
await result.flush()
await kill()
}
}
const toNumber = (a: string) => +a.replaceAll(',', '')
const arrange = () => {
const table = readFileSync('results/results.md', {
encoding: 'utf-8'
})
const orders = []
const [title, divider, ...rows] = table.split('\n')
for (const row of rows) {
const data = row
.replace(/\ /g, '')
.split('|')
.filter((a) => a)
if (data.length !== commands.length + 3) continue
const [name, runtime, total] = data
orders.push({
name,
runtime,
total: toNumber(total),
row
})
}
const content = [
title,
divider,
...orders.sort((a, b) => b.total - a.total).map((a) => a.row)
].join('\n')
console.log(content)
writeFileSync('results/results.md', content)
process.exit(0)
}
process.on('beforeExit', async () => {
await killPort(3000)
})
main().then(arrange)