Files
joke-app/apps/server/src/rooms/room.test.ts
EJClaw 19c163f4d2 시간 제한 없음은 정말 무제한, 대기실 설정은 바꾸면 바로 적용, 모르는 사람 기다리기(빠른 시작·공개 방) 제거
- 오목에서 [시간 제한 없음]을 골라도 30초가 흐르던 문제: 대기실 설정이 [설정 저장]을 눌러야
  서버에 반영되어, 누르지 않고 [게임 시작]하면 기본값(한 수 30초)으로 시작했다. 이제 설정은
  바꾸는 즉시 서버에 보낸다(저장 버튼 없음, 휴대폰 시트는 [닫기]만). 빠르게 여러 번 눌러도
  먼저 온 방 정보가 새 값을 되돌리지 않게 lib/option-sync.ts로 맞춘다.
- 시간 제한 없음(오목·체스·장기·오델로·바둑·쿼리도): 무응답 한도(idleLimitSec, 5~10분 뒤 시간패)와
  그 카운트다운을 없앴다. 체스는 첫 수 제한도 피셔일 때만. 연결이 끊긴 사람의 접속 유예는 그대로.
- 홈의 [지금 열린 방] 탭, 게임 소개의 [아무나와 빠른 시작]·기다리는 방 목록, 대기실의 방 공개
  설정을 뺐다(방은 모두 친구만). 서버 API는 남겨 두고 화면에서만 부르지 않는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:42:46 +09:00

229 lines
8.9 KiB
TypeScript

/** 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<string, AnyGameDefinition> = 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);
});
});