|
| 1 | +#!/usr/bin/env node |
| 2 | +import { writeFileSync } from "node:fs"; |
| 3 | +import { performance } from "node:perf_hooks"; |
| 4 | + |
| 5 | +const baseUrl = (process.env.PERF_BASE_URL || "http://127.0.0.1:3000").replace( |
| 6 | + /\/$/, |
| 7 | + "", |
| 8 | +); |
| 9 | +const paths = (process.env.PERF_PATHS || "/api/health,/api/metrics") |
| 10 | + .split(",") |
| 11 | + .map((path) => path.trim()) |
| 12 | + .filter(Boolean); |
| 13 | +const concurrency = Math.max( |
| 14 | + 1, |
| 15 | + Number.parseInt(process.env.PERF_CONCURRENCY || "8", 10) || 8, |
| 16 | +); |
| 17 | +const requestsPerPath = Math.max( |
| 18 | + 1, |
| 19 | + Number.parseInt(process.env.PERF_REQUESTS || "100", 10) || 100, |
| 20 | +); |
| 21 | +const timeoutMs = Math.max( |
| 22 | + 1000, |
| 23 | + Number.parseInt(process.env.PERF_TIMEOUT_MS || "10000", 10) || 10000, |
| 24 | +); |
| 25 | +const maxP95Ms = Math.max( |
| 26 | + 1, |
| 27 | + Number.parseFloat(process.env.PERF_MAX_P95_MS || "500") || 500, |
| 28 | +); |
| 29 | +const outputPath = process.env.PERF_OUTPUT || ""; |
| 30 | + |
| 31 | +function percentile(values, pct) { |
| 32 | + if (!values.length) return 0; |
| 33 | + const sorted = [...values].sort((a, b) => a - b); |
| 34 | + const index = Math.min( |
| 35 | + sorted.length - 1, |
| 36 | + Math.max(0, Math.ceil((pct / 100) * sorted.length) - 1), |
| 37 | + ); |
| 38 | + return sorted[index]; |
| 39 | +} |
| 40 | + |
| 41 | +function stats(samples) { |
| 42 | + const avg = samples.reduce((sum, value) => sum + value, 0) / samples.length; |
| 43 | + return { |
| 44 | + count: samples.length, |
| 45 | + avgMs: Number(avg.toFixed(2)), |
| 46 | + p50Ms: Number(percentile(samples, 50).toFixed(2)), |
| 47 | + p95Ms: Number(percentile(samples, 95).toFixed(2)), |
| 48 | + p99Ms: Number(percentile(samples, 99).toFixed(2)), |
| 49 | + minMs: Number(Math.min(...samples).toFixed(2)), |
| 50 | + maxMs: Number(Math.max(...samples).toFixed(2)), |
| 51 | + }; |
| 52 | +} |
| 53 | + |
| 54 | +async function fetchWithTimeout(url) { |
| 55 | + const controller = new AbortController(); |
| 56 | + const timer = setTimeout( |
| 57 | + () => controller.abort(new Error(`Timed out after ${timeoutMs}ms`)), |
| 58 | + timeoutMs, |
| 59 | + ); |
| 60 | + const started = performance.now(); |
| 61 | + |
| 62 | + try { |
| 63 | + const response = await fetch(url, { |
| 64 | + method: "GET", |
| 65 | + headers: { |
| 66 | + Accept: "application/json, text/plain, */*", |
| 67 | + }, |
| 68 | + signal: controller.signal, |
| 69 | + }); |
| 70 | + |
| 71 | + await response.arrayBuffer(); |
| 72 | + return { |
| 73 | + ok: response.ok, |
| 74 | + status: response.status, |
| 75 | + durationMs: performance.now() - started, |
| 76 | + }; |
| 77 | + } finally { |
| 78 | + clearTimeout(timer); |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +async function benchmarkPath(path) { |
| 83 | + const url = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`; |
| 84 | + const durations = []; |
| 85 | + const statuses = new Map(); |
| 86 | + const failures = []; |
| 87 | + let nextIndex = 0; |
| 88 | + |
| 89 | + async function worker() { |
| 90 | + while (nextIndex < requestsPerPath) { |
| 91 | + const current = nextIndex++; |
| 92 | + try { |
| 93 | + const result = await fetchWithTimeout(url); |
| 94 | + durations.push(result.durationMs); |
| 95 | + statuses.set(result.status, (statuses.get(result.status) || 0) + 1); |
| 96 | + if (!result.ok) { |
| 97 | + failures.push({ index: current, status: result.status }); |
| 98 | + } |
| 99 | + } catch (error) { |
| 100 | + failures.push({ |
| 101 | + index: current, |
| 102 | + error: error instanceof Error ? error.message : String(error), |
| 103 | + }); |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + const workers = Array.from({ length: concurrency }, () => worker()); |
| 109 | + await Promise.all(workers); |
| 110 | + |
| 111 | + const summary = stats(durations); |
| 112 | + return { |
| 113 | + path, |
| 114 | + url, |
| 115 | + concurrency, |
| 116 | + requests: requestsPerPath, |
| 117 | + statuses: Object.fromEntries(statuses.entries()), |
| 118 | + failures, |
| 119 | + ...summary, |
| 120 | + thresholdMs: maxP95Ms, |
| 121 | + passed: failures.length === 0 && summary.p95Ms <= maxP95Ms, |
| 122 | + }; |
| 123 | +} |
| 124 | + |
| 125 | +async function main() { |
| 126 | + console.log(`[perf] Base URL: ${baseUrl}`); |
| 127 | + console.log(`[perf] Paths: ${paths.join(", ")}`); |
| 128 | + console.log( |
| 129 | + `[perf] Concurrency: ${concurrency}, requests/path: ${requestsPerPath}, timeout: ${timeoutMs}ms`, |
| 130 | + ); |
| 131 | + console.log(`[perf] P95 threshold: ${maxP95Ms}ms`); |
| 132 | + |
| 133 | + const results = []; |
| 134 | + for (const path of paths) { |
| 135 | + const result = await benchmarkPath(path); |
| 136 | + results.push(result); |
| 137 | + const verdict = result.passed ? "PASS" : "FAIL"; |
| 138 | + console.log( |
| 139 | + `[perf] ${verdict} ${path} p95=${result.p95Ms}ms avg=${result.avgMs}ms max=${result.maxMs}ms statuses=${JSON.stringify(result.statuses)}`, |
| 140 | + ); |
| 141 | + if (result.failures.length > 0) { |
| 142 | + console.log(`[perf] failures: ${result.failures.length}`); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + const report = { |
| 147 | + baseUrl, |
| 148 | + concurrency, |
| 149 | + requestsPerPath, |
| 150 | + timeoutMs, |
| 151 | + maxP95Ms, |
| 152 | + generatedAt: new Date().toISOString(), |
| 153 | + results, |
| 154 | + }; |
| 155 | + |
| 156 | + if (outputPath) { |
| 157 | + writeFileSync(outputPath, JSON.stringify(report, null, 2)); |
| 158 | + console.log(`[perf] Report written to ${outputPath}`); |
| 159 | + } |
| 160 | + |
| 161 | + const failed = results.filter((result) => !result.passed); |
| 162 | + if (failed.length > 0) { |
| 163 | + console.error( |
| 164 | + `[perf] ${failed.length} path(s) exceeded the threshold or returned errors.`, |
| 165 | + ); |
| 166 | + process.exitCode = 1; |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +main().catch((error) => { |
| 171 | + console.error("[perf] Benchmark failed:", error); |
| 172 | + process.exitCode = 1; |
| 173 | +}); |
0 commit comments