10단계 다듬기: axe 접근성 검사(첫 화면·대기실·게임·정답 공개·결과·관리자, PC/휴대폰 × 밝은/어두운 화면) 위반 0으로 고침(배지·정답 글자 대비, 게임 화면 main·방 정보 영역, 제목 순서, 별 아이콘), 100명 부하 시험 + TJ는 최근 2년만, 멜론 곡 정보는 가사·연도 없는 곡부터

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:43:26 +09:00
parent 46240ac699
commit 674cd377b4
10 changed files with 313 additions and 19 deletions

128
e2e/a11y.e2e.ts Normal file
View File

@@ -0,0 +1,128 @@
/**
* Stage 10 accessibility (docs/03 접근성, docs/10 다듬기): axe-core on 첫 화면 · 대기실 · 게임 · 정답 공개 · 결과 · 관리자 노래,
* PC and phone, light and dark. Any violation (any impact) fails. Run: bun run build && bun e2e/a11y.e2e.ts
*/
import { chromium, type BrowserContext, type Page } from 'playwright-core';
import { mkdtempSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { Catalog } from '../apps/server/src/collector/catalog';
const PORT = Number(process.env.E2E_PORT ?? 4625);
const ORIGIN = `http://localhost:${PORT}`;
const AXE = readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8');
const SUPER = '900000000000000001';
const app = startServer({
config: loadConfig({
PORT: String(PORT),
DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-a11y-')), 'app.db'),
PUBLIC_ORIGIN: ORIGIN,
SUPERADMIN_DISCORD_IDS: SUPER,
DISCORD_CLIENT_ID: '1561284577564037140',
DISCORD_CLIENT_SECRET: 'e2e',
}),
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '검사관리자', avatar: null }),
gameTiming: { countdownMs: 300, revealMs: 4000 },
});
{
const c = new Catalog(app.db);
for (let i = 1; i <= 4; i++) {
const [id] = c.upsert({ title: `검사곡${i}`, artists: [{ name: `검사가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 'e2e', ref: String(i) });
c.autoLevel(id!, 'all', 3);
app.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`fake${String(i).padStart(7, '0')}`, id!);
}
}
const titleOf = (vid: string) => app.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(vid)!.title;
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
let bad = 0;
async function audit(page: Page, name: string) {
await page.addScriptTag({ content: AXE });
const res = await page.evaluate(async () => (window as any).axe.run(document, { resultTypes: ['violations'] }));
if (res.violations.length) {
bad += res.violations.length;
console.log(`✗ ${name}: ${res.violations.map((v: any) => `${v.id}[${v.impact}](${v.nodes.length}) ${v.nodes[0]?.target?.join(' ')}`).join('; ')}`);
} else console.log(`✓ ${name}`);
}
async function guest(ctx: BrowserContext, name: string): Promise<Page> {
await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByLabel('게스트 닉네임 (2~12자)').fill(name);
await p.getByRole('button', { name: '게스트로 시작' }).click();
await p.getByRole('button', { name: `내 계정: ${name}` }).waitFor();
return p;
}
try {
let n = 0;
for (const [label, ctxOpts] of [
['PC', { viewport: { width: 1440, height: 900 } }],
['phone', { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }],
] as const) {
for (const theme of ['light', 'dark'] as const) {
const ctx = await browser.newContext({ ...ctxOpts, locale: 'ko-KR', colorScheme: theme });
const first = await ctx.newPage();
await first.goto(ORIGIN + '/');
await first.getByRole('button', { name: '게스트로 시작' }).waitFor();
await audit(first, `${label}/${theme} 첫 화면`);
await first.close();
const p = await guest(ctx, `검사${++n}`);
await p.getByRole('button', { name: '+ 방 만들기' }).click();
await p.waitForURL(/\/r\/\d{6}$/);
await p.locator('.pool-banner').waitFor();
await audit(p, `${label}/${theme} 대기실`);
await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
await p.getByRole('button', { name: '게임 시작' }).click();
await p.getByRole('button', { name: '그대로 시작' }).click();
await p.locator('.stage .lp.spin').waitFor({ timeout: 10000 });
await p.getByLabel('채팅 입력').fill('모르겠다');
await p.getByLabel('채팅 입력').press('Enter');
await audit(p, `${label}/${theme} 게임 화면`);
const vid = await p.evaluate(() => (window as any).mqPlayer.video() as string);
await p.getByLabel('채팅 입력').fill(titleOf(vid));
await p.getByLabel('채팅 입력').press('Enter');
await p.locator('.reveal').waitFor();
await audit(p, `${label}/${theme} 정답 공개`);
await p.getByRole('button', { name: '⏹ 끝내기' }).click();
await p.getByRole('button', { name: '끝내기', exact: true }).click();
await p.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
await audit(p, `${label}/${theme} 결과`);
await p.getByRole('link', { name: '← 방 목록' }).click();
await ctx.close();
}
}
// 관리자 노래 화면 (PC, light / dark)
for (const theme of ['light', 'dark'] as const) {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR', colorScheme: theme });
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
const consent = new URL(res.headers.get('location')!);
const back = `${ORIGIN}/api/auth/discord/callback?code=${SUPER}&state=${consent.searchParams.get('state')}`;
await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `<script>location.replace(${JSON.stringify(back)})</script>` });
});
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
await p.getByRole('button', { name: '내 계정: 검사관리자' }).waitFor();
await p.goto(ORIGIN + '/admin/songs');
await p.locator('.data-table tbody tr').first().waitFor();
await audit(p, `PC/${theme} 관리자 노래`);
await p.goto(ORIGIN + '/admin/stats');
await p.getByRole('heading', { name: '통계' }).waitFor();
await audit(p, `PC/${theme} 관리자 통계`);
await ctx.close();
}
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
bad++;
} finally {
await browser.close();
await app.stop();
}
console.log(bad ? `A11Y FAILED (${bad})` : 'A11Y PASSED');
process.exit(bad ? 1 : 0);

21
e2e/load-server.ts Normal file
View File

@@ -0,0 +1,21 @@
/** Server process for e2e/load.ts: same startServer as production, seeded with playable songs. */
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { Catalog } from '../apps/server/src/collector/catalog';
const app = startServer({
config: loadConfig({ PORT: process.env.PORT!, DB_PATH: process.env.DB_PATH!, PUBLIC_ORIGIN: process.env.PUBLIC_ORIGIN!, TRUST_PROXY: '1' }),
log: () => {},
staticDir: null,
gameTiming: { countdownMs: 1000, revealMs: 1500 },
});
const c = new Catalog(app.db);
for (let i = 1; i <= 20; i++) {
const [id] = c.upsert({ title: `부하곡${i}`, artists: [{ name: `부하가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 'load', ref: String(i) });
c.autoLevel(id!, 'all', 3);
app.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`load${String(i).padStart(7, '0')}`, id!);
}
setInterval(() => process.send?.({ rss: process.memoryUsage().rss }), 1000);
console.log('ready');
void join;

124
e2e/load.ts Normal file
View File

@@ -0,0 +1,124 @@
/**
* 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);