M0: 기술 검증 - 구조 설계, STT 워커, 앱 코어, 게임 PC 진단

- docs/dev/ARCHITECTURE.md: 코어-워커-사이트 인터페이스 계약
- worker/: faster-whisper 한국어 STT, 음량 정규화, 4단계 잡음 판정, 사전 교정, GPU 감지·모델/CUDA 다운로드, 롤 채팅 OCR·r3dlog, 파인튜닝 파이프라인 (39 tests)
- app/src/core: 디스코드 DAVE 음성 녹음(Ogg Opus), STT 대기열, 발로란트/롤 로컬 API 어댑터, 타임라인·기록 API, 사이트 중계, 7일 음성 삭제, 진단
- tools/gen-dictionary.mjs: 공식 게임 데이터 기반 기본 단어사전 (1993단어)
- M0 결과: DAVE 연결 1.06s Ready, CPU tiny STT 3.6s→0.31s, 가짜 Riot 서버 통합 테스트 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 01:17:48 +09:00
parent 4596989ba7
commit 7c9146cd2d
95 changed files with 18435 additions and 0 deletions

185
app/test/core.test.ts Normal file
View File

@@ -0,0 +1,185 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { Store } from '../src/core/db/db.ts';
import { Timeline, timeLabel } from '../src/core/timeline.ts';
import { diffWords, Dictionary } from '../src/core/dict/dictionary.ts';
import { realignWords } from '../src/core/api/server.ts';
import { processMatchDetails } from '../src/core/games/valorant.ts';
import { GameAssets } from '../src/core/games/assets.ts';
import { OggOpusWriter, opusSamples, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
import { Retention } from '../src/core/retention.ts';
import { makeValDetails, SELF } from './fixtures/make-val-details.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-test-'));
test('Ogg Opus writer: ffmpeg 가 읽을 수 있고 길이가 맞다', () => {
const dir = tmp();
const src = path.join(dir, 'src.ogg');
// 2초 톤을 Opus 로 만든 뒤 패킷을 꺼내 다시 쓴다
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-ac', '2', '-ar', '48000', '-c:a', 'libopus', '-frame_duration', '20', src]);
const packets = readOggPackets(fs.readFileSync(src)).slice(2); // OpusHead, OpusTags 제외
const out = path.join(dir, 'out.ogg');
const w = new OggOpusWriter(out);
for (const p of packets) w.write(p);
for (let i = 0; i < 25; i++) w.write(SILENCE_FRAME); // 0.5초 무음 채우기
w.close();
assert.equal(opusSamples(SILENCE_FRAME), 960);
const dur = Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', out]).toString());
assert.ok(Math.abs(dur - 2.5) < 0.05, `duration ${dur}`);
// 끝까지 디코드되는지
execFileSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'null', '-']);
});
function readOggPackets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
let pos = 0;
let cur: Buffer[] = [];
while (pos < buf.length) {
const nseg = buf[pos + 26];
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
let p = pos + 27 + nseg;
for (const l of lacing) {
cur.push(buf.subarray(p, p + l));
p += l;
if (l < 255) {
out.push(Buffer.concat(cur));
cur = [];
}
}
pos = p;
}
return out;
}
test('단어 diff: 고친 단어 쌍 추출', () => {
assert.deepEqual(diffWords('레이저 궁 빠졌어 비 싸이트 로태 하자', '레이즈 궁 빠졌어 B 사이트 로테 하자'), [
['레이저', '레이즈'],
['비 싸이트', 'B 사이트'],
['로태', '로테'],
]);
assert.deepEqual(diffWords('같은 문장', '같은 문장'), []);
});
test('단어 시각 재배치', () => {
const old = [
{ w: '레이저', s: 0.1, e: 0.5 },
{ w: '궁', s: 0.6, e: 0.8 },
];
assert.deepEqual(realignWords(old, '레이즈 궁', 1).map((w) => [w.w, w.s]), [
['레이즈', 0.1],
['궁', 0.6],
]);
const re = realignWords(old, '레이즈 궁 빠졌어', 1);
assert.equal(re.length, 3);
assert.equal(re[0].s, 0.1);
assert.ok(Math.abs(re[2].e - 0.8) < 0.02);
});
test('사전: 기본 사전 적재, 상황별 핫워드, 사이트 교정 학습', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const dict = new Dictionary(store, path.join(import.meta.dirname, '..', 'resources'), () => ({ valorant: true, lol: true, daily: true }));
dict.seed();
const hv = dict.hotwords('valorant').split(' ');
assert.ok(hv.length > 20 && hv.length <= 60);
assert.ok(hv.includes('레이즈') || hv.includes('제트'), hv.slice(0, 10).join(','));
assert.ok(dict.corrections().some((c) => c.from === '레이저' && c.to === '레이즈'));
assert.equal(dict.learn('나 오퍼래잇 삼', '나 오퍼레이터 삼'), 1);
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇' && c.to === '오퍼레이터'));
assert.ok(dict.hotwords('valorant').split(' ')[0] === '오퍼레이터', '사이트 교정 단어가 가장 먼저');
// 다시 seed 해도 사이트 교정은 남는다
dict.seed();
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇'));
store.close();
});
test('발로란트 경기 상세 → 라운드·킬·시간 표시', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const assets = new GameAssets(path.join(dir, 'cache'));
const S = Date.UTC(2026, 9, 15, 12, 0, 0);
const res = processMatchDetails(makeValDetails(S), SELF, assets, 'val-m-0001', S + 3000);
assert.equal(res.clockOffset, 0);
assert.equal(res.rounds.length, 3);
// R1 전투 시작 = 60000-25000 = 35000
assert.equal(res.rounds[0].combat_at, S + 35000);
assert.equal(res.rounds[0].started_at, S + 5000);
// R3 전투 시작 = 330000-20000 = 310000, R2 는 보간
assert.equal(res.rounds[2].combat_at, S + 310000);
assert.ok(res.rounds[1].combat_at > res.rounds[0].combat_at && res.rounds[1].combat_at < res.rounds[2].combat_at);
assert.deepEqual(res.result, { win: true, score: { ally: 2, enemy: 1 } });
const kills = res.events.filter((e) => e.type === 'kill');
assert.equal(kills.length, 4);
assert.ok(res.events.some((e) => e.type === 'spike' && JSON.parse(e.data).action === 'defuse'));
store.upsertMatch({ id: 'val-m-0001', game: 'valorant', started_at: S, ended_at: S + 420000, status: 'complete' });
store.replaceRounds('val-m-0001', res.rounds);
const ctx = { match: store.getMatch('val-m-0001')!, rounds: store.rounds('val-m-0001') };
// R1 전투 42초 후
assert.deepEqual(timeLabel(S + 35000 + 42000, ctx).primary, 'R1 · 0:42');
assert.equal(timeLabel(S + 35000 + 42000, ctx).secondary, '1:17');
// 구매 단계
assert.equal(timeLabel(S + 10000, ctx).primary, 'R1 · 구매');
// 경기 밖: 현실 시각
assert.match(timeLabel(S + 3600000, ctx).primary, /^\d\d:\d\d:\d\d$/);
store.close();
});
test('타임라인 조회: 필터·검색·커서', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
store.upsertUser({ id: 'u1', name: '승한', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
const t0 = Date.UTC(2026, 9, 15, 12, 0, 0);
const texts = ['스모크 깔게 미드로 와', '레이즈 궁 빠졌어', '오퍼 사줘', '배고프다 치킨 먹자', 'B 사이트 로테 하자'];
texts.forEach((t, i) => {
store.insertUtterance({ id: `x${i}`, session_id: null, user_id: i % 2 ? 'u2' : 'u1', started_at: t0 + i * 1000, ended_at: t0 + i * 1000 + 800, audio_path: null, match_id: null });
store.updateUtteranceResult(`x${i}`, { text: t, raw_text: t, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 2, model: 'tiny', status: 'realtime' });
});
store.insertUtterance({ id: 'n1', session_id: null, user_id: 'u1', started_at: t0 + 9000, ended_at: t0 + 9500, audio_path: null, match_id: null });
store.updateUtteranceResult('n1', { text: null, raw_text: '시청해 주셔서 감사합니다', words: [], noise: true, noise_reason: 'hallucination', confidence: 0.2, lufs: -40, gain_db: 20, model: 'tiny', status: 'realtime' });
let page = tl.query({ limit: 3 });
assert.equal(page.items.length, 3);
assert.equal(page.items[0].id, 'n1');
const page2 = tl.query({ limit: 3, cursor: page.next! });
assert.deepEqual(page2.items.map((i) => i.id), ['x2', 'x1', 'x0']);
assert.equal(tl.query({ hideNoise: true }).items.length, 5);
assert.deepEqual(tl.query({ q: '레이즈 궁' }).items.map((i) => i.id), ['x1']);
assert.deepEqual(tl.query({ q: '오퍼' }).items.map((i) => i.id), ['x2']);
assert.equal(tl.query({ users: ['u2'] }).items.length, 2);
page = tl.query({ order: 'asc', limit: 2 });
assert.deepEqual(page.items.map((i) => i.id), ['x0', 'x1']);
// 교정하면 검색 색인도 바뀐다
store.correctUtterance('x3', '배고프다 피자 먹자', []);
assert.deepEqual(tl.query({ q: '피자' }).items.map((i) => i.id), ['x3']);
assert.equal(tl.query({ q: '치킨' }).items.length, 0);
store.close();
});
test('7일 지난 음성만 삭제, 텍스트는 남음', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const audio = path.join(dir, 'audio', '2026-10-01');
fs.mkdirSync(audio, { recursive: true });
const now = Date.now();
for (const [id, age] of [
['old', 8],
['new', 2],
] as const) {
const f = path.join(audio, `${id}.ogg`);
fs.writeFileSync(f, 'x'.repeat(100));
store.insertUtterance({ id, session_id: null, user_id: 'u', started_at: now - age * 86400000, ended_at: now - age * 86400000 + 500, audio_path: f, match_id: null });
store.updateUtteranceResult(id, { text: id, raw_text: id, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -18, gain_db: 0, model: 'm', status: 'precise' });
}
const r = new Retention(store, () => 7, () => path.join(dir, 'audio')).run(now);
assert.equal(r.deleted, 1);
assert.ok(!fs.existsSync(path.join(audio, 'old.ogg')));
assert.ok(fs.existsSync(path.join(audio, 'new.ogg')));
assert.equal(store.getUtterance('old')!.text, 'old');
assert.equal(store.getUtterance('old')!.audio_deleted, 1);
store.close();
});

