ci: simplify HTTP benchmark implementation (#4226)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: simplify HTTP benchmark with relative comparison - Move HTTP benchmarking from perf-measures to benchmarks/http-server - Remove octocov integration for HTTP benchmarks - Implement direct GitHub Actions commenting - Consolidate output formatting with structured data - Add Markdown file generation for PR comments 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: use origin/main as default baseline and add git fetch - Change default baseline from 'main' to 'origin/main' for CI compatibility - Add git fetch to ensure remote refs are available - Fixes GitHub Actions error with git checkout main 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * feat: add /benchmark command workflow - Create separate command.yml for PR comment triggers - Remove automatic benchmark execution from ci.yml - Add /benchmark command to trigger HTTP benchmarks on demand - Update README with command usage instructions 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * feat: add permission check for benchmark command - Restrict /benchmark command to users with admin, maintain, or write permissions - Add user permission validation before running benchmark - Fail gracefully with clear error message for unauthorized users 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: revert to automatic benchmark execution on PR - Remove command.yml workflow (no longer needed) - Add HTTP benchmark job back to ci.yml for automatic execution - Reduce default duration from 10s to 5s for faster CI - Update README to reflect automatic execution 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * perf: eliminate build step for faster benchmark execution - Use TypeScript source files directly instead of compiled dist - Remove build requirements from benchmark process - Change log message from "Building" to "Preparing" - Remove package.json copy (not needed for simple imports) - Maintain 10s duration for both local and CI execution This significantly reduces benchmark execution time by skipping the TypeScript compilation step entirely. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: use github.graphql instead of github.rest.graphql - Correct GraphQL API usage for minimizing comments - Fix TypeError in GitHub Actions script 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Claude <noreply@anthropic.com>
Diff stats
9 files+403 added−468 removed
- other:+403 added−468 removed
Provenance
- Commit
b96de9f- Tree
6b96317- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
c43c53f
9 files changed+403 added−468 removed
modified:.github/actions/perf-measures/action.yml-14 removed
37 unmodified lines383940414243444546474849505152534243444546474861495051523 unmodified lines5657585973606137 unmodified lines bun run build bun perf-measures/bundle-check/scripts/check-bundle-size.ts > perf-measures/bundle-check/size.json shell: bash
- name: Install bombardier for speed check run: | wget -O bombardier https://github.com/codesenberg/bombardier/releases/download/v2.0.1/bombardier-linux-amd64 chmod +x bombardier sudo mv bombardier /usr/local/bin/ shell: bash
- name: Performance measurement of HTTP speed check run: | bun perf-measures/speed-check/scripts/benchmark.ts --ci > perf-measures/speed-check/results.json shell: bash
- name: Run octocov if: ${{ inputs.target-ref == 'auto' }} uses: k1LoW/octocov-action@v1 with: config: perf-measures/.octocov.consolidated.perf-measures.yml env: OCTOCOV_CUSTOM_METRICS_BUNDLE_SIZE_CHECK: perf-measures/bundle-check/size.json OCTOCOV_CUSTOM_METRICS_SPEED_CHECK: perf-measures/speed-check/results.json OCTOCOV_CUSTOM_METRICS_DIAGNOSTICS_TSC: perf-measures/type-check/diagnostics-tsc.json OCTOCOV_CUSTOM_METRICS_DIAGNOSTICS_TSGO: perf-measures/type-check/diagnostics-tsgo.json
- name: Run octocov with custom target ref3 unmodified lines config: perf-measures/.octocov.consolidated.perf-measures.main.yml env: OCTOCOV_GITHUB_REF: 'refs/heads/main' OCTOCOV_CUSTOM_METRICS_BUNDLE_SIZE_CHECK: perf-measures/bundle-check/size.json OCTOCOV_CUSTOM_METRICS_SPEED_CHECK: perf-measures/speed-check/results.json OCTOCOV_CUSTOM_METRICS_DIAGNOSTICS_TSC: perf-measures/type-check/diagnostics-tsc.json OCTOCOV_CUSTOM_METRICS_DIAGNOSTICS_TSGO: perf-measures/type-check/diagnostics-tsgo.jsonmodified:.github/workflows/ci.yml+55 added-2 removed
181 unmodified lines182 name: coverage-lambda-edge183 path: coverage/184 185 perf-measures-check-on-pr:186- name: 'Type & Bundle size & Speed Check on PR'186+ name: 'Type & Bundle size Check on PR'187 runs-on: ubuntu-latest188 if: github.event_name == 'pull_request'189 steps:190 - uses: actions/checkout@v4191 - uses: ./.github/actions/perf-measures192 with:193 target-ref: 'auto'194 195+ http-benchmark-on-pr:196+ name: 'HTTP Speed Check on PR'197+ runs-on: ubuntu-latest198+ if: github.event_name == 'pull_request'199+ steps:200+ - uses: actions/checkout@v4201+ - uses: oven-sh/setup-bun@v2202+ - run: bun install203+ - name: Install bombardier204+ run: |205+ wget -O bombardier https://github.com/codesenberg/bombardier/releases/download/v2.0.1/bombardier-linux-amd64206+ chmod +x bombardier207+ sudo mv bombardier /usr/local/bin/208+ - name: Run HTTP benchmark209+ run: |210+ cd benchmarks/http-server211+ bun run benchmark.ts212+ - name: Comment PR213+ uses: actions/github-script@v7214+ with:215+ script: |216+ const fs = require('fs');217+ const results = fs.readFileSync('benchmarks/http-server/benchmark-results.md', 'utf8');218+219+ // Minimize previous benchmark comments220+ const comments = await github.rest.issues.listComments({221+ owner: context.repo.owner,222+ repo: context.repo.repo,223+ issue_number: context.issue.number224+ });225+226+ for (const comment of comments.data) {227+ if (comment.body.includes('## HTTP Performance Benchmark')) {228+ await github.graphql(`229+ mutation {230+ minimizeComment(input: { subjectId: "${comment.node_id}", classifier: OUTDATED }) {231+ minimizedComment {232+ isMinimized233+ }234+ }235+ }236+ `);237+ }238+ }239+240+ // Post new comment241+ github.rest.issues.createComment({242+ issue_number: context.issue.number,243+ owner: context.repo.owner,244+ repo: context.repo.repo,245+ body: results246+ });247+248 perf-measures-check-on-main:196- name: 'Type & Bundle size & Speed Check on Main'249+ name: 'Type & Bundle size Check on Main'250 runs-on: ubuntu-latest251 if: github.ref == 'refs/heads/main'252 steps:253 - uses: actions/checkout@v43 unmodified linesadded:benchmarks/http-server/.gitignore+2 added
1+.benchmark-temp/2+benchmark-results.mdadded:benchmarks/http-server/benchmark.ts+325 added
1+/**2+ * Hono HTTP Performance Benchmark3+ *4+ * Inspired by https://github.com/SaltyAom/bun-http-framework-benchmark5+ *6+ * Usage:7+ * bun run benchmark.ts [options]8+ *9+ * Options:10+ * --baseline=<ref> Git reference for baseline (default: main)11+ * --target=<ref> Git reference for target (default: current)12+ * --runs=<number> Number of benchmark runs (default: 1)13+ * --duration=<number> Duration of each test in seconds (default: 10)14+ * --skip-tests Skip endpoint validation tests15+ */16+17+import { spawn } from 'node:child_process'18+import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'19+import { join } from 'node:path'20+21+// Configuration from command line arguments22+const baseline = process.argv.find((arg) => arg.startsWith('--baseline='))?.split('=')[1] || 'origin/main'23+const target = process.argv.find((arg) => arg.startsWith('--target='))?.split('=')[1] || 'current'24+const runs = parseInt(process.argv.find((arg) => arg.startsWith('--runs='))?.split('=')[1] || '1')25+const duration = parseInt(26+ process.argv.find((arg) => arg.startsWith('--duration='))?.split('=')[1] || '10'27+)28+const concurrency = 50029+const skipTests = process.argv.includes('--skip-tests')30+31+const SCRIPT_DIR = import.meta.dirname32+const TEMP_DIR = join(SCRIPT_DIR, '.benchmark-temp')33+const HONO_ROOT = join(SCRIPT_DIR, '../..')34+35+// Test app template (embedded to avoid file dependency issues)36+const getAppTemplate = () => `import { Hono } from './src/index.ts'37+import { RegExpRouter } from './src/router/reg-exp-router/index.ts'38+39+const app = new Hono({ router: new RegExpRouter() })40+41+app42+ .get('/', (c) => c.text('Hi'))43+ .post('/json', (c) => c.req.json().then(c.json))44+ .get('/id/:id', (c) => {45+ const id = c.req.param('id')46+ const name = c.req.query('name')47+ c.header('x-powered-by', 'benchmark')48+ return c.text(\`\${id} \${name}\`)49+ })50+51+export default app`52+53+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))54+55+const runCommand = async (command: string, cwd: string) => {56+ const parts = command.split(' ')57+ const proc = spawn(parts[0], parts.slice(1), { cwd })58+59+ let stdout = ''60+ let stderr = ''61+62+ proc.stdout.on('data', (data) => {63+ stdout += data64+ })65+ proc.stderr.on('data', (data) => {66+ stderr += data67+ })68+69+ const exitCode = await new Promise<number>((resolve) => {70+ proc.on('close', resolve)71+ })72+73+ if (exitCode !== 0) {74+ console.error(`Command failed: ${command}`)75+ console.error(`Exit code: ${exitCode}`)76+ console.error(`Stdout: ${stdout}`)77+ console.error(`Stderr: ${stderr}`)78+ throw new Error(`Command failed: ${command}`)79+ }80+81+ return { stdout, stderr }82+}83+84+const setupTemp = () => {85+ if (existsSync(TEMP_DIR)) {86+ rmSync(TEMP_DIR, { recursive: true })87+ }88+ mkdirSync(TEMP_DIR, { recursive: true })89+ writeFileSync(join(TEMP_DIR, 'body.json'), '{"hello":"world"}')90+}91+92+const buildVersion = async (version: string, name: string) => {93+ console.log(`📦 Preparing ${name} (${version})...`)94+95+ let needsRestore = false96+ let stashRef = ''97+98+ if (version === 'current') {99+ // No build needed - use src directly100+ } else {101+ // Ensure we have the latest remote refs102+ await runCommand('git fetch origin', HONO_ROOT)103+ 104+ try {105+ const stashResult = await runCommand('git stash push -m "benchmark-temp"', HONO_ROOT)106+ needsRestore = stashResult.stdout.includes('Saved working directory')107+ if (needsRestore) {108+ stashRef = 'stash@{0}'109+ }110+ } catch {111+ // No changes to stash112+ }113+114+ await runCommand(`git checkout ${version}`, HONO_ROOT)115+ await runCommand('bun install', HONO_ROOT)116+ // No build needed - use src directly117+ }118+119+ const versionDir = join(TEMP_DIR, name)120+ mkdirSync(versionDir, { recursive: true })121+ await runCommand(`cp -r ${HONO_ROOT}/src ${versionDir}/src`, process.cwd())122+123+ const appPath = join(versionDir, 'app.ts')124+ writeFileSync(appPath, getAppTemplate())125+126+ // Test endpoints (optional)127+ if (!skipTests) {128+ console.log(`🧪 Testing endpoints for ${name}...`)129+ const server = spawn('bun', [appPath], {130+ cwd: TEMP_DIR,131+ env: { ...process.env, NODE_ENV: 'production' },132+ })133+ await sleep(2000)134+135+ try {136+ const res1 = await fetch('http://127.0.0.1:3000/')137+ if ((await res1.text()) !== 'Hi') {138+ throw new Error('[GET /] test failed')139+ }140+141+ const res2 = await fetch('http://127.0.0.1:3000/id/1?name=bun')142+ if (res2.headers.get('x-powered-by') !== 'benchmark' || (await res2.text()) !== '1 bun') {143+ throw new Error('[GET /id/:id] test failed')144+ }145+146+ const body = JSON.stringify({ hello: 'world' })147+ const res3 = await fetch('http://127.0.0.1:3000/json', {148+ method: 'POST',149+ body,150+ headers: { 'content-type': 'application/json', 'content-length': body.length.toString() },151+ })152+ if (153+ !res3.headers.get('content-type')?.includes('application/json') ||154+ (await res3.text()) !== body155+ ) {156+ throw new Error('[POST /json] test failed')157+ }158+159+ console.log(` ✅ Tests passed for ${name}`)160+ } finally {161+ server.kill()162+ await sleep(1000)163+ }164+ } else {165+ console.log(` ⏭️ Skipping endpoint tests for ${name}`)166+ }167+168+ // Restore git state169+ if (version !== 'current' && needsRestore) {170+ await runCommand('git checkout -', HONO_ROOT)171+ await runCommand(`git stash pop ${stashRef}`, HONO_ROOT)172+ } else if (version !== 'current') {173+ await runCommand('git checkout -', HONO_ROOT)174+ }175+176+ return appPath177+}178+179+const runBenchmark = async (appPath: string, name: string) => {180+ console.log(`⚡ Running HTTP benchmark for ${name}...`)181+182+ const bodyFile = join(TEMP_DIR, 'body.json')183+ const commands = [184+ `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/`,185+ `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/id/1?name=bun`,186+ `bombardier --fasthttp -c ${concurrency} -d ${duration}s -m POST -H Content-Type:application/json -f ${bodyFile} http://127.0.0.1:3000/json`,187+ ]188+189+ const allRuns: number[][] = []190+191+ for (let run = 0; run < runs; run++) {192+ console.log(` Run ${run + 1}/${runs}`)193+194+ const server = spawn('bun', [appPath], {195+ cwd: TEMP_DIR,196+ env: { ...process.env, NODE_ENV: 'production' },197+ })198+ await sleep(1000)199+200+ const runResults: number[] = []201+202+ try {203+ for (const command of commands) {204+ const result = await runCommand(command, process.cwd())205+ console.log(result.stdout)206+207+ const match = result.stdout.match(/Reqs\/sec\s+(\d+[.|,]\d+)/)208+ if (match) {209+ runResults.push(parseFloat(match[1].replace(',', '')))210+ } else {211+ console.log('❌ Failed to parse result')212+ runResults.push(0)213+ }214+ }215+ } finally {216+ server.kill()217+ await sleep(500)218+ }219+220+ allRuns.push(runResults)221+ }222+223+ const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length224+225+ const ping = average(allRuns.map((run) => run[0]))226+ const query = average(allRuns.map((run) => run[1]))227+ const body = average(allRuns.map((run) => run[2]))228+ const overall = (ping + query + body) / 3229+230+ return { name, average: overall, ping, query, body, runs: allRuns.map((run) => average(run)) }231+}232+233+const main = async () => {234+ console.log('🏁 Hono HTTP Benchmark')235+ console.log('======================')236+ console.log(`Baseline: ${baseline}`)237+ console.log(`Target: ${target}`)238+ console.log(`Runs: ${runs}`)239+ console.log(`Duration: ${duration}s`)240+ console.log(`Concurrency: ${concurrency}`)241+ console.log(`Skip Tests: ${skipTests}`)242+ console.log('')243+244+ setupTemp()245+246+ try {247+ // Compare baseline vs target248+ const baselinePath = await buildVersion(baseline, 'baseline')249+ const targetPath = await buildVersion(target, 'target')250+251+ const baselineResult = await runBenchmark(baselinePath, 'baseline')252+ const targetResult = await runBenchmark(targetPath, 'target')253+254+ // Calculate changes255+ const calculateChange = (target: number, baseline: number) =>256+ (((target - baseline) / baseline) * 100).toFixed(2)257+258+ const changes = {259+ average: calculateChange(targetResult.average, baselineResult.average),260+ ping: calculateChange(targetResult.ping, baselineResult.ping),261+ query: calculateChange(targetResult.query, baselineResult.query),262+ body: calculateChange(targetResult.body, baselineResult.body),263+ }264+265+ // Format numbers266+ const format = (num: number) => num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')267+ const formatChange = (change: string) => (Number(change) >= 0 ? '+' : '') + change + '%'268+269+ // Generate table data270+ const rows = [271+ {272+ framework: `hono (${baseline})`,273+ runtime: 'bun',274+ average: format(baselineResult.average),275+ ping: format(baselineResult.ping),276+ query: format(baselineResult.query),277+ body: format(baselineResult.body),278+ },279+ {280+ framework: `hono (${target})`,281+ runtime: 'bun',282+ average: format(targetResult.average),283+ ping: format(targetResult.ping),284+ query: format(targetResult.query),285+ body: format(targetResult.body),286+ },287+ {288+ framework: 'Change',289+ runtime: '',290+ average: formatChange(changes.average),291+ ping: formatChange(changes.ping),292+ query: formatChange(changes.query),293+ body: formatChange(changes.body),294+ },295+ ]296+297+ const table = [298+ '| Framework | Runtime | Average | Ping | Query | Body |',299+ '| --- | --- | --- | --- | --- | --- |',300+ ...rows.map(301+ (row) =>302+ `| ${row.framework} | ${row.runtime} | ${row.average} | ${row.ping} | ${row.query} | ${row.body} |`303+ ),304+ ]305+306+ // Console output307+ console.log('')308+ table.forEach((line) => console.log(line))309+ console.log('')310+311+ // Markdown output312+ const markdownOutput = ['## HTTP Performance Benchmark', '', ...table].join('\n')313+314+ writeFileSync(join(SCRIPT_DIR, 'benchmark-results.md'), markdownOutput)315+ } catch (error) {316+ console.error('❌ Benchmark failed:', error)317+ throw error318+ } finally {319+ if (existsSync(TEMP_DIR)) {320+ rmSync(TEMP_DIR, { recursive: true })321+ }322+ }323+}324+325+main()added:benchmarks/http-server/README.md+21 added
123456789101112131415161718192021# Hono HTTP Benchmark
HTTP performance benchmarking tool that compares main vs current versions.
## Usage
### In Pull Requests
HTTP benchmarks are automatically run for each pull request and results are commented on the PR.
### Local Development
```bashcd benchmarks/http-serverbun run benchmark.ts```
## Prerequisites
- Bun v1.0+- bombardier (`brew install bombardier` on macOS)deleted:perf-measures/speed-check/scripts/benchmark.ts-390 removed
1-/**2- * Hono HTTP Performance Benchmark3- *4- * Inspired by https://github.com/SaltyAom/bun-http-framework-benchmark5- *6- * Usage:7- * bun run benchmark.ts [options]8- *9- * Options:10- * --baseline=<ref> Git reference for baseline (default: main)11- * --target=<ref> Git reference for target (default: current)12- * --runs=<number> Number of benchmark runs (default: 1)13- * --duration=<number> Duration of each test in seconds (default: 10)14- * --skip-tests Skip endpoint validation tests15- */16-17-import { spawn } from 'node:child_process'18-import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'19-import { join } from 'node:path'20-21-// Configuration from command line arguments22-const ciMode = process.argv.includes('--ci')23-const baseline = process.argv.find((arg) => arg.startsWith('--baseline='))?.split('=')[1] || 'main'24-const target = process.argv.find((arg) => arg.startsWith('--target='))?.split('=')[1] || 'current'25-const runs = parseInt(process.argv.find((arg) => arg.startsWith('--runs='))?.split('=')[1] || '1')26-const duration = parseInt(27- process.argv.find((arg) => arg.startsWith('--duration='))?.split('=')[1] || '10'28-)29-const concurrency = 50030-const skipTests = process.argv.includes('--skip-tests')31-32-const SCRIPT_DIR = join(import.meta.dirname, '..')33-const TEMP_DIR = join(SCRIPT_DIR, '.benchmark-temp')34-const HONO_ROOT = join(SCRIPT_DIR, '../..')35-36-// Test app template (embedded to avoid file dependency issues)37-const getAppTemplate = () => `import { Hono } from './dist/index.js'38-import { RegExpRouter } from './dist/router/reg-exp-router/index.js'39-40-const app = new Hono({ router: new RegExpRouter() })41-42-app43- .get('/', (c) => c.text('Hi'))44- .post('/json', (c) => c.req.json().then(c.json))45- .get('/id/:id', (c) => {46- const id = c.req.param('id')47- const name = c.req.query('name')48- c.header('x-powered-by', 'benchmark')49- return c.text(\`\${id} \${name}\`)50- })51-52-export default app`53-54-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))55-56-const log = (...args: unknown[]) => {57- if (!ciMode) {58- console.log(...args)59- }60-}61-62-const runCommand = async (command: string, cwd: string) => {63- const parts = command.split(' ')64- const proc = spawn(parts[0], parts.slice(1), { cwd })65-66- let stdout = ''67- let stderr = ''68-69- proc.stdout.on('data', (data) => {70- stdout += data71- })72- proc.stderr.on('data', (data) => {73- stderr += data74- })75-76- const exitCode = await new Promise<number>((resolve) => {77- proc.on('close', resolve)78- })79-80- if (exitCode !== 0) {81- console.error(`Command failed: ${command}`)82- console.error(`Exit code: ${exitCode}`)83- console.error(`Stdout: ${stdout}`)84- console.error(`Stderr: ${stderr}`)85- throw new Error(`Command failed: ${command}`)86- }87-88- return { stdout, stderr }89-}90-91-const setupTemp = () => {92- if (existsSync(TEMP_DIR)) {93- rmSync(TEMP_DIR, { recursive: true })94- }95- mkdirSync(TEMP_DIR, { recursive: true })96- writeFileSync(join(TEMP_DIR, 'body.json'), '{"hello":"world"}')97-}98-99-const buildVersion = async (version: string, name: string) => {100- log(`📦 Building ${name} (${version})...`)101-102- let needsRestore = false103- let stashRef = ''104-105- if (version === 'current') {106- if (!ciMode) {107- await runCommand('bun run build', HONO_ROOT)108- }109- } else {110- try {111- const stashResult = await runCommand('git stash push -m "benchmark-temp"', HONO_ROOT)112- needsRestore = stashResult.stdout.includes('Saved working directory')113- if (needsRestore) {114- stashRef = 'stash@{0}'115- }116- } catch {117- // No changes to stash118- }119-120- await runCommand(`git checkout ${version}`, HONO_ROOT)121- await runCommand('bun install', HONO_ROOT)122- if (!ciMode) {123- await runCommand('bun run build', HONO_ROOT)124- }125- }126-127- const versionDir = join(TEMP_DIR, name)128- mkdirSync(versionDir, { recursive: true })129- await runCommand(`cp -r ${HONO_ROOT}/dist ${versionDir}/dist`, process.cwd())130-131- const appPath = join(versionDir, 'app.js')132- writeFileSync(appPath, getAppTemplate())133-134- // Test endpoints (optional)135- if (!skipTests) {136- log(`🧪 Testing endpoints for ${name}...`)137- const server = spawn('bun', [appPath], {138- cwd: TEMP_DIR,139- env: { ...process.env, NODE_ENV: 'production' },140- })141- await sleep(2000)142-143- try {144- const res1 = await fetch('http://127.0.0.1:3000/')145- if ((await res1.text()) !== 'Hi') {146- throw new Error('[GET /] test failed')147- }148-149- const res2 = await fetch('http://127.0.0.1:3000/id/1?name=bun')150- if (res2.headers.get('x-powered-by') !== 'benchmark' || (await res2.text()) !== '1 bun') {151- throw new Error('[GET /id/:id] test failed')152- }153-154- const body = JSON.stringify({ hello: 'world' })155- const res3 = await fetch('http://127.0.0.1:3000/json', {156- method: 'POST',157- body,158- headers: { 'content-type': 'application/json', 'content-length': body.length.toString() },159- })160- if (161- !res3.headers.get('content-type')?.includes('application/json') ||162- (await res3.text()) !== body163- ) {164- throw new Error('[POST /json] test failed')165- }166-167- log(` ✅ Tests passed for ${name}`)168- } finally {169- server.kill()170- await sleep(1000)171- }172- } else {173- log(` ⏭️ Skipping endpoint tests for ${name}`)174- }175-176- // Restore git state177- if (version !== 'current' && needsRestore) {178- await runCommand('git checkout -', HONO_ROOT)179- await runCommand(`git stash pop ${stashRef}`, HONO_ROOT)180- } else if (version !== 'current') {181- await runCommand('git checkout -', HONO_ROOT)182- }183-184- return appPath185-}186-187-const runBenchmark = async (appPath: string, name: string) => {188- log(`⚡ Running HTTP benchmark for ${name}...`)189-190- const bodyFile = join(TEMP_DIR, 'body.json')191- const commands = [192- `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/`,193- `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/id/1?name=bun`,194- `bombardier --fasthttp -c ${concurrency} -d ${duration}s -m POST -H Content-Type:application/json -f ${bodyFile} http://127.0.0.1:3000/json`,195- ]196-197- const allRuns: number[][] = []198-199- for (let run = 0; run < runs; run++) {200- log(` Run ${run + 1}/${runs}`)201-202- const server = spawn('bun', [appPath], {203- cwd: TEMP_DIR,204- env: { ...process.env, NODE_ENV: 'production' },205- })206- await sleep(1000)207-208- const runResults: number[] = []209-210- try {211- for (const command of commands) {212- const result = await runCommand(command, process.cwd())213- log(result.stdout)214-215- const match = result.stdout.match(/Reqs\/sec\s+(\d+[.|,]\d+)/)216- if (match) {217- runResults.push(parseFloat(match[1].replace(',', '')))218- } else {219- log('❌ Failed to parse result')220- runResults.push(0)221- }222- }223- } finally {224- server.kill()225- await sleep(500)226- }227-228- allRuns.push(runResults)229- }230-231- const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length232-233- const ping = average(allRuns.map((run) => run[0]))234- const query = average(allRuns.map((run) => run[1]))235- const body = average(allRuns.map((run) => run[2]))236- const overall = (ping + query + body) / 3237-238- return { name, average: overall, ping, query, body, runs: allRuns.map((run) => average(run)) }239-}240-241-const main = async () => {242- log('🏁 Hono HTTP Benchmark')243- log('======================')244- log(`Baseline: ${baseline}`)245- log(`Target: ${target}`)246- log(`Runs: ${runs}`)247- log(`Duration: ${duration}s`)248- log(`Concurrency: ${concurrency}`)249- log(`Skip Tests: ${skipTests}`)250- log('')251-252- setupTemp()253-254- try {255- if (ciMode) {256- // CI mode: measure current branch only (dist already built)257- const versionDir = join(TEMP_DIR, 'current')258- mkdirSync(versionDir, { recursive: true })259- const distPath = join(HONO_ROOT, 'dist')260- await runCommand(`cp -r ${distPath} ${versionDir}/`, process.cwd())261-262- const appPath = join(versionDir, 'app.js')263- writeFileSync(appPath, getAppTemplate())264-265- const targetResult = await runBenchmark(appPath, 'current')266-267- // Generate octocov-compatible output268- const benchmark = {269- key: 'speed-check',270- name: 'HTTP speed check',271- metrics: [272- {273- key: 'ping',274- name: 'Ping (req/s)',275- value: targetResult.ping,276- unit: 'req/s',277- },278- {279- key: 'query',280- name: 'Query (req/s)',281- value: targetResult.query,282- unit: 'req/s',283- },284- {285- key: 'body',286- name: 'Body (req/s)',287- value: targetResult.body,288- unit: 'req/s',289- },290- {291- key: 'average',292- name: 'Average (req/s)',293- value: targetResult.average,294- unit: 'req/s',295- },296- ],297- }298-299- console.log(JSON.stringify(benchmark, null, 2))300- return301- }302-303- // Normal mode: compare baseline vs target304- const baselinePath = await buildVersion(baseline, 'baseline')305- const targetPath = await buildVersion(target, 'target')306-307- const baselineResult = await runBenchmark(baselinePath, 'baseline')308- const targetResult = await runBenchmark(targetPath, 'target')309-310- // Calculate changes311- const overallChange = (312- ((targetResult.average - baselineResult.average) / baselineResult.average) *313- 100314- ).toFixed(2)315- const pingChange = (316- ((targetResult.ping - baselineResult.ping) / baselineResult.ping) *317- 100318- ).toFixed(2)319- const queryChange = (320- ((targetResult.query - baselineResult.query) / baselineResult.query) *321- 100322- ).toFixed(2)323- const bodyChange = (324- ((targetResult.body - baselineResult.body) / baselineResult.body) *325- 100326- ).toFixed(2)327-328- // Format output329- const baselineName = `hono (${baseline})`330- const targetName = `hono (${target})`331- const maxNameLength = Math.max(baselineName.length, targetName.length, 16)332-333- const formatName = (name: string) => name.padEnd(maxNameLength)334- const formatNumber = (num: number) => num.toFixed(2).padStart(10)335- const formatAverage = (num: number) => num.toFixed(3).padStart(7)336- const formatChange = (change: string) =>337- ((Number(change) >= 0 ? '+' : '') + change + '%').padStart(10)338-339- console.log('')340- console.log(341- `| ${'Framework'.padEnd(342- maxNameLength343- )} | Runtime | Average | Ping | Query | Body |`344- )345- console.log(346- `| ${'-'.repeat(maxNameLength)} | ------- | ------- | ---------- | ---------- | ---------- |`347- )348- console.log(349- `| ${formatName(baselineName)} | bun | ${formatAverage(350- baselineResult.average351- )} | ${formatNumber(baselineResult.ping)} | ${formatNumber(352- baselineResult.query353- )} | ${formatNumber(baselineResult.body)} |`354- )355- console.log(356- `| ${formatName(targetName)} | bun | ${formatAverage(357- targetResult.average358- )} | ${formatNumber(targetResult.ping)} | ${formatNumber(359- targetResult.query360- )} | ${formatNumber(targetResult.body)} |`361- )362- console.log(363- `| ${' '.repeat(maxNameLength)} | | ${(364- (Number(overallChange) >= 0 ? '+' : '') +365- overallChange +366- '%'367- ).padStart(7)} | ${formatChange(pingChange)} | ${formatChange(queryChange)} | ${formatChange(368- bodyChange369- )} |`370- )371- console.log('')372-373- // Individual changes summary374- console.log('📊 Performance Changes:')375- console.log(` Overall: ${Number(overallChange) >= 0 ? '+' : ''}${overallChange}%`)376- console.log(` Ping: ${Number(pingChange) >= 0 ? '+' : ''}${pingChange}%`)377- console.log(` Query: ${Number(queryChange) >= 0 ? '+' : ''}${queryChange}%`)378- console.log(` Body: ${Number(bodyChange) >= 0 ? '+' : ''}${bodyChange}%`)379- console.log('')380- } catch (error) {381- console.error('❌ Benchmark failed:', error)382- throw error383- } finally {384- if (existsSync(TEMP_DIR)) {385- rmSync(TEMP_DIR, { recursive: true })386- }387- }388-}389-390-main()deleted:perf-measures/speed-check/.gitignore-2 removed
1-benchmark-results.json2-.benchmark-tempdeleted:perf-measures/speed-check/README.md-58 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Hono HTTP Benchmark
A performance benchmarking tool for measuring HTTP performance of Hono.
This tool is inspired by and references the [bun-http-framework-benchmark](https://github.com/SaltyAom/bun-http-framework-benchmark) project, adapting some test patterns and bombardier usage.
## 📋 Prerequisites
- [Bun](https://bun.sh/) v1.0+- [bombardier](https://github.com/codesenberg/bombardier) - `brew install bombardier` (macOS) or download from releases
## 🚀 Usage
```bashcd perf-measures/speed-check
# Compare current branch vs mainbun run scripts/benchmark.ts
# Compare against specific versionbun run scripts/benchmark.ts --baseline=v4.7.11
# Custom configurationbun run scripts/benchmark.ts --baseline=main --target=current --runs=3
# CI mode (current branch only, JSON output for octocov)bun run scripts/benchmark.ts --ci```
## 📊 Metrics
- **Ping**: `GET /` - Basic response performance- **Query**: `GET /id/:id?name=bun` - Parameter handling performance- **Body**: `POST /json` - JSON processing performance
## 📁 Output
### Console Output
```txt| Framework | Runtime | Average | Ping | Query | Body || ---------------- | ------- | ------- | ---------- | ---------- | ---------- || hono (main) | bun | 77,413.913 | 91,466.05 | 73,813.05 | 66,962.64 || hono (current) | bun | 77,151.263 | 90,319.35 | 73,774.59 | 67,359.85 |
Performance change: -0.34%```
### File Output
`benchmark-results.json` - Results data in JSON format
## 🏗️ How it works
1. **Build**: Checkout and build specified Git revisions2. **Test**: Verify endpoints work correctly3. **Benchmark**: Run bombardier load tests4. **Results**: Output performance comparisonmodified:perf-measures/.octocov.consolidated.perf-measures.yml-2 removed
14 unmodified lines1516171819201920212214 unmodified lines if: truecustomMetrics: bundle-size-check: key: bundle-size-check speed-check: key: speed-check diagnostics-tsc: key: diagnostics-tsc diagnostics-typescript-go: key: diagnostics-typescript-goNo newline at end of fileNo newline at end of file