Files
game_voice_recorder/app/test/replays.test.ts

213 lines
11 KiB
TypeScript

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 zlib from 'node:zlib';
import WebSocket from 'ws';
import { Store } from '../src/core/db/db.ts';
import { buildApi } from '../src/core/api/server.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { Replays } from '../src/core/replays.ts';
import { RelayClient } from '../src/core/relay/client.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-replay-'));
const ID = '4145f041-7d83-4785-ac4b-b532154f14a4';
const ID2 = '0e1f2a3b-0000-4000-8000-000000000002';
/** 가짜 변환기: 호출 횟수를 세고, 모드 파일에 따라 성공 · 실패 · 느림 */
function fakeTool(dir: string): { tool: string; calls: () => number; mode: (m: 'ok' | 'fail' | 'slow') => void } {
const tool = path.join(dir, 'gvr-replay');
const count = path.join(dir, 'calls');
const modeFile = path.join(dir, 'mode');
fs.writeFileSync(modeFile, 'ok');
fs.writeFileSync(
tool,
`#!/bin/sh
echo x >> "${count}"
mode=$(cat "${modeFile}")
if [ "$mode" = fail ]; then echo '{"ok":false,"error":"InvalidDataException: bad chunk"}'; exit 1; fi
if [ "$mode" = slow ]; then sleep 2; fi
printf '{"format":"gvr-replay","v":1,"matchId":"%s","players":[]}' "$(basename "$1" .vrf)" > "$2"
echo '{"ok":true,"map":"/Game/Maps/Infinity/Infinity","players":10,"rounds":20,"kills":146}'
`,
{ mode: 0o755 },
);
return { tool, calls: () => (fs.existsSync(count) ? fs.readFileSync(count, 'utf8').split('\n').filter(Boolean).length : 0), mode: (m) => fs.writeFileSync(modeFile, m) };
}
function setup(waitMs = 15000) {
const dir = tmp();
const saved = path.join(dir, 'VALORANT', 'Saved');
const demos = path.join(saved, 'Demos');
fs.mkdirSync(demos, { recursive: true });
const t = fakeTool(dir);
const replays = new Replays({ dirs: () => [saved], tool: t.tool, cacheDir: () => path.join(dir, 'GVR-Data', 'replays'), version: '1.5.0', waitMs });
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertMatch({ id: `val-${ID}`, game: 'valorant', started_at: Date.now() - 3600000 });
store.upsertMatch({ id: `val-${ID2}`, game: 'valorant', started_at: Date.now() - 7200000 });
store.upsertMatch({ id: 'lol-KR_1', game: 'lol', started_at: Date.now() - 7200000 });
return { dir, saved, demos, replays, store, ...t };
}
const api = (s: ReturnType<typeof setup>) =>
buildApi({
store: s.store,
timeline: new Timeline(s.store),
games: {} as any,
dict: {} as any,
culprit: {} as any,
bus: new Bus(),
settings: () => ({}) as any,
trainingDir: () => path.join(s.dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
replays: s.replays,
});
test('리플레이 찾기: Saved 아래 <경기 ID>.vrf (하위 폴더 포함), 로그 폴더 · 이름이 다른 파일은 무시', () => {
const s = setup();
fs.writeFileSync(path.join(s.demos, `${ID.toUpperCase()}.vrf`), 'a');
fs.mkdirSync(path.join(s.demos, 'old'), { recursive: true });
fs.writeFileSync(path.join(s.demos, 'old', `${ID2}.vrf`), 'b');
fs.writeFileSync(path.join(s.demos, 'notes.vrf'), 'c');
fs.mkdirSync(path.join(s.saved, 'Logs'), { recursive: true });
fs.writeFileSync(path.join(s.saved, 'Logs', '11111111-1111-4111-8111-111111111111.vrf'), 'd');
const ids = s.replays.list().map((r) => r.matchId);
assert.deepEqual(ids.sort(), [ID, ID2].sort());
assert.equal(s.replays.find(ID.toUpperCase())?.matchId, ID);
});
test('3D 리플레이 API: 처음 열면 변환해서 gzip JSON, 다음부터는 보관본 (변환 한 번)', async () => {
const s = setup();
const app = await api(s);
const miss = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(miss.statusCode, 404);
assert.equal(miss.json().error, 'replay_not_found');
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r.statusCode, 200);
assert.equal(r.headers['content-encoding'], 'gzip');
assert.match(String(r.headers['content-type']), /application\/json/);
const body = JSON.parse(zlib.gunzipSync(r.rawPayload).toString('utf8'));
assert.equal(body.format, 'gvr-replay');
assert.equal(body.matchId, ID);
const again = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(again.statusCode, 200);
assert.equal(s.calls(), 1, '두 번째는 변환하지 않는다');
// 목록: 경기 기록과 변환 여부
const list = (await app.inject({ url: '/api/replays' })).json();
assert.deepEqual(list.map((x: any) => [x.matchId, x.match, x.converted]), [[ID, `val-${ID}`, true]]);
// 롤 경기 · 없는 경기
assert.equal((await app.inject({ url: '/api/matches/lol-KR_1/replay' })).json().error, 'replay_not_found');
assert.equal((await app.inject({ url: '/api/matches/val-nope/replay' })).statusCode, 404);
});
test('변환 실패는 422 로 이유를 알리고, 같은 파일은 다시 변환하지 않는다 (파일이 바뀌면 다시)', async () => {
const s = setup();
const app = await api(s);
const vrf = path.join(s.demos, `${ID}.vrf`);
fs.writeFileSync(vrf, 'broken');
s.mode('fail');
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r.statusCode, 422);
assert.equal(r.json().error, 'replay_failed');
assert.match(r.json().message, /bad chunk/);
await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(s.calls(), 1);
// 다시 내려받음 (크기 · 시각이 바뀜) → 다시 변환
s.mode('ok');
fs.writeFileSync(vrf, 'fixed replay');
fs.utimesSync(vrf, new Date(), new Date(Date.now() + 5000));
const ok = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(ok.statusCode, 200);
assert.equal(s.calls(), 2);
});
test('변환이 기다리는 시간보다 길면 202 converting, 끝나면 200 (같은 파일을 두 번 변환하지 않음)', async () => {
const s = setup(300);
const app = await api(s);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
s.mode('slow');
const r1 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r1.statusCode, 202);
assert.equal(r1.json().status, 'converting');
const r2 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r2.statusCode, 202);
let last = r2;
for (let i = 0; i < 20 && last.statusCode === 202; i++) {
await new Promise((res) => setTimeout(res, 300));
last = await app.inject({ url: `/api/matches/val-${ID}/replay` });
}
assert.equal(last.statusCode, 200);
assert.equal(s.calls(), 1);
});
test('변환기가 없으면 500 replay_tool_missing', async () => {
const s = setup();
const replays = new Replays({ dirs: () => [s.saved], tool: path.join(s.dir, 'none.exe'), cacheDir: () => path.join(s.dir, 'c'), version: '1' });
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
assert.deepEqual(await replays.get(ID), { state: 'no_tool' });
});
test('중계: gzip 리플레이는 바이너리 조각 + content-encoding 으로 사이트 서버에 간다', async () => {
const s = setup();
const app = await api(s);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
const relay = new RelayClient(app, new Bus(), () => ({ serverUrl: 'https://x', deviceId: null, deviceKey: null, name: 'pc', version: 't', guildId: null }));
const sent: any[] = [];
(relay as any).ws = { readyState: WebSocket.OPEN, bufferedAmount: 0, send: (m: any) => sent.push(m) };
await (relay as any).handle({ t: 'req', id: 'r1', method: 'GET', path: `/api/matches/val-${ID}/replay`, headers: {}, user: { id: 'u', name: 'u', avatar: null }, body: null });
const head = JSON.parse(sent[0]);
assert.equal(head.t, 'res_head');
assert.equal(head.status, 200);
assert.equal(head.headers['content-encoding'], 'gzip');
const chunks = sent.slice(1, -1).map((b: Buffer) => b.subarray(4 + b.readUInt32BE(0)));
assert.equal(JSON.parse(sent.at(-1)).t, 'res_end');
assert.equal(JSON.parse(zlib.gunzipSync(Buffer.concat(chunks)).toString()).matchId, ID);
});
test('실제 변환기 (tools/replay-extract 리눅스 빌드 + 13.08 리플레이가 있을 때만)', { skip: !fs.existsSync(path.join(os.homedir(), 'work/vrf/match.vrf')) || !fs.existsSync(path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay')) }, async () => {
if (!process.env.DOTNET_ROOT && fs.existsSync(path.join(os.homedir(), '.dotnet'))) process.env.DOTNET_ROOT = path.join(os.homedir(), '.dotnet');
const dir = tmp();
const demos = path.join(dir, 'Demos');
fs.mkdirSync(demos);
fs.symlinkSync(path.join(os.homedir(), 'work/vrf/match.vrf'), path.join(demos, `${ID}.vrf`));
const replays = new Replays({ dirs: () => [dir], tool: path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay'), cacheDir: () => path.join(dir, 'c'), version: '1' });
const r = await replays.get(ID, 120000);
assert.equal(r.state, 'ready');
const j = JSON.parse(zlib.gunzipSync(fs.readFileSync((r as any).file)).toString());
assert.equal(j.matchId, ID);
assert.equal(j.players.length, 10);
assert.ok(j.kills.length > 100);
});
test('경기 목록 리플레이 필터: yes = 리플레이 파일이 있는 발로란트 경기, no = 없는 발로란트 경기 (롤 제외) · 요약에 replay', async () => {
const s = setup();
const app = await buildApi({
store: s.store,
timeline: new Timeline(s.store),
games: { modeKeys: () => [], summary: (m: any) => ({ id: m.id, game: m.game }) } as any,
dict: {} as any,
culprit: {} as any,
bus: new Bus(),
settings: () => ({}) as any,
trainingDir: () => path.join(s.dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
replays: s.replays,
});
const get = async (qs: string) => (await app.inject({ url: `/api/matches${qs}` })).json() as { id: string; replay?: boolean }[];
// 리플레이를 하나도 안 받았으면 yes 는 빈 목록, no 는 발로란트 경기 전부
assert.deepEqual(await get('?replay=yes'), []);
assert.deepEqual((await get('?replay=no')).map((m) => m.id), [`val-${ID}`, `val-${ID2}`]);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
(s.replays as any).scanCache = null; // 10초 목록 캐시 무시
const all = await get('');
assert.deepEqual(Object.fromEntries(all.map((m) => [m.id, m.replay])), { [`val-${ID}`]: true, [`val-${ID2}`]: false, 'lol-KR_1': undefined });
assert.deepEqual((await get('?replay=yes')).map((m) => m.id), [`val-${ID}`]);
assert.deepEqual((await get('?replay=no')).map((m) => m.id), [`val-${ID2}`]);
assert.deepEqual(await get('?replay=no&game=lol'), []);
});