/** Room-level tests with a controllable clock: timers, grace period, restore, error isolation. */ import { describe, expect, test } from 'bun:test'; import { z } from 'zod'; import type { AnyGameDefinition } from '@bg/engine'; import type { ServerMessage } from '@bg/shared'; import { GAMES } from '@bg/games'; import { openDb } from '../db'; import { Room, type Conn, type RoomConfig, type RoomSnapshot } from './room'; import { RoomStore } from './store'; function harness(games: Record = GAMES) { const db = openDb(':memory:'); const store = new RoomStore(db); let now = 1_000_000; const clock = { now: () => now, advance: (ms: number) => (now += ms) }; const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now, }; const config: RoomConfig = { gameId: Object.keys(games)[0]!, options: Object.values(games)[0]!.defaultOptions, maxPlayers: 2, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60, }; const room = new Room('room1', '482913', config, 'A', deps); store.insertRoom({ id: 'room1', code: '482913', hostId: 'A', gameId: config.gameId, status: 'lobby', visibility: 'private', config, stateJson: '{}', now: now }); const conn = (userId: string) => { const msgs: ServerMessage[] = []; const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; return c; }; return { room, store, clock, deps, conn, db }; } describe('Room timers', () => { test('8. turn timeout applies onTimeout (omok perMove autoMove)', () => { const { room, clock, conn } = harness(); const a = conn('A'); const b = conn('B'); room.join(a, 'player'); room.join(b, 'player'); room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } }); expect(room.start('A')).toBeNull(); room.clearTimer(); expect(room.effectiveDeadline()).toBe(clock.now() + 10_000); clock.advance(9_999); room.onTimer(); room.clearTimer(); expect((room.game!.state as any).moves).toHaveLength(0); clock.advance(1); room.onTimer(); room.clearTimer(); expect((room.game!.state as any).moves).toHaveLength(1); expect((room.game!.state as any).moves[0].auto).toBe(true); }); test('disconnected player is auto-acted after the grace period, not before the turn deadline rules', () => { const { room, clock, conn } = harness(); const a = conn('A'); const b = conn('B'); room.join(a, 'player'); room.join(b, 'player'); room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'none' } } }); room.start('A'); room.clearTimer(); // No time control: no turn deadline. Black disconnects → only the 60s grace applies. room.disconnect(a); room.clearTimer(); expect(room.effectiveDeadline()).toBe(clock.now() + 60_000); expect(b.msgs.some((m) => m.t === 'notice' && m.code === 'disconnected')).toBe(true); // Reconnect before the grace period ends → no deadline again. clock.advance(30_000); room.join(conn('A'), 'player'); room.clearTimer(); expect(room.effectiveDeadline()).toBeNull(); }); test('restore postpones overdue deadlines by 30s and keeps game state', () => { const { room, clock, conn, deps, store } = harness(); room.join(conn('A'), 'player'); room.join(conn('B'), 'player'); room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } }); room.start('A'); room.clearTimer(); room.act('A', 1, { type: 'place', x: 7, y: 7 }); room.clearTimer(); const { seq, stateJson } = store.openRooms()[0]!; clock.advance(600_000); // server was down for 10 minutes const restored = Room.restore('room1', '482913', seq, JSON.parse(stateJson) as RoomSnapshot, deps); restored.clearTimer(); expect((restored.game!.state as any).moves).toHaveLength(1); const d = restored.effectiveDeadline()!; expect(d).toBeGreaterThanOrEqual(clock.now() + 30_000); expect(d).toBeLessThan(clock.now() + 60_000); expect(restored.roomView().seats.every((s) => s && !s.connected)).toBe(true); }); }); describe('Room isolation and lobby', () => { const boom: AnyGameDefinition = { id: 'boom', nameKo: '폭탄', minPlayers: 2, maxPlayers: 2, stateVersion: 1, defaultOptions: {}, optionsSchema: z.object({}), actionSchema: z.object({ type: z.literal('go') }), setup: ({ players }) => ({ players, n: 0 }), validate: () => ({ ok: true }), apply: () => { throw new Error('bug'); }, view: (s) => s, activePlayers: (s: any) => s.players, onTimeout: () => ({ type: 'go' }), result: () => null, }; test('a throwing game rejects the action, keeps state, pauses after 3 errors', () => { const { room, conn } = harness({ boom }); const a = conn('A'); room.join(a, 'player'); room.join(conn('B'), 'player'); room.start('A'); for (let i = 1; i <= 3; i++) room.act('A', i, { type: 'go' }); expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(3); expect(room.status).toBe('paused'); expect((room.game!.state as any).n).toBe(0); expect(room.voidGame('A')).toBeNull(); expect(room.status).toBe('finished'); }); test('seat rules: start needs min players, only host starts, kicked users cannot rejoin', () => { const { room, conn } = harness(); room.join(conn('A'), 'player'); expect(room.start('A')).toBe('1명 더 필요해요.'); room.join(conn('B'), 'player'); expect(room.start('B')).toBe('방장만 시작할 수 있어요.'); room.join(conn('C'), 'player'); expect(room.spectators.has('C')).toBe(true); expect(room.kick('A', 'C')).toBeNull(); expect(room.join(conn('C'), 'player')).toBe('방장이 내보낸 방에는 다시 들어갈 수 없어요.'); }); test('rematch starts when all seated players vote; colours alternate with gameNo', () => { const { room, conn } = harness(); room.join(conn('A'), 'player'); room.join(conn('B'), 'player'); room.configure('A', { options: { colorAssignment: 'alternate' } }); room.start('A'); room.clearTimer(); expect((room.game!.state as any).players.black).toBe('A'); room.act('B', 1, { type: 'resign' }); expect(room.status).toBe('finished'); expect(room.sessionStats).toEqual({ A: { played: 1, wins: 1 }, B: { played: 1, wins: 0 } }); room.rematch('A'); expect(room.status).toBe('finished'); room.rematch('B'); room.clearTimer(); expect(room.status).toBe('playing'); expect(room.gameNo).toBe(2); expect((room.game!.state as any).players.black).toBe('B'); }); test('leaving mid-game resigns via onLeave', () => { const { room, conn } = harness(); room.join(conn('A'), 'player'); room.join(conn('B'), 'player'); room.start('A'); room.clearTimer(); room.leave('B'); expect(room.status).toBe('finished'); expect(room.lastResult?.ranking).toEqual([['A'], ['B']]); expect(room.seatOf('B')).toBe(-1); }); }); describe('윷놀이 room rules', () => { const yutGames = () => ({ yut: GAMES.yut! }); test('team mode follows the game range to 8 seats and refuses odd counts via playerCountError', () => { const { room, conn } = harness(yutGames()); room.join(conn('A'), 'player'); expect(room.configure('A', { maxPlayers: 4 })).toBeNull(); expect(room.configure('A', { options: { ...GAMES.yut!.defaultOptions, mode: 'team' } })).toBeNull(); expect(room.seats).toHaveLength(8); for (const u of ['B', 'C', 'D', 'E']) room.join(conn(u), 'player'); expect(room.start('A')).toBe('팀전은 4명, 6명, 8명(짝수)으로만 할 수 있어요.'); room.join(conn('F'), 'player'); expect(room.start('A')).toBeNull(); room.clearTimer(); expect((room.game!.state as any).sides.map((s: any) => s.members)).toEqual([ ['A', 'C', 'E'], ['B', 'D', 'F'], ]); }); test('a disconnected player is auto-played after the grace period; reconnecting gets the current view', () => { const { room, clock, conn } = harness(yutGames()); const conns = { A: conn('A'), B: conn('B') }; room.join(conns.A, 'player'); room.join(conns.B, 'player'); room.configure('A', { options: { ...GAMES.yut!.defaultOptions, turnSeconds: null } }); expect(room.start('A')).toBeNull(); room.clearTimer(); const cur = (room.game!.state as any).current as 'A' | 'B'; room.disconnect(conns[cur]); room.clearTimer(); expect(room.effectiveDeadline()).toBe(clock.now() + 60_000); clock.advance(60_000); room.onTimer(); room.clearTimer(); expect((room.game!.state as any).turnSeq).toBe(1); const back = conn(cur); room.join(back, 'player'); room.clearTimer(); const st = back.msgs.find((m) => m.t === 'state') as any; expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq); }); });