84
app/test/e2e-stt.test.ts Normal file
View File

@@ -0,0 +1,84 @@
// 실제 STT 워커(CPU, tiny)와 코어를 붙여 "발화 저장 → 대기열 → STT → DB → 실시간 이벤트 → API" 를 확인한다.
// 워커 venv(worker/.venv)와 HF 캐시의 tiny 모델이 있어야 한다. 없으면 건너뛴다.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const root = path.resolve(import.meta.dirname, '..', '..');
const py = path.join(root, 'worker', '.venv', 'bin', 'python');
const hfTiny = path.join(os.homedir(), '.cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots');
const skip = !fs.existsSync(py) || !fs.existsSync(hfTiny);
test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API', { skip, timeout: 180000 }, async () => {
const { startCore } = await import('../src/core/index.ts');
const dataDir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-e2e-'));
const models = path.join(dataDir, 'models');
fs.mkdirSync(models, { recursive: true });
fs.symlinkSync(path.join(hfTiny, fs.readdirSync(hfTiny)[0]), path.join(models, 'tiny'));
fs.writeFileSync(
path.join(dataDir, 'settings.json'),
JSON.stringify({ stt: { realtimeModel: 'tiny', preciseModel: 'tiny', device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }),
);
const core = await startCore({
dataDir,
resourcesDir: path.join(root, 'app', 'resources'),
worker: { cmd: py, args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') },
version: 'test',
});
const live: any[] = [];
core.bus.on('live', (e) => live.push(e));
try {
const wait = async (fn: () => boolean, ms: number, label: string) => {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error(`timeout ${label}: ${JSON.stringify(core.stt.status)}`);
await new Promise((r) => setTimeout(r, 100));
}
};
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 60000, 'model load');
core.store.upsertUser({ id: 'u1', name: '승한', avatar: null });
const fx = path.join(root, 'worker', 'tests', 'fixtures');
const items: [string, string][] = [
['speech', 'speech_ko.ogg'],
['quiet', 'speech_ko_quiet.ogg'],
['keys', 'keyboard_clicks.ogg'],
];
const t0 = Date.now();
for (const [id, f] of items) {
const dst = path.join(core.paths().audio, 'test', `${id}.ogg`);
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.copyFileSync(path.join(fx, f), dst);
core.store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: t0, ended_at: t0 + 3000, audio_path: dst, match_id: null });
core.stt.enqueue(id, 'realtime');
}
await wait(() => items.every(([id]) => core.store.getUtterance(id)!.status !== 'pending'), 120000, 'transcribe');
const sp = core.store.getUtterance('speech')!;
console.log('speech →', sp.text, '| raw:', sp.raw_text, '| gain', sp.gain_db);
assert.ok(['realtime', 'precise'].includes(sp.status), sp.status);
assert.ok(sp.text && sp.text.includes('레이즈'), sp.text ?? '');
assert.ok(JSON.parse(sp.words).length >= 3);
const q = core.store.getUtterance('quiet')!;
assert.ok(q.gain_db > 15, `quiet gain ${q.gain_db}`);
const k = core.store.getUtterance('keys')!;
assert.equal(k.noise, 1);
assert.ok(live.filter((e) => e.type === 'utterance.updated').length >= 3);
// 기록 API (사이트가 중계로 부르는 것과 같은 경로)
const res = await core.api.inject({ method: 'GET', url: '/api/timeline?limit=10' });
const page = res.json();
assert.equal(page.items.length, 3);
const audio = await core.api.inject({ method: 'GET', url: '/api/audio/speech', headers: { range: 'bytes=0-99' } });
assert.equal(audio.statusCode, 206);
assert.equal(audio.rawPayload.length, 100);
// 사이트 교정 → 사전·학습 데이터
const patched = await core.api.inject({ method: 'PATCH', url: '/api/utterances/speech', payload: { text: '레이즈 궁 빠졌어 B 사이트 로테 하자' } });
assert.equal(patched.json().corrected, true);
assert.equal(core.store.trainingSamples().length, 1);
assert.ok(fs.existsSync(core.store.trainingSamples()[0].audio_path));
const search = (await core.api.inject({ method: 'GET', url: '/api/timeline?q=' + encodeURIComponent('B 사이트') })).json();
assert.deepEqual(search.items.map((i: any) => i.id), ['speech']);
} finally {
await core.stop();
}
});

