331 lines
11 KiB
JavaScript
331 lines
11 KiB
JavaScript
/**
|
|
* Concurrent candle-predict load test (single | multi | auto).
|
|
*
|
|
* Usage (from host):
|
|
* node backend/scripts/loadtest-bets.js --tokens path.json --mode single --n 500
|
|
*
|
|
* Env:
|
|
* LOADTEST_BASE_URL=http://127.0.0.1:9080
|
|
* LOADTEST_INTERVAL=1
|
|
* LOADTEST_STAKE=0.01
|
|
* LOADTEST_MIN_SECONDS=25 // wait until betting window has at least this many seconds left
|
|
* LOADTEST_CONCURRENCY=0 // 0 = all at once (N)
|
|
* LOADTEST_TIMEOUT_MS=30000
|
|
*/
|
|
const http = require('http');
|
|
const https = require('https');
|
|
const fs = require('fs');
|
|
const { URL } = require('url');
|
|
|
|
function arg(name, fallback) {
|
|
const idx = process.argv.indexOf(`--${name}`);
|
|
if (idx >= 0 && process.argv[idx + 1]) return process.argv[idx + 1];
|
|
return fallback;
|
|
}
|
|
|
|
const baseUrl = (arg('base', process.env.LOADTEST_BASE_URL || 'http://127.0.0.1:9080')).replace(/\/$/, '');
|
|
const mode = String(arg('mode', 'single'));
|
|
const tokensPath = arg('tokens', process.env.LOADTEST_TOKENS || '');
|
|
const n = Number(arg('n', process.env.LOADTEST_N || '0'));
|
|
const offset = Number(arg('offset', process.env.LOADTEST_OFFSET || '0'));
|
|
const intervalMinutes = Number(arg('interval', process.env.LOADTEST_INTERVAL || '1'));
|
|
const stakeAmount = Number(arg('stake', process.env.LOADTEST_STAKE || '0.01'));
|
|
const minSeconds = Number(arg('minSeconds', process.env.LOADTEST_MIN_SECONDS || '25'));
|
|
const timeoutMs = Number(arg('timeoutMs', process.env.LOADTEST_TIMEOUT_MS || '30000'));
|
|
const concurrencyArg = Number(arg('concurrency', process.env.LOADTEST_CONCURRENCY || '0'));
|
|
const waitMs = Number(arg('waitMs', process.env.LOADTEST_WAIT_MS || '120000'));
|
|
// Soft latency budget for PASS (queueing under burst often exceeds 2s on local Docker).
|
|
const latencyBudgetMs = Number(arg('latencyMs', process.env.LOADTEST_LATENCY_MS || '10000'));
|
|
const requireNewRound = String(arg('requireNewRound', process.env.LOADTEST_REQUIRE_NEW_ROUND || '')).trim();
|
|
const ignoreAlreadyBet = ['1', 'true', 'yes'].includes(
|
|
String(arg('ignoreAlreadyBet', process.env.LOADTEST_IGNORE_ALREADY_BET || '')).toLowerCase()
|
|
);
|
|
|
|
if (!tokensPath) {
|
|
console.error('Missing --tokens path.json');
|
|
process.exit(1);
|
|
}
|
|
if (!['single', 'multi', 'auto'].includes(mode)) {
|
|
console.error('--mode must be single|multi|auto');
|
|
process.exit(1);
|
|
}
|
|
|
|
const file = JSON.parse(fs.readFileSync(tokensPath, 'utf8'));
|
|
const allTokens = file.tokens || file;
|
|
const sliced = n > 0 ? allTokens.slice(offset, offset + n) : allTokens.slice(offset);
|
|
const selected = sliced.map((t) => (typeof t === 'string' ? { token: t } : t));
|
|
if (!selected.length) {
|
|
console.error(`No tokens loaded (offset=${offset} n=${n} total=${allTokens.length})`);
|
|
process.exit(1);
|
|
}
|
|
const concurrency = concurrencyArg > 0 ? concurrencyArg : selected.length;
|
|
|
|
function request(method, path, { headers = {}, body, timeout = timeoutMs } = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const url = new URL(path, baseUrl);
|
|
const lib = url.protocol === 'https:' ? https : http;
|
|
const payload = body ? Buffer.from(body) : null;
|
|
const req = lib.request(
|
|
url,
|
|
{
|
|
method,
|
|
headers: {
|
|
...headers,
|
|
...(payload
|
|
? { 'Content-Type': 'application/json', 'Content-Length': payload.length }
|
|
: {}),
|
|
},
|
|
timeout,
|
|
},
|
|
(res) => {
|
|
const chunks = [];
|
|
res.on('data', (c) => chunks.push(c));
|
|
res.on('end', () => {
|
|
const raw = Buffer.concat(chunks).toString('utf8');
|
|
let json = null;
|
|
try {
|
|
json = raw ? JSON.parse(raw) : null;
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
resolve({ status: res.statusCode || 0, headers: res.headers, raw, json });
|
|
});
|
|
}
|
|
);
|
|
req.on('timeout', () => req.destroy(new Error(`timeout ${method} ${path}`)));
|
|
req.on('error', reject);
|
|
if (payload) req.write(payload);
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
function percentile(sorted, p) {
|
|
if (!sorted.length) return null;
|
|
const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
|
|
return sorted[idx];
|
|
}
|
|
|
|
async function waitForBettingWindow() {
|
|
const path = `/api/v1/games/candle-predict/state?intervalMinutes=${intervalMinutes}`;
|
|
const started = Date.now();
|
|
let last = null;
|
|
while (Date.now() - started < waitMs) {
|
|
const token = selected[0].token;
|
|
const res = await request('GET', path, {
|
|
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
});
|
|
last = res;
|
|
const round = res.json?.round;
|
|
const status = round?.status;
|
|
const sec = Number(round?.secondsToClose ?? 0);
|
|
const roundId = round?.id || '';
|
|
const isNewEnough = !requireNewRound || roundId !== requireNewRound;
|
|
if (res.status === 200 && status === 'betting' && sec >= minSeconds && isNewEnough) {
|
|
console.log(`[wait] betting ready secondsToClose=${sec} round=${roundId}`);
|
|
return round;
|
|
}
|
|
const msg = `status=${res.status} roundStatus=${status || '-'} sec=${sec || 0} round=${roundId || '-'} new=${isNewEnough}`;
|
|
process.stdout.write(`[wait] ${msg}\n`);
|
|
await new Promise((r) => setTimeout(r, 1500));
|
|
}
|
|
throw new Error(
|
|
`Timed out waiting for betting window (>=${minSeconds}s). last=${JSON.stringify(last?.json?.round || last?.raw?.slice?.(0, 200))}`
|
|
);
|
|
}
|
|
|
|
function buildBody(i) {
|
|
if (mode === 'single') {
|
|
return JSON.stringify({
|
|
direction: i % 2 === 0 ? 'long' : 'short',
|
|
stakeAmount,
|
|
intervalMinutes,
|
|
stakeAccountKind: 'main',
|
|
idempotencyKey: `lt-single-${Date.now()}-${i}`,
|
|
});
|
|
}
|
|
if (mode === 'multi') {
|
|
return JSON.stringify({
|
|
level: 2,
|
|
sequence: i % 2 === 0 ? ['long', 'short'] : ['short', 'long'],
|
|
stakeAmount,
|
|
intervalMinutes,
|
|
stakeAccountKind: 'main',
|
|
idempotencyKey: `lt-multi-${Date.now()}-${i}`,
|
|
});
|
|
}
|
|
// auto
|
|
return JSON.stringify({
|
|
enabled: true,
|
|
direction: i % 2 === 0 ? 'long' : 'short',
|
|
stakeAmount,
|
|
mode: 'each_round',
|
|
intervalMinutes,
|
|
stakeAccountKind: 'main',
|
|
validateWalletBalance: true,
|
|
attemptImmediateBet: false,
|
|
});
|
|
}
|
|
|
|
function endpoint() {
|
|
if (mode === 'single') return '/api/v1/games/candle-predict/bets';
|
|
if (mode === 'multi') return '/api/v1/games/candle-predict/bets/multi';
|
|
return '/api/v1/games/candle-predict/auto';
|
|
}
|
|
|
|
function method() {
|
|
return mode === 'auto' ? 'PUT' : 'POST';
|
|
}
|
|
|
|
function isSuccess(status) {
|
|
if (mode === 'auto') return status === 200 || status === 201;
|
|
return status === 201;
|
|
}
|
|
|
|
async function mapPool(items, limit, fn) {
|
|
const results = new Array(items.length);
|
|
let next = 0;
|
|
async function worker() {
|
|
while (true) {
|
|
const i = next++;
|
|
if (i >= items.length) return;
|
|
results[i] = await fn(items[i], i);
|
|
}
|
|
}
|
|
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
|
|
await Promise.all(workers);
|
|
return results;
|
|
}
|
|
|
|
function classifyError(status, raw, json) {
|
|
const msg = String(json?.error || json?.message || raw || '').toLowerCase();
|
|
if (status === 429) return 'rate_limit';
|
|
if (status === 0) return 'network';
|
|
if (status >= 500) return 'server_5xx';
|
|
if (msg.includes('window') || msg.includes('closed')) return 'window_closed';
|
|
if (msg.includes('already')) return 'already_bet';
|
|
if (msg.includes('insufficient')) return 'insufficient_balance';
|
|
if (msg.includes('disabled')) return 'disabled';
|
|
if (msg.includes('in_progress') || msg.includes('multi')) return 'multi_conflict';
|
|
return `http_${status}`;
|
|
}
|
|
|
|
async function main() {
|
|
console.log('=== LOADTEST candle-predict ===');
|
|
console.log(
|
|
JSON.stringify({
|
|
baseUrl,
|
|
mode,
|
|
n: selected.length,
|
|
offset,
|
|
concurrency,
|
|
intervalMinutes,
|
|
stakeAmount,
|
|
minSeconds,
|
|
requireNewRound: requireNewRound || null,
|
|
})
|
|
);
|
|
|
|
let round = null;
|
|
if (mode !== 'auto') {
|
|
round = await waitForBettingWindow();
|
|
} else {
|
|
console.log('[wait] auto mode skips betting-window gate');
|
|
}
|
|
if (round?.id) console.log(`ROUND_ID=${round.id}`);
|
|
|
|
const path = endpoint();
|
|
const httpMethod = method();
|
|
const t0 = Date.now();
|
|
const results = await mapPool(selected, concurrency, async (u, i) => {
|
|
const started = Date.now();
|
|
try {
|
|
const res = await request(httpMethod, path, {
|
|
headers: {
|
|
Authorization: `Bearer ${u.token}`,
|
|
Accept: 'application/json',
|
|
'Idempotency-Key': `lt-${mode}-${Date.now()}-${i}`,
|
|
},
|
|
body: buildBody(i),
|
|
});
|
|
return {
|
|
i,
|
|
status: res.status,
|
|
ms: Date.now() - started,
|
|
ok: isSuccess(res.status),
|
|
err: isSuccess(res.status) ? null : classifyError(res.status, res.raw, res.json),
|
|
snippet: isSuccess(res.status) ? null : String(res.raw || '').slice(0, 160),
|
|
};
|
|
} catch (e) {
|
|
return {
|
|
i,
|
|
status: 0,
|
|
ms: Date.now() - started,
|
|
ok: false,
|
|
err: 'network',
|
|
snippet: String(e.message || e).slice(0, 160),
|
|
};
|
|
}
|
|
});
|
|
const elapsed = Date.now() - t0;
|
|
const latencies = results.map((r) => r.ms).sort((a, b) => a - b);
|
|
const eligible = ignoreAlreadyBet
|
|
? results.filter((r) => r.ok || r.err !== 'already_bet')
|
|
: results;
|
|
const okCount = results.filter((r) => r.ok).length;
|
|
const okRate = ignoreAlreadyBet
|
|
? eligible.length
|
|
? eligible.filter((r) => r.ok).length / eligible.length
|
|
: 0
|
|
: okCount / selected.length;
|
|
const byStatus = {};
|
|
const byErr = {};
|
|
for (const r of results) {
|
|
byStatus[r.status] = (byStatus[r.status] || 0) + 1;
|
|
if (!r.ok) byErr[r.err || 'unknown'] = (byErr[r.err || 'unknown'] || 0) + 1;
|
|
}
|
|
const summary = {
|
|
mode,
|
|
n: selected.length,
|
|
offset,
|
|
concurrency,
|
|
roundId: round?.id || null,
|
|
elapsedMs: elapsed,
|
|
rps: selected.length / (elapsed / 1000),
|
|
ok: okCount,
|
|
okRate,
|
|
p50: percentile(latencies, 50),
|
|
p95: percentile(latencies, 95),
|
|
p99: percentile(latencies, 99),
|
|
max: latencies[latencies.length - 1] || null,
|
|
byStatus,
|
|
byErr,
|
|
failSamples: results.filter((r) => !r.ok).slice(0, 8),
|
|
};
|
|
console.log('=== SUMMARY ===');
|
|
console.log(JSON.stringify(summary, null, 2));
|
|
|
|
const server5xx = (byErr.server_5xx || 0) / selected.length;
|
|
const rateLimited = (byErr.rate_limit || 0) / selected.length;
|
|
const latencyOk = summary.p95 == null || summary.p95 <= latencyBudgetMs;
|
|
const pass =
|
|
summary.okRate >= 0.99 &&
|
|
latencyOk &&
|
|
server5xx <= 0.005 &&
|
|
rateLimited <= 0.01;
|
|
console.log(
|
|
JSON.stringify({
|
|
latencyBudgetMs,
|
|
latencyOk,
|
|
server5xxRate: server5xx,
|
|
rateLimitedRate: rateLimited,
|
|
})
|
|
);
|
|
console.log(`LOADTEST_PASS=${pass ? 1 : 0}`);
|
|
process.exit(pass ? 0 : 2);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|