/ opencodehub / scripts / perf / load-baseline.mjs
Swadhin Biswas fix(ts): eliminate all 127 TypeScript errors · 4/21/2026
18087d6
174 lines · 4.6 KB
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
#!/usr/bin/env node
import { writeFileSync } from "node:fs";
import { performance } from "node:perf_hooks";

const baseUrl = (process.env.PERF_BASE_URL || "http://127.0.0.1:3000").replace(
  /\/$/,
  "",
);
const paths = (process.env.PERF_PATHS || "/api/health,/api/metrics")
  .split(",")
  .map((path) => path.trim())
  .filter(Boolean);
const concurrency = Math.max(
  1,
  Number.parseInt(process.env.PERF_CONCURRENCY || "8", 10) || 8,
);
const requestsPerPath = Math.max(
  1,
  Number.parseInt(process.env.PERF_REQUESTS || "100", 10) || 100,
);
const timeoutMs = Math.max(
  1000,
  Number.parseInt(process.env.PERF_TIMEOUT_MS || "10000", 10) || 10000,
);
const maxP95Ms = Math.max(
  1,
  Number.parseFloat(process.env.PERF_MAX_P95_MS || "500") || 500,
);
const outputPath = process.env.PERF_OUTPUT || "";

function percentile(values, pct) {
  if (!values.length) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const index = Math.min(
    sorted.length - 1,
    Math.max(0, Math.ceil((pct / 100) * sorted.length) - 1),
  );
  return sorted[index];
}

function stats(samples) {
  const avg = samples.reduce((sum, value) => sum + value, 0) / samples.length;
  return {
    count: samples.length,
    avgMs: Number(avg.toFixed(2)),
    p50Ms: Number(percentile(samples, 50).toFixed(2)),
    p95Ms: Number(percentile(samples, 95).toFixed(2)),
    p99Ms: Number(percentile(samples, 99).toFixed(2)),
    minMs: Number(Math.min(...samples).toFixed(2)),
    maxMs: Number(Math.max(...samples).toFixed(2)),
  };
}

async function fetchWithTimeout(url) {
  const controller = new AbortController();
  const timer = setTimeout(
    () => controller.abort(new Error(`Timed out after ${timeoutMs}ms`)),
    timeoutMs,
  );
  const started = performance.now();

  try {
    const response = await fetch(url, {
      method: "GET",
      headers: {
        Accept: "application/json, text/plain, */*",
      },
      signal: controller.signal,
    });

    await response.arrayBuffer();
    return {
      ok: response.ok,
      status: response.status,
      durationMs: performance.now() - started,
    };
  } finally {
    clearTimeout(timer);
  }
}

async function benchmarkPath(path) {
  const url = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
  const durations = [];
  const statuses = new Map();
  const failures = [];
  let nextIndex = 0;

  async function worker() {
    while (nextIndex < requestsPerPath) {
      const current = nextIndex++;
      try {
        const result = await fetchWithTimeout(url);
        durations.push(result.durationMs);
        statuses.set(result.status, (statuses.get(result.status) || 0) + 1);
        if (!result.ok) {
          failures.push({ index: current, status: result.status });
        }
      } catch (error) {
        failures.push({
          index: current,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }
  }

  const workers = Array.from({ length: concurrency }, () => worker());
  await Promise.all(workers);

  const summary = stats(durations);
  return {
    path,
    url,
    concurrency,
    requests: requestsPerPath,
    statuses: Object.fromEntries(statuses.entries()),
    failures,
    ...summary,
    thresholdMs: maxP95Ms,
    passed: failures.length === 0 && summary.p95Ms <= maxP95Ms,
  };
}

async function main() {
  console.log(`[perf] Base URL: ${baseUrl}`);
  console.log(`[perf] Paths: ${paths.join(", ")}`);
  console.log(
    `[perf] Concurrency: ${concurrency}, requests/path: ${requestsPerPath}, timeout: ${timeoutMs}ms`,
  );
  console.log(`[perf] P95 threshold: ${maxP95Ms}ms`);

  const results = [];
  for (const path of paths) {
    const result = await benchmarkPath(path);
    results.push(result);
    const verdict = result.passed ? "PASS" : "FAIL";
    console.log(
      `[perf] ${verdict} ${path} p95=${result.p95Ms}ms avg=${result.avgMs}ms max=${result.maxMs}ms statuses=${JSON.stringify(result.statuses)}`,
    );
    if (result.failures.length > 0) {
      console.log(`[perf]   failures: ${result.failures.length}`);
    }
  }

  const report = {
    baseUrl,
    concurrency,
    requestsPerPath,
    timeoutMs,
    maxP95Ms,
    generatedAt: new Date().toISOString(),
    results,
  };

  if (outputPath) {
    writeFileSync(outputPath, JSON.stringify(report, null, 2));
    console.log(`[perf] Report written to ${outputPath}`);
  }

  const failed = results.filter((result) => !result.passed);
  if (failed.length > 0) {
    console.error(
      `[perf] ${failed.length} path(s) exceeded the threshold or returned errors.`,
    );
    process.exitCode = 1;
  }
}

main().catch((error) => {
  console.error("[perf] Benchmark failed:", error);
  process.exitCode = 1;
});