|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * FreelanceFlow API Benchmark Suite |
| 4 | + * Uses autocannon to measure p50/p95/p99 latency, RPS, error rate, TTFB |
| 5 | + * for all /api/* endpoints. |
| 6 | + * |
| 7 | + * Usage: npm run benchmark |
| 8 | + * Config: .env.benchmark |
| 9 | + */ |
| 10 | + |
| 11 | +import autocannon from "autocannon"; |
| 12 | +import { readFileSync, writeFileSync, mkdirSync } from "fs"; |
| 13 | +import { resolve, dirname } from "path"; |
| 14 | +import { fileURLToPath } from "url"; |
| 15 | +import dotenv from "dotenv"; |
| 16 | + |
| 17 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 18 | +const ROOT = resolve(__dirname, ".."); |
| 19 | + |
| 20 | +dotenv.config({ path: resolve(ROOT, ".env.benchmark") }); |
| 21 | + |
| 22 | +const HOST = process.env.BENCHMARK_HOST || "http://localhost:3000"; |
| 23 | +const DURATION = parseInt(process.env.BENCHMARK_DURATION || "10", 10); |
| 24 | +const CONNECTIONS = parseInt(process.env.BENCHMARK_CONNECTIONS || "10", 10); |
| 25 | +const AUTH_TOKEN = process.env.BENCHMARK_AUTH_TOKEN || ""; |
| 26 | +const ADMIN_TOKEN = process.env.BENCHMARK_ADMIN_TOKEN || ""; |
| 27 | +const RESULTS_DIR = resolve(ROOT, process.env.BENCHMARK_RESULTS_DIR || "benchmarks/results"); |
| 28 | + |
| 29 | +const authHeader = AUTH_TOKEN ? { Authorization: `Bearer ${AUTH_TOKEN}` } : {}; |
| 30 | +const adminHeader = ADMIN_TOKEN ? { Authorization: `Bearer ${ADMIN_TOKEN}` } : {}; |
| 31 | + |
| 32 | +/** Endpoint definitions */ |
| 33 | +const ENDPOINTS = [ |
| 34 | + { name: "health", path: "/health", method: "GET", headers: {} }, |
| 35 | + { name: "auth_register", path: "/api/auth/register", method: "POST", headers: { "Content-Type": "application/json" }, |
| 36 | + body: JSON.stringify({ email: "bench@test.com", password: "Bench1234!", name: "Bench User", role: "freelancer" }) }, |
| 37 | + { name: "auth_login", path: "/api/auth/login", method: "POST", headers: { "Content-Type": "application/json" }, |
| 38 | + body: JSON.stringify({ email: "bench@test.com", password: "Bench1234!" }) }, |
| 39 | + { name: "jobs_list", path: "/api/jobs", method: "GET", headers: authHeader }, |
| 40 | + { name: "users_list", path: "/api/users", method: "GET", headers: adminHeader }, |
| 41 | + { name: "proposals_list", path: "/api/proposals", method: "GET", headers: authHeader }, |
| 42 | + { name: "search", path: "/api/search?q=developer", method: "GET", headers: {} }, |
| 43 | + { name: "reviews_list", path: "/api/reviews", method: "GET", headers: authHeader }, |
| 44 | + { name: "messages_list", path: "/api/messages", method: "GET", headers: authHeader }, |
| 45 | + { name: "notifications_list", path: "/api/notifications", method: "GET", headers: authHeader }, |
| 46 | + { name: "admin_users", path: "/api/admin/users", method: "GET", headers: adminHeader }, |
| 47 | +]; |
| 48 | + |
| 49 | +function extractMetrics(result) { |
| 50 | + const lat = result.latency; |
| 51 | + const req = result.requests; |
| 52 | + const errors = result.errors || 0; |
| 53 | + const totalReqs = req.total || 1; |
| 54 | + return { |
| 55 | + p50_ms: lat.p50, |
| 56 | + p95_ms: lat.p95, |
| 57 | + p99_ms: lat.p99, |
| 58 | + mean_ms: Math.round(lat.mean), |
| 59 | + rps_peak: req.max, |
| 60 | + rps_sustained: Math.round(req.mean), |
| 61 | + error_rate_pct: parseFloat(((errors / totalReqs) * 100).toFixed(2)), |
| 62 | + ttfb_p95_ms: lat.p95, |
| 63 | + total_requests: totalReqs, |
| 64 | + duration_s: result.duration, |
| 65 | + }; |
| 66 | +} |
| 67 | + |
| 68 | +async function runBenchmark(endpoint) { |
| 69 | + return new Promise((resolve, reject) => { |
| 70 | + const opts = { |
| 71 | + url: `${HOST}${endpoint.path}`, |
| 72 | + method: endpoint.method, |
| 73 | + headers: endpoint.headers || {}, |
| 74 | + body: endpoint.body, |
| 75 | + duration: DURATION, |
| 76 | + connections: CONNECTIONS, |
| 77 | + pipelining: 1, |
| 78 | + }; |
| 79 | + const instance = autocannon(opts, (err, result) => { |
| 80 | + if (err) return reject(err); |
| 81 | + resolve(result); |
| 82 | + }); |
| 83 | + autocannon.track(instance, { renderProgressBar: false }); |
| 84 | + }); |
| 85 | +} |
| 86 | + |
| 87 | +async function main() { |
| 88 | + mkdirSync(RESULTS_DIR, { recursive: true }); |
| 89 | + |
| 90 | + const thresholds = JSON.parse(readFileSync(resolve(ROOT, "benchmarks/thresholds.json"), "utf8")); |
| 91 | + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); |
| 92 | + const allResults = []; |
| 93 | + const violations = []; |
| 94 | + |
| 95 | + console.log(`\n🚀 FreelanceFlow API Benchmark Suite`); |
| 96 | + console.log(` Host: ${HOST} | Duration: ${DURATION}s | Connections: ${CONNECTIONS}\n`); |
| 97 | + |
| 98 | + for (const endpoint of ENDPOINTS) { |
| 99 | + process.stdout.write(` Benchmarking ${endpoint.method} ${endpoint.path} ... `); |
| 100 | + try { |
| 101 | + const raw = await runBenchmark(endpoint); |
| 102 | + const metrics = extractMetrics(raw); |
| 103 | + const result = { endpoint: endpoint.name, path: endpoint.path, method: endpoint.method, ...metrics }; |
| 104 | + allResults.push(result); |
| 105 | + |
| 106 | + // Check threshold |
| 107 | + const key = Object.keys(thresholds.endpoints).find(k => endpoint.path.startsWith(k)); |
| 108 | + const threshold = key ? thresholds.endpoints[key].p99_latency_ms : thresholds.defaults.p99_latency_ms; |
| 109 | + const passed = metrics.p99_ms <= threshold; |
| 110 | + if (!passed) violations.push({ ...result, threshold_ms: threshold }); |
| 111 | + |
| 112 | + console.log(`p99=${metrics.p99_ms}ms rps=${metrics.rps_sustained} err=${metrics.error_rate_pct}% ${passed ? "✅" : "❌ THRESHOLD EXCEEDED"}`); |
| 113 | + } catch (err) { |
| 114 | + console.log(`ERROR: ${err.message}`); |
| 115 | + allResults.push({ endpoint: endpoint.name, path: endpoint.path, method: endpoint.method, error: err.message }); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + // Write JSON results |
| 120 | + const jsonPath = resolve(RESULTS_DIR, `benchmark-${timestamp}.json`); |
| 121 | + writeFileSync(jsonPath, JSON.stringify({ timestamp, host: HOST, duration_s: DURATION, connections: CONNECTIONS, results: allResults }, null, 2)); |
| 122 | + |
| 123 | + // Write Markdown summary |
| 124 | + const mdPath = resolve(RESULTS_DIR, `benchmark-${timestamp}.md`); |
| 125 | + const mdLines = [ |
| 126 | + `# API Benchmark Results`, |
| 127 | + ``, |
| 128 | + `**Date:** ${new Date().toISOString()} `, |
| 129 | + `**Host:** ${HOST} `, |
| 130 | + `**Duration:** ${DURATION}s per endpoint `, |
| 131 | + `**Connections:** ${CONNECTIONS} concurrent `, |
| 132 | + ``, |
| 133 | + `## Results`, |
| 134 | + ``, |
| 135 | + `| Endpoint | Method | p50 (ms) | p95 (ms) | p99 (ms) | RPS | Error % | Status |`, |
| 136 | + `|----------|--------|----------|----------|----------|-----|---------|--------|`, |
| 137 | + ...allResults.map(r => { |
| 138 | + if (r.error) return `| ${r.path} | ${r.method} | - | - | - | - | - | ❌ ERROR |`; |
| 139 | + const key = Object.keys(thresholds.endpoints).find(k => r.path.startsWith(k)); |
| 140 | + const threshold = key ? thresholds.endpoints[key].p99_latency_ms : thresholds.defaults.p99_latency_ms; |
| 141 | + const status = r.p99_ms <= threshold ? "✅ PASS" : "❌ FAIL"; |
| 142 | + return `| ${r.path} | ${r.method} | ${r.p50_ms} | ${r.p95_ms} | ${r.p99_ms} | ${r.rps_sustained} | ${r.error_rate_pct}% | ${status} |`; |
| 143 | + }), |
| 144 | + ``, |
| 145 | + violations.length > 0 |
| 146 | + ? `## ⚠️ Threshold Violations\n\n${violations.map(v => `- **${v.path}**: p99=${v.p99_ms}ms exceeds threshold of ${v.threshold_ms}ms`).join("\n")}` |
| 147 | + : `## ✅ All endpoints within thresholds`, |
| 148 | + ]; |
| 149 | + writeFileSync(mdPath, mdLines.join("\n")); |
| 150 | + |
| 151 | + console.log(`\n📊 Results saved:`); |
| 152 | + console.log(` JSON: ${jsonPath}`); |
| 153 | + console.log(` MD: ${mdPath}`); |
| 154 | + |
| 155 | + if (violations.length > 0) { |
| 156 | + console.error(`\n❌ ${violations.length} threshold violation(s) detected. CI gate FAILED.`); |
| 157 | + process.exit(1); |
| 158 | + } else { |
| 159 | + console.log(`\n✅ All endpoints within thresholds. CI gate PASSED.`); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +main().catch(err => { console.error(err); process.exit(1); }); |
0 commit comments