10단계 다듬기: axe 접근성 검사(첫 화면·대기실·게임·정답 공개·결과·관리자, PC/휴대폰 × 밝은/어두운 화면) 위반 0으로 고침(배지·정답 글자 대비, 게임 화면 main·방 정보 영역, 제목 순서, 별 아이콘), 100명 부하 시험 + TJ는 최근 2년만, 멜론 곡 정보는 가사·연도 없는 곡부터
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -133,7 +133,8 @@ export function chartSpecs(opts: { from?: number; to?: number; sources?: string[
|
||||
...(await sleep(2500).then(async () => parseGenie(await get(`https://www.genie.co.kr/chart/musicHistory?year=${y}&category=0&pg=2`)))),
|
||||
],
|
||||
});
|
||||
if (want('tj-ye') && y >= 2008)
|
||||
// TJ's API only answers for about the last two years (older ranges → resultCode 98).
|
||||
if (want('tj-ye') && y >= 2024)
|
||||
out.push({
|
||||
source: 'tj',
|
||||
chart: 'year',
|
||||
@@ -284,7 +285,7 @@ export async function fillMelonDetails(db: Database, opts: { limit?: number; del
|
||||
.query<{ id: number; melon_id: number; genres_source: string | null }, [number]>(
|
||||
`SELECT s.id, s.melon_id, s.genres_source FROM songs s WHERE s.deleted_at IS NULL AND s.melon_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM signals g WHERE g.song_id = s.id AND g.kind = 'melon_detail')
|
||||
ORDER BY (s.youtube_status = 'matched') DESC, s.id LIMIT ?`,
|
||||
ORDER BY NOT EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id) DESC, (s.year IS NULL) DESC, (s.youtube_status = 'matched') DESC, s.id LIMIT ?`,
|
||||
)
|
||||
.all(opts.limit ?? 500);
|
||||
const job = new Job(db, 'melon-detail', rows.length);
|
||||
|
||||
@@ -30,8 +30,11 @@ function Stars({ n }: { n: number | null }) {
|
||||
if (!n) return null;
|
||||
const color = n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)';
|
||||
return (
|
||||
<span className="mini-stars" style={{ color }} aria-label={`난이도 ${n}단계`}>
|
||||
★{n}
|
||||
<span className="mini-stars" role="img" aria-label={`난이도 ${n}단계`}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden>
|
||||
<path fill={color} d="M12 2l3 6.9 7.5.7-5.7 5 1.7 7.4L12 18.3 5.5 22l1.7-7.4-5.7-5 7.5-.7z" />
|
||||
</svg>
|
||||
{n}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -104,8 +107,8 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
const late = isHost ? game.waiting.filter((w) => now - w.since >= LATE_MS) : [];
|
||||
|
||||
return (
|
||||
<div className="game">
|
||||
<div className="gbar">
|
||||
<main className="game">
|
||||
<div className="gbar" role="toolbar" aria-label="게임 조작">
|
||||
<div className="q">
|
||||
문제 {game.n} <span>/ {game.total}</span>
|
||||
</div>
|
||||
@@ -139,7 +142,7 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</div>
|
||||
<div className="ggrid">
|
||||
<aside className="side scoreboard" aria-label="점수판">
|
||||
<h3>점수판 · {game.scores.length}명</h3>
|
||||
<h2>점수판 · {game.scores.length}명</h2>
|
||||
<ol>
|
||||
{game.scores.map((s, i) => {
|
||||
// ties share a rank (same score and same average time)
|
||||
@@ -248,7 +251,7 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
/>
|
||||
</div>
|
||||
<aside className="side hist" aria-label="지난 문제">
|
||||
<h3>지난 문제</h3>
|
||||
<h2>지난 문제</h2>
|
||||
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
|
||||
{[...game.history].reverse().map((h) => (
|
||||
<div key={h.n} className="h">
|
||||
@@ -271,7 +274,7 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</div>
|
||||
)}
|
||||
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ export default function RoomPage() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="roombar">
|
||||
<section className="roombar" aria-label="방 정보">
|
||||
<Link to="/" className="btn btn-sm btn-ghost">
|
||||
← 방 목록
|
||||
</Link>
|
||||
@@ -131,7 +131,7 @@ export default function RoomPage() {
|
||||
<button type="button" className="btn btn-sm" onClick={() => setConfirmLeave(true)}>
|
||||
🚪 나가기
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
{playing ? (
|
||||
<GameScreen room={room} game={game} />
|
||||
) : (
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
--on-primary: #fff;
|
||||
--mustard: #f2b544;
|
||||
--coral: #e4573d;
|
||||
--correct: #2f8f4e;
|
||||
--correct: #24733d; /* docs/03 #2F8F4E, darkened for 4.5:1 text contrast (axe) */
|
||||
--correct-soft: #ddf0e2;
|
||||
--danger: #b3261e;
|
||||
--danger-soft: #f8dcd6;
|
||||
@@ -143,8 +143,10 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; }
|
||||
.card.ink { border: 2px solid var(--ink); }
|
||||
.badge { display: inline-flex; align-items: center; height: 22px; padding: 0 8px; border-radius: 6px; font-size: 0.8rem; font-weight: 750; background: var(--surface-2); color: var(--text-sub); }
|
||||
.badge.teal { background: var(--primary-soft); color: var(--primary); }
|
||||
.badge.live { background: var(--coral); color: #fff; }
|
||||
.badge.ok { background: var(--correct-soft); color: var(--correct); }
|
||||
.badge.live { background: #b83a24; color: #fff; }
|
||||
.badge.ok { background: var(--correct-soft); color: #22693a; }
|
||||
:root[data-theme='dark'] .badge.ok, :root[data-theme='dark'] .badge.teal { color: #9fd9de; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .badge.ok, :root[data-theme='auto'] .badge.teal { color: #9fd9de; } }
|
||||
.badge.warn { background: var(--warning-soft); color: #8a5a00; }
|
||||
:root[data-theme='dark'] .badge.warn { color: var(--mustard); }
|
||||
.chip { min-height: 30px; padding: 0 11px; border-radius: 999px; border: 1.5px solid var(--line); background: var(--surface); font: inherit; font-weight: 650; font-size: 0.87rem; display: inline-flex; align-items: center; gap: 5px; color: var(--text); cursor: pointer; }
|
||||
@@ -220,7 +222,7 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; }
|
||||
.chat { display: flex; flex-direction: column; gap: 8px; position: relative; padding: 14px 16px; }
|
||||
.chat-log { height: 280px; overflow-y: auto; font-size: 0.95rem; line-height: 1.7; overscroll-behavior: contain; }
|
||||
.chat-line { padding: 0 6px; border-radius: 6px; overflow-wrap: anywhere; }
|
||||
.chat-line b { font-weight: 800; margin-right: 8px; color: hsl(var(--name-h, 200) 55% 38%); }
|
||||
.chat-line b { font-weight: 800; margin-right: 8px; color: hsl(var(--name-h, 200) 60% 30%); }
|
||||
.chat-line.me { background: var(--surface-2); }
|
||||
:root[data-theme='dark'] .chat-line b { color: hsl(var(--name-h, 200) 65% 72%); }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
@@ -268,7 +270,7 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; }
|
||||
.yr { position: relative; height: 62px; margin: 0 10px; }
|
||||
.yr .track { position: absolute; top: 27px; left: 0; right: 0; height: 7px; border-radius: 9px; background: var(--surface-3); }
|
||||
.yr .fill { position: absolute; top: 27px; height: 7px; background: var(--primary); border-radius: 9px; }
|
||||
.yr .bub { position: absolute; margin-left: -24px; width: 48px; text-align: center; background: var(--primary); color: #fff; font-weight: 800; font-size: 0.85rem; border-radius: 7px; padding: 1px 0; pointer-events: none; }
|
||||
.yr .bub { position: absolute; margin-left: -24px; width: 48px; text-align: center; background: var(--primary); color: var(--on-primary); font-weight: 800; font-size: 0.85rem; border-radius: 7px; padding: 1px 0; pointer-events: none; }
|
||||
.yr .bub.up { top: 0; }
|
||||
.yr .bub.dn { top: 42px; }
|
||||
.yr input[type='range'] { position: absolute; top: 20px; left: -10px; width: calc(100% + 20px); margin: 0; background: none; pointer-events: none; -webkit-appearance: none; appearance: none; height: 21px; }
|
||||
@@ -342,7 +344,7 @@ input.input.sm { width: 76px; }
|
||||
.vol input { width: 90px; accent-color: var(--mustard); }
|
||||
.ggrid { flex: 1; display: grid; grid-template-columns: 250px minmax(0, 1fr) 280px; gap: 16px; padding: 16px 20px; min-height: 0; max-width: 1600px; width: 100%; margin: 0 auto; }
|
||||
.side { background: var(--surface); border: 1.5px solid var(--line); border-radius: var(--radius); padding: 14px; overflow-y: auto; max-height: calc(100vh - 190px); }
|
||||
.side h3 { font-size: 0.85rem; font-weight: 800; color: var(--text-sub); margin-bottom: 8px; }
|
||||
.side h2, .side h3 { font-size: 0.85rem; font-weight: 800; color: var(--text-sub); margin-bottom: 8px; }
|
||||
.scoreboard ol { list-style: none; margin: 0; padding: 0; }
|
||||
.sb { display: flex; align-items: center; gap: 8px; padding: 6px; border-radius: 10px; font-weight: 700; font-size: 0.93rem; transition: transform 0.3s; }
|
||||
.sb .rk { width: 20px; text-align: center; font-weight: 850; color: var(--text-sub); }
|
||||
@@ -393,7 +395,8 @@ input.input.sm { width: 76px; }
|
||||
.hist .t { font-weight: 800; }
|
||||
.hist .m { color: var(--text-sub); font-size: 0.8rem; margin-top: 2px; display: flex; align-items: center; gap: 6px; }
|
||||
.hist .n { display: inline-block; width: 22px; font-weight: 850; color: var(--text-sub); }
|
||||
.mini-stars { font-weight: 850; font-size: 0.8rem; }
|
||||
.mini-stars { font-weight: 850; font-size: 0.8rem; display: inline-flex; align-items: center; gap: 1px; color: var(--text); }
|
||||
.mini-stars svg { width: 11px; height: 11px; }
|
||||
.unlock-overlay { position: fixed; inset: 0; z-index: 40; background: rgba(20, 18, 14, 0.55); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; color: #fff; text-align: center; padding: 20px; }
|
||||
.unlock-overlay .btn { font-size: 1.3rem; min-height: 64px; padding: 0 28px; }
|
||||
.sound-card { background: var(--warning-soft); border-color: var(--ink); }
|
||||
|
||||
3
bun.lock
3
bun.lock
@@ -6,6 +6,7 @@
|
||||
"name": "music-quiz",
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.2",
|
||||
"axe-core": "4.13.0",
|
||||
"playwright-core": "1.63.0",
|
||||
"typescript": "5.9.3",
|
||||
},
|
||||
@@ -99,6 +100,8 @@
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/plugin-react@6.1.1", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "oxc-transform-react": "^0.145.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler", "oxc-transform-react"] }, "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw=="],
|
||||
|
||||
"axe-core": ["axe-core@4.13.0", "", {}, "sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A=="],
|
||||
|
||||
"bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
|
||||
|
||||
"cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="],
|
||||
|
||||
@@ -117,3 +117,13 @@ collect_jobs(id PK, kind, params_json, status, progress, log, started_at, finish
|
||||
- 노라보세 `youtube_id`는 **팬 가사 영상인 경우가 많다**(표본 4곡 중 3곡). 그래서 그대로 쓰지 않고 후보로만 두고, 유튜브 뮤직 노래 검색으로 Topic 음원을 다시 찾는다
|
||||
- 노라보세 API는 50곡 묶음 중 일부 조합에서 500을 낸다 → 묶음을 반으로 나눠 다시 요청
|
||||
- 로그인 없는 유튜브 검색(대체 수단)은 Topic 채널 이름이 영문(`Hong Kyung-Min - Topic`)이라 한글 가수명과 안 맞아 확정률이 낮다(표본 60곡 중 19곡). 쿠키로 하는 노래 탭 검색은 가수명이 한글로 나온다
|
||||
|
||||
## 9단계 수집 확장에서 알게 된 것 (2026-10-18)
|
||||
- 수집기: `apps/server/src/collector/charts.ts`(차트·멜론 곡 정보), `heatmap.ts`(하이라이트), `levels.ts`(난이도). 관리자 "수집" 화면이나 `cli.ts charts|melon-detail|heatmap|levels`로 실행
|
||||
- 멜론 연도별(가요·팝 1984~작년)·실시간은 곡 ID가 있어서 **새 곡도 만든다**. 지니 연도별(1990~)·벅스 실시간·TJ는 이미 있는 곡에만 붙인다(제목만 다른 같은 곡이 따로 생기지 않게)
|
||||
- TJ 노래방 차트 API는 **최근 약 2년만** 준다(그 전 기간은 resultCode 98). 그래서 2024년부터만 모은다
|
||||
- 벅스 연도별은 자바스크립트 화면이라 이번에는 빼고 실시간만
|
||||
- 하이라이트: 유튜브 시청 페이지의 "많이 다시 본 구간"(heatmap markers 100개). 영상 첫 부분은 누구나 거기서 시작해서 항상 높으니 앞 10%·끝 5%는 빼고 3칸 평균 최고점의 한 칸 앞. 광(狂) 73.5초(yt-dlp 표시 75.8초와 같은 후렴)
|
||||
- 난이도 점수 = 차트 40 + 노라보세 단계 20 + 노래방 15 + 퀴즈 출현 15 + 가수 히트곡 수 10. 유튜브 조회수는 아직 안 모아서 사람 손으로 매긴 노라보세 단계가 그 몫을 맡는다. 순위 비율로 10단계(상위 3%·5%·10%·12%·15%·15%·12%·12%·11%·5%), 전체 + 곡이 150곡 이상인 장르·연대별. 관리자가 정한 단계는 그대로
|
||||
- 스포티파이 플레이리스트는 앱 키가 없어 하지 않았다(Q12). 유튜브 연도별 플레이리스트도 같은 집 IP의 music_bot_v2 차단 위험 때문에 뺐다
|
||||
|
||||
|
||||
128
e2e/a11y.e2e.ts
Normal file
128
e2e/a11y.e2e.ts
Normal 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
21
e2e/load-server.ts
Normal 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
124
e2e/load.ts
Normal 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);
|
||||
@@ -11,10 +11,11 @@
|
||||
"build": "bun run --filter '@mq/web' build",
|
||||
"typecheck": "tsc -p packages/shared && tsc -p apps/server && tsc -p apps/web",
|
||||
"test": "bun test --timeout 20000",
|
||||
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts"
|
||||
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts && bun e2e/a11y.e2e.ts && bun e2e/load.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.2",
|
||||
"axe-core": "4.13.0",
|
||||
"playwright-core": "1.63.0",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user