Files
back_end_oudelaa/scripts/perf-all-routes.js

420 lines
31 KiB
JavaScript

// All gateway routes, private local MongoDB only. Never accepts a remote database or origin.
require('ts-node/register');
require('reflect-metadata');
const { spawn } = require('node:child_process');
const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve, dirname } = require('node:path');
const { createServer } = require('node:net');
const { performance } = require('node:perf_hooks');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const { JwtService } = require('@nestjs/jwt');
const { io } = require('socket.io-client');
const { catalog, routeFor } = require('./perf-route-catalog');
const { buildDataset, modelsFor, id } = require('./seed-demo');
async function freePort() {
const server = createServer();
await new Promise((done) => server.listen(0, '127.0.0.1', done));
const port = server.address().port;
await new Promise((done) => server.close(done));
return port;
}
async function stop(child) {
if (!child?.pid || child.exitCode !== null || child.signalCode !== null) return;
const stopped = new Promise((done) => child.once('exit', done));
child.kill(); await stopped;
}
function summarize(samples) {
if (!samples.length) return null;
const times = samples.map((row) => row.durationMs).sort((a, b) => a - b);
return { requests: times.length, avgMs: +(times.reduce((a, b) => a + b, 0) / times.length).toFixed(2),
p50Ms: times[Math.ceil(times.length * .5) - 1], p95Ms: times[Math.ceil(times.length * .95) - 1],
minMs: times[0], maxMs: times.at(-1) };
}
function socketEvent(socket, event, predicate = () => true) {
return new Promise((done, reject) => {
const clean = () => { clearTimeout(timer); socket.off(event, received); socket.off('socket_error', failed); socket.off('connect_error', failed); };
const received = (data) => { if (predicate(data)) { clean(); done(data); } };
const failed = () => { clean(); reject(new Error(`Socket event failed: ${event}`)); };
const timer = setTimeout(() => { clean(); reject(new Error(`Socket event timeout: ${event}`)); }, 5000);
socket.on(event, received); socket.on('socket_error', failed); socket.on('connect_error', failed);
});
}
async function realtimeMeasurements(origin, userToken, otherToken) {
const results = [];
for (const transport of ['websocket', 'polling']) {
const sockets = [], connections = [], messages = [], notifications = [];
try {
const connect = async (namespace, token) => {
const socket = io(origin + namespace, { path: '/socket.io', auth: { token },
transports: [transport], autoConnect: false, forceNew: true, reconnection: false });
sockets.push(socket);
// Presence is emitted after server-side JWT/account checks for chat.
const ready = socketEvent(socket, namespace === '/chat' ? 'presence' : 'connect');
const started = performance.now(); socket.connect(); await ready;
connections.push({ namespace, durationMs: +(performance.now() - started).toFixed(3) });
return socket;
};
const sender = await connect('/chat', userToken);
const receiver = await connect('/chat', otherToken);
const inbox = await connect('/notifications', otherToken);
for (const socket of [sender, receiver]) {
const joined = socketEvent(socket, 'joined_conversation');
socket.emit('join_conversation', { conversationId: String(id('Conversation', 0)) }); await joined;
}
for (let i = 0; i < 7; i++) {
const content = `private socket timing ${transport} ${i}`;
const started = performance.now();
const received = socketEvent(receiver, 'new_message', (data) => data.content === content)
.then(() => messages.push({ durationMs: performance.now() - started }));
const notified = socketEvent(inbox, 'notification_created', (data) => data.previewText === content)
.then(() => notifications.push({ durationMs: performance.now() - started }));
sender.emit('send_message', { conversationId: String(id('Conversation', 0)), content, messageType: 'text' });
await Promise.all([received, notified]);
}
results.push({ transport, status: 'passed', connections, messageDelivery: summarize(messages),
notificationDelivery: summarize(notifications), note: 'Private localhost delivery between two authenticated users; no FCM/device delivery.' });
} catch (error) { results.push({ transport, status: 'failed', error: error.message }); }
finally { for (const socket of sockets) socket.disconnect(); }
}
return results;
}
function fixturePath(route) {
const p = route.path;
const genericKind = p.includes('comments') ? 'Comment' : p.includes('repair-shops') ? 'RepairShop'
: /marketplace\/(?:instruments|listings)/.test(p) ? 'Instrument' : p.includes('orders') ? 'Order'
: p.includes('notifications') ? 'Notification' : p.includes('posts') ? 'Post' : 'User';
const values = {
id: String(id(genericKind, p === '/api/v1/orders/admin/:id' ? 3 : genericKind === 'User' ? 4 : 0)),
userId: String(id('User', 4)), targetUserId: String(id('User', 7)), authorId: String(id('User', 4)),
followerId: String(id('User', 5)), adminId: String(id('User', 0)), shopId: String(id('User', 0)),
postId: String(id('Post', 4)), commentId: String(id('Comment', 4)),
conversationId: String(id('Conversation', 0)), messageId: String(id('Message', 0)),
requestId: String(id('CollaborationRequest', 0)), reportId: String(id('Report', 0)),
ticketId: String(id('SupportTicket', 0)), caseId: String(id('SuperAdminCase', 0)),
orderId: String(id('Order', 0)), listingId: String(id('Instrument', 1)),
targetType: 'post', targetId: String(id('Post', 4)), historyId: String(id('SettingsHistory', 0)),
instrumentId: String(id('Instrument', 1)), repairShopId: String(id('RepairShop', 0)),
username: 'oud_demo_5', hashtag: 'موسيقى', tag: 'موسيقى',
type: 'follows', sessionId: 'isolated-unavailable-session', jti: 'isolated-unavailable-session',
};
let missing = false;
const path = p.replace(/:([A-Za-z0-9_]+)/g, (_, key) => {
if (!values[key]) { missing = true; return 'missing-fixture'; }
return encodeURIComponent(values[key]);
});
return missing || path.includes('*') ? null : path;
}
async function main() {
const arg = (name, fallback) => { const at = process.argv.indexOf(name); return at < 0 ? fallback : process.argv[at + 1]; };
const sampleCount = Number(arg('--samples', '7'));
if (!Number.isInteger(sampleCount) || sampleCount < 1 || sampleCount > 30) throw new Error('--samples: 1..30');
const output = resolve(arg('--output', 'docs/performance/ALL-ROUTES-2026-11-15.json'));
const scenarioDir = arg('--scenarios', 'docs/performance/route-final-scenarios');
const routes = catalog();
const directory = mkdtempSync(join(tmpdir(), 'oudelaa-route-perf-'));
const mongoPort = await freePort();
const port = await freePort();
const origin = `http://127.0.0.1:${port}`;
const uri = `mongodb://127.0.0.1:${mongoPort}/private_route_performance`;
const mongo = spawn(process.env.MONGOD_BINARY || 'mongod', ['--dbpath', directory, '--port', String(mongoPort),
'--bind_ip', '127.0.0.1', '--replSet', 'routePerf', '--logpath', join(directory, 'mongo.log')],
{ windowsHide: true, stdio: 'ignore' });
let connection, api;
try {
await new Promise((done, reject) => { mongo.once('spawn', done); mongo.once('error', reject); });
connection = await mongoose.createConnection(`${uri}?directConnection=true`, { serverSelectionTimeoutMS: 15000 }).asPromise();
await connection.db.admin().command({ replSetInitiate: { _id: 'routePerf', members: [{ _id: 0, host: `127.0.0.1:${mongoPort}` }] } });
// Seed-only fixture builder has no application bootstrap, email, payment or external calls.
const dataset = buildDataset(await bcrypt.hash('IsolatedPerf123!', 8));
dataset.User.forEach((user, index) => { user.email = `private_perf_${index}@example.com`; });
const models = modelsFor(connection);
await Promise.all(Object.values(models).map((model) => model.init()));
for (const [name, docs] of Object.entries(dataset)) await models[name].insertMany(docs);
const { AiMusicArchiveSchema } = require('../src/modules/media/schemas/ai-music-archive.schema.ts');
const Archive = connection.model('AiMusicArchive', AiMusicArchiveSchema);
await Archive.create({ _id: id('AiMusicArchive', 0), userId: id('User', 4), title: 'Private archive fixture',
audioUrl: '/uploads/private-perf.mp3', durationSeconds: 5 });
const { SuperAdminSettingsHistorySchema } = require('../src/modules/superadmin/schemas/superadmin-settings-history.schema.ts');
await connection.model('SuperAdminSettingsHistory', SuperAdminSettingsHistorySchema).create({
_id: id('SettingsHistory', 0), updatedBy: 'private-perf', previousSettings: {}, nextSettings: {}, changedFields: [],
});
const snapshots = await Promise.all(Object.values(connection.models).map(async (model) => ({
// Raw fixture documents retain select:false fields such as password hashes.
model, documents: await model.collection.find({}).toArray(),
})));
const restoreFixtures = async () => {
await Promise.all(snapshots.map(async ({ model, documents }) => {
await model.deleteMany({});
if (documents.length) await model.collection.insertMany(documents);
}));
};
const { NOTIFICATION_TYPES } = require('../src/modules/notifications/schemas/notification.schema.ts');
await models.Notification.insertMany(Array.from({ length: 6000 }, (_, i) => ({
recipientId: id('User', i % 5 ? 4 : 5), actorId: id('User', 7),
type: NOTIFICATION_TYPES[i % NOTIFICATION_TYPES.length], read: i % 4 === 0,
createdAt: new Date(Date.now() - i * 1000), title: `Private timing fixture ${i}`,
})));
const jwt = new JwtService();
const tokens = {
user: jwt.sign({ sub: String(id('User', 4)), role: 'user', tokenType: 'access' }, { secret: 'isolated-route-access-secret', expiresIn: '1h' }),
admin: jwt.sign({ sub: String(id('User', 0)), role: 'admin', tokenType: 'access' }, { secret: 'isolated-route-access-secret', expiresIn: '1h' }),
superadmin: jwt.sign({ sub: 'isolated-superadmin', tokenType: 'superadmin_access',
permissions: Object.values(require('../src/modules/superadmin/superadmin-permissions.ts').SUPERADMIN_PERMISSIONS) },
{ secret: 'isolated-route-superadmin-secret', expiresIn: '1h' }),
other: jwt.sign({ sub: String(id('User', 7)), role: 'user', tokenType: 'access' },
{ secret: 'isolated-route-access-secret', expiresIn: '1h' }),
followApprover: jwt.sign({ sub: String(id('User', 8)), role: 'user', tokenType: 'access' },
{ secret: 'isolated-route-access-secret', expiresIn: '1h' }),
};
api = spawn(process.execPath, [resolve('dist/main.js')], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: {
...process.env, NODE_ENV: 'test', HOST: '127.0.0.1', PORT: String(port), MONGODB_URI: `${uri}?replicaSet=routePerf`,
MONGODB_AUTO_INDEX: 'true', PUBLIC_BASE_URL: origin, STORAGE_PROVIDER: 'local', MEDIA_ACCESS_MODE: 'direct',
STORAGE_PUBLIC_BASE_URL: origin, STORAGE_BASE_PATH: 'uploads', JWT_ACCESS_SECRET: 'isolated-route-access-secret',
JWT_REFRESH_SECRET: 'isolated-route-refresh-secret', SUPERADMIN_EMAIL: 'private-perf@example.com',
SUPERADMIN_PASSWORD: 'IsolatedPerf123!', SUPERADMIN_PASSWORD_HASH: '', SUPERADMIN_TOTP_SECRET: '',
SUPERADMIN_ACCESS_SECRET: 'isolated-route-superadmin-secret', SUPERADMIN_REFRESH_SECRET: 'isolated-route-superadmin-refresh',
EMAIL_ENABLED: 'false', REDIS_ENABLED: 'false', REDIS_SOCKET_ADAPTER_ENABLED: 'false', QUEUE_ENABLED: 'false',
NOTIFICATION_SERVICE_ENABLED: 'false', OUTBOX_DISPATCHER_ENABLED: 'false', FCM_ENABLED: 'false', AI_MUSIC_ENABLED: 'false',
IMAGE_PROCESSING_ENABLED: 'false', VIDEO_PROCESSING_ENABLED: 'false', AUDIO_PROCESSING_ENABLED: 'false',
SEARCH_ENGINE: 'regex', RESPONSE_ENVELOPE_ENABLED: 'false', SWAGGER_ENABLED: 'false', REQUEST_LOGGING_ENABLED: 'false',
FEED_TIMING_LOGS_ENABLED: 'false', FEED_CACHE_ENABLED: 'false', BCRYPT_SALT_ROUNDS: '8',
} });
let logs = '';
for (const stream of [api.stdout, api.stderr]) stream.on('data', (chunk) => { logs = (logs + chunk).slice(-2000); });
const started = performance.now();
while (true) {
try { const r = await fetch(`${origin}/api/v1/health/ready`, { signal: AbortSignal.timeout(1000) }); await r.text(); if (r.ok) break; } catch { /* startup */ }
if (api.exitCode !== null || performance.now() - started > 45000) throw new Error(`Private API startup failed: ${logs}`);
await new Promise((done) => setTimeout(done, 100));
}
const samples = [];
const request = async (route, path, method = 'GET', probe = false, fixtureBody) => {
const headers = tokens[route.auth] ? { Authorization: `Bearer ${tokens[route.auth]}` } : {};
if ((probe || fixtureBody?.json) && ['POST', 'PATCH', 'PUT'].includes(method)) headers['Content-Type'] = 'application/json';
const start = performance.now();
let status = 0;
try {
const response = await fetch(origin + path, { method, headers, redirect: 'manual',
signal: AbortSignal.timeout(15000), ...(fixtureBody ? { body: fixtureBody.json ?? fixtureBody.form }
: headers['Content-Type'] ? { body: '{}' } : {}) });
status = response.status; await response.arrayBuffer();
} catch { /* Failed transport is kept as status zero, never a successful latency. */ }
const row = { method, path: route.path, status, durationMs: +(performance.now() - start).toFixed(3),
contractPassed: status >= 200 && status < 300 && !probe,
source: probe ? 'empty-payload-probe-only' : method === 'GET' ? 'isolated-authenticated-read' : 'postman-fixture-write' };
samples.push(row); return row;
};
const excluded = (route) => /\/auth\/google|\/media\/hls\//.test(route.path);
for (const route of routes.filter((r) => r.method === 'GET')) {
const path = route.path === '/api/v1/media/ai/music/archive/:id'
? `/api/v1/media/ai/music/archive/${id('AiMusicArchive', 0)}` : fixturePath(route);
if (!path || excluded(route)) continue;
const query = route.path === '/api/v1/search' || route.path === '/api/v1/music-world/search'
|| route.path.startsWith('/api/v1/search/') ? '?q=music' : '';
await request(route, path + query); // cold sample retained separately
for (let i = 0; i < sampleCount; i++) {
const row = await request(route, path + query); row.warm = true;
}
console.log(`GET ${route.path} ${samples.at(-1).status}`);
}
const realtime = await realtimeMeasurements(origin, tokens.user, tokens.other);
// Real write scenarios are captured by the existing e2e suite. Remaining local
// routes receive one empty-body probe, explicitly excluded from feature latency.
const scenarioSamples = [];
try {
for (const file of readdirSync(scenarioDir).filter((name) => name.endsWith('.jsonl'))) {
for (const line of readFileSync(join(scenarioDir, file), 'utf8').trim().split('\n').filter(Boolean)) scenarioSamples.push(JSON.parse(line));
}
} catch (error) { if (error.code !== 'ENOENT') throw error; }
samples.push(...scenarioSamples);
const flatten = (items) => items.flatMap((item) => item.item ? flatten(item.item) : item.request ? [item] : []);
const collection = JSON.parse(readFileSync('postman/Oudelaa-Auth-Users-Posts.postman_collection.json', 'utf8'));
const examples = flatten(collection.item);
const variables = Object.fromEntries((collection.variable || []).map((entry) => [entry.key, String(entry.value)]));
Object.assign(variables, {
baseUrl: origin + '/api/v1', email: 'private_perf_4@example.com', password: 'IsolatedPerf123!',
registerEmail: 'private_perf_new@example.com', registerUsername: 'private_perf_new', newPassword: 'IsolatedPerfNew123!',
username: 'oud_demo_5', userId: String(id('User', 4)), targetUserId: String(id('User', 7)),
targetUsername: 'oud_demo_8', secondaryUsername: 'oud_demo_8', mentionUsername: 'oud_demo_8',
adminId: String(id('User', 0)), adminUserId: String(id('User', 0)), adminEmail: 'private_perf_0@example.com',
adminPassword: 'IsolatedPerf123!', ownPostId: String(id('Post', 4)), postId: String(id('Post', 4)),
ownCommentId: String(id('Comment', 3)), commentId: String(id('Comment', 4)),
conversationId: String(id('Conversation', 0)), messageId: String(id('Message', 1)), replyToMessageId: String(id('Message', 0)),
listingId: String(id('Instrument', 0)), instrumentId: String(id('Instrument', 0)), repairShopId: String(id('RepairShop', 0)),
collaboratorId: String(id('User', 7)), collaborationRequestId: String(id('CollaborationRequest', 0)),
followRequestId: String(id('FollowRequest', 0)), notificationId: String(id('Notification', 4)),
reportId: String(id('Report', 0)), supportTicketId: String(id('SupportTicket', 0)),
historyId: String(id('SettingsHistory', 0)), aiArchiveItemId: String(id('AiMusicArchive', 0)),
supportAdminId: String(id('User', 0)), caseId: String(id('SuperAdminCase', 0)), followerId: String(id('User', 5)),
targetAccessToken: tokens.user, accessToken: tokens.user, adminAccessToken: tokens.admin,
superAdminAccessToken: tokens.superadmin, bulkActionTargetId: String(id('User', 7)),
});
const substitute = (value) => String(value).replace(/\{\{([^}]+)\}\}/g, (match, key) => variables[key] ?? match);
const fixtureSetup = async (path, body) => {
const response = await fetch(origin + path, { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), redirect: 'manual', signal: AbortSignal.timeout(15000) });
const data = await response.json();
if (!response.ok) throw new Error(`Private auth fixture setup failed: ${path} HTTP ${response.status}`);
return data.data ?? data;
};
for (const route of routes.filter((r) => r.method !== 'GET')) {
if (samples.some((s) => s.method === route.method && s.path === route.path && s.contractPassed && s.status < 300)) continue;
const example = examples.find((item) => {
const url = typeof item.request.url === 'string' ? item.request.url : item.request.url?.raw;
return url && item.request.method === route.method
&& routeFor(routes, route.method, url.replace('{{baseUrl}}', origin + '/api/v1'))?.path === route.path;
});
if (!example) continue;
const body = example.request.body;
// Every independent write starts from the same small, validated fixture set.
await restoreFixtures();
variables.registerEmail = route.path === '/api/v1/auth/register' ? 'private_perf_new@example.com' : variables.email;
if (['/api/v1/auth/logout', '/api/v1/auth/refresh', '/api/v1/auth/sessions/:jti/revoke'].includes(route.path)) {
const login = await fixtureSetup('/api/v1/auth/login', { email: variables.email, password: variables.password });
variables.refreshToken = login.refreshToken;
variables.sessionJti = jwt.decode(login.refreshToken)?.jti ?? '';
}
if (['/api/v1/auth/verify-reset-code', '/api/v1/auth/reset-password'].includes(route.path)) {
const reset = await fixtureSetup('/api/v1/auth/forgot-password', { email: variables.email });
variables.resetCode = reset.debugCode;
if (route.path === '/api/v1/auth/reset-password') {
const verified = await fixtureSetup('/api/v1/auth/verify-reset-code', { email: variables.email, code: reset.debugCode });
variables.resetToken = verified.resetToken;
}
}
if (route.path === '/api/v1/auth/send-email-verification') {
await models.User.updateOne({ _id: id('User', 4) }, { $set: { isEmailVerified: false } });
}
if (route.path === '/api/v1/marketplace/admin/repair-shops' && route.method === 'POST') {
await models.RepairShop.deleteMany({ ownerAdminId: id('User', 0) });
}
let fixtureBody;
if (body?.mode === 'raw') {
let json = substitute(body.raw).replaceAll('StrongPass123!', 'IsolatedPerf123!');
if (route.path === '/api/v1/superadmin/cases') json = JSON.stringify({ title: 'Private performance review',
caseType: 'report_review', resourceType: 'post', resourceId: String(id('Post', 4)), priority: 'normal' });
if (route.path === '/api/v1/superadmin/cases/:caseId') json = JSON.stringify({ status: 'in_review', priority: 'high' });
if (route.path === '/api/v1/superadmin/bulk-actions') json = JSON.stringify({ resourceType: 'post',
targetIds: [String(id('Post', 4))], action: 'flag', reason: 'Private fixture' });
if (json.includes('{{')) continue;
try { JSON.parse(json); } catch { continue; }
fixtureBody = { json };
} else if (body?.mode === 'formdata') {
const form = new FormData();
let unresolved = false;
for (const field of body.formdata.filter((field) => !field.disabled && field.type !== 'file')) {
const value = substitute(field.value);
if (value.includes('{{')) { unresolved = true; break; }
form.append(field.key, value);
}
if (unresolved) continue;
fixtureBody = { form };
} else if (body) continue;
const template = typeof example.request.url === 'string' ? example.request.url : example.request.url.raw;
const url = substitute(template);
if (url.includes('{{')) continue;
const parsed = new URL(url);
if (parsed.origin !== origin || !parsed.pathname.startsWith('/api/v1/')) throw new Error('Private fixture escaped loopback');
if (routeFor(routes, route.method, parsed.pathname)?.path !== route.path) continue;
const actor = /collaboration-requests\/:requestId\/(approve|reject)$/.test(route.path) ? 'other'
: /follows\/requests\/:requestId\/(approve|reject)$/.test(route.path) ? 'followApprover' : route.auth;
const row = await request({ ...route, auth: actor }, parsed.pathname + parsed.search, route.method, false, fixtureBody);
console.log(`${route.method} ${route.path} ${row.status} (fixture)`);
}
const post = String(id('Post', 4)), targetPost = String(id('Post', 7));
const listing = String(id('Instrument', 0)), repair = String(id('RepairShop', 0));
const comment = String(id('Comment', 4)), target = String(id('User', 7));
const makeForm = (fields) => { const form = new FormData(); for (const [key, value] of Object.entries(fields)) form.append(key, String(value)); return form; };
const manualCases = [
{ method: 'POST', path: '/api/v1/auth/change-password', body: { currentPassword: variables.password, newPassword: 'PrivateChanged123!' } },
{ method: 'POST', path: '/api/v1/auth/superadmin/logout', setup: async () => {
const login = await fixtureSetup('/api/v1/auth/superadmin/login', { email: 'private-perf@example.com', password: variables.password });
return { refreshToken: login.refreshToken };
} },
{ method: 'POST', path: '/api/v1/chat/messages/upload', form: () => {
const form = makeForm({ conversationId: id('Conversation', 0), messageType: 'image', content: 'Private upload fixture' });
form.append('mediaFile', new Blob([Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WlH0i8AAAAASUVORK5CYII=', 'base64')], { type: 'image/png' }), 'private-perf.png');
return form;
} },
{ method: 'PATCH', path: `/api/v1/collaboration-requests/${id('CollaborationRequest', 0)}/cancel`, body: {} },
{ method: 'DELETE', path: `/api/v1/comments/${id('Comment', 3)}` },
{ method: 'POST', path: '/api/v1/devices/register', body: { fcmToken: 'private-perf-token', platform: 'android', deviceId: 'private-perf-device' } },
{ method: 'POST', path: '/api/v1/devices/unregister', body: { deviceId: 'private-perf-device' }, setup: async () => {
const r = routes.find((r) => r.path === '/api/v1/devices/register');
await request(r, r.path, 'POST', false, { json: JSON.stringify({ fcmToken: 'private-perf-token', platform: 'android', deviceId: 'private-perf-device' }) });
} },
{ method: 'POST', path: '/api/v1/engagement/events', body: { postId: post, type: 'impression' } },
{ method: 'POST', path: '/api/v1/internal/maintenance/reconcile-post-counters', body: {} },
{ method: 'POST', path: `/api/v1/marketplace/superadmin/admins/${id('User', 0)}/listings`, body: {
title: 'Private fixture listing', price: 100, quantity: 4, listingCategory: 'musical_instrument' } },
{ method: 'POST', path: `/api/v1/marketplace/superadmin/admins/${id('User', 0)}/repair-shops`, body: { name: 'Private fixture repair' },
setup: () => models.RepairShop.deleteMany({ ownerAdminId: id('User', 0) }) },
{ method: 'DELETE', path: `/api/v1/marketplace/superadmin/listings/${listing}` },
{ method: 'PATCH', path: `/api/v1/marketplace/superadmin/listings/${listing}/status`, body: { isActive: false, reason: 'Private fixture' } },
{ method: 'DELETE', path: `/api/v1/marketplace/superadmin/repair-shops/${repair}` },
{ method: 'PATCH', path: `/api/v1/marketplace/superadmin/repair-shops/${repair}/status`, body: { isActive: false, reason: 'Private fixture' } },
{ method: 'POST', path: '/api/v1/orders', body: { listingId: String(id('Instrument', 4)), quantity: 1, customerName: 'Private buyer', customerPhone: '+966500000000' } },
{ method: 'POST', path: `/api/v1/posts/${targetPost}/collaboration-requests`, body: { collaborationType: 'duet', message: 'Private fixture' } },
{ method: 'POST', path: `/api/v1/posts/${post}/play`, body: {}, setup: () => models.Post.updateOne({ _id: id('Post', 4) },
{ $set: { postType: 'audio', audioUrl: origin + '/uploads/private-perf.mp3', durationSeconds: 5 } }) },
{ method: 'POST', path: `/api/v1/posts/${targetPost}/repost`, body: { content: 'Private quote' } },
{ method: 'DELETE', path: `/api/v1/posts/admin/${post}` },
{ method: 'POST', path: '/api/v1/posts/reels', form: () => makeForm({ videoUrl: origin + '/uploads/private-perf.mp4', durationSeconds: 5, content: 'Private reel metadata' }) },
{ method: 'POST', path: `/api/v1/superadmin/comments/${comment}/restore`, body: {},
setup: () => models.Comment.updateOne({ _id: id('Comment', 4) }, { $set: { isDeleted: true } }) },
{ method: 'POST', path: `/api/v1/superadmin/posts/${post}/restore`, body: {},
setup: () => models.Post.updateOne({ _id: id('Post', 4) }, { $set: { isDeleted: true } }) },
{ method: 'POST', path: `/api/v1/users/${target}/follow`, body: {} },
{ method: 'DELETE', path: `/api/v1/users/${target}/follow` },
{ method: 'POST', path: '/api/v1/users/admin/create-admin', body: { name: 'Private admin fixture', username: 'private_new_admin',
email: 'private_new_admin@example.com', password: variables.password, confirmPassword: variables.password } },
];
for (const fixture of manualCases) {
const route = routeFor(routes, fixture.method, fixture.path);
if (!route || samples.some((s) => s.method === route.method && s.path === route.path && s.contractPassed && s.status < 300)) continue;
await restoreFixtures();
const prepared = fixture.setup ? await fixture.setup() : undefined;
const body = fixture.body ?? (fixture.path === '/api/v1/auth/superadmin/logout' ? prepared : undefined);
const fixtureBody = fixture.form ? { form: fixture.form() } : body ? { json: JSON.stringify(body) } : undefined;
const row = await request(route, fixture.path, fixture.method, false, fixtureBody);
row.source = 'explicit-private-fixture';
console.log(`${route.method} ${route.path} ${row.status} (explicit fixture)`);
}
for (const route of routes.filter((r) => r.method !== 'GET')) {
if (samples.some((s) => s.method === route.method && s.path === route.path && s.contractPassed && s.status < 300)) continue;
const path = fixturePath(route);
if (path && !excluded(route)) { await restoreFixtures(); await request(route, path, route.method, true); }
}
const rows = routes.map((route) => {
const observed = samples.filter((s) => s.method === route.method && s.path === route.path);
const success = observed.filter((s) => s.contractPassed && s.status >= 200 && s.status < 300);
const reads = success.filter((s) => s.source === 'isolated-authenticated-read' && s.warm);
return { ...route, coverage: success.length ? 'successful-scenario' : observed.length ? 'probe-or-failure-only' : 'not-exercised',
successfulLatency: summarize(reads.length ? reads : success), exploratorySmallSample: (reads.length || success.length) < 30,
statusCounts: observed.reduce((a, s) => { a[s.status] = (a[s.status] || 0) + 1; return a; }, {}),
sampleSources: [...new Set(observed.map((s) => s.source))] };
});
const report = { capturedAt: new Date().toISOString(), environment: 'private localhost MongoDB replica set + real HTTP API',
dataset: { ...Object.fromEntries(Object.entries(dataset).map(([k, v]) => [k, v.length])), Notification: dataset.Notification.length + 6000 },
disabledDependencies: ['Redis', 'SMTP', 'FCM', 'AI music', 'image/audio/video processing', 'notification worker'],
notes: ['All gateway controller URLs inventoried. External OAuth and signed S3 HLS need dedicated integration environments.',
'2xx empty-body probes are NOT validated feature scenarios. Errors/probes are excluded from successfulLatency.',
'Read samples include the full response body, JWT authentication and response middleware. Warm timings follow one cold request.',
'Write coverage combines asserted integration scenarios and single Postman fixture requests. 2xx fixture requests are not full business-flow assertions. The validated seed fixtures are restored before each independent write.',
'Small-sample p95 is exploratory; this is not a capacity/load test. Fixture sizes differ between existing write scenarios and read sweep.',
'No credentials, response bodies, query values or resolved resource IDs are stored. Local temporary database is retained for inspection.'],
realtime, counts: { totalRoutes: rows.length, successful: rows.filter((r) => r.coverage === 'successful-scenario').length,
probeOrFailureOnly: rows.filter((r) => r.coverage === 'probe-or-failure-only').length,
notExercised: rows.filter((r) => r.coverage === 'not-exercised').length }, rows, samples };
mkdirSync(dirname(output), { recursive: true });
writeFileSync(output, JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify(report.counts));
console.log(`Saved ${output}`);
} finally { await stop(api); if (connection) await connection.close(); await stop(mongo); }
}
main().catch((error) => { console.error(error.message); process.exitCode = 1; });