58
app/test/fixtures/make-val-details.ts vendored Normal file
View File

@@ -0,0 +1,58 @@
// 발로란트 match-details 형태의 합성 데이터 (pd.<shard>.a.pvp.net/match-details/v1/matches/{id} 응답 구조)
export const SELF = 'self-puuid-0001';
export const ASCENT = '/Game/Maps/Ascent/Ascent';
const JETT = 'add6443a-41bd-e414-f6ad-e58d267f4e95';
const SAGE = '569fdd95-4d10-43ab-ca70-79becc718b46';
const REYNA = 'a3bfb853-43b2-7238-a4f1-ad90e9e46bcc';
const VANDAL = '9c82e19d-4575-0200-1a81-3eacf00cf872';
export function makeValDetails(gameStart: number) {
const players = [
{ subject: SELF, gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: JETT, competitiveTier: 15, stats: { score: 4200, roundsPlayed: 3, kills: 3, deaths: 1, assists: 1 } },
{ subject: 'ally-2', gameName: '민수', tagLine: 'KR1', teamId: 'Blue', characterId: SAGE, competitiveTier: 14, stats: { score: 1800, roundsPlayed: 3, kills: 1, deaths: 2, assists: 3 } },
{ subject: 'enemy-1', gameName: '상대1', tagLine: '0000', teamId: 'Red', characterId: REYNA, competitiveTier: 15, stats: { score: 3000, roundsPlayed: 3, kills: 2, deaths: 3, assists: 0 } },
];
const kill = (gameTime: number, roundTime: number, killer: string, victim: string) => ({
gameTime,
roundTime,
killer,
victim,
victimLocation: { x: 6500, y: -7000 },
assistants: [],
playerLocations: [],
finishingDamage: { damageType: 'Weapon', damageItem: VANDAL.toUpperCase(), isSecondaryFireMode: false },
});
const roundResults = [
{
roundNum: 0,
roundResult: 'Eliminated',
winningTeam: 'Blue',
playerStats: [
{ subject: SELF, kills: [kill(60000, 25000, SELF, 'enemy-1')], economy: { spent: 800, remaining: 0, weapon: '', loadoutValue: 800 } },
{ subject: 'enemy-1', kills: [kill(70000, 35000, 'enemy-1', 'ally-2')] },
],
},
// 킬 없는 라운드 (시간 초과) → 보간
{ roundNum: 1, roundResult: 'Round timer expired', winningTeam: 'Red', playerStats: [] },
{
roundNum: 2,
roundResult: 'Bomb defused',
winningTeam: 'Blue',
plantRoundTime: 40000,
defuseRoundTime: 80000,
bombPlanter: 'enemy-1',
bombDefuser: SELF,
plantSite: 'B',
playerStats: [{ subject: SELF, kills: [kill(330000, 20000, SELF, 'enemy-1'), kill(331000, 21000, SELF, 'enemy-1')] }],
},
];
return {
matchInfo: { matchId: 'm-0001', mapId: ASCENT, gameStartMillis: gameStart, gameLengthMillis: 420000, queueID: 'competitive', gameMode: '/Game/GameModes/Bomb/BombGameMode.BombGameMode_C', isCompleted: true },
players,
teams: [
{ teamId: 'Blue', won: true, roundsWon: 2 },
{ teamId: 'Red', won: false, roundsWon: 1 },
],
roundResults,
};
}

