Skip to content
Myr

ci: add HTTP speed check (#4220)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* chore: add HTTP benchmark tool Add performance benchmarking tool inspired by bun-http-framework-benchmark: - Test ping/query/body endpoints - Compare Git revisions - Output results in table format 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * format * chore: rename http-benchmark to speed-check Rename directory from perf-measures/http-benchmark to perf-measures/speed-check for better naming consistency. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * feat(perf-measures): add speed-check HTTP benchmark tool 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * refactored * format * feat: integrate speed-check into perf-measures with CI support Add HTTP performance benchmarking to the consolidated performance measurement system with --ci mode support. - Move benchmark.ts to scripts/ directory for consistency - Add --ci flag for CI-optimized execution (silent mode, JSON output) - Integrate speed-check results into octocov configuration - Install bombardier automatically in CI - Preserve detailed comparison mode for local development 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: update CI job names to include Speed Check Update GitHub Actions job names to reflect the addition of HTTP speed checking alongside type checking and bundle size checking. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: update bombardier download to use latest version and correct URL Fix 404 error by updating to bombardier v2.0.1 and downloading the binary directly instead of using a tar.gz archive that no longer exists. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: optimize speed-check for CI and improve display order - Skip buildVersion in CI mode and use existing dist folder directly - Reorder metrics display: Bundle size -> Speed check -> Compiler diagnostics - Eliminate unnecessary build steps that caused CI failures 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: correct dist folder path in CI mode and lint issues - Fix cp command path from `/dist` to `${HONO_ROOT}/dist` - Change log function parameter type from any[] to unknown[] - Run format:fix and lint:fix to resolve style issues 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * debug: add path debugging for CI dist folder issue * clean: remove debug code * format * fix: use script file location for reliable path resolution Replace process.cwd() with import.meta.dirname to ensure paths are resolved relative to the script file location, not the execution directory. This fixes dist folder path issues in CI. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * fixed the order and title ---------

authored by Yusuke Wada · committed by GitHub · parent c549d3e · Browse files · 7 files+470 added−2 removed
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

7 files+470 added−2 removed

  • other:+470 added−2 removed

7 files+470 added−2 removed

modified:.github/actions/perf-measures/action.yml+14 added
modified:.github/workflows/ci.yml+2 added-2 removed
181 unmodified lines
182 name: coverage-lambda-edge183 path: coverage/184185 perf-measures-check-on-pr:186 name: 'Type & Bundle size Check on PR'186 name: 'Type & Bundle size & Speed Check on PR'187 runs-on: ubuntu-latest188 if: github.event_name == 'pull_request'189 steps:190 - uses: actions/checkout@v4
1 unmodified line
192 with:193 target-ref: 'auto'194195 perf-measures-check-on-main:196 name: 'Type & Bundle size Check on Main'196 name: 'Type & Bundle size & Speed Check on Main'197 runs-on: ubuntu-latest198 if: github.ref == 'refs/heads/main'199 steps:200 - uses: actions/checkout@v4
3 unmodified lines
added:perf-measures/speed-check/scripts/benchmark.ts+390 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 */1617import { spawn } from 'node:child_process'18import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'19import { join } from 'node:path'2021// Configuration from command line arguments22const ciMode = process.argv.includes('--ci')23const baseline = process.argv.find((arg) => arg.startsWith('--baseline='))?.split('=')[1] || 'main'24const target = process.argv.find((arg) => arg.startsWith('--target='))?.split('=')[1] || 'current'25const runs = parseInt(process.argv.find((arg) => arg.startsWith('--runs='))?.split('=')[1] || '1')26const duration = parseInt(27 process.argv.find((arg) => arg.startsWith('--duration='))?.split('=')[1] || '10'28)29const concurrency = 50030const skipTests = process.argv.includes('--skip-tests')3132const SCRIPT_DIR = join(import.meta.dirname, '..')33const TEMP_DIR = join(SCRIPT_DIR, '.benchmark-temp')34const HONO_ROOT = join(SCRIPT_DIR, '../..')3536// Test app template (embedded to avoid file dependency issues)37const getAppTemplate = () => `import { Hono } from './dist/index.js'38import { RegExpRouter } from './dist/router/reg-exp-router/index.js'3940const app = new Hono({ router: new RegExpRouter() })4142app43 .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 })5152export default app`5354const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))5556const log = (...args: unknown[]) => {57 if (!ciMode) {58 console.log(...args)59 }60}6162const runCommand = async (command: string, cwd: string) => {63 const parts = command.split(' ')64 const proc = spawn(parts[0], parts.slice(1), { cwd })6566 let stdout = ''67 let stderr = ''6869 proc.stdout.on('data', (data) => {70 stdout += data71 })72 proc.stderr.on('data', (data) => {73 stderr += data74 })7576 const exitCode = await new Promise<number>((resolve) => {77 proc.on('close', resolve)78 })7980 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 }8788 return { stdout, stderr }89}9091const 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}9899const buildVersion = async (version: string, name: string) => {100 log(`📦 Building ${name} (${version})...`)101102 let needsRestore = false103 let stashRef = ''104105 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 }119120 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 }126127 const versionDir = join(TEMP_DIR, name)128 mkdirSync(versionDir, { recursive: true })129 await runCommand(`cp -r ${HONO_ROOT}/dist ${versionDir}/dist`, process.cwd())130131 const appPath = join(versionDir, 'app.js')132 writeFileSync(appPath, getAppTemplate())133134 // 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)142143 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 }148149 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 }153154 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 }166167 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 }175176 // 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 }183184 return appPath185}186187const runBenchmark = async (appPath: string, name: string) => {188 log(`⚡ Running HTTP benchmark for ${name}...`)189190 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 ]196197 const allRuns: number[][] = []198199 for (let run = 0; run < runs; run++) {200 log(` Run ${run + 1}/${runs}`)201202 const server = spawn('bun', [appPath], {203 cwd: TEMP_DIR,204 env: { ...process.env, NODE_ENV: 'production' },205 })206 await sleep(1000)207208 const runResults: number[] = []209210 try {211 for (const command of commands) {212 const result = await runCommand(command, process.cwd())213 log(result.stdout)214215 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 }227228 allRuns.push(runResults)229 }230231 const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length232233 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) / 3237238 return { name, average: overall, ping, query, body, runs: allRuns.map((run) => average(run)) }239}240241const 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('')251252 setupTemp()253254 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())261262 const appPath = join(versionDir, 'app.js')263 writeFileSync(appPath, getAppTemplate())264265 const targetResult = await runBenchmark(appPath, 'current')266267 // 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 }298299 console.log(JSON.stringify(benchmark, null, 2))300 return301 }302303 // Normal mode: compare baseline vs target304 const baselinePath = await buildVersion(baseline, 'baseline')305 const targetPath = await buildVersion(target, 'target')306307 const baselineResult = await runBenchmark(baselinePath, 'baseline')308 const targetResult = await runBenchmark(targetPath, 'target')309310 // 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)327328 // Format output329 const baselineName = `hono (${baseline})`330 const targetName = `hono (${target})`331 const maxNameLength = Math.max(baselineName.length, targetName.length, 16)332333 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)338339 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('')372373 // 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}389390main()
added:perf-measures/speed-check/.gitignore+2 added
1benchmark-results.json2.benchmark-temp
added:perf-measures/speed-check/README.md+58 added
modified:perf-measures/.octocov.consolidated.perf-measures.main.yml+2 added
modified:perf-measures/.octocov.consolidated.perf-measures.yml+2 added