Files
music_quiz/e2e/load.ts

125 lines
5.8 KiB
TypeScript

/**
* Stage 10 load test (docs/10 다듬기): 100 people in one room on a separate server process.
* Chat: time from one player's send until all 100 have it (target < 200ms). Game: 3 questions with 100 players
* (all ready → one play time for everyone, answer block reaches everyone). Reports server memory.
* Run: bun e2e/load.ts (N=100 by default)
*/
import { mkdtempSync } from 'node:fs';
import { join } from 'node:path';
const N = Number(process.env.N ?? 100);
const PORT = Number(process.env.E2E_PORT ?? 4627);
const ORIGIN = `http://localhost:${PORT}`;
const DB_PATH = join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-load-')), 'app.db');
let rss = 0;
const server = Bun.spawn(['bun', join(import.meta.dir, 'load-server.ts')], {
env: { ...process.env, PORT: String(PORT), DB_PATH, PUBLIC_ORIGIN: ORIGIN },
stdout: 'pipe',
ipc: (m: { rss: number }) => (rss = Math.max(rss, m.rss)),
});
const reader = server.stdout.getReader();
for (let buf = ''; !buf.includes('ready'); ) buf += new TextDecoder().decode((await reader.read()).value);
type Msg = { t: string; [k: string]: any };
class Player {
ws!: WebSocket;
inbox: Msg[] = [];
listeners = new Set<(m: Msg) => void>();
constructor(readonly cookie: string) {}
connect() {
return new Promise<void>((resolve) => {
this.ws = new WebSocket(ORIGIN.replace('http', 'ws') + '/ws', { headers: { cookie: this.cookie, origin: ORIGIN } } as unknown as string[]);
this.ws.onmessage = (e) => {
const m = JSON.parse(String(e.data)) as Msg;
if (m.t === 'prepare') this.send({ t: 'audio', n: m.n, ev: 'ready' });
this.inbox.push(m);
if (this.inbox.length > 500) this.inbox.splice(0, 250);
for (const l of this.listeners) l(m);
if (m.t === 'welcome') resolve();
};
});
}
send(m: unknown) {
this.ws.send(JSON.stringify(m));
}
next(pred: (m: Msg) => boolean, ms = 10000) {
return new Promise<Msg>((resolve, reject) => {
const t = setTimeout(() => (this.listeners.delete(l), reject(new Error('timeout'))), ms);
const l = (m: Msg) => pred(m) && (clearTimeout(t), this.listeners.delete(l), resolve(m));
this.listeners.add(l);
});
}
}
async function guest(i: number): Promise<string> {
const r = await fetch(`${ORIGIN}/api/auth/guest`, { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN, 'x-forwarded-for': `10.1.${i >> 8}.${i & 255}` }, body: JSON.stringify({ nickname: `부하${i}` }) });
return r.headers.getSetCookie()[0]!.split(';')[0]!;
}
const pct = (xs: number[], p: number) => [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor((xs.length * p) / 100))]!;
let failed = false;
try {
const players: Player[] = [];
for (let i = 0; i < N; i++) {
const p = new Player(await guest(i));
await p.connect();
players.push(p);
}
const host = players[0]!;
const code = (await (await fetch(`${ORIGIN}/api/rooms`, { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN, cookie: host.cookie }, body: JSON.stringify({ config: { listenSec: 10, count: 10 } }) })).json()).code;
const t0 = performance.now();
await Promise.all(players.map(async (p) => (p.send({ t: 'join', code }), p.next((m) => m.t === 'room'))));
await host.next((m) => m.t === 'room' && m.room.players.length === N);
console.log(`✓ ${N}명 입장 (${Math.round(performance.now() - t0)}ms)`);
// chat latency: one sender at a time, until every player has the line
const lat: number[] = [];
for (let k = 0; k < 100; k++) {
const from = players[(k * 7) % N]!;
const text = `부하채팅${k}`;
const s = performance.now();
const all = Promise.all(players.map((p) => p.next((m) => m.t === 'chat' && m.line.text === text)));
from.send({ t: 'chat', text });
await all;
lat.push(performance.now() - s);
}
// burst: 20 people send at the same instant
const burst: number[] = [];
{
const s = performance.now();
const texts = players.slice(0, 20).map((_, i) => `동시${i}`);
const all = Promise.all(players.map((p) => Promise.all(texts.map((t) => p.next((m) => m.t === 'chat' && m.line.text === t)))));
players.slice(0, 20).forEach((p, i) => p.send({ t: 'chat', text: texts[i] }));
await all;
burst.push(performance.now() - s);
}
console.log(`${pct(lat, 95) < 200 ? '✓' : '✗'} 채팅이 ${N}명 모두에게 닿는 시간: 중간 ${pct(lat, 50).toFixed(1)}ms, 95% ${pct(lat, 95).toFixed(1)}ms, 최대 ${Math.max(...lat).toFixed(1)}ms · 20명 동시 ${burst[0]!.toFixed(1)}ms`);
if (pct(lat, 95) >= 200) failed = true;
// game: 3 questions
host.send({ t: 'start' });
for (let n = 1; n <= 3; n++) {
const plays = await Promise.all(players.map((p) => p.next((m) => m.t === 'play' && m.n === n, 15000)));
const same = new Set(plays.map((m) => m.startAt)).size === 1;
const prep = players[0]!.inbox.findLast((m) => m.t === 'prepare' && m.n === n)!;
const title = `부하곡${Number(prep.videoId.slice(4))}`;
await new Promise((r) => setTimeout(r, Math.max(0, plays[0]!.startAt - Date.now()) + 20));
const s = performance.now();
const all = Promise.all(players.map((p) => p.next((m) => m.t === 'answer')));
players[n * 11]!.send({ t: 'chat', text: title });
await all;
console.log(`${same ? '✓' : '✗'} ${n}번 문제: ${N}명 모두 같은 시작 시각, 정답 블록이 모두에게 ${(performance.now() - s).toFixed(1)}ms`);
if (!same) failed = true;
}
host.send({ t: 'game', action: 'end' });
await host.next((m) => m.t === 'game' && m.game?.phase === 'result');
console.log(`✓ 결과 화면 · 서버 메모리 최대 ${Math.round(rss / 1048576)}MB`);
for (const p of players) p.ws.close();
} catch (e) {
console.log('✗', (e as Error).message);
failed = true;
} finally {
server.kill();
}
console.log(failed ? 'LOAD FAILED' : 'LOAD PASSED');
process.exit(failed ? 1 : 0);