123
app/test/games.test.ts Normal file
View File

@@ -0,0 +1,123 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { startMockRiot, lolLiveData } from './mock/riot.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-games-'));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function until(fn: () => boolean, ms = 8000, label = 'condition') {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
await sleep(50);
}
}
test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅→라운드→종료→상세', async () => {
const dir = tmp();
const mock = await startMockRiot(path.join(dir, 'mock'));
process.env.GVR_RIOT_LOCKFILE = mock.lockfile;
process.env.GVR_LCU_LOCKFILE = mock.lockfile;
process.env.GVR_VAL_GLZ = mock.base;
process.env.GVR_VAL_PD = mock.base;
process.env.GVR_LOL_LIVE_URL = mock.base;
process.env.GVR_POLL_MS = '150';
process.env.GVR_DETAIL_RETRY_MS = '100';
const { Store } = await import('../src/core/db/db.ts');
const { Timeline } = await import('../src/core/timeline.ts');
const { GameAssets } = await import('../src/core/games/assets.ts');
const { GameManager } = await import('../src/core/games/manager.ts');
const { Bus } = await import('../src/core/util/events.ts');
const { defaultSettings } = await import('../src/core/settings.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
const live: any[] = [];
bus.on('live', (e) => live.push(e));
const tl = new Timeline(store);
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
const sttCalls: string[] = [];
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
const assets = new GameAssets(path.join(dir, 'cache'));
(assets as any).refresh = async () => undefined; // 네트워크 없이
assets.lol = {
at: Date.now(),
version: '16.20.1',
champions: { ahri: { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' }, 'key:103': { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' } },
items: {},
};
const s = defaultSettings();
store.upsertUser({ id: 'owner', name: '승한', avatar: null });
const gm = new GameManager(store, assets, worker, stt, tl, bus, () => s, () => 'owner');
gm.start();
try {
// ---- 발로란트
await until(() => gm.status().valorant.connected, 5000, 'val connected');
mock.st.valStart = Date.now() - 2000;
mock.st.valState = 'INGAME';
await until(() => !!store.getMatch('val-m-0001'), 5000, 'val match start');
assert.equal(store.getMatch('val-m-0001')!.status, 'live');
mock.st.valMessages.push({ mid: 'c1', cid: 'm-0001-blue@ares-coregame.kr1.pvp.net', body: '스모크 깔게', game_name: '민수', puuid: 'ally-2', time: String(Date.now()) });
mock.st.valMessages.push({ mid: 'c2', cid: 'm-0001-all@ares-coregame.kr1.pvp.net', body: 'gg', game_name: '상대1', puuid: 'enemy-1', time: String(Date.now()) });
await until(() => store.events('val-m-0001').filter((e) => e.type === 'chat').length === 2, 5000, 'chat');
mock.st.ally = 1;
await until(() => store.events('val-m-0001').some((e) => e.type === 'round_end'), 5000, 'live round');
// 발화 하나 (경기 중)
store.insertUtterance({ id: 'u-val', session_id: null, user_id: 'owner', started_at: Date.now(), ended_at: Date.now() + 500, audio_path: null, match_id: gm.liveMatchAt(Date.now()) });
assert.equal(store.getUtterance('u-val')!.match_id, 'val-m-0001');
mock.st.valState = 'MENUS';
await until(() => store.getMatch('val-m-0001')!.status === 'complete', 8000, 'val details');
const ev = store.events('val-m-0001');
assert.equal(ev.filter((e) => e.type === 'kill').length, 4);
assert.equal(ev.filter((e) => e.type === 'chat').length, 2, '채팅은 상세 적용 뒤에도 남는다');
assert.ok(!ev.some((e) => e.id.includes('live-round')), '실시간 라운드는 상세로 교체');
assert.equal(store.rounds('val-m-0001').length, 3);
assert.ok(sttCalls.includes('start') && sttCalls.includes('end'));
assert.ok(store.listAccounts().some((a) => a.user_id === 'owner' && a.puuid === 'self-puuid-0001'), '주인 계정 자동 연결');
const sum = gm.summary(store.getMatch('val-m-0001')!);
assert.deepEqual(sum.score, { ally: 2, enemy: 1 });
assert.equal(sum.win, true);
// ---- 롤
mock.st.lolPhase = 'ChampSelect';
await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat');
mock.st.lolPhase = 'InProgress';
mock.st.lolLive = lolLiveData(120, [
{ EventID: 0, EventName: 'GameStart', EventTime: 0.05 },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '승한', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 2, EventName: 'DragonKill', EventTime: 90.0, KillerName: '민수', DragonType: 'Fire', Stolen: 'False' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '승한', TurretKilled: 'Turret_T2_R_03_A' },
]);
await until(() => !!store.getMatch('lol-7001'), 5000, 'lol start');
await until(() => store.events('lol-7001').length >= 4, 5000, 'lol events');
const lev = store.events('lol-7001');
const chat = lev.find((e) => e.type === 'chat')!;
assert.equal(JSON.parse(chat.data).text, '정글 갱 갈게요');
assert.equal(JSON.parse(chat.data).source, 'lcu');
const drag = JSON.parse(lev.find((e) => e.type === 'object' && e.data.includes('dragon'))!.data);
assert.equal(drag.label, '화염의 용');
assert.equal(drag.ally, true);
const tower = JSON.parse(lev.find((e) => e.data.includes('"tower"'))!.data);
assert.equal(tower.team, 'ORDER');
// 게임 시간 표시
const k = lev.find((e) => e.type === 'kill')!;
assert.equal(tl.eventItem(k).time.primary, '1:15');
mock.st.lolLive = null;
mock.st.lolPhase = 'EndOfGame';
mock.st.lolHistoryReady = true;
await until(() => store.getMatch('lol-7001')!.status === 'complete', 8000, 'lol history');
const det = JSON.parse(store.getMatch('lol-7001')!.detail!);
assert.equal(det.goldDiff.length, 2);
assert.equal(det.goldDiff[1].diff, 1700);
assert.equal(det.players[0].character.id, 'Ahri');
const kill = store.events('lol-7001').find((e) => e.type === 'kill')!;
assert.deepEqual(JSON.parse(kill.data).location, { x: 7000, y: 7200 });
} finally {
gm.stop();
await mock.close();
store.close();
}
});

