479 lines
20 KiB
JavaScript
479 lines
20 KiB
JavaScript
// Repeatable HTTP benchmark against a private, disposable MongoDB instance.
|
|
// Never reads connection strings or credentials from .env.
|
|
const { spawn } = require('node:child_process');
|
|
const { mkdtempSync, writeFileSync, existsSync } = require('node:fs');
|
|
const { tmpdir, cpus } = require('node:os');
|
|
const { join, resolve } = require('node:path');
|
|
const { createServer } = require('node:net');
|
|
const { performance } = require('node:perf_hooks');
|
|
const mongoose = require('mongoose');
|
|
const { JwtService } = require('@nestjs/jwt');
|
|
const { mixedReadWorkload } = require('./perf-mixed-read');
|
|
const { parseArgs } = require('./load-test');
|
|
|
|
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 || child.exitCode !== null || child.signalCode !== null || !child.pid) return;
|
|
const exited = new Promise((done) => child.once('exit', done));
|
|
child.kill();
|
|
await exited;
|
|
}
|
|
|
|
async function workload(url, token, seconds = 5, concurrency = 8) {
|
|
const request = async () => {
|
|
const start = performance.now();
|
|
const response = await fetch(typeof url === 'function' ? url() : url, {
|
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
signal: AbortSignal.timeout(15000),
|
|
});
|
|
const body = await response.text();
|
|
if (!response.ok) throw new Error(`Benchmark HTTP ${response.status}: ${body.slice(0, 200)}`);
|
|
return performance.now() - start;
|
|
};
|
|
for (let i = 0; i < 5; i++) await request();
|
|
const times = [];
|
|
const start = performance.now();
|
|
const deadline = start + seconds * 1000;
|
|
await Promise.all(
|
|
Array.from({ length: concurrency }, async () => {
|
|
while (performance.now() < deadline) times.push(await request());
|
|
}),
|
|
);
|
|
const elapsed = performance.now() - start;
|
|
times.sort((a, b) => a - b);
|
|
return {
|
|
concurrency,
|
|
requests: times.length,
|
|
successRate: 100,
|
|
rps: +((times.length * 1000) / elapsed).toFixed(2),
|
|
averageMs: +(times.reduce((sum, value) => sum + value, 0) / times.length).toFixed(2),
|
|
p95Ms: +times[Math.ceil(times.length * 0.95) - 1].toFixed(2),
|
|
p99Ms: +times[Math.ceil(times.length * 0.99) - 1].toFixed(2),
|
|
};
|
|
}
|
|
|
|
async function main() {
|
|
const integerOption = (name, fallback, min, max) => {
|
|
const index = process.argv.indexOf(name);
|
|
if (index < 0) return fallback;
|
|
const value = Number(process.argv[index + 1]);
|
|
if (!Number.isSafeInteger(value) || value < min || value > max) {
|
|
throw new Error(`${name} must be an integer from ${min} to ${max}`);
|
|
}
|
|
return value;
|
|
};
|
|
const postCount = integerOption('--posts', 6000, 5000, 500000);
|
|
const seconds = integerOption('--duration', 5, 1, 28800);
|
|
const concurrency = integerOption('--concurrency', 8, 1, 500);
|
|
const userCount = integerOption('--users', 60, 2, 5000);
|
|
const compare = process.argv.includes('--mixed-compare');
|
|
const mixedOnly = compare || process.argv.includes('--mixed-only');
|
|
const mixed = mixedOnly || process.argv.includes('--mixed');
|
|
if (mixed && userCount < concurrency) throw new Error('--users must be at least --concurrency for mixed load');
|
|
if (mixed && process.argv.includes('--database-only')) throw new Error('Mixed load cannot use --database-only');
|
|
const mixedGates = { minSuccessRate: 99, maxP95Ms: 500, ...Object.fromEntries(
|
|
Object.entries(parseArgs(process.argv.slice(2)).gates).filter(([, value]) => value !== undefined),
|
|
) };
|
|
const buildIndex = process.argv.indexOf('--build-dir');
|
|
if (buildIndex >= 0 && !process.argv[buildIndex + 1])
|
|
throw new Error('--build-dir requires a path');
|
|
const buildDir = resolve(buildIndex < 0 ? 'dist' : process.argv[buildIndex + 1]);
|
|
if (compare && buildDir !== resolve('dist')) throw new Error('--mixed-compare requires the current default dist build');
|
|
const outputIndex = process.argv.indexOf('--output');
|
|
const output = outputIndex < 0 ? null : process.argv[outputIndex + 1];
|
|
if (outputIndex >= 0 && !output) throw new Error('--output requires a file path');
|
|
const directory = mkdtempSync(join(tmpdir(), 'oudelaa-perf-'));
|
|
const mongoPort = await freePort();
|
|
const mongo = spawn(
|
|
process.env.MONGOD_BINARY || 'mongod',
|
|
[
|
|
'--dbpath',
|
|
directory,
|
|
'--port',
|
|
String(mongoPort),
|
|
'--bind_ip',
|
|
'127.0.0.1',
|
|
'--logpath',
|
|
join(directory, 'mongo.log'),
|
|
],
|
|
{ windowsHide: true, stdio: 'ignore' },
|
|
);
|
|
let connection;
|
|
let api;
|
|
try {
|
|
await new Promise((done, reject) => {
|
|
mongo.once('spawn', done);
|
|
mongo.once('error', reject);
|
|
});
|
|
const uri = `mongodb://127.0.0.1:${mongoPort}/isolated_performance`;
|
|
connection = await mongoose
|
|
.createConnection(uri, { serverSelectionTimeoutMS: 15000 })
|
|
.asPromise();
|
|
const { UserSchema } = require(join(buildDir, 'legacy/src/modules/users/schemas/user.schema'));
|
|
const { PostSchema } = require(join(buildDir, 'legacy/src/modules/posts/schemas/post.schema'));
|
|
const User = connection.model('User', UserSchema);
|
|
const Post = connection.model('Post', PostSchema);
|
|
const users = await User.insertMany(
|
|
Array.from({ length: userCount }, (_, i) => ({
|
|
_id: new mongoose.Types.ObjectId((i + 1).toString(16).padStart(24, '0')),
|
|
name: `Benchmark User ${i}`,
|
|
username: `benchmark_${i}`,
|
|
email: `bench${i}@example.com`,
|
|
password: 'benchmark-unused-password',
|
|
isDisabled: false,
|
|
isPrivate: false,
|
|
})),
|
|
);
|
|
const now = new Date('2026-11-01T12:00:00Z').getTime();
|
|
for (let offset = 0; offset < postCount; offset += 1000) {
|
|
await Post.insertMany(
|
|
Array.from({ length: Math.min(1000, postCount - offset) }, (_, index) => {
|
|
const i = offset + index;
|
|
return {
|
|
_id: new mongoose.Types.ObjectId((i + 1000).toString(16).padStart(24, '0')),
|
|
authorId: users[1 + (i % (userCount - 1))]._id,
|
|
content: `Benchmark music post ${i}`,
|
|
postType: 'text',
|
|
visibility: 'public',
|
|
isDeleted: false,
|
|
isArchived: false,
|
|
moderationStatus: 'active',
|
|
hashtags: ['music', 'oud', `genre${i % 10}`],
|
|
likesCount: i % 97,
|
|
shareCount: i % 53,
|
|
commentsCount: i % 31,
|
|
savesCount: i % 23,
|
|
viewCount: i % 997,
|
|
playCount: i % 89,
|
|
createdAt: new Date(now - i * 60000),
|
|
};
|
|
}),
|
|
);
|
|
}
|
|
await Promise.all([User.init(), Post.init()]);
|
|
if (mixed) {
|
|
const follows = users.flatMap((user, index) => Array.from({ length: Math.min(5, userCount - 1) }, (_, offset) => ({
|
|
followerId: user._id, followingId: users[(index + offset + 1) % userCount]._id, createdAt: new Date(now),
|
|
})));
|
|
await connection.collection('follows').insertMany(follows);
|
|
for (let offset = 0; offset < userCount; offset += 100) {
|
|
await connection.collection('notifications').insertMany(users.slice(offset, offset + 100).flatMap((user) =>
|
|
Array.from({ length: 10 }, () => ({ recipientId: user._id, type: 'like', read: false, createdAt: new Date(now) })),
|
|
));
|
|
}
|
|
}
|
|
const token = new JwtService().sign(
|
|
{ sub: users[0].id, role: 'user', tokenType: 'access' },
|
|
{
|
|
secret: 'isolated-benchmark-access-secret',
|
|
expiresIn: seconds * 10 + 300,
|
|
},
|
|
);
|
|
const result = {
|
|
date: new Date().toISOString(),
|
|
node: process.version,
|
|
cpu: cpus()[0].model,
|
|
dataset: { users: userCount, posts: postCount,
|
|
...(mixed ? { followsPerUser: Math.min(5, userCount - 1), notificationsPerUser: 10, postType: 'text' } : {}),
|
|
},
|
|
durationSeconds: seconds,
|
|
dependencyMode: 'local MongoDB, no Redis/external services',
|
|
workloads: {},
|
|
};
|
|
if (process.argv.includes('--search-plans')) {
|
|
result.searchPlans = await require('./perf-search-plans')(Post, users[0]._id);
|
|
}
|
|
const modes = process.argv.includes('--database-only') ? [] : compare
|
|
? [{ cached: true, baseline: true }, { cached: true, baseline: false }]
|
|
: (mixedOnly ? [true] : [false, true]).map((cached) => ({ cached, baseline: false }));
|
|
for (const { cached, baseline } of modes) {
|
|
const port = await freePort();
|
|
const base = `http://127.0.0.1:${port}/api/v1`;
|
|
const started = performance.now();
|
|
let recentLogs = '';
|
|
api = spawn(process.execPath, [...(baseline ? ['--require', resolve('scripts/perf-previous-runtime.js')] : []), join(buildDir, '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,
|
|
MONGODB_AUTO_INDEX: 'true',
|
|
PUBLIC_BASE_URL: `http://127.0.0.1:${port}`,
|
|
JWT_ACCESS_SECRET: 'isolated-benchmark-access-secret',
|
|
JWT_REFRESH_SECRET: 'isolated-benchmark-refresh-secret',
|
|
SUPERADMIN_EMAIL: 'benchmark@example.com',
|
|
SUPERADMIN_PASSWORD: 'Benchmark123!',
|
|
SUPERADMIN_PASSWORD_HASH: '',
|
|
SUPERADMIN_TOTP_SECRET: '',
|
|
SUPERADMIN_ACCESS_SECRET: 'isolated-superadmin-access-secret',
|
|
SUPERADMIN_REFRESH_SECRET: 'isolated-superadmin-refresh-secret',
|
|
REDIS_ENABLED: 'false',
|
|
REDIS_SOCKET_ADAPTER_ENABLED: 'false',
|
|
QUEUE_ENABLED: 'false',
|
|
EMAIL_ENABLED: 'false',
|
|
AI_MUSIC_ENABLED: 'false',
|
|
FCM_ENABLED: 'false',
|
|
NOTIFICATION_SERVICE_ENABLED: 'false',
|
|
OUTBOX_DISPATCHER_ENABLED: 'false',
|
|
STORAGE_PROVIDER: 'local',
|
|
MEDIA_ACCESS_MODE: 'direct',
|
|
STORAGE_PUBLIC_BASE_URL: `http://127.0.0.1:${port}`,
|
|
STORAGE_BASE_PATH: 'uploads',
|
|
IMAGE_PROCESSING_ENABLED: 'false',
|
|
VIDEO_PROCESSING_ENABLED: 'false',
|
|
VIDEO_JOBS_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: String(cached),
|
|
},
|
|
});
|
|
for (const stream of [api.stdout, api.stderr])
|
|
stream.on('data', (chunk) => {
|
|
recentLogs = (recentLogs + chunk.toString()).slice(-3000);
|
|
});
|
|
api.on('error', (error) => {
|
|
recentLogs += error.message;
|
|
});
|
|
let ready = false;
|
|
while (performance.now() - started < 45000 && api.exitCode === null) {
|
|
try {
|
|
const response = await fetch(`${base}/health/ready`, {
|
|
signal: AbortSignal.timeout(1000),
|
|
});
|
|
await response.text();
|
|
if (response.ok) {
|
|
ready = true;
|
|
break;
|
|
}
|
|
} catch {
|
|
/* Startup is polled with bounded requests. */
|
|
}
|
|
await new Promise((done) => setTimeout(done, 100));
|
|
}
|
|
if (!ready) throw new Error(`Isolated API failed to start: ${recentLogs}`);
|
|
result.workloads[cached ? 'startupCachedMs' : 'startupUncachedMs'] = +(
|
|
performance.now() - started
|
|
).toFixed(2);
|
|
const endpoints = mixedOnly ? {} : cached
|
|
? { cachedFeed: '/feed/me?followingOnly=false&includeSuggestions=false&limit=20' }
|
|
: {
|
|
health: '/health',
|
|
uncachedFeed: '/feed/me?followingOnly=false&includeSuggestions=false&limit=20',
|
|
trending: '/feed/trending?limit=20',
|
|
search: '/search?q=music&type=posts&limit=20',
|
|
};
|
|
for (const [name, path] of Object.entries(endpoints)) {
|
|
console.log(`Measuring ${name}...`);
|
|
result.workloads[name] = await workload(`${base}${path}`, token, seconds, concurrency);
|
|
console.log(JSON.stringify({ name, ...result.workloads[name] }));
|
|
}
|
|
if (!cached) {
|
|
const response = await fetch(`${base}/feed/trending?limit=20`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
const page = await response.json();
|
|
if (!page.nextCursor) throw new Error('Missing trending nextCursor');
|
|
result.workloads.trendingCursor = await workload(
|
|
`${base}/feed/trending?limit=20&cursor=${encodeURIComponent(page.nextCursor)}`,
|
|
token,
|
|
seconds,
|
|
concurrency,
|
|
);
|
|
}
|
|
// Vary page metadata while keeping the cursor authoritative, so each
|
|
// request selects the same second page but cannot hit the response cache.
|
|
// Fixed snapshot cursors intentionally expire; keep this sample short.
|
|
if (!mixedOnly && seconds <= 30) {
|
|
const path = '/feed/me?followingOnly=false&includeSuggestions=false&limit=20';
|
|
const response = await fetch(`${base}${path}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
const first = await response.json();
|
|
if (!first.nextCursor) throw new Error('Missing feed nextCursor');
|
|
let page = 2;
|
|
const name = cached ? 'rankedNextPageWithoutResponseCache' : 'coldNextPage';
|
|
console.log(`Measuring ${name}...`);
|
|
result.workloads[name] = await workload(() => `${base}${path}&cursor=${encodeURIComponent(first.nextCursor)}&page=${page++}`,
|
|
token, seconds, concurrency);
|
|
console.log(JSON.stringify({ name, ...result.workloads[name] }));
|
|
}
|
|
if (mixed && cached) {
|
|
console.log('Measuring multi-user mixed reads (including cold viewer caches)...');
|
|
const viewers = users.map((user) => ({ id: user.id, token: new JwtService().sign(
|
|
{ sub: user.id, role: 'user', tokenType: 'access' },
|
|
{ secret: 'isolated-benchmark-access-secret', expiresIn: seconds + 300 },
|
|
) }));
|
|
const postIds = Array.from({ length: Math.min(postCount, 100) }, (_, i) =>
|
|
(i + 1000).toString(16).padStart(24, '0'));
|
|
const name = baseline ? 'mixedReadsBaseline' : 'mixedReads';
|
|
result.workloads[name] = await mixedReadWorkload({ base, users: viewers, postIds,
|
|
seconds, concurrency, gates: mixedGates });
|
|
console.log(JSON.stringify({ name, ...result.workloads[name] }));
|
|
if (!baseline && !result.workloads[name].performanceGates.passed) process.exitCode = 2;
|
|
}
|
|
await stop(api);
|
|
api = null;
|
|
}
|
|
if (mixedOnly) {
|
|
if (output) writeFileSync(output, JSON.stringify(result, null, 2) + '\n');
|
|
return;
|
|
}
|
|
const explain = await Post.find({
|
|
visibility: 'public',
|
|
isDeleted: { $ne: true },
|
|
isArchived: { $ne: true },
|
|
moderationStatus: { $ne: 'hidden' },
|
|
})
|
|
.sort({
|
|
shareCount: -1,
|
|
likesCount: -1,
|
|
commentsCount: -1,
|
|
savesCount: -1,
|
|
viewCount: -1,
|
|
playCount: -1,
|
|
createdAt: -1,
|
|
_id: -1,
|
|
})
|
|
.limit(20)
|
|
.explain('executionStats');
|
|
result.trendingExplain = {
|
|
nReturned: explain.executionStats.nReturned,
|
|
totalKeysExamined: explain.executionStats.totalKeysExamined,
|
|
totalDocsExamined: explain.executionStats.totalDocsExamined,
|
|
hasBlockingSort: JSON.stringify(explain.queryPlanner.winningPlan).includes('"stage":"SORT"'),
|
|
};
|
|
// Exercise the real repository with identical ranks and timestamps. An
|
|
// insertion/deletion ahead of the boundary must not shift its next page.
|
|
const cursorModule = join(buildDir, 'legacy/src/common/utils/trending-cursor.util.js');
|
|
if (existsSync(cursorModule)) {
|
|
const { FeedRepository } = require(join(buildDir, 'legacy/src/modules/feed/feed.repository'));
|
|
const {
|
|
encodeTrendingCursor,
|
|
decodeTrendingCursor,
|
|
buildTrendingBoundary,
|
|
TRENDING_SORT,
|
|
} = require(cursorModule);
|
|
const activeFilter = {
|
|
visibility: 'public',
|
|
isDeleted: { $ne: true },
|
|
isArchived: { $ne: true },
|
|
moderationStatus: { $ne: 'hidden' },
|
|
};
|
|
const anchor = await Post.findOne(activeFilter).sort(TRENDING_SORT).skip(3999);
|
|
const deepCursor = decodeTrendingCursor(encodeTrendingCursor(anchor, 4000));
|
|
const offsetExplain = await Post.find(activeFilter)
|
|
.sort(TRENDING_SORT)
|
|
.skip(4000)
|
|
.limit(20)
|
|
.explain('executionStats');
|
|
const cursorExplain = await Post.find({
|
|
$and: [activeFilter, buildTrendingBoundary(deepCursor)],
|
|
})
|
|
.sort(TRENDING_SORT)
|
|
.limit(20)
|
|
.explain('executionStats');
|
|
const stats = (plan) => ({
|
|
returned: plan.executionStats.nReturned,
|
|
keysExamined: plan.executionStats.totalKeysExamined,
|
|
docsExamined: plan.executionStats.totalDocsExamined,
|
|
});
|
|
result.deepPaginationExplain = {
|
|
offset: 4000,
|
|
skip: stats(offsetExplain),
|
|
keyset: stats(cursorExplain),
|
|
};
|
|
if (
|
|
cursorExplain.executionStats.totalKeysExamined >=
|
|
offsetExplain.executionStats.totalKeysExamined
|
|
) {
|
|
throw new Error('Keyset query no longer improves index work for the deep-page fixture');
|
|
}
|
|
const repository = new FeedRepository(Post, null);
|
|
if (typeof repository.findFeedPostsByIds === 'function') {
|
|
const candidates = await repository.findCandidatePosts(activeFilter, 400);
|
|
if (candidates.some((post) => 'content' in post || typeof post.toObject === 'function')) {
|
|
throw new Error('Candidate lookup unexpectedly loads full or hydrated posts');
|
|
}
|
|
const ids = candidates.slice(0, 20).map((post) => String(post._id));
|
|
const selected = await repository.findFeedPostsByIds(activeFilter, ids);
|
|
if (
|
|
selected.length !== 20 ||
|
|
selected.some((post) => typeof post.toObject !== 'function')
|
|
) {
|
|
throw new Error('Selected page hydration failed');
|
|
}
|
|
await Post.updateOne({ _id: ids[0] }, { $set: { isDeleted: true } });
|
|
const rechecked = await repository.findFeedPostsByIds(activeFilter, ids);
|
|
if (rechecked.length !== 19) throw new Error('Selection did not recheck deletion rules');
|
|
result.feedCandidateValidation = {
|
|
rankingRows: candidates.length,
|
|
hydratedRankingRows: 0,
|
|
hydratedPageRows: selected.length,
|
|
deletionRecheck: 'passed',
|
|
};
|
|
}
|
|
const tied = await Post.insertMany(
|
|
Array.from({ length: 6 }, (_, i) => ({
|
|
authorId: users[1]._id,
|
|
content: `Cursor tie fixture ${i}`,
|
|
visibility: 'public',
|
|
shareCount: 1_000_000,
|
|
createdAt: new Date(now),
|
|
})),
|
|
);
|
|
const filter = { visibility: 'public', shareCount: { $gte: 1_000_000 } };
|
|
const first = await repository.findTrendingPublicPosts(filter, 0, 3);
|
|
const cursor = decodeTrendingCursor(encodeTrendingCursor(first[2], 3));
|
|
const expectedIds = tied
|
|
.map((post) => post.id)
|
|
.sort()
|
|
.reverse()
|
|
.slice(3);
|
|
const second = await repository.findTrendingPublicPosts(filter, 0, 3, cursor);
|
|
await Post.create({
|
|
authorId: users[1]._id,
|
|
content: 'Inserted ahead of cursor',
|
|
visibility: 'public',
|
|
shareCount: 1_000_001,
|
|
createdAt: new Date(now),
|
|
});
|
|
await Post.deleteOne({ _id: first[0]._id });
|
|
const afterMutation = await repository.findTrendingPublicPosts(filter, 0, 3, cursor);
|
|
if (
|
|
JSON.stringify(second.map((post) => post.id)) !== JSON.stringify(expectedIds) ||
|
|
JSON.stringify(afterMutation.map((post) => post.id)) !== JSON.stringify(expectedIds)
|
|
) {
|
|
throw new Error('Real MongoDB keyset pagination failed tie/mutation validation');
|
|
}
|
|
result.keysetValidation = {
|
|
tiedRanks: 'passed',
|
|
insertionAhead: 'passed',
|
|
deletionAhead: 'passed',
|
|
};
|
|
}
|
|
if (output) writeFileSync(output, JSON.stringify(result, null, 2) + '\n');
|
|
console.log(JSON.stringify(result, null, 2));
|
|
} finally {
|
|
await stop(api);
|
|
if (connection) await connection.close();
|
|
await stop(mongo);
|
|
}
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error.message);
|
|
process.exitCode = 1;
|
|
});
|