Files
joke-app/apps/server/src/rooms/room.test.ts
EJClaw f793391b79 제한 시간 보정 2: 같은 마감 안에서는 투표로 답할 사람이 줄어도 준 시간 유지, 마감은 남은 답할 사람 중 가장 늦은 화면 기준, 자체 시계를 쓰는 게임도 늘어난 마감을 표시
- room: reveal 단계 키를 게임 마감만으로, clockExtra = max(본인, 답할 사람들)
- 라이어·마피아·아발론 시계, 뱅 반응·차례 타이머, 바둑 계가·마작 울기 타이머가 방 마감(연출 시간 포함)을 따름
- 아발론 암살 마감: 당겨진 마감은 숨기고 늘어난 마감은 보여 줌(무제한이면 그대로 숨김)
- 테스트: 공통 재투표(대표자 A·느린 B·A 투표 후 유지), e2e 라이어 화면 시계 = 방 마감

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:25 +09:00

473 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 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('a turn clock starts when the player\'s screen has finished animating (settled), not before', () => {
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();
const base = clock.now() + 10_000;
// A screen that never reported keeps the old clock (pages from before this change, computers).
expect(room.effectiveDeadline()).toBe(base);
// A's screen finishes the opening 1.5 s later: A's clock is 1.5 s longer, and everyone is told the new deadline.
clock.advance(1_500);
room.settled('A', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 1_500);
expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 1_500 });
clock.advance(10_000 - 1);
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);
// Next state, B to move: a late report for an older state counts nothing, and B (who never reported) keeps the plain clock.
const seq = room.seq;
const base2 = clock.now() + 10_000;
room.settled('A', seq - 1);
expect(room.effectiveDeadline()).toBe(base2); // B is to move and B never reported: B's clock is unchanged
room.settled('B', seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base2);
});
test('a player who reported once but not yet for this state: the timer waits for the screen (at most 15 s at ×1)', () => {
const { room, clock, conn } = 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.settled('A', room.seq);
room.settled('B', room.seq);
room.clearTimer();
// A plays; B (to move) has not reported this new state yet
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
room.clearTimer();
const base = clock.now() + 10_000;
expect(room.effectiveDeadline()).toBe(base + 15_000);
clock.advance(2_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 2_000);
});
test('a deadline moved by a screen that reported before is told to every client (omok)', () => {
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 } } });
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
room.clearTimer();
const base = clock.now() + 10_000;
const sent = b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number };
expect(sent.deadline).toBe(base);
clock.advance(2_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 2_000);
for (const c of [a, b]) expect(c.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 2_000 });
});
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);
});
});
describe('Room chat (2026-10-13)', () => {
test('no pace limit: any number of lines in the same instant all go through, in order', () => {
const { room, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
const lines = Array.from({ length: 30 }, (_, i) => `줄 ${i}`);
for (const t of lines) expect(room.chat('A', t)).toBeNull();
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines);
});
test('lines sent before joining come back marked as replay; live lines are not', () => {
const { room, conn } = harness();
const a = conn('A');
room.join(a, 'player');
room.chat('A', '먼저 한 말');
const b = conn('B');
room.join(b, 'player');
room.chat('A', '지금 한 말');
const got = b.msgs.filter((m) => m.t === 'chat').map((m) => [(m as { text: string }).text, (m as { replay?: true }).replay ?? false]);
expect(got).toEqual([
['먼저 한 말', true],
['지금 한 말', false],
]);
expect((a.msgs.find((m) => m.t === 'chat') as { replay?: true }).replay).toBeUndefined();
});
test('typing at a person\'s pace (a line every 0.4 s) never waits', () => {
const { room, clock, conn } = harness();
room.join(conn('A'), 'player');
for (let i = 0; i < 30; i++) {
expect(room.chat('A', `줄 ${i}`)).toBeNull();
clock.advance(400);
}
});
test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => {
const { room, clock, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
const typingOf = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m) => m.t === 'typing');
room.typing('A', true, 'room');
room.typing('A', true, 'room');
expect(typingOf(b)).toEqual([{ t: 'typing', from: 'A', on: true, ch: 'room' }]);
expect(typingOf(a)).toHaveLength(0);
clock.advance(1000);
room.typing('A', true, 'room');
room.typing('A', false, 'room');
expect(typingOf(b)).toHaveLength(3);
// Game chat signal only while a game with its own chat runs (omok has none).
room.typing('A', true, 'game');
expect(typingOf(b)).toHaveLength(3);
// Chat off: nothing.
room.configure('A', { chatEnabled: false });
clock.advance(1000);
room.typing('A', true, 'room');
expect(typingOf(b)).toHaveLength(3);
});
});
describe('Room clocks after the animation (shared steps)', () => {
// Like 라이어 게임's last guess: everybody votes, then only the liar (B) answers, while the room times a stand-in (A).
const guess: AnyGameDefinition = {
id: 'guess',
nameKo: '맞히기',
minPlayers: 2,
maxPlayers: 2,
stateVersion: 1,
defaultOptions: {},
optionsSchema: z.object({}),
actionSchema: z.object({ type: z.enum(['go', 'chat']) }),
setup: ({ players, now }) => ({ players, step: 'vote', deadlineAt: now + 10_000, chats: 0 }),
validate: () => ({ ok: true }),
apply: (s: any, _p, a: any, { now }) => ({ state: a.type === 'go' ? { ...s, step: 'guess', deadlineAt: now + 10_000 } : { ...s, chats: s.chats + 1 }, events: [] }),
view: (s) => s,
activePlayers: (s: any) => (s.step === 'guess' ? [s.players[1]] : s.players),
timeoutPlayers: (s: any) => (s.step === 'guess' ? [s.players[0]] : s.players),
deadline: (s: any) => s.deadlineAt,
onTimeout: () => ({ type: 'chat' }),
result: () => null,
};
test('the stand-in\'s clock waits for the real answerer\'s screen, and a chat line keeps the time given', () => {
const { room, clock, conn } = harness({ guess });
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, { type: 'go' }); // → only B answers now, A is the timed stand-in
room.clearTimer();
const base = clock.now() + 10_000;
clock.advance(1_000);
room.settled('A', room.seq); // A's screen is quick: that must not start B's clock
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 15_000);
clock.advance(5_000);
room.settled('B', room.seq); // B's screen took 6 s
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
// A chat line in the same step keeps B's 6 s.
clock.advance(1_000);
room.act('A', 2, { type: 'chat' });
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
// B still gets the whole 10 s from when the screen settled: nothing fires a moment before that.
clock.advance(base + 6_000 - clock.now() - 1);
room.onTimer();
room.clearTimer();
expect((room.game!.state as any).chats).toBe(1);
});
// A re-vote: A and B both vote under one shared clock that the room times through A.
const revote: AnyGameDefinition = {
...guess,
id: 'revote',
actionSchema: z.object({ type: z.enum(['go', 'vote', 'chat']) }),
setup: ({ players, now }) => ({ players, step: 'start', deadlineAt: now + 10_000, voted: [] as string[], chats: 0 }),
apply: (s: any, p, a: any, { now }) => ({
state: a.type === 'go' ? { ...s, step: 'vote', deadlineAt: now + 10_000 } : a.type === 'vote' ? { ...s, voted: [...s.voted, p] } : { ...s, chats: s.chats + 1 },
events: [],
}),
activePlayers: (s: any) => (s.step === 'vote' ? s.players.filter((p: string) => !s.voted.includes(p)) : s.players),
timeoutPlayers: (s: any) => (s.step === 'vote' ? [s.players[0]] : s.players),
};
test('a shared vote: the clock waits for the slowest voter\'s screen, and someone voting keeps that time', () => {
const { room, clock, conn } = harness({ revote });
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, { type: 'go' });
room.clearTimer();
const base = clock.now() + 10_000;
clock.advance(220);
room.settled('A', room.seq); // A (also the timed stand-in) is done in 0.22 s …
clock.advance(5_780);
room.settled('B', room.seq); // … B only after 6 s: the shared clock gives everybody those 6 s
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect(a.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
// A votes: only B is left to answer, same clock: still 6 s more.
room.act('A', 2, { type: 'vote' });
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000);
});
});