/** * Replays (docs/09 §8): every game played to the end through a real Room (random legal actions, timeouts, * streamed strokes, leaves) is rebuilt from the seed + room_log, and each player's replay shows exactly the * views that player was sent while playing. */ import { describe, expect, test } from 'bun:test'; import { SeededRng, type AnyGameDefinition } from '@bg/engine'; import { applyViewPatch, type ReplayData, type ServerMessage } from '@bg/shared'; import { GAMES } from '@bg/games'; import { openDb } from '../db'; import { Room, type Conn, type RoomConfig } from './room'; import { RoomStore } from './store'; import { Replays, rebuildGame, sameOutcome, type ReplayInput } from './replay'; const json = (v: unknown) => JSON.parse(JSON.stringify(v)); function playerCount(def: AnyGameDefinition): number { const r = def.playersFor ? def.playersFor(def.defaultOptions) : { min: def.minPlayers, max: def.maxPlayers }; const lo = Math.max(r.min, 2); for (const n of [lo + 1, lo, lo + 2, r.min]) { if (n >= r.min && n <= r.max && !def.playerCountError?.(def.defaultOptions, n)) return n; } throw new Error(`${def.id}: no player count`); } /** Plays one game of `gameId` through a Room with a fake clock. Returns everything the assertions need. */ function playThrough(gameId: string, seed: number) { const def = GAMES[gameId]!; const db = openDb(':memory:'); const store = new RoomStore(db); let now = 1_700_000_000_000; const clock = { now: () => now }; const players = Array.from({ length: playerCount(def) }, (_, i) => `P${i + 1}`); const users = { publicUser: (id: string) => ({ id, nickname: `닉${id}`, avatar: null, kind: 'guest' as const }) }; const config: RoomConfig = { gameId, options: def.defaultOptions, maxPlayers: players.length, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60, }; const room = new Room('room1', '482913', config, players[0]!, { store, games: GAMES, users, now: clock.now }); store.insertRoom({ id: 'room1', code: '482913', hostId: players[0]!, gameId, status: 'lobby', visibility: 'private', config, stateJson: '{}', now }); const conns: Record = {}; for (const p of players) { const msgs: ServerMessage[] = []; conns[p] = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} }; room.join(conns[p]!, 'player'); } const startIdx = Object.fromEntries(players.map((p) => [p, conns[p]!.msgs.length])); expect(room.start(players[0]!)).toBeNull(); room.clearTimer(); const rng = new SeededRng([seed, seed * 7 + 1, 0x9e3779b9, seed ^ 0x55]); let cs = 0; const left = new Set(); const counts = { act: 0, timeout: 0, leave: 0 }; const fireTimer = (at: number) => { now = Math.max(now, at); room.onTimer(); room.clearTimer(); counts.timeout++; }; const finished = () => !room.game || room.game.finished; for (let step = 0; step < 4000 && !finished(); step++) { const deadline = room.effectiveDeadline(); const dt = 50 + rng.int(1500); // A due deadline fires before anyone's next move, as the real timer would; sometimes jump to it on purpose. if (deadline !== null && (now + dt >= deadline || rng.next() < 0.03)) { fireTimer(deadline); continue; } now += dt; const state = room.game!.state; const actives = def.activePlayers(state).filter((p: string) => !left.has(p)); if (actives.length === 0) continue; const actor = actives[rng.int(actives.length)]!; const legal = (def.legalActions?.(state, actor) ?? []).filter( (a: unknown) => def.actionSchema.safeParse(a).success && def.validate(state, actor, a, { now }).ok, ); if (legal.length === 0) continue; room.act(actor, ++cs, legal[rng.int(legal.length)]); room.clearTimer(); counts.act++; } // Rare long games: players leave one by one (onLeave auto actions) until the game ends. for (const p of [...players].reverse()) { if (finished()) break; room.leave(p); room.clearTimer(); left.add(p); counts.leave++; for (let i = 0; i < 50 && !finished() && room.effectiveDeadline() !== null; i++) fireTimer(room.effectiveDeadline()!); } room.flushStream(); expect(finished()).toBe(true); return { def, db, store, room, conns, players, startIdx, users, counts, left }; } /** Decodes frames into full views, as the replay page does. */ function decode(data: ReplayData): unknown[] { const views: unknown[] = []; let v: unknown; for (const f of data.frames) { v = f.view !== undefined ? f.view : applyViewPatch(v, f.patch); views.push(v); } return views; } describe('replay: every game, played through a Room, rebuilds exactly', () => { for (const gameId of Object.keys(GAMES)) { test(gameId, async () => { const seed = 1 + Object.keys(GAMES).indexOf(gameId); const { def, db, store, room, conns, players, startIdx, users, counts, left } = playThrough(gameId, seed); const g = room.game!; const row = db.query<{ seed: string; result_json: string; started_at: number; options_json: string }, [string]>('SELECT * FROM games WHERE id = ?').get(g.gamePk)!; expect(row.result_json).toBe(JSON.stringify(room.lastResult)); // The rebuilt state equals the live one, field for field. const log = store.log('room1').filter((e) => e.gameNo === room.gameNo); const start = log.find((e) => e.kind === 'start')!; expect(start.at).toBe(row.started_at); const input: ReplayInput = { seedHex: row.seed, options: JSON.parse(row.options_json), players: (start.data as { players: string[] }).players, startedAt: row.started_at, gameNo: room.gameNo, actions: log.filter((e) => e.kind === 'act' || e.kind === 'auto').map((e) => ({ actorId: e.actorId!, kind: e.kind, data: e.data, at: e.at })), }; const final = rebuildGame(def, input); expect(JSON.stringify(def.result(final))).toBe(row.result_json); expect(JSON.stringify(final)).toBe(JSON.stringify(g.state)); const replays = new Replays(db, GAMES, users, () => 1_700_000_000_000); for (const p of players) { const r = await replays.get(g.gamePk, p); if (!r.ok) throw new Error(`${gameId} ${p}: ${r.status} ${r.error}`); const data = JSON.parse(r.body) as ReplayData; expect(data.me).toBe(p); expect(data.result).toEqual(json(room.lastResult)); const views = decode(data); const frameCount = 1 + input.actions.filter((a) => !(a.kind === 'act' && def.isStreamAction?.(a.data))).length; expect(views).toHaveLength(frameCount); // Final frame = what a (re)joining player is sent now. const c = conns[p]!; const before = c.msgs.length; room.sendSync(c); const sync = c.msgs.slice(before).find((m) => m.t === 'state') as Extract; expect(views.at(-1)).toEqual(json(sync.view)); // Every frame = the view this player was sent live, in order (games without a separate sync view). if (!def.syncView) { const live = c.msgs .slice(startIdx[p], before) .filter((m): m is Extract => m.t === 'state') .map((m) => json(m.view)); if (left.has(p)) expect(views.slice(0, live.length)).toEqual(live); else expect([...live.slice(0, -1)]).toEqual(views); // the last message repeats the final view (gameOver) } } if (process.env.REPLAY_STATS) { const t0 = performance.now(); const r = await new Replays(db, GAMES, users, () => 1_700_000_000_000).get(g.gamePk, players[0]!); const ms = performance.now() - t0; const body = r.ok ? r.body : ''; const views = decode(JSON.parse(body)); const fullViews = views.reduce((n, v) => n + JSON.stringify(v).length, 0); console.log( JSON.stringify({ gameId, players: players.length, ...counts, log: input.actions.length, frames: views.length, bodyKB: +(body.length / 1024).toFixed(1), gzipKB: +(Bun.gzipSync(body).length / 1024).toFixed(1), fullViewsKB: +(fullViews / 1024).toFixed(1), rebuildMs: +ms.toFixed(1), }), ); } }); } }); describe('replay: access and edge cases', () => { function omokRoom() { const db = openDb(':memory:'); const store = new RoomStore(db); let now = 1_700_000_000_000; const clock = { now: () => now, advance: (ms: number) => (now += ms) }; const users = { publicUser: (id: string) => ({ id, nickname: `닉${id}`, avatar: null, kind: 'guest' as const }) }; const config: RoomConfig = { gameId: 'omok', options: { ...GAMES.omok!.defaultOptions, colorAssignment: 'hostBlack' }, maxPlayers: 2, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60, }; const room = new Room('room1', '482913', config, 'A', { store, games: GAMES, users, now: clock.now }); store.insertRoom({ id: 'room1', code: '482913', hostId: 'A', gameId: 'omok', status: 'lobby', visibility: 'private', config, stateJson: '{}', now }); for (const u of ['A', 'B']) room.join({ userId: u, send: () => {}, close: () => {} }, 'player'); expect(room.start('A')).toBeNull(); room.clearTimer(); return { db, room, clock, users }; } test('leaving mid-game: the onLeave action is the last (auto) frame; only finished games, only players', async () => { const { db, room, clock, users } = omokRoom(); const replays = new Replays(db, GAMES, users); const pk = room.game!.gamePk; expect(room.roomView().lastGamePk).toBeNull(); expect(await replays.get(pk, 'A')).toMatchObject({ ok: false, status: 409 }); clock.advance(1234); room.act('A', 1, { type: 'place', x: 7, y: 7 }); clock.advance(999); room.leave('B'); room.clearTimer(); expect(room.game!.finished).toBe(true); expect(room.roomView().lastGamePk).toBe(pk); const r = await replays.get(pk, 'A'); if (!r.ok) throw new Error(r.error); const data = JSON.parse(r.body) as ReplayData; expect(data.frames.map((f) => [f.actor, f.auto ?? false])).toEqual([ [null, false], ['A', false], ['B', true], ]); expect(data.frames[1]!.at).toBe(1_700_000_001_234); expect(data.players.B!.nickname).toBe('닉B'); // The seed and the raw log stay on the server. const seed = db.query<{ seed: string }, [string]>('SELECT seed FROM games WHERE id = ?').get(pk)!.seed; expect(r.body).not.toContain(seed); expect(await replays.get(pk, 'C')).toMatchObject({ ok: false, status: 403 }); expect(await replays.get('01J0000000000000000000000X', 'A')).toMatchObject({ ok: false, status: 404 }); }); test('guest merged into a member keeps their seat; changed rules or a purged log are not replayable', async () => { const { db, room, users } = omokRoom(); room.act('A', 1, { type: 'place', x: 7, y: 7 }); room.leave('B'); const pk = room.game!.gamePk; db.query("UPDATE game_players SET user_id = 'M' WHERE user_id = 'B'").run(); const merged = await new Replays(db, GAMES, users).get(pk, 'M'); if (!merged.ok) throw new Error(merged.error); expect((JSON.parse(merged.body) as ReplayData).me).toBe('B'); const bumped = { ...GAMES, omok: { ...GAMES.omok!, stateVersion: GAMES.omok!.stateVersion + 1 } }; expect(await new Replays(db, bumped, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 }); // A rules change that alters the outcome is caught by the rebuilt-result check. const changed = { ...GAMES, omok: { ...GAMES.omok!, result: () => null } }; expect(await new Replays(db, changed, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 }); db.query("DELETE FROM room_log WHERE kind = 'start'").run(); expect(await new Replays(db, GAMES, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 }); }); test('practice games (marked "practice") and games recorded before final scores existed are replayable', async () => { const { db, room, users } = omokRoom(); room.act('A', 1, { type: 'place', x: 7, y: 7 }); room.leave('B'); const pk = room.game!.gamePk; const stored = JSON.parse(db.query<{ result_json: string }, [string]>('SELECT result_json FROM games WHERE id = ?').get(pk)!.result_json); // As the store writes a game played with computers. db.query('UPDATE games SET result_json = ? WHERE id = ?').run(JSON.stringify({ ...stored, practice: true }), pk); const practice = await new Replays(db, GAMES, users).get(pk, 'A'); expect(practice.ok).toBe(true); // A scored game recorded without scoreText gets it from the rebuilt game; a changed outcome still fails. const scored = { ...GAMES, omok: { ...GAMES.omok!, result: (st: unknown) => { const r = GAMES.omok!.result(st); return r && { ...r, scoreText: { A: '1점', B: '0점' } }; } } }; const old = await new Replays(db, scored, users).get(pk, 'A'); if (!old.ok) throw new Error(old.error); expect((JSON.parse(old.body) as ReplayData).result.scoreText).toEqual({ A: '1점', B: '0점' }); expect(sameOutcome({ ranking: [['A'], ['B']], summary: 'x', reason: 'normal' }, { ranking: [['B'], ['A']], summary: 'x', reason: 'normal' })).toBe(false); }); test('my games list: newest first, paged, with ranks and nicknames', async () => { const { db, room, clock, users } = omokRoom(); room.act('A', 1, { type: 'place', x: 7, y: 7 }); room.leave('B'); const first = room.game!.gamePk; // Second game: B comes back and wins when A leaves. room.join({ userId: 'B', send: () => {}, close: () => {} }, 'player'); clock.advance(10); expect(room.start('A')).toBeNull(); room.clearTimer(); room.leave('A'); const second = room.game!.gamePk; const replays = new Replays(db, GAMES, users, clock.now); const p1 = replays.listForUser('B', null, 1); expect(p1.games.map((g) => g.gamePk)).toEqual([second]); expect(p1.games[0]).toMatchObject({ gameId: 'omok', myRank: 1, replayable: true }); expect(p1.games[0]!.players).toEqual([ { nickname: '닉B', rank: 1, me: true }, { nickname: '닉A', rank: 2, me: false }, ]); const p2 = replays.listForUser('B', p1.next, 1); expect(p2.games.map((g) => [g.gamePk, g.myRank])).toEqual([[first, 2]]); expect(p2.next).toBeNull(); expect(replays.listForUser('C', null, 20)).toEqual({ games: [], next: null }); // Past the log retention the list no longer offers a replay. const later = new Replays(db, GAMES, users, () => clock.now() + 91 * 24 * 3600_000); expect(later.listForUser('B', null, 5).games.every((g) => !g.replayable)).toBe(true); }); });