- 회귀 테스트: 서버 2개(수정 전 코드에서 실패 확인), e2e 1단계 추가 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
322 lines
12 KiB
TypeScript
322 lines
12 KiB
TypeScript
/**
|
|
* Rooms and waiting room (docs/04, docs/05 중간 입장·퇴장·방장). In memory; unlimited players (no seats).
|
|
* Stage 4: join/leave, host, kick, ready, settings with live song count. Games start in stage 5.
|
|
*/
|
|
import type { Database } from 'bun:sqlite';
|
|
import type { ServerWebSocket } from 'bun';
|
|
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, configSummary, type ChatLine, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared';
|
|
import { artistsByIds, countPool } from '../songs/pool';
|
|
import type { WsData } from '../ws/gateway';
|
|
|
|
/** Back within this long after a disconnect: keeps the place (and later the score). */
|
|
export const GRACE_MS = 60_000;
|
|
const EMPTY_ROOM_MS = 5 * 60_000;
|
|
/** Chat lines a newcomer gets (the screen keeps 200, docs/06). */
|
|
export const CHAT_HISTORY = 100;
|
|
|
|
interface Player {
|
|
joinedAt: number;
|
|
ready: boolean;
|
|
conns: Set<ServerWebSocket<WsData>>;
|
|
offlineSince: number | null;
|
|
}
|
|
|
|
export interface PublicUserLookup {
|
|
(id: string): { id: string; nickname: string; avatar: string | null; kind: 'guest' | 'member' } | null;
|
|
}
|
|
|
|
export class Room {
|
|
config: RoomConfig;
|
|
hostId: string;
|
|
password: string | null = null;
|
|
status: 'lobby' | 'playing' = 'lobby';
|
|
players = new Map<string, Player>();
|
|
pool = { playable: 0, total: 0 };
|
|
createdAt = Date.now();
|
|
emptySince: number | null = null;
|
|
chat: ChatLine[] = [];
|
|
private seq = 0;
|
|
|
|
constructor(
|
|
readonly code: string,
|
|
hostId: string,
|
|
config: RoomConfig,
|
|
private deps: { db: Database; user: PublicUserLookup },
|
|
) {
|
|
this.hostId = hostId;
|
|
this.config = config;
|
|
this.recount();
|
|
}
|
|
|
|
recount(): void {
|
|
this.pool = countPool(this.deps.db, this.config);
|
|
}
|
|
|
|
online(): string[] {
|
|
return [...this.players].filter(([, p]) => p.conns.size > 0).map(([id]) => id);
|
|
}
|
|
|
|
view(): RoomView {
|
|
return {
|
|
code: this.code,
|
|
hostId: this.hostId,
|
|
status: this.status,
|
|
config: this.config,
|
|
hasPassword: !!this.password,
|
|
players: [...this.players].map(([id, p]) => {
|
|
const u = this.deps.user(id);
|
|
return { id, nickname: u?.nickname ?? '?', avatar: u?.avatar ?? null, kind: u?.kind ?? 'guest', ready: p.ready, online: p.conns.size > 0 };
|
|
}),
|
|
pool: this.pool,
|
|
artists: artistsByIds(this.deps.db, this.config.artistIds),
|
|
};
|
|
}
|
|
|
|
send(m: ServerMessage, only?: string): void {
|
|
const json = JSON.stringify(m);
|
|
for (const [id, p] of this.players) if (!only || id === only) for (const ws of p.conns) ws.send(json);
|
|
}
|
|
|
|
broadcast(): void {
|
|
this.send({ t: 'room', room: this.view() });
|
|
}
|
|
|
|
/** Relays at once (docs/12 채팅 무조건 실시간). userId null = system line (입장/퇴장/방장). */
|
|
say(userId: string | null, text: string, n?: string): ChatLine {
|
|
const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId, nickname: userId ? (this.deps.user(userId)?.nickname ?? '?') : '', text };
|
|
if (n) line.n = n;
|
|
this.chat.push(line);
|
|
if (this.chat.length > CHAT_HISTORY) this.chat.shift();
|
|
this.send({ t: 'chat', code: this.code, line });
|
|
return line;
|
|
}
|
|
|
|
nick(userId: string): string {
|
|
return this.deps.user(userId)?.nickname ?? '?';
|
|
}
|
|
|
|
/** Earliest joined online player becomes host (docs/05 방장이 나가면). */
|
|
pickHost(): void {
|
|
const next = [...this.players].filter(([, p]) => p.conns.size > 0).sort((a, b) => a[1].joinedAt - b[1].joinedAt)[0]
|
|
?? [...this.players].sort((a, b) => a[1].joinedAt - b[1].joinedAt)[0];
|
|
if (next) this.hostId = next[0];
|
|
}
|
|
}
|
|
|
|
export interface PublicRoom {
|
|
code: string;
|
|
title: string;
|
|
host: string;
|
|
players: number;
|
|
status: 'lobby' | 'playing';
|
|
hasPassword: boolean;
|
|
summary: string[];
|
|
pool: number;
|
|
}
|
|
|
|
export class RoomManager {
|
|
rooms = new Map<string, Room>();
|
|
/** userId → room code (one room at a time). */
|
|
private where = new Map<string, string>();
|
|
|
|
constructor(private deps: { db: Database; user: PublicUserLookup; genreName: (id: string) => string; log?: (msg: string, extra?: Record<string, unknown>) => void }) {}
|
|
|
|
private newCode(): string {
|
|
for (;;) {
|
|
const code = String(100000 + Math.floor(Math.random() * 900000));
|
|
if (!this.rooms.has(code)) return code;
|
|
}
|
|
}
|
|
|
|
create(hostId: string, init: Partial<RoomConfig> = {}): Room | string {
|
|
const nick = this.deps.user(hostId)?.nickname ?? '';
|
|
const cfg = applyConfigPatch({ ...DEFAULT_ROOM_CONFIG, title: `${nick}님의 방`.slice(0, 40) }, init);
|
|
if (typeof cfg === 'string') return cfg;
|
|
const room = new Room(this.newCode(), hostId, cfg, this.deps);
|
|
// Empty until someone joins: a room created and never entered expires like any empty room.
|
|
room.emptySince = Date.now();
|
|
this.rooms.set(room.code, room);
|
|
this.deps.log?.('room created', { code: room.code, host: hostId });
|
|
return room;
|
|
}
|
|
|
|
get(code: string): Room | undefined {
|
|
return this.rooms.get(code);
|
|
}
|
|
|
|
roomOf(userId: string): Room | undefined {
|
|
const c = this.where.get(userId);
|
|
return c ? this.rooms.get(c) : undefined;
|
|
}
|
|
|
|
publicRooms(): PublicRoom[] {
|
|
return [...this.rooms.values()]
|
|
.filter((r) => r.config.visibility !== 'private' && r.players.size > 0)
|
|
.map((r) => ({
|
|
code: r.code,
|
|
title: r.config.title,
|
|
host: this.deps.user(r.hostId)?.nickname ?? '',
|
|
players: r.players.size,
|
|
status: r.status,
|
|
hasPassword: r.config.visibility === 'password' && !!r.password,
|
|
summary: configSummary(r.config, this.deps.genreName),
|
|
pool: r.pool.playable,
|
|
}))
|
|
.sort((a, b) => b.players - a.players);
|
|
}
|
|
|
|
join(ws: ServerWebSocket<WsData>, code: string, password?: string): string | null {
|
|
const userId = ws.data.userId;
|
|
const room = this.rooms.get(code);
|
|
if (!room) return '방을 찾을 수 없어요. 코드를 다시 확인해 주세요.';
|
|
const already = room.players.get(userId);
|
|
if (!already && room.config.visibility === 'password' && room.password && password !== room.password && room.hostId !== userId) {
|
|
return room.password && password ? '비밀번호가 틀렸어요.' : '비밀번호가 필요한 방이에요.';
|
|
}
|
|
// One room at a time: leave the previous one (other tabs there are told).
|
|
const prev = this.roomOf(userId);
|
|
if (prev && prev !== room) this.removePlayer(prev, userId, 'elsewhere');
|
|
if (ws.data.roomCode && ws.data.roomCode !== code) this.detach(ws);
|
|
const p = already ?? { joinedAt: Date.now(), ready: false, conns: new Set(), offlineSince: null };
|
|
p.conns.add(ws);
|
|
p.offlineSince = null;
|
|
room.players.set(userId, p);
|
|
room.emptySince = null;
|
|
this.where.set(userId, code);
|
|
ws.data.roomCode = code;
|
|
if (!room.players.has(room.hostId)) room.hostId = userId;
|
|
ws.send(JSON.stringify({ t: 'chatlog', code, lines: room.chat } satisfies ServerMessage));
|
|
room.broadcast();
|
|
if (!already) room.say(null, `${room.nick(userId)}님이 들어왔어요`);
|
|
return null;
|
|
}
|
|
|
|
/** Socket closed or switched rooms: the player stays (grace period) until swept. */
|
|
detach(ws: ServerWebSocket<WsData>): void {
|
|
const code = ws.data.roomCode;
|
|
ws.data.roomCode = undefined;
|
|
const room = code ? this.rooms.get(code) : undefined;
|
|
const p = room?.players.get(ws.data.userId);
|
|
if (!room || !p) return;
|
|
p.conns.delete(ws);
|
|
if (p.conns.size === 0) {
|
|
p.offlineSince = Date.now();
|
|
p.ready = false;
|
|
const wasHost = room.hostId === ws.data.userId;
|
|
if (wasHost) room.pickHost();
|
|
room.broadcast();
|
|
if (wasHost && room.hostId !== ws.data.userId) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
|
|
}
|
|
}
|
|
|
|
leave(ws: ServerWebSocket<WsData>): void {
|
|
const room = this.roomOf(ws.data.userId);
|
|
if (room) this.removePlayer(room, ws.data.userId, 'leave');
|
|
}
|
|
|
|
removePlayer(room: Room, userId: string, reason: 'leave' | 'kicked' | 'closed' | 'elsewhere'): void {
|
|
const p = room.players.get(userId);
|
|
if (!p) return;
|
|
room.send({ t: 'left', code: room.code, reason }, userId);
|
|
for (const ws of p.conns) ws.data.roomCode = undefined;
|
|
room.players.delete(userId);
|
|
if (this.where.get(userId) === room.code) this.where.delete(userId);
|
|
if (room.players.size === 0) {
|
|
room.emptySince = Date.now();
|
|
return;
|
|
}
|
|
const wasHost = room.hostId === userId;
|
|
if (wasHost) room.pickHost();
|
|
room.broadcast();
|
|
room.say(null, `${room.nick(userId)}님이 ${reason === 'kicked' ? '내보내졌어요' : '나갔어요'}`);
|
|
if (wasHost) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
|
|
}
|
|
|
|
/** Host-only actions. Returns an error message or null. */
|
|
hostAction(ws: ServerWebSocket<WsData>, fn: (room: Room) => string | null): string | null {
|
|
const room = this.roomOf(ws.data.userId);
|
|
if (!room) return '방에 들어가 있지 않아요.';
|
|
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
|
if (room.status !== 'lobby') return '대기실에서만 바꿀 수 있어요.';
|
|
return fn(room);
|
|
}
|
|
|
|
setConfig(ws: ServerWebSocket<WsData>, patch: Record<string, unknown>): string | null {
|
|
return this.hostAction(ws, (room) => {
|
|
const next = applyConfigPatch(room.config, patch);
|
|
if (typeof next === 'string') return next;
|
|
room.config = next;
|
|
// Settings changed: everyone confirms again (joke-app behaviour, docs/04).
|
|
for (const p of room.players.values()) p.ready = false;
|
|
room.recount();
|
|
room.broadcast();
|
|
return null;
|
|
});
|
|
}
|
|
|
|
setPassword(ws: ServerWebSocket<WsData>, value: string | null): string | null {
|
|
return this.hostAction(ws, (room) => {
|
|
room.password = value;
|
|
room.broadcast();
|
|
return null;
|
|
});
|
|
}
|
|
|
|
ready(ws: ServerWebSocket<WsData>, on: boolean): string | null {
|
|
const room = this.roomOf(ws.data.userId);
|
|
const p = room?.players.get(ws.data.userId);
|
|
if (!room || !p) return '방에 들어가 있지 않아요.';
|
|
p.ready = on;
|
|
room.broadcast();
|
|
return null;
|
|
}
|
|
|
|
kick(ws: ServerWebSocket<WsData>, target: string): string | null {
|
|
const room = this.roomOf(ws.data.userId);
|
|
if (!room) return '방에 들어가 있지 않아요.';
|
|
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
|
if (target === ws.data.userId || !room.players.has(target)) return '내보낼 수 없는 사람이에요.';
|
|
this.removePlayer(room, target, 'kicked');
|
|
return null;
|
|
}
|
|
|
|
giveHost(ws: ServerWebSocket<WsData>, target: string): string | null {
|
|
const room = this.roomOf(ws.data.userId);
|
|
if (!room) return '방에 들어가 있지 않아요.';
|
|
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
|
if (!room.players.get(target)?.conns.size) return '접속 중인 사람에게만 넘길 수 있어요.';
|
|
room.hostId = target;
|
|
room.broadcast();
|
|
room.say(null, `방장이 ${room.nick(target)}님으로 바뀌었어요`);
|
|
return null;
|
|
}
|
|
|
|
/** Chat line from a player in the room (docs/06). Flood guard is applied by the gateway. */
|
|
chat(ws: ServerWebSocket<WsData>, text: string, n?: string): string | null {
|
|
const room = this.roomOf(ws.data.userId);
|
|
if (!room || ws.data.roomCode !== room.code) return '방에 들어가 있지 않아요.';
|
|
const t = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
|
if (!t) return '빈 메시지는 보낼 수 없어요.';
|
|
room.say(ws.data.userId, t, n);
|
|
return null;
|
|
}
|
|
|
|
/** Every 10s: drop players gone longer than the grace period, close rooms left empty. */
|
|
sweep(now = Date.now()): void {
|
|
for (const room of this.rooms.values()) {
|
|
for (const [id, p] of room.players) if (p.offlineSince && now - p.offlineSince > GRACE_MS) this.removePlayer(room, id, 'closed');
|
|
if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.rooms.delete(room.code);
|
|
}
|
|
}
|
|
|
|
/** Song catalog changed (admin edit / collector in its own process): refresh the counts shown in lobbies, only telling rooms whose count moved. */
|
|
recountAll(): void {
|
|
for (const r of this.rooms.values()) {
|
|
if (r.players.size === 0) continue;
|
|
const before = r.pool;
|
|
r.recount();
|
|
if (before.playable !== r.pool.playable || before.total !== r.pool.total) r.broadcast();
|
|
}
|
|
}
|
|
}
|