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

82 lines
5.4 KiB
JavaScript

// Bounded authenticated reads using a dedicated account. Credentials stay on stdin/in memory.
const { execFileSync } = require('node:child_process');
const { readFileSync, writeFileSync, mkdirSync } = require('node:fs');
const { resolve, dirname } = require('node:path');
const { performance } = require('node:perf_hooks');
const { parse } = require('dotenv');
async function main() {
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-AUTHENTICATED-2026-11-15.json');
const curl = process.platform === 'win32' ? 'curl.exe' : 'curl';
const samples = [];
const quote = (value) => JSON.stringify(String(value));
const send = async (path, token, body) => {
// No shell, redirects, debug output, URL credentials or secret command-line arguments.
const config = ['silent', 'show-error', 'connect-timeout = 5', 'max-time = 15',
`url = ${quote(origin + path)}`, 'write-out = "\\n%{json}"'];
if (token) config.push(`header = ${quote(`Authorization: Bearer ${token}`)}`);
if (body) config.push('request = "POST"', 'header = "Content-Type: application/json"', `data = ${quote(JSON.stringify(body))}`);
const started = performance.now();
let stdout = '';
try { stdout = execFileSync(curl, ['--config', '-'], { input: config.join('\n'), encoding: 'utf8',
timeout: 20000, maxBuffer: 8 * 1024 * 1024, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); }
catch (error) { stdout = String(error.stdout || ''); }
const split = stdout.lastIndexOf('\n');
let metrics = {}, json;
try { metrics = JSON.parse(stdout.slice(split + 1)); } catch { /* transport failure */ }
try { json = JSON.parse(stdout.slice(0, split)); } catch { /* non-JSON */ }
const row = { method: body ? 'POST' : 'GET', path, status: metrics.http_code || 0,
totalMs: metrics.time_total != null ? +(metrics.time_total * 1000).toFixed(2) : +(performance.now() - started).toFixed(2),
ttfbMs: metrics.time_starttransfer != null ? +(metrics.time_starttransfer * 1000).toFixed(2) : null,
bytes: metrics.size_download ?? 0 };
samples.push(row);
await new Promise((done) => setTimeout(done, 350));
return { row, data: json?.data ?? json };
};
let limitation;
// Check availability before reading credentials or creating a login session.
const health = await send('/api/v1/health');
if (health.row.status !== 200) limitation = 'Public health unavailable from measurement environment; no login attempted.';
else {
let credentials;
try { credentials = parse(readFileSync(resolve('.env.perf.local'))); }
catch { throw new Error('Create the ignored .env.perf.local with PERF_TEST_EMAIL and PERF_TEST_PASSWORD.'); }
if (!credentials.PERF_TEST_EMAIL || !credentials.PERF_TEST_PASSWORD) throw new Error('Dedicated test-account fields are missing.');
const login = await send('/api/v1/auth/login', null, { email: credentials.PERF_TEST_EMAIL, password: credentials.PERF_TEST_PASSWORD });
credentials = null;
if (login.row.status !== 200 || !login.data?.accessToken) limitation = 'Test-account login failed; no authenticated reads attempted.';
else {
const token = login.data.accessToken;
for (const path of [
'/api/v1/auth/sessions', '/api/v1/users/me/dashboard', '/api/v1/users/me/share-friends',
'/api/v1/feed/me?limit=10', '/api/v1/feed/trending?limit=10', '/api/v1/feed/explore?limit=10',
'/api/v1/feed/reels?limit=10', '/api/v1/search?q=music&limit=10', '/api/v1/search/suggestions?q=music',
'/api/v1/chat/conversations?limit=10', '/api/v1/notifications?limit=10', '/api/v1/notifications/unread-counts',
'/api/v1/reports/options', '/api/v1/reports/me?limit=10', '/api/v1/saves/me?limit=10',
'/api/v1/support/tickets?limit=10', '/api/v1/blocks', '/api/v1/engagement/me/summary',
]) {
for (let i = 0; i < 5; i++) {
const result = await send(path, token);
if ([401, 429].includes(result.row.status) || result.row.status >= 500 || result.row.status === 0) {
limitation = `Stopped on HTTP ${result.row.status} at ${path}; no repeated login or load pressure.`; break;
}
}
if (limitation) break;
}
// Revoke only this newly-created benchmark session. Never persist refresh tokens.
if (login.data.refreshToken) await send('/api/v1/auth/logout', token, { refreshToken: login.data.refreshToken });
login.data = null;
}
}
mkdirSync(dirname(output), { recursive: true });
writeFileSync(output, JSON.stringify({ origin, capturedAt: new Date().toISOString(), concurrency: 1,
limitation: limitation ?? null, notes: ['Dedicated account; one login and logout, bounded GET requests only thereafter.',
'No response bodies, account identifiers, credentials or tokens stored. RTT includes TLS/network.',
'Five samples per URL are exploratory. This is not an all-route or capacity benchmark.'], samples }, null, 2) + '\n');
console.log(JSON.stringify({ requests: samples.length, limitation: limitation ?? null, output }));
if (limitation) process.exitCode = 1;
}
main().catch(() => { console.error('Authenticated measurement failed. Check the local credentials file and network; no credentials logged.'); process.exitCode = 1; });