// Lasttest: simuliert N Spieler (plus Gäste) per WebSocket und misst Antwortzeiten, Spieltakt, Speicher, CPU und das // Wachstum der Datenbank. // // node scripts/loadtest.mjs --players 30 --duration 180 // node scripts/loadtest.mjs --players 50 --data /pfad/zur/kopie --mode turbo --json bericht.json // node scripts/loadtest.mjs --url http://127.0.0.1:8086 --pid 1234 --data /data --players 10 (laufender Server) // // Ohne --url startet das Skript einen eigenen Server (eigener Port, eigene Kopie der Daten; --data = Vorlage, die // kopiert wird – das Original bleibt unberührt). Dann sind CPU und Speicher des Serverprozesses direkt messbar // (/proc, nur Linux). Die simulierten Spieler verhalten sich wie der Browser-Client: Origin-Header, Anmeldung über // das Token, „clientEnv“, Eingabezähler „hi“ bei Handelsbefehlen und zufällige Denkpausen. Die Bot-Erkennung bleibt // eingeschaltet; verlangt sie trotzdem eine Menschen-Bestätigung, wird das gezählt und beantwortet. // // Gemessen wird: // – Antwortzeit je Befehl (Anfrage → „reply“ mit derselben reqId), p50/p95/p99/max, Fehler mit häufigstem Text // – Spieltakt: Abstand der „market“-Nachrichten bei den Clients sowie Dauer eines Takts laut /metrics // – HTTP-Antwortzeit von /api/health (zeigt, ob die Ereignisschleife hängt) und die Verzögerung der Ereignisschleife // laut /metrics (wibosim_eventloop_delay_ms, Fenster von 10 s) // – Zwischenkurse für die Anzeige (Nachricht „px“, displayticks.js): Anzahl und Bytes je Client // – CPU (Anteil eines Kerns) und RSS des Serverprozesses, Datenmenge je Client // – Bytes je Nachrichtentyp (auch Antworten) und auf der Leitung (nach Kompression); Delta-Takt wie der Browser // (--no-delta: alter Client mit voller Kursliste; --hidden 0.3: Anteil der Tabs im Hintergrund) // – Größe von Datenbank, WAL und Sicherungen vorher/nachher, hochgerechnet je Stunde import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { spawn } from 'node:child_process'; import { parseArgs } from 'node:util'; import { fileURLToPath, pathToFileURL } from 'node:url'; import WebSocket from 'ws'; import { MarketSync, MK_PROTO } from '../public/js/mkdelta.js'; const HERE = path.dirname(fileURLToPath(import.meta.url)); const SERVER_DIR = path.resolve(HERE, '..'); const UA = 'Mozilla/5.0 (X11; Linux) WiBoSim-Lasttest'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // ------------------------------------------------------------------ Hilfsfunktionen (getestet in src/sysloadtest.test.js) /** Perzentil (0–100) einer Zahlenliste, nächster Rang; leere Liste → null */ export function pct(list, p) { if (!list.length) return null; const a = [...list].sort((x, y) => x - y); const i = Math.min(a.length - 1, Math.max(0, Math.ceil((p / 100) * a.length) - 1)); return a[i]; } /** Kennzahlen einer Messreihe */ export function stats(list) { if (!list.length) return { n: 0, avg: null, p50: null, p95: null, p99: null, max: null }; const sum = list.reduce((s, x) => s + x, 0); return { n: list.length, avg: sum / list.length, p50: pct(list, 50), p95: pct(list, 95), p99: pct(list, 99), max: Math.max(...list) }; } /** Prometheus-Text von /metrics → {name: Zahl}; Einträge mit Labels unter `name{le="10"}` */ export function parseMetrics(text) { const out = {}; for (const line of String(text).split('\n')) { const m = /^([a-z0-9_]+(?:\{[^}]*\})?)\s+(-?[\d.eE+]+)$/.exec(line.trim()); if (m) out[m[1]] = Number(m[2]); } return out; } /** * Histogramm (kumulative Buckets) zwischen zwei Abfragen von /metrics: Anzahl, Mittel, p50/p95 (linear im Bucket * geschätzt; liegt das Quantil im offenen Bucket, wird die letzte Grenze zurückgegeben) und Anteile über Grenzen. */ export function histDiff(m0, m1, name) { const les = Object.keys(m1).map((k) => new RegExp(`^${name}_bucket\\{le="([^"]+)"\\}$`).exec(k)?.[1]).filter(Boolean) .map((x) => (x === '+Inf' ? Infinity : Number(x))).sort((a, b) => a - b); const cum = (le) => { const k = `${name}_bucket{le="${le === Infinity ? '+Inf' : le}"}`; return (m1[k] ?? 0) - (m0[k] ?? 0); }; const count = (m1[`${name}_count`] ?? 0) - (m0[`${name}_count`] ?? 0); if (!les.length || count <= 0) return null; const q = (p) => { const want = p * count; let prevLe = 0, prevC = 0; for (const le of les) { const c = cum(le); if (c >= want) return le === Infinity ? prevLe : prevLe + ((want - prevC) / Math.max(1, c - prevC)) * (le - prevLe); prevLe = le; prevC = c; } return prevLe; }; const over = Object.fromEntries(les.filter(Number.isFinite).map((le) => [le, count - cum(le)])); return { count, avg: ((m1[`${name}_sum`] ?? 0) - (m0[`${name}_sum`] ?? 0)) / count, p50: q(0.5), p95: q(0.95), over }; } /** /proc//stat → CPU-Zeit (utime+stime) in Ticks; Feld 2 (Name) kann Leerzeichen enthalten */ export function parseProcStat(text) { const rest = String(text).slice(String(text).lastIndexOf(')') + 2).split(' '); // rest[0] = Feld 3 (state) → utime = Feld 14 = rest[11], stime = Feld 15 = rest[12] return Number(rest[11]) + Number(rest[12]); } /** CPU-Ticks und RSS eines Prozesses (Linux); sonst null */ export function procSample(pid) { try { const ticks = parseProcStat(fs.readFileSync(`/proc/${pid}/stat`, 'utf8')); const rssKb = Number(/VmRSS:\s+(\d+)/.exec(fs.readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1] ?? NaN); return { ticks, rss: rssKb * 1024, t: performance.now() }; } catch { return null; } } /** Größen in einem Datenordner: Datenbank, WAL, Sicherungen (Bytes) */ export function dataSizes(dir) { const st = (f) => { try { return fs.statSync(f).size; } catch { return 0; } }; let backups = 0, backupCount = 0; try { for (const f of fs.readdirSync(path.join(dir, 'backups'))) if (f.endsWith('.db')) { backups += st(path.join(dir, 'backups', f)); backupCount++; } } catch { /* keine Sicherungen */ } const db = st(path.join(dir, 'wibosim.db')), wal = st(path.join(dir, 'wibosim.db-wal')); return { db, wal, total: db + wal, backups, backupCount }; } /** Zufällige Wartezeit um einen Mittelwert (exponentiell, begrenzt) – menschlich unregelmäßig */ export function thinkMs(mean, rnd = Math.random) { return Math.round(Math.min(mean * 4, Math.max(mean * 0.15, -Math.log(1 - rnd()) * mean))); } /** gewichtete Auswahl: [[wert, gewicht], …] */ export function pick(list, rnd = Math.random) { const total = list.reduce((s, [, w]) => s + w, 0); let x = rnd() * total; for (const [v, w] of list) { if ((x -= w) < 0) return v; } return list[list.length - 1][0]; } const mb = (b) => (b == null ? '–' : `${(b / 1048576).toFixed(1)} MB`); const ms = (x) => (x == null ? '–' : `${x < 10 ? x.toFixed(1) : Math.round(x)} ms`); /** * Bericht als Text (deutsch). piFactor: wie viel langsamer der Zielrechner je Kern ist (Schätzung, siehe Kopf). * @param {any} r Ergebnis von run() */ export function formatReport(r, { piFactor = 4 } = {}) { const L = []; L.push(`Lasttest WiBoSim – ${r.players} Spieler + ${r.guests} Gäste, ${r.durationSec} s Messzeit (Modus ${r.mode ?? 'extern'}, Takt ${r.tickMs ?? '?'} ms)`); L.push(`Anfragen: ${r.requests.total} (${(r.requests.total / r.durationSec).toFixed(1)}/s), Fehler ${r.requests.errors}, ohne Antwort ${r.requests.timeouts}, Menschen-Bestätigungen ${r.humanChecks}, Verbindungsabbrüche ${r.disconnects}`); L.push(''); L.push('Antwortzeiten je Befehl n p50 p95 p99 max Größe Fehler'); for (const [k, v] of Object.entries(r.latency).sort((a, b) => b[1].n - a[1].n)) { L.push(` ${k.padEnd(26)} ${String(v.n).padStart(5)} ${ms(v.p50).padStart(7)} ${ms(v.p95).padStart(7)} ${ms(v.p99).padStart(7)} ${ms(v.max).padStart(7)} ${`${(v.kb ?? 0).toFixed(1)} kB`.padStart(8)} ${v.errors || ''}`); } const all = r.latencyAll; L.push(` ${'alle'.padEnd(26)} ${String(all.n).padStart(5)} ${ms(all.p50).padStart(7)} ${ms(all.p95).padStart(7)} ${ms(all.p99).padStart(7)} ${ms(all.max).padStart(7)}`); if (Object.keys(r.errorTexts).length) { L.push('Häufigste Fehlermeldungen:'); for (const [t, n] of Object.entries(r.errorTexts).sort((a, b) => b[1] - a[1]).slice(0, 6)) L.push(` ${n}× ${t}`); } L.push(''); const iv = r.tick.interval; if (r.phases && Object.keys(r.phases).length) { const n = Object.values(r.phases).reduce((a, b) => a + b, 0); L.push(`Börsenphasen während der Messung: ${Object.entries(r.phases).map(([k, v]) => `${k} ${Math.round((v / n) * 100)} %`).join(', ')}`); } L.push(`Spieltakt (Abstand der Marktdaten beim Client): p50 ${ms(iv.p50)}, p95 ${ms(iv.p95)}, max ${ms(iv.max)} (Soll ${r.tickMs ?? '?'} ms)`); const sm = r.tick.serverMs; if (sm) L.push(`Dauer eines Takts laut Server: Mittel ${ms(sm.avg)}, p50 ≈ ${ms(sm.p50)}, p95 ≈ ${ms(sm.p95)}, längster seit Start ${ms(sm.max)}; über 100 ms: ${sm.over?.[100] ?? '?'} von ${sm.count} Takten, ${r.tick.errors ?? 0} Fehler`); L.push(`HTTP /api/health: p50 ${ms(r.health.p50)}, p95 ${ms(r.health.p95)}, max ${ms(r.health.max)}`); if (r.eld) L.push(`Ereignisschleife (Verzögerung je 10-s-Fenster): p50 Ø ${ms(r.eld.p50)}, p99 Ø ${ms(r.eld.p99)}, p99 höchstens ${ms(r.eld.p99max)}, längste ${ms(r.eld.max)}`); if (r.display) L.push(`Zwischenkurse (Anzeige): ${r.display.on ? `an, Takt ${r.display.ms} ms` : 'aus'}; ${r.display.sent} Nachrichten „px“ in ${r.display.steps} Schritten (${(r.display.perClientSec ?? 0).toFixed(2)} je Client und s, ${((r.display.bytesPerClientSec ?? 0) / 1024).toFixed(2)} kB/s je Client)`); L.push(`Datenmenge je Client: ${(r.bytesPerClientSec / 1024).toFixed(1)} kB/s (alle ${((r.bytesPerClientSec * (r.players + r.guests)) / 1024).toFixed(0)} kB/s)`); if (r.push && Object.keys(r.push).length) { const tot = Object.values(r.push).reduce((a, b) => a + b.bytes, 0); L.push(` davon Push-Nachrichten: ${Object.entries(r.push).sort((a, b) => b[1].bytes - a[1].bytes).slice(0, 6).map(([k, v]) => `${k} ${Math.round((v.bytes / Math.max(1, tot)) * 100)} % (Ø ${(v.bytes / v.n / 1024).toFixed(1)} kB)`).join(', ')}`); } if (r.wirePerClientSec != null) L.push(`Auf der Leitung (nach Kompression, mit Rahmen): ${(r.wirePerClientSec / 1024).toFixed(1)} kB/s je Client (alle ${((r.wirePerClientSec * (r.players + r.guests)) / 1024).toFixed(0)} kB/s)`); if (r.types && Object.keys(r.types).length) L.push(typeTable(r)); if (r.delta != null) L.push(`Delta-Takt: ${r.delta ? 'an' : 'aus (alter Client)'}${r.hiddenClients ? `, ${r.hiddenClients} Tabs im Hintergrund` : ''}; Lücken/Schlüsselbild-Anforderungen ${r.gaps ?? 0}${r.net ? `; Server: ${r.net.delta} Deltas, ${r.net.key} Schlüsselbilder, ${r.net.skipped} ausgelassen (Hintergrund), Orderbuch unverändert ${r.net.bookSkipped}×, Rangliste unverändert ${r.net.lbSkipped}×, Depot unverändert ${r.net.pfSkipped ?? 0}×; letztes Delta ${(r.net.deltaBytes / 1024).toFixed(1)} kB, Schlüsselbild ${(r.net.keyBytes / 1024).toFixed(1)} kB` : ''}`); if (r.cpu) L.push(`CPU Server: Mittel ${r.cpu.avg.toFixed(0)} %, Spitze ${r.cpu.max.toFixed(0)} % eines Kerns (Lastgenerator selbst: ${r.loadgenCpu.toFixed(0)} %)`); if (r.mem) L.push(`Speicher Server (RSS): Start ${mb(r.mem.start)}, Ende ${mb(r.mem.end)}, Spitze ${mb(r.mem.max)}${r.mem.heapMax ? `; JS-Heap belegt bis ${mb(r.mem.heapMax)} (Grenze ${mb(r.mem.heapLimit)})` : ''}`); if (r.disk) { const d = r.disk; L.push(`Datenbank: ${mb(d.before.total)} → ${mb(d.after.total)} (davon WAL ${mb(d.after.wal)}); Datei ohne WAL ${mb(d.before.db)} → ${mb(d.after.db)}, mit WAL hochgerechnet ${d.growthPerHour >= 0 ? '+' : ''}${mb(d.growthPerHour)} je Stunde; Sicherungen ${d.after.backupCount} (${mb(d.after.backups)})`); if (r.days) L.push(`Handelstage im Test: ${r.days.from} → ${r.days.to}${r.days.to > r.days.from ? ` (≈ ${mb((d.after.db - d.before.db) / (r.days.to - r.days.from))} je Handelstag)` : ''}`); } if (r.cpu && r.tick.serverMs) { L.push(''); L.push(`Schätzung Raspberry Pi (Faktor ${piFactor} langsamer je Kern): Takt Mittel ${ms(r.tick.serverMs.avg * piFactor)}, p95 ${ms(r.tick.serverMs.p95 * piFactor)}; CPU ≈ ${Math.round(r.cpu.avg * piFactor)} % eines Kerns`); } return L.join('\n'); } /** Bytes je Nachrichtentyp (alle Nachrichten vom Server, auch Antworten) als Tabelle; je Client und Sekunde */ export function typeTable(r) { const n = Math.max(1, r.players + r.guests), secs = Math.max(1, r.durationSec); const rows = Object.entries(r.types).sort((a, b) => b[1].bytes - a[1].bytes); const tot = rows.reduce((a, [, v]) => a + v.bytes, 0); const L = [' Nachrichtentyp Anzahl Ø Größe kB/s je Client Anteil']; for (const [k, v] of rows.slice(0, 12)) { L.push(` ${k.padEnd(24)} ${String(v.n).padStart(7)} ${`${(v.bytes / v.n / 1024).toFixed(2)} kB`.padStart(10)} ${(v.bytes / n / secs / 1024).toFixed(2).padStart(16)} ${`${Math.round((v.bytes / Math.max(1, tot)) * 100)} %`.padStart(8)}`); } return L.join('\n'); } // ------------------------------------------------------------------ Server starten (eigener Prozess) async function startServer({ data, port, mode, prof, dayMs, env = {} }) { // belegter Port: sonst würde unbemerkt ein fremder Server gemessen const busy = await fetch(`http://127.0.0.1:${port}/api/health`).then(() => true, () => false); if (busy) throw new Error(`Port ${port} ist belegt – bitte einen freien Port mit --port wählen`); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-last-')); if (data) for (const f of fs.readdirSync(data)) { const s = path.join(data, f); if (fs.statSync(s).isFile()) fs.copyFileSync(s, path.join(dir, f)); } const args = ['--disable-warning=ExperimentalWarning']; if (prof) args.push('--cpu-prof', `--cpu-prof-dir=${prof}`); args.push(path.join(SERVER_DIR, 'src', 'index.js')); const log = fs.openSync(path.join(dir, 'server.log'), 'a'); const proc = spawn(process.execPath, args, { // WIBO_DEV_CLOCK=1: schnelle Uhr trotz NODE_ENV=production (sonst gilt nur Echtzeit) // TRUST_PROXY=loopback: jeder simulierte Spieler bekommt per X-Forwarded-For eine eigene Adresse (Grenzen je Anschluss) env: { ...process.env, PORT: String(port), DATA_DIR: dir, TIME_MODE: mode, WIBO_DEV_CLOCK: '1', TRUST_PROXY: 'loopback', NODE_ENV: 'production', ...(dayMs ? { DAY_MS: String(dayMs) } : {}), ...env }, stdio: ['ignore', log, log], }); const base = `http://127.0.0.1:${port}`; for (let i = 0; i < 300; i++) { if (proc.exitCode !== null) throw new Error(`Server beendet (Protokoll: ${path.join(dir, 'server.log')})`); try { const r = await fetch(`${base}/api/health`); if (r.ok) return { proc, dir, base }; } catch { /* startet noch */ } await sleep(100); } proc.kill('SIGTERM'); throw new Error('Server startet nicht'); } async function stopServer(proc) { if (!proc || proc.exitCode !== null) return; const done = new Promise((r) => proc.once('exit', r)); proc.kill('SIGTERM'); await Promise.race([done, sleep(8000)]); if (proc.exitCode === null) proc.kill('SIGKILL'); } // ------------------------------------------------------------------ Simulierte Clients class Client { constructor(ctx, i, { token = null, guest = false } = {}) { Object.assign(this, { ctx, i, token, guest }); this.seq = 1; this.pending = new Map(); this.symbols = []; this.prices = new Map(); this.orders = []; this.holdings = new Map(); this.lastMarket = 0; this.closed = false; this.ip = `10.77.${Math.floor(i / 250)}.${(i % 250) + 1}`; this.sync = new MarketSync(); this.hidden = false; } connect() { const { base } = this.ctx; return new Promise((resolve, reject) => { const ws = new WebSocket(`${base.replace(/^http/, 'ws')}/ws`, { headers: { origin: base, 'user-agent': UA, 'x-forwarded-for': this.ip }, perMessageDeflate: this.ctx.deflate !== false }); this.ws = ws; let hello = false; ws.on('message', (raw) => { this.ctx.bytes += raw.length; this.lastSize = raw.length; let m; try { m = JSON.parse(raw.toString()); } catch { return; } if (this.ctx.measuring) { const b = (this.ctx.types[m.type] ??= { n: 0, bytes: 0 }); b.n++; b.bytes += raw.length; } if (m.type === 'hello') { this.#market(m.market); if (!hello) { hello = true; if (this.ctx.delta) this.send('net', { v: MK_PROTO, hidden: this.hidden }, { record: false }); resolve(); } return; } if (this.ctx.measuring && m.type !== 'reply') { const b = (this.ctx.push[m.type] ??= { n: 0, bytes: 0 }); b.n++; b.bytes += raw.length; } this.#onMessage(m); }); ws.on('error', (e) => { if (!hello) reject(e); }); ws.on('unexpected-response', (_q, res) => { if (!hello) reject(new Error(`WebSocket abgelehnt: HTTP ${res.statusCode}`)); }); ws.on('close', () => { if (!this.ctx.stopping) this.ctx.disconnects++; this.closed = true; for (const p of this.pending.values()) p.resolve({ ok: false, error: 'Verbindung getrennt' }); this.pending.clear(); }); }); } #market(mk) { if (!mk?.tickers) return; for (const t of mk.tickers) if (t.last > 0 && t.kind === 'stock') this.prices.set(t.symbol, t.last); if (!this.symbols.length) this.symbols = [...this.prices.keys()]; } #onMessage(m) { const ctx = this.ctx; if (m.type === 'market' || m.type === 'mkd') { const now = performance.now(); if (this.lastMarket && ctx.measuring && !this.hidden) ctx.intervals.push(now - this.lastMarket); this.lastMarket = now; // wie der Browser (netsync.js): Schlüsselbild übernehmen, Delta anwenden, bei Lücke Schlüsselbild anfordern const st = m.type === 'market' ? this.sync.key(m) : this.sync.delta(m); if (st) this.#market(st); else if (!this.asked || now - this.asked > 5000) { this.asked = now; ctx.gaps++; this.send('net', { key: true }, { record: false }); } } else if (m.type === 'portfolio') { this.#portfolio(m.portfolio); } else if (m.type === 'humanCheck') { this.#humanCheck(m.nonce); } else if (m.type === 'reply' && this.pending.has(m.reqId)) { const p = this.pending.get(m.reqId); this.pending.delete(m.reqId); p.resolve(m); } } #portfolio(pf) { if (!pf) return; this.holdings = new Map((pf.positions ?? pf.holdings ?? []).map((x) => [x.symbol, x.qty ?? x.shares ?? 0])); if (Array.isArray(pf.orders)) this.orders = pf.orders.map((o) => o.id).filter(Boolean); } #humanCheck(nonce) { if (!nonce) return; this.ctx.humanChecks++; this.send('humanCheck', { nonce, ms: 1500 + Math.random() * 3000, trusted: true }, { record: false }); } /** Befehl senden und auf die Antwort warten; Zeit wird unter label erfasst */ send(type, data = {}, { label = type, record = true } = {}) { if (this.closed || this.ws.readyState !== 1) return Promise.resolve({ ok: false, error: 'nicht verbunden' }); const reqId = this.seq++; const t0 = performance.now(); const ctx = this.ctx; return new Promise((resolve) => { const timer = setTimeout(() => { if (this.pending.delete(reqId)) { if (ctx.measuring && record) ctx.timeouts++; resolve({ ok: false, error: 'Zeitüberschreitung' }); } }, 15_000); this.pending.set(reqId, { resolve: (m) => { clearTimeout(timer); if (record && ctx.measuring) { const lat = (ctx.lat[label] ??= { t: [], errors: 0, bytes: 0 }); lat.t.push(performance.now() - t0); lat.bytes += this.lastSize ?? 0; if (!m.ok) { lat.errors++; ctx.errors++; const e = String(m.error ?? '?').slice(0, 90); ctx.errorTexts[e] = (ctx.errorTexts[e] ?? 0) + 1; } } if (m.humanCheck) this.#humanCheck(m.humanCheck); if (m.portfolio) this.#portfolio(m.portfolio); resolve(m); }, }); this.ws.send(JSON.stringify({ ...data, type, reqId })); }); } async login() { const r = await this.send('auth', { token: this.token }, { record: false }); if (!r.ok) throw new Error(`Anmeldung fehlgeschlagen: ${r.error}`); await this.send('clientEnv', { wd: false }, { record: false }); } sym() { return this.symbols[Math.floor(Math.random() * this.symbols.length)] ?? 'NVLT'; } /** ein Schritt: Ansicht wechseln, nachschlagen oder handeln */ async step() { const s = this.sym(); const views = [ ['subscribe', 4], ['company', 3], ['chart', 3], ['leaderboard', 2], ['paper', 1], ['parliament', 1], ['calendar', 1], ['briefing', 1], ]; const player = this.guest ? [] : [['portfolio', 3], ['journal', 1], ['todo', 1], ['orderLimit', 3], ['orderMarket', 2], ['sell', 1], ['cancel', 1]]; const what = pick([...views, ...player]); const hi = { hi: 1 + Math.floor(Math.random() * 4) }; // wie der Browser: echte Eingaben seit dem letzten Befehl const cid = () => `lt${this.i}x${this.seq}${Math.random().toString(36).slice(2, 8)}`; switch (what) { case 'subscribe': return this.send('subscribe', { symbol: s }); case 'company': return this.send('company', { symbol: s }); case 'chart': return this.send('chart', { symbol: s, range: pick([['1T', 2], ['1W', 2], ['1M', 3], ['1Q', 1], ['1J', 1]]) }, { label: 'chart' }); case 'orderLimit': { const last = this.prices.get(s) ?? 0; if (!last) return null; const side = Math.random() < 0.6 ? 'buy' : 'sell'; if (side === 'sell' && !(this.holdings.get(s) > 0)) return this.send('order', { symbol: s, side: 'buy', orderType: 'limit', price: +(last * (0.97 + Math.random() * 0.03)).toFixed(2), qty: 1 + Math.floor(Math.random() * 20), clientId: cid(), ...hi }, { label: 'order (limit)' }); const price = +(last * (side === 'buy' ? 0.97 + Math.random() * 0.035 : 0.995 + Math.random() * 0.035)).toFixed(2); const r = await this.send('order', { symbol: s, side, orderType: 'limit', price, qty: Math.max(1, Math.min(this.holdings.get(s) ?? 20, 1 + Math.floor(Math.random() * 20))), clientId: cid(), ...hi }, { label: 'order (limit)' }); if (r.ok && r.order?.id && r.order.status !== 'filled') this.orders.push(r.order.id); return r; } case 'orderMarket': return this.send('order', { symbol: s, side: 'buy', orderType: 'market', qty: 1 + Math.floor(Math.random() * 10), clientId: cid(), ...hi }, { label: 'order (market)' }); case 'sell': { const own = [...this.holdings].filter(([, q]) => q > 0); if (!own.length) return this.send('portfolio'); const [sym, q] = own[Math.floor(Math.random() * own.length)]; return this.send('order', { symbol: sym, side: 'sell', orderType: 'market', qty: Math.max(1, Math.floor(q / 2)), clientId: cid(), ...hi }, { label: 'order (market)' }); } case 'cancel': { const id = this.orders.shift(); return id ? this.send('cancel', { orderId: id, ...hi }) : this.send('portfolio'); } default: return this.send(what); } } async loop(until, think) { while (!this.ctx.stopping && !this.closed && performance.now() < until) { await sleep(thinkMs(think)); if (this.ctx.stopping || this.closed) break; try { await this.step(); } catch (e) { this.ctx.errorTexts[`Client: ${e.message}`] = (this.ctx.errorTexts[`Client: ${e.message}`] ?? 0) + 1; } } } close() { try { this.ws?.close(); } catch { /* egal */ } } } /** Konto anlegen bzw. anmelden (jedes mit eigener X-Forwarded-For-Adresse) → Token */ async function account(base, name, password, ip) { const post = (url, body) => fetch(base + url, { method: 'POST', headers: { 'content-type': 'application/json', origin: base, 'x-forwarded-for': ip, 'user-agent': UA }, body: JSON.stringify(body) }) .then(async (r) => ({ status: r.status, body: await r.json().catch(() => ({})) })); const reg = await post('/api/register', { name, password }); if (reg.status === 200 && reg.body.token) return reg.body.token; const r = await post('/api/login', { name, password }); if (r.status !== 200 || !r.body.token) throw new Error(`Konto ${name}: Registrierung „${reg.body.error ?? reg.status}“, Anmeldung „${r.body.error ?? r.status}“`); return r.body.token; } // ------------------------------------------------------------------ Lauf /** * @param {{players?: number, guests?: number, duration?: number, warmup?: number, think?: number, url?: string, data?: string, * port?: number, mode?: string, pid?: number, prefix?: string, password?: string, prof?: string, log?: (s: string) => void}} o */ export async function run(o = {}) { const players = o.players ?? 30, guests = o.guests ?? Math.round(players / 5); const duration = o.duration ?? 120, warmup = o.warmup ?? 10, think = o.think ?? 4000; const log = o.log ?? (() => {}); let srv = null, base = o.url?.replace(/\/$/, ''), pid = o.pid ?? null, dataDir = o.url ? (o.data ?? null) : null; if (!base) { // ohne --port: zufälliger Port, bei Belegung (oder Startfehler) ein anderer for (let i = 0; !srv; i++) { try { srv = await startServer({ data: o.data, port: o.port ?? 22_000 + Math.floor(Math.random() * 3000), mode: o.mode ?? 'turbo', prof: o.prof, dayMs: o.dayMs, env: o.env }); } catch (e) { if (o.port || i >= 4) throw e; } } base = srv.base; pid = srv.proc.pid; dataDir = srv.dir; log(`Eigener Server gestartet: ${base} (PID ${pid}, Daten ${dataDir})`); } const ctx = { base, bytes: 0, push: {}, types: {}, lat: {}, errors: 0, timeouts: 0, errorTexts: {}, intervals: [], humanChecks: 0, disconnects: 0, gaps: 0, measuring: false, stopping: false, delta: o.delta !== false, deflate: o.deflate !== false }; const clients = []; const result = {}; try { // Konten und Verbindungen (gestaffelt wie echte Spieler, die nacheinander kommen) const prefix = o.prefix ?? `lt${Date.now().toString(36).slice(-4)}`; const password = o.password ?? 'lasttest-geheim-1'; for (let i = 0; i < players + guests; i++) { const guest = i >= players; const c = new Client(ctx, i, { guest }); c.hidden = (o.hidden ?? 0) > 0 && i % Math.max(1, Math.round(1 / o.hidden)) === 0; // Anteil der Tabs im Hintergrund if (!guest) c.token = await account(base, `${prefix}-${i}`, password, c.ip); await c.connect(); if (!guest) await c.login(); clients.push(c); } log(`${players} Spieler und ${guests} Gäste verbunden – Aufwärmen ${warmup} s, dann ${duration} s Messung`); const until = performance.now() + (warmup + duration) * 1000; const loops = clients.map((c) => c.loop(until, think)); await sleep(warmup * 1000); // Messphase const health = [], cpu = [], rss = [], heap = [], phases = {}, eld = { p50: [], p99: [], max: [] }; const metricsOf = async () => { try { return parseMetrics(await (await fetch(`${base}/metrics`, { headers: process.env.OPS_TOKEN ? { 'x-ops-token': process.env.OPS_TOKEN } : {} })).text()); } catch { return {}; } }; const day = async () => { try { return (await (await fetch(`${base}/api/health`)).json()).day; } catch { return null; } }; const m0 = await metricsOf(); const day0 = await day(); const disk0 = dataDir ? dataSizes(dataDir) : null; const lg0 = process.cpuUsage(); ctx.measuring = true; ctx.bytes = 0; ctx.gaps = 0; const wire0 = clients.reduce((a, c) => a + (c.ws?._socket?.bytesRead ?? 0), 0); const t0 = performance.now(); let prev = pid ? procSample(pid) : null; const memStart = prev?.rss ?? m0.wibosim_rss_bytes ?? null; const hz = 100; // USER_HZ unter Linux while (performance.now() - t0 < duration * 1000) { await sleep(2000); const h0 = performance.now(); try { const h = await (await fetch(`${base}/api/health`)).json(); health.push(performance.now() - h0); phases[h.phase] = (phases[h.phase] ?? 0) + 1; } catch { /* zählt nicht */ } const m = await metricsOf(); const cur = pid ? procSample(pid) : null; if (cur && prev) cpu.push(((cur.ticks - prev.ticks) / hz) / ((cur.t - prev.t) / 1000) * 100); if (cur) { rss.push(cur.rss); prev = cur; } else if (m.wibosim_rss_bytes) rss.push(m.wibosim_rss_bytes); if (m.wibosim_heap_used_bytes) heap.push(m.wibosim_heap_used_bytes); for (const q of ['p50', 'p99', 'max']) { const x = m[`wibosim_eventloop_delay_ms{q="${q}"}`]; if (Number.isFinite(x) && x > 0) eld[q].push(x); } } const secs = (performance.now() - t0) / 1000; ctx.measuring = false; const wire1 = clients.reduce((a, c) => a + (c.ws?._socket?.bytesRead ?? 0), 0); const bytes = ctx.bytes; // hier festhalten: bis alle Clients ihre letzte Anfrage beendet haben, kommen weitere Takte an const lg = process.cpuUsage(lg0); const m1 = await metricsOf(); const day1 = await day(); ctx.stopping = true; await Promise.race([Promise.all(loops), sleep(16_000)]); const disk1 = dataDir ? dataSizes(dataDir) : null; const latency = {}; const allT = []; for (const [k, v] of Object.entries(ctx.lat)) { latency[k] = { ...stats(v.t), errors: v.errors, kb: v.bytes / Math.max(1, v.t.length) / 1024 }; allT.push(...v.t); } const total = allT.length + ctx.timeouts; Object.assign(result, { players, guests, durationSec: Math.round(secs), mode: srv ? (o.mode ?? 'turbo') : null, think, tickMs: null, requests: { total, errors: ctx.errors, timeouts: ctx.timeouts }, latency, latencyAll: stats(allT), errorTexts: ctx.errorTexts, humanChecks: ctx.humanChecks, disconnects: ctx.disconnects, tick: { interval: stats(ctx.intervals), serverMs: (() => { const h = histDiff(m0, m1, 'wibosim_tick_duration_ms'); return h ? { ...h, max: m1.wibosim_tick_ms_max ?? null } : null; })(), ticks: m1.wibosim_ticks_total != null && m0.wibosim_ticks_total != null ? m1.wibosim_ticks_total - m0.wibosim_ticks_total : null, errors: m1.wibosim_tick_errors_total != null && m0.wibosim_tick_errors_total != null ? m1.wibosim_tick_errors_total - m0.wibosim_tick_errors_total : null, }, health: stats(health), bytesPerClientSec: bytes / secs / Math.max(1, clients.length), push: ctx.push, types: ctx.types, wirePerClientSec: (wire1 - wire0) / secs / Math.max(1, clients.length), gaps: ctx.gaps, delta: ctx.delta, hiddenClients: clients.filter((c) => c.hidden).length, net: (() => { const k = (n) => (m1[`wibosim_net_sent_total{kind="${n}"}`] ?? 0) - (m0[`wibosim_net_sent_total{kind="${n}"}`] ?? 0); return m1['wibosim_net_sent_total{kind="key"}'] != null ? { key: k('key'), delta: k('delta'), skipped: k('skipped'), bookSkipped: k('bookSkipped'), lbSkipped: k('lbSkipped'), pfSkipped: k('pfSkipped'), keyBytes: m1['wibosim_net_frame_bytes{kind="key"}'], deltaBytes: m1['wibosim_net_frame_bytes{kind="delta"}'] } : null; })(), cpu: cpu.length ? { avg: cpu.reduce((s, x) => s + x, 0) / cpu.length, max: Math.max(...cpu) } : null, loadgenCpu: ((lg.user + lg.system) / 1e6 / secs) * 100, mem: rss.length ? { start: memStart, end: rss[rss.length - 1], max: Math.max(...rss), heapMax: heap.length ? Math.max(...heap) : null, heapLimit: m1.wibosim_heap_limit_bytes ?? null } : null, disk: disk0 ? { before: disk0, after: disk1, growthPerHour: ((disk1.total - disk0.total) / secs) * 3600 } : null, days: day0 != null && day1 != null ? { from: day0, to: day1 } : null, phases, eld: eld.p99.length ? { p50: stats(eld.p50).avg, p99: stats(eld.p99).avg, p99max: Math.max(...eld.p99), max: Math.max(...eld.max) } : null, display: m1['wibosim_display_ticks_total{kind="sent"}'] != null ? (() => { const k = (n) => (m1[`wibosim_display_ticks_total{kind="${n}"}`] ?? 0) - (m0[`wibosim_display_ticks_total{kind="${n}"}`] ?? 0); const nC = Math.max(1, clients.length), px = ctx.types.px; return { on: k('steps') > 0, ms: o.env?.DISPLAY_TICK_MS ? Number(o.env.DISPLAY_TICK_MS) : 500, sent: k('sent'), steps: k('steps'), perClientSec: k('sent') / secs / nC, bytesPerClientSec: (px?.bytes ?? 0) / secs / nC }; })() : null, }); if (m1.wibosim_tick_target_ms) result.tickMs = m1.wibosim_tick_target_ms; } finally { ctx.stopping = true; for (const c of clients) c.close(); if (srv) { await stopServer(srv.proc); if (!o.keep) fs.rmSync(srv.dir, { recursive: true, force: true }); else log(`Daten bleiben erhalten: ${srv.dir}`); } } return result; } // ------------------------------------------------------------------ Aufruf von der Kommandozeile if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { const { values: a } = parseArgs({ options: { players: { type: 'string', default: '30' }, guests: { type: 'string' }, duration: { type: 'string', default: '120' }, warmup: { type: 'string', default: '10' }, think: { type: 'string', default: '4000' }, url: { type: 'string' }, data: { type: 'string' }, port: { type: 'string' }, mode: { type: 'string', default: 'turbo' }, pid: { type: 'string' }, 'day-ms': { type: 'string' }, prefix: { type: 'string' }, password: { type: 'string' }, json: { type: 'string' }, keep: { type: 'boolean', default: false }, prof: { type: 'string' }, 'pi-factor': { type: 'string', default: '4' }, 'no-delta': { type: 'boolean', default: false }, 'server-env': { type: 'string' }, 'no-deflate': { type: 'boolean', default: false }, hidden: { type: 'string' }, }, }); const r = await run({ players: Number(a.players), guests: a.guests !== undefined ? Number(a.guests) : undefined, duration: Number(a.duration), warmup: Number(a.warmup), think: Number(a.think), url: a.url, data: a.data, port: a.port ? Number(a.port) : undefined, mode: a.mode, pid: a.pid ? Number(a.pid) : undefined, dayMs: a['day-ms'] ? Number(a['day-ms']) : undefined, prefix: a.prefix, password: a.password, keep: a.keep, prof: a.prof, log: (s) => console.log(s), delta: !a['no-delta'], env: Object.fromEntries((a['server-env'] ?? '').split(',').filter(Boolean).map((x) => x.split('='))), deflate: !a['no-deflate'], hidden: a.hidden ? Number(a.hidden) : 0, }); console.log(`\n${formatReport(r, { piFactor: Number(a['pi-factor']) })}`); if (a.json) fs.writeFileSync(a.json, JSON.stringify(r, null, 2)); }