162
app/test/mock/riot.ts Normal file
View File

@@ -0,0 +1,162 @@
// 가짜 Riot 서버 (발로란트 로컬 API · glz · pd, 롤 게임 클라이언트 API · LCU). 응답 구조는 실제 API 와 같게 맞췄다.
// 테스트와 M0 시연용. 실제 게임 PC 검증은 진단 화면(M0)으로 한다.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import { makeValDetails, SELF, ASCENT } from '../fixtures/make-val-details.ts';
export interface MockState {
valState: 'MENUS' | 'PREGAME' | 'INGAME';
ally: number;
enemy: number;
valMessages: any[];
valMatchId: string;
valStart: number;
lolLive: any | null;
lolPhase: string;
lolGameId: number;
lolHistoryReady: boolean;
lolStart: number;
}
export async function startMockRiot(dir: string) {
fs.mkdirSync(dir, { recursive: true });
const key = path.join(dir, 'key.pem');
const cert = path.join(dir, 'cert.pem');
if (!fs.existsSync(cert))
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', key, '-out', cert, '-days', '2', '-subj', '/CN=127.0.0.1'], { stdio: 'ignore' });
const st: MockState = {
valState: 'MENUS',
ally: 0,
enemy: 0,
valMessages: [],
valMatchId: 'm-0001',
valStart: 0,
lolLive: null,
lolPhase: 'None',
lolGameId: 7001,
lolHistoryReady: false,
lolStart: 0,
};
const password = 'pw-test';
const presence = () => {
const priv = {
isValid: true,
sessionLoopState: st.valState,
matchMap: ASCENT,
partyOwnerMatchScoreAllyTeam: st.ally,
partyOwnerMatchScoreEnemyTeam: st.enemy,
provisioningFlow: 'Matchmaking',
queueId: 'competitive',
};
return Buffer.from(JSON.stringify(priv)).toString('base64');
};
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
// ---- Riot Client local
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
[
/^\/product-session\/v1\/external-sessions$/,
() => [200, { 'host_app': { productId: 'valorant', version: 'release-11.08-shipping-1-3765', launchConfiguration: { arguments: ['-ares-deployment=kr', '-config-endpoint=https://shared.kr.a.pvp.net'] } } }],
],
[/^\/chat\/v4\/presences$/, () => [200, { presences: [{ puuid: SELF, product: 'valorant', private: presence() }] }]],
[/^\/chat\/v6\/messages$/, () => [200, { messages: st.valMessages }]],
// ---- glz
[/^\/core-game\/v1\/players\/(.+)$/, () => (st.valState === 'INGAME' ? [200, { Subject: SELF, MatchID: st.valMatchId }] : [404, { errorCode: 'RESOURCE_NOT_FOUND' }])],
[
/^\/core-game\/v1\/matches\/(.+)$/,
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
],
// ---- pd
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU
[/^\/lol-gameflow\/v1\/gameflow-phase$/, () => [200, st.lolPhase]],
[/^\/lol-gameflow\/v1\/session$/, () => [200, { phase: st.lolPhase, gameData: { gameId: st.lolGameId, queue: { description: '솔로 랭크', id: 420 } } }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' }]],
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
];
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
const url = new URL(req.url || '/', 'https://x');
for (const [re, fn] of routes) {
const m = url.pathname.match(re);
if (!m) continue;
const [code, body] = fn(m, String(req.headers.authorization || ''));
res.writeHead(code, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
return;
}
res.writeHead(404);
res.end('{}');
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const port = (server.address() as any).port as number;
const lockfile = path.join(dir, 'lockfile');
fs.writeFileSync(lockfile, `Riot Client:1234:${port}:${password}:https`);
return { st, port, lockfile, base: `https://127.0.0.1:${port}`, close: () => new Promise<void>((r) => server.close(() => r())) };
}
export function lolLiveData(gameTime: number, events: any[]) {
const player = (name: string, raw: string, ko: string, team: string, k: number) => ({
riotId: `${name}#KR1`,
riotIdGameName: name,
riotIdTagLine: 'KR1',
summonerName: name,
rawChampionName: `game_character_displayname_${raw}`,
championName: ko,
team,
level: 9,
scores: { kills: k, deaths: 1, assists: 2, creepScore: 80 },
items: [{ itemID: 3031, displayName: '무한의 대검', count: 1 }],
});
return {
activePlayer: { riotId: '승한#KR1', summonerName: '승한', currentGold: 500 },
allPlayers: [player('승한', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
events: { Events: events },
gameData: { gameMode: 'CLASSIC', gameTime, mapName: 'Map11', mapNumber: 11 },
};
}
function lolHistory() {
return {
gameId: 7001,
gameDuration: 1500,
queueId: 420,
participants: [
{ participantId: 1, championId: 103, teamId: 100, stats: { kills: 5, deaths: 2, assists: 7, totalMinionsKilled: 180, neutralMinionsKilled: 10, goldEarned: 11000, item0: 3031, win: true, champLevel: 16 } },
{ participantId: 2, championId: 64, teamId: 100, stats: { kills: 3, deaths: 4, assists: 9, totalMinionsKilled: 30, neutralMinionsKilled: 140, goldEarned: 9000, win: true } },
{ participantId: 6, championId: 86, teamId: 200, stats: { kills: 4, deaths: 6, assists: 2, totalMinionsKilled: 170, neutralMinionsKilled: 0, goldEarned: 8500, win: false } },
],
participantIdentities: [
{ participantId: 1, player: { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' } },
{ participantId: 2, player: { puuid: 'lol-2', gameName: '민수', tagLine: 'KR1' } },
{ participantId: 6, player: { puuid: 'lol-6', gameName: '적1', tagLine: 'KR9' } },
],
teams: [
{ teamId: 100, win: 'Win' },
{ teamId: 200, win: 'Fail' },
],
};
}
function lolTimeline() {
return {
frames: [
{ timestamp: 0, participantFrames: { '1': { totalGold: 500 }, '2': { totalGold: 500 }, '6': { totalGold: 500 } }, events: [] },
{
timestamp: 60000,
participantFrames: { '1': { totalGold: 1500 }, '2': { totalGold: 1200 }, '6': { totalGold: 1000 } },
events: [
{ type: 'CHAMPION_KILL', timestamp: 75000, killerId: 1, victimId: 6, assistingParticipantIds: [2], position: { x: 7000, y: 7200 } },
{ type: 'ELITE_MONSTER_KILL', timestamp: 90000, killerId: 2, monsterType: 'DRAGON', monsterSubType: 'FIRE_DRAGON', position: { x: 9866, y: 4414 } },
{ type: 'BUILDING_KILL', timestamp: 95000, killerId: 1, teamId: 200, buildingType: 'TOWER_BUILDING', position: { x: 8955, y: 8510 } },
],
},
],
};
}