Files
back_end_oudelaa/scripts/measure-live-readonly.js

132 lines
6.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Bounded public GET measurements. No login, writes, credentials or concurrency.
const { execFileSync } = require('node:child_process');
const { mkdtempSync, readFileSync, writeFileSync, mkdirSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const origin = new URL(process.argv[2] || 'https://oudelaa-api1-web-35ee485c.hosted.cumin.dev').origin;
if (!origin.startsWith('https://')) throw new Error('HTTPS origin required');
const output = resolve(process.argv[3] || 'docs/performance/LIVE-API-READONLY-2026-11-14.json');
const curl = process.platform === 'win32' ? 'curl.exe' : 'curl';
const directory = mkdtempSync(join(tmpdir(), 'oudelaa-readonly-speed-'));
const rows = [];
const summaries = [];
let transfers = 0;
const percentile = (sorted, fraction) => sorted[Math.ceil(sorted.length * fraction) - 1] ?? null;
const round = (value) => Math.round(value * 100) / 100;
const average = (values) => values.length ? round(values.reduce((sum, value) => sum + value, 0) / values.length) : null;
const quote = (value) => JSON.stringify(String(value).replaceAll('\\', '/'));
function inspectBody(body) {
try {
const json = JSON.parse(body);
const data = json.data ?? json;
return {
json: true, envelope: !!json.data,
keys: data && typeof data === 'object' ? Object.keys(data) : [],
itemsCount: Array.isArray(data.items) ? data.items.length : null,
total: typeof data.total === 'number' ? data.total : null,
status: typeof data.status === 'string' ? data.status : null,
};
} catch { return { json: false }; }
}
function measure(path, samples, expectedStatus = 200) {
if (!path.startsWith('/api/v1/') || path.includes('\n') || transfers + samples > 50) {
throw new Error('Only bounded /api/v1/ GET measurements are allowed');
}
const files = [];
const config = ['rate = "3/s"'];
for (let i = 0; i < samples; i++) {
if (i) config.push('next');
const file = join(directory, `${transfers++}.json`);
files.push(file);
config.push('silent', 'show-error', 'connect-timeout = 5', 'max-time = 10',
`url = ${quote(origin + path)}`, `output = ${quote(file)}`, 'write-out = "%{json}\\n"');
}
let stdout;
try {
stdout = execFileSync(curl, ['--config', '-'], {
input: config.join('\n'), encoding: 'utf8', timeout: 55000,
maxBuffer: 1024 * 1024, windowsHide: true,
});
} catch (error) { stdout = String(error.stdout || ''); }
const metrics = stdout.trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
let lastBody = '';
const group = files.map((file, index) => {
try { lastBody = readFileSync(file, 'utf8'); } catch { lastBody = ''; }
const entry = metrics[index];
const row = {
path, sample: index + 1, expectedStatus, status: entry?.http_code ?? 0,
curlExit: entry?.exitcode ?? -1, totalMs: entry ? round(entry.time_total * 1000) : null,
ttfbMs: entry ? round(entry.time_starttransfer * 1000) : null,
dnsMs: entry ? round(entry.time_namelookup * 1000) : null,
tlsCumulativeMs: entry ? round(entry.time_appconnect * 1000) : null,
newConnections: entry?.num_connects ?? null, bytes: entry?.size_download ?? 0,
body: inspectBody(lastBody),
};
rows.push(row);
return row;
});
const valid = group.filter((row) => row.curlExit === 0 && row.status === expectedStatus);
const fresh = valid.filter((row) => row.newConnections > 0);
const reused = valid.filter((row) => row.newConnections === 0);
const times = valid.map((row) => row.totalMs).sort((a, b) => a - b);
const summary = {
path, expectedStatus, requests: samples, expectedResponses: valid.length,
statusCounts: group.reduce((counts, row) => ({ ...counts, [row.status]: (counts[row.status] ?? 0) + 1 }), {}),
freshConnections: fresh.length, reusedConnections: reused.length,
avgMs: average(times), freshAvgMs: average(fresh.map((row) => row.totalMs)),
reusedAvgMs: average(reused.map((row) => row.totalMs)),
p50Ms: percentile(times, 0.5), p95Ms: percentile(times, 0.95),
minMs: times[0] ?? null, maxMs: times.at(-1) ?? null,
body: group.at(-1)?.body,
interpretation: expectedStatus === 401 ? 'Unauthenticated guard probe; not authorized feature latency' : 'Public read latency',
};
summaries.push(summary);
console.log(JSON.stringify(summary));
try { return JSON.parse(lastBody).data ?? JSON.parse(lastBody); } catch { return null; }
}
try {
const results = {};
for (const path of [
'/api/v1/health', '/api/v1/health/ready',
'/api/v1/marketplace/home?listingsLimit=5&instrumentsLimit=5&repairShopsLimit=5',
'/api/v1/marketplace/listings?limit=10', '/api/v1/marketplace/instruments?limit=10',
'/api/v1/marketplace/repair-shops?limit=10', '/api/v1/marketplace/listings?q=oud&limit=5',
]) results[path] = measure(path, 5);
// Only request details using IDs actually returned by the public catalog.
const listing = results['/api/v1/marketplace/listings?limit=10']?.items?.[0];
const listingId = String(listing?.id ?? listing?._id ?? '');
const shopId = String(listing?.shopId ?? '');
if (/^[a-f0-9]{24}$/i.test(listingId)) measure(`/api/v1/marketplace/listings/${listingId}`, 3);
if (/^[a-f0-9]{24}$/i.test(shopId)) {
measure(`/api/v1/marketplace/shops/${shopId}`, 3);
measure(`/api/v1/marketplace/shops/${shopId}/listings?limit=5`, 3);
}
for (const path of [
'/api/v1/feed/me?limit=5', '/api/v1/search?q=oud&limit=5',
'/api/v1/chat/conversations?limit=5', '/api/v1/notifications?limit=5',
'/api/v1/reports/options', '/api/v1/auth/sessions',
]) measure(path, 1, 401);
mkdirSync(require('node:path').dirname(output), { recursive: true });
writeFileSync(output, JSON.stringify({
origin, capturedAt: new Date().toISOString(), method: 'GET', concurrency: 1,
maxRequestRatePerSecond: 3, requestCount: rows.length,
notes: ['No credentials; no state-changing operations; no redirects.',
'First connection vs reused connection is detected from curl num_connects, not assumed.',
'Body output stores only structure/count/status; temporary response bodies are removed.',
'P95 from 3–5 samples is exploratory and equals the maximum under nearest-rank estimation.',
'401 probes do not measure the authenticated feature or prove the route exists.'],
summaries, samples: rows,
}, null, 2) + '\n');
console.log(`Saved ${rows.length} GET measurements to ${output}`);
} finally {
// Delete only the exact temporary files created above; never recursively delete paths.
for (let i = 0; i < transfers; i++) rmSync(join(directory, `${i}.json`), { force: true });
require('node:fs').rmdirSync(directory);
}