Files
back_end_oudelaa/scripts/perf-mixed-read.js

174 lines
7.8 KiB
JavaScript

const { performance } = require('node:perf_hooks');
const { evaluatePerformanceGates } = require('./load-test');
// Millisecond buckets bound memory even during multi-hour runs. Percentiles
// are conservative upper bounds, not exact sample percentiles.
const BUCKETS = [5, 10, 20, 30, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 1500, 2000, 3000, 5000, 10000, 15000];
const MIX = ['feed', 'feed', 'feed', 'feed', 'trending', 'trending', 'post', 'profile', 'notifications', 'search'];
const emptyStats = () => ({
requests: 0, successes: 0, totalMs: 0, maxMs: 0,
buckets: Array(BUCKETS.length + 1).fill(0), statuses: {},
timeouts: 0, networkErrors: 0, invalidPayloads: 0,
});
function record(stats, elapsed, status, outcome) {
stats.requests += 1;
stats.statuses[status] = (stats.statuses[status] ?? 0) + 1;
if (outcome !== 'success') {
if (outcome === 'timeout') stats.timeouts += 1;
if (outcome === 'network') stats.networkErrors += 1;
if (outcome === 'payload') stats.invalidPayloads += 1;
return;
}
stats.successes += 1;
stats.totalMs += elapsed;
stats.maxMs = Math.max(stats.maxMs, elapsed);
const index = BUCKETS.findIndex((bound) => elapsed <= bound);
stats.buckets[index < 0 ? BUCKETS.length : index] += 1;
}
function summarize(stats, elapsedMs) {
const percentile = (fraction) => {
if (!stats.successes) return null;
const target = Math.ceil(stats.successes * fraction);
let count = 0;
for (let i = 0; i < stats.buckets.length; i += 1) {
count += stats.buckets[i];
if (count >= target) return BUCKETS[i] ?? Math.ceil(stats.maxMs);
}
return Math.ceil(stats.maxMs);
};
return {
requests: stats.requests,
successes: stats.successes,
successRate: stats.requests ? +(100 * stats.successes / stats.requests).toFixed(3) : 0,
requestsPerSecond: +(stats.requests * 1000 / elapsedMs).toFixed(2),
successfulRequestsPerSecond: +(stats.successes * 1000 / elapsedMs).toFixed(2),
latencyMs: {
average: stats.successes ? +(stats.totalMs / stats.successes).toFixed(2) : null,
p95: percentile(0.95), p99: percentile(0.99),
},
statuses: stats.statuses, timeouts: stats.timeouts,
networkErrors: stats.networkErrors, invalidPayloads: stats.invalidPayloads,
};
}
function performanceGates(summary, gates) {
// A fast failure must never count as a low-latency successful response.
return evaluatePerformanceGates({
...summary,
requestsPerSecond: summary.successfulRequestsPerSecond,
latencyMs: {
p95: summary.latencyMs.p95 ?? Infinity,
p99: summary.latencyMs.p99 ?? Infinity,
},
}, gates);
}
async function mixedReadWorkload({ base, users, postIds, seconds, concurrency, timeoutMs = 15000,
gates = { minSuccessRate: 99, maxP95Ms: 500 } }) {
const origin = new URL(base);
if (origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' || origin.username || origin.password || origin.search || origin.hash) {
throw new Error('Mixed benchmark requires a private HTTP 127.0.0.1 API');
}
if (!Number.isInteger(concurrency) || concurrency < 1 || users.length < concurrency) {
throw new Error('Mixed benchmark requires at least one distinct synthetic user per worker');
}
if (!Number.isFinite(seconds) || seconds <= 0 || seconds > 28800 || !postIds.length ||
users.some((user) => !user.id || !user.token) || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new Error('Invalid mixed benchmark dataset or duration');
}
const overall = emptyStats();
const routes = Object.fromEntries([...new Set(MIX)].map((name) => [name, emptyStats()]));
const seenUsers = new Set();
let cursorResets = 0, paginatedRequests = 0, pageStarts = 0;
const startedAt = performance.now();
const deadline = startedAt + seconds * 1000;
const feedPath = '/feed/me?followingOnly=false&includeSuggestions=false&limit=20';
await Promise.all(Array.from({ length: concurrency }, async (_, worker) => {
// Disjoint user pools prevent workers sharing a cursor or a viewer cache.
const pool = users.filter((_, index) => index % concurrency === worker);
let iteration = 0, userIndex = 0, cursor = null;
while (performance.now() < deadline) {
const user = pool[userIndex];
const name = MIX[iteration % MIX.length];
seenUsers.add(user.id);
const paths = {
feed: feedPath + (cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''),
trending: '/feed/trending?limit=20',
post: `/posts/${postIds[(worker + iteration) % postIds.length]}`,
profile: `/users/${user.id}`,
notifications: '/notifications/unread-counts',
search: `/search?q=genre${worker % 10}&type=posts&limit=20`,
};
const began = performance.now();
let status = '0', outcome = 'network';
try {
if (name === 'feed') {
if (cursor) paginatedRequests += 1;
else pageStarts += 1;
}
const response = await fetch(`${base}${paths[name]}`, {
headers: { Authorization: `Bearer ${user.token}` },
redirect: 'error', signal: AbortSignal.timeout(timeoutMs),
});
status = String(response.status);
const body = await response.text();
outcome = 'http';
if (name === 'feed' && response.status === 410) {
cursor = null;
cursorResets += 1;
}
if (response.ok) {
outcome = 'payload';
const value = JSON.parse(body);
const page = name === 'search' ? value.posts : value;
if (['feed', 'trending', 'search'].includes(name)) {
if (!Array.isArray(page?.items) || page.items.length === 0) throw new Error('Empty benchmark feed/search page');
if (name === 'feed') cursor = value.nextCursor ?? null;
} else if (name === 'profile' || name === 'post') {
const expected = name === 'profile' ? user.id : postIds[(worker + iteration) % postIds.length];
if (String(value._id ?? value.id) !== expected) throw new Error('Wrong benchmark entity');
} else if (!value || !['total', 'interactions', 'messages', 'follows', 'followRequests', 'collaboration', 'system']
.every((key) => Number.isInteger(value[key]) && value[key] >= 0)) {
throw new Error('Invalid notification counts');
}
outcome = 'success';
}
} catch (error) {
if (outcome !== 'payload') outcome = error.name === 'TimeoutError' || error.name === 'AbortError' ? 'timeout' : 'network';
}
const elapsed = performance.now() - began;
record(overall, elapsed, status, outcome);
record(routes[name], elapsed, status, outcome);
iteration += 1;
if (iteration % MIX.length === 0) {
userIndex = (userIndex + 1) % pool.length;
cursor = null;
}
}
}));
const elapsedMs = performance.now() - startedAt;
const summary = summarize(overall, elapsedMs);
const perRoute = Object.fromEntries(Object.entries(routes).map(([name, stats]) => {
const value = summarize(stats, elapsedMs);
const { minRequestsPerSecond: _totalThroughput, ...routeGates } = gates;
return [name, { ...value, performanceGates: performanceGates(value, routeGates) }];
}));
const gateResult = performanceGates(summary, gates);
return {
...summary, concurrency, configuredUsers: users.length, measuredUsers: seenUsers.size,
durationSeconds: seconds, elapsedMs: +elapsedMs.toFixed(2),
model: 'closed-loop, one request per worker; no think time; cold cache included',
percentileMethod: 'upper bounds from fixed millisecond histogram; successful responses only',
mix: MIX, paginatedRequests, pageStarts, cursorResets, perRoute,
performanceGates: {
...gateResult,
passed: gateResult.passed && Object.values(perRoute).every((route) =>
route.successes > 0 && route.performanceGates.passed),
},
};
}
module.exports = { mixedReadWorkload };