4단계 방·대기실: 방 만들기(게스트 포함)·6자리 코드·열린 방 목록(🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·넘기기·내보내기·60초 자리 유지), 방 설정 전체 즉시 반영, 조건에 맞는 곡 N곡 + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내

- 서버 테스트 49개, 브라우저 e2e(e2e/rooms.e2e.ts, 3명) 11단계
- 사용자 결정(추천안)은 docs/12 "4단계 확인"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 21:07:54 +09:00
parent c018bc5a9d
commit 735ddd0322
24 changed files with 2391 additions and 15 deletions

View File

@@ -21,6 +21,8 @@ export interface AdminDeps {
db: Database;
/** Injected for tests. */
checkEmbed?: (videoId: string) => Promise<EmbedState>;
/** Lobby song counts depend on the catalog. */
onCatalogChange?: () => void;
}
type Env = { Variables: { userId: string | null; role: Role } };
@@ -140,6 +142,7 @@ export function createAdminApp(d: AdminDeps) {
const genres = new Set(genreList(d.db).map((g) => g.id));
if (rest.genres?.some((g) => !genres.has(g))) return c.json({ error: '없는 장르가 있어요.' }, 400);
updateSong(d.db, id, { ...rest, youtubeId }, embed);
d.onCatalogChange?.();
const after = getSong(d.db, id)!;
d.audit.log(actor(c), 'song.update', String(id), { title: before.song.title, artist: before.song.artist }, parsed.data);
return c.json(after);

View File

@@ -11,6 +11,11 @@ import { WindowLimiter } from '../ws/rate-limit';
import { createAdminApp, type AdminDeps } from './admin';
import type { Roles } from '../admin/roles';
import type { SettingsStore } from '../admin/settings';
import type { Database } from 'bun:sqlite';
import type { RoomManager } from '../rooms/manager';
import { genreList } from '../songs/store';
import { countPool, searchArtists, yearBounds } from '../songs/pool';
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, type RoomConfig } from '@mq/shared';
export interface HttpDeps {
config: Config;
@@ -18,6 +23,8 @@ export interface HttpDeps {
sessions: Sessions;
roles: Roles;
settings: SettingsStore;
rooms: RoomManager;
db: Database;
/** Injected for tests. */
discordExchange?: (code: string, redirectUri: string) => Promise<DiscordUser>;
ipOf: (req: Request) => string;
@@ -195,6 +202,50 @@ export function createHttpApp(d: HttpDeps) {
return c.json({ me: toPublicUser(d.users.get(u)!) });
});
// ------------------------------------------------------------ rooms (docs/04, stage 4)
const createLimiter = new WindowLimiter(10, 60_000);
const lookupLimiter = new WindowLimiter(60, 60_000);
/** Static data for the settings form: genres with groups, year span, level names come from @mq/shared. */
app.get('/api/catalog/meta', (c) =>
c.json({ genres: genreList(d.db).filter((g) => !g.hidden).map(({ id, name, grp }) => ({ id, name, grp })), years: yearBounds(d.db) }),
);
app.get('/api/artists', (c) => {
const q = (c.req.query('q') ?? '').trim().slice(0, 40);
if (!q) return c.json({ artists: [] });
if (!lookupLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
return c.json({ artists: searchArtists(d.db, q) });
});
app.get('/api/rooms', (c) => c.json({ rooms: d.rooms.publicRooms() }));
app.post('/api/rooms', async (c) => {
const u = userOf(c);
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
if (d.settings.getSite().maintenance) return c.json({ error: '점검 중이라 새 방을 만들 수 없어요.' }, 503);
if (!createLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
const body = (await c.req.json().catch(() => ({}))) as { config?: Partial<RoomConfig> };
const r = d.rooms.create(u, body.config ?? {});
if (typeof r === 'string') return c.json({ error: r }, 400);
return c.json({ code: r.code });
});
/** Room preview for the join screen (no login needed). */
app.get('/api/rooms/:code', (c) => {
if (!lookupLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
const r = d.rooms.get(c.req.param('code'));
if (!r) return c.json({ error: '방을 찾을 수 없어요. 코드를 다시 확인해 주세요.' }, 404);
return c.json({ code: r.code, title: r.config.title, players: r.players.size, status: r.status, needsPassword: r.config.visibility === 'password' && !!r.password });
});
/** "조건에 맞는 곡 N곡" for a config that isn't a room yet (e.g. the 무제한 label). */
app.post('/api/pool/count', async (c) => {
const cfg = applyConfigPatch(DEFAULT_ROOM_CONFIG, await c.req.json().catch(() => null));
if (typeof cfg === 'string') return c.json({ error: cfg }, 400);
return c.json(countPool(d.db, cfg));
});
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings }));
app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404));

View File

@@ -0,0 +1,225 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { DEFAULT_ROOM_CONFIG, voteThreshold, type RoomView, type ServerMessage } from '@mq/shared';
import { Catalog } from './collector/catalog';
import { openDb } from './db';
import { countPool } from './songs/pool';
import { Client, api, boot, guest, sleep, tempDbPath } from './test-utils';
describe('song pool rules (docs/04, docs/12 Q7·Q9)', () => {
const db = openDb(tempDbPath());
const c = new Catalog(db);
const add = (title: string, genres: string[], year: number, level: number, matched = true, extraLevels: [string, number][] = []) => {
const [id] = c.upsert({ title, artists: [{ name: `가수${title}` }], year, genres, source: 't', ref: title });
c.autoLevel(id, 'all', level);
for (const [scope, lv] of extraLevels) c.autoLevel(id, scope, lv);
if (matched) db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'x' WHERE id = ?").run(id);
return id;
};
add('국내발라드', ['kpop', 'ballad'], 2005, 3);
add('국내댄스', ['kpop', 'dance'], 2010, 3);
add('해외발라드', ['pop', 'ballad'], 2005, 3);
add('어려운국내발라드', ['kpop', 'ballad'], 1995, 6, true, [['genre:ballad', 3]]); // 전체 6단계, 발라드 안에서는 3단계
add('90년대에선쉬움', ['kpop', 'rock'], 1994, 7, true, [['decade:1990', 3]]);
add('미확정', ['kpop', 'ballad'], 2005, 3, false);
const cfg = (p: Partial<typeof DEFAULT_ROOM_CONFIG>) => ({ ...DEFAULT_ROOM_CONFIG, ...p });
test('different groups AND, same group OR', () => {
// kpop AND ballad: 국내발라드 + 어려운국내발라드 (level 3 within ballad); 미확정 has no video
expect(countPool(db, cfg({ genres: ['kpop', 'ballad'] })).playable).toBe(2);
// ballad OR dance: 국내발라드, 국내댄스, 해외발라드, 어려운국내발라드
expect(countPool(db, cfg({ genres: ['ballad', 'dance'] })).playable).toBe(4);
// kpop AND (ballad OR dance): 해외발라드 drops out
expect(countPool(db, cfg({ genres: ['kpop', 'ballad', 'dance'] })).playable).toBe(3);
});
test('level N only, with per-scope levels counting (a song can sit in several levels)', () => {
expect(countPool(db, cfg({})).playable).toBe(3); // level 3 overall: 국내발라드, 국내댄스, 해외발라드
expect(countPool(db, cfg({ genres: ['ballad'] })).playable).toBe(3); // + 어려운국내발라드 (ballad scope 3)
expect(countPool(db, cfg({ level: 6 })).playable).toBe(1);
expect(countPool(db, cfg({ yearFrom: 1990, yearTo: 1999 })).playable).toBe(1); // 90년대에선쉬움 via decade scope
});
test('year range and playable vs total', () => {
expect(countPool(db, cfg({ yearFrom: 2006 })).playable).toBe(1);
expect(countPool(db, cfg({ genres: ['kpop', 'ballad'], yearFrom: 2000 }))).toEqual({ playable: 1, total: 2 }); // 국내발라드 + 미확정
});
test('vote thresholds round up and stay within the player count', () => {
expect(voteThreshold('1/3', 7)).toBe(3);
expect(voteThreshold('2/3', 3)).toBe(2);
expect(voteThreshold('all', 5)).toBe(5);
expect(voteThreshold('2', 1)).toBe(1);
expect(voteThreshold('none', 5)).toBeNull();
});
});
describe('rooms over WebSocket', () => {
let s: ReturnType<typeof boot>;
afterEach(async () => s && (await s.stop()));
const lastRoom = (cl: Client) => [...cl.messages].reverse().find((m) => m.t === 'room') as { room: RoomView } | undefined;
const nextRoom = (cl: Client, pred: (r: RoomView) => boolean = () => true) =>
new Promise<RoomView>((resolve, reject) => {
const start = Date.now();
const tick = () => {
const m = lastRoom(cl);
if (m && pred(m.room)) return resolve(m.room);
if (Date.now() - start > 2000) return reject(new Error(`no matching room view; last ${JSON.stringify(m?.room?.players)}`));
setTimeout(tick, 10);
};
tick();
});
const errorOf = (cl: Client) => cl.waitFor((m) => m.t === 'error') as Promise<Extract<ServerMessage, { t: 'error' }>>;
async function setup() {
s = boot();
const a = await guest(s.base, '방장');
const b = await guest(s.base, '손님');
const create = await api(s.base, '/api/rooms', { method: 'POST', cookie: a.cookie, body: JSON.stringify({}) });
expect(create.res.status).toBe(200);
const code: string = create.body.code;
const ca = await new Client(s.base, a.cookie).connect();
const cb = await new Client(s.base, b.cookie).connect();
ca.send({ t: 'join', code });
await nextRoom(ca, (r) => r.players.length === 1);
cb.send({ t: 'join', code });
await nextRoom(ca, (r) => r.players.length === 2);
return { a, b, ca, cb, code };
}
test('create, join, both see each other; the creator is host with default settings', async () => {
const { a, cb, code } = await setup();
const r = await nextRoom(cb, (x) => x.players.length === 2);
expect(r.hostId).toBe(a.id);
expect(r.config).toMatchObject({ title: '방장님의 방', level: 3, answer: 'title', strict: { space: true, number: true, symbol: true }, hint: 'none', count: 30 });
expect((await api(s.base, '/api/rooms')).body.rooms.map((x: any) => x.code)).toEqual([code]);
expect((await api(s.base, `/api/rooms/${code}`)).body).toMatchObject({ code, players: 2, status: 'lobby' });
});
test('only the host changes settings; a change resets ready and reaches everyone', async () => {
const { ca, cb } = await setup();
cb.send({ t: 'ready', on: true });
await nextRoom(ca, (r) => r.players.some((p) => p.ready));
cb.send({ t: 'config', patch: { level: 5 } });
expect((await errorOf(cb)).message).toContain('방장만');
ca.send({ t: 'config', patch: { level: 5, hint: 'manual', hintVotes: '1/2', genres: ['ballad'], count: 0 } });
const r = await nextRoom(cb, (x) => x.config.level === 5);
expect(r.config).toMatchObject({ hint: 'manual', hintVotes: '1/2', genres: ['ballad'], count: 0 });
expect(r.players.every((p) => !p.ready)).toBe(true);
ca.send({ t: 'config', patch: { listenSec: 7 } });
expect((await errorOf(ca)).message).toContain('올바르지 않아요');
});
test('host can kick and hand over; when the host leaves the next player becomes host', async () => {
const { a, b, ca, cb, code } = await setup();
ca.send({ t: 'host', userId: b.id });
expect((await nextRoom(cb, (r) => r.hostId === b.id)).hostId).toBe(b.id);
cb.send({ t: 'kick', userId: a.id });
await ca.waitFor((m) => m.t === 'left' && m.reason === 'kicked');
expect((await nextRoom(cb, (r) => r.players.length === 1)).players[0]!.id).toBe(b.id);
// a comes back and b leaves: a is host again
ca.send({ t: 'join', code });
await nextRoom(cb, (r) => r.players.length === 2);
cb.send({ t: 'leave' });
expect((await nextRoom(ca, (r) => r.players.length === 1)).hostId).toBe(a.id);
});
test('password rooms need the password; private rooms are not listed', async () => {
const { ca, code } = await setup();
ca.send({ t: 'config', patch: { visibility: 'password' } });
ca.send({ t: 'password', value: 'abcd' });
await nextRoom(ca, (r) => r.hasPassword);
const c = await guest(s.base, '셋째');
const cc = await new Client(s.base, c.cookie).connect();
cc.send({ t: 'join', code });
expect((await errorOf(cc)).message).toContain('비밀번호');
cc.send({ t: 'join', code, password: 'abcd' });
await nextRoom(cc, (r) => r.players.length === 3);
expect((await api(s.base, '/api/rooms')).body.rooms[0].hasPassword).toBe(true);
ca.send({ t: 'config', patch: { visibility: 'private' } });
await nextRoom(ca, (r) => r.config.visibility === 'private');
expect((await api(s.base, '/api/rooms')).body.rooms).toEqual([]);
});
test('a disconnected player keeps the place for the grace period, then is removed', async () => {
const { a, b, ca, cb } = await setup();
cb.close();
const r = await nextRoom(ca, (x) => x.players.some((p) => p.id === b.id && !p.online));
expect(r.players.length).toBe(2);
s.rooms.sweep(Date.now() + 61_000);
expect((await nextRoom(ca, (x) => x.players.length === 1)).players[0]!.id).toBe(a.id);
});
test('no player limit: 40 people in one room', async () => {
const { ca, code } = await setup();
const clients: Client[] = [];
for (let i = 0; i < 38; i++) {
// straight to the DB: the guest sign-up endpoint is rate limited per IP
const u = s.users.createGuest(`손님${i}`);
const cl = await new Client(s.base, `sid=${s.sessions.create(u.id, 'guest', null).token}`).connect();
cl.send({ t: 'join', code });
clients.push(cl);
}
expect((await nextRoom(ca, (r) => r.players.length === 40)).players.length).toBe(40);
for (const cl of clients) cl.close();
await sleep(20);
});
test('joining another room leaves the first one', async () => {
const { a, ca, cb, code } = await setup();
const other = (await api(s.base, '/api/rooms', { method: 'POST', cookie: a.cookie, body: '{}' })).body.code;
ca.send({ t: 'join', code: other });
await nextRoom(ca, (r) => r.code === other);
expect((await nextRoom(cb, (r) => r.code === code && r.players.length === 1)).players.length).toBe(1);
});
const chatOf = (cl: Client) => cl.messages.filter((m) => m.t === 'chat').map((m) => (m as Extract<ServerMessage, { t: 'chat' }>).line);
test('waiting-room chat: relayed to everyone in order with a nonce echo, system lines for join/leave/host, history for newcomers', async () => {
const { a, b, ca, cb, code } = await setup();
ca.send({ t: 'chat', text: ' 안녕\u0007하세요 ', n: 'x1' });
const got = await cb.waitFor((m) => m.t === 'chat' && m.line.userId === a.id);
expect(got).toMatchObject({ t: 'chat', code, line: { userId: a.id, nickname: '방장', text: '안녕 하세요', n: 'x1' } });
cb.send({ t: 'chat', text: 'ㅎㅇ' });
await ca.waitFor((m) => m.t === 'chat' && m.line.userId === b.id);
const lines = chatOf(ca);
expect(lines.map((l) => l.seq)).toEqual([...lines.map((l) => l.seq)].sort((x, y) => x - y));
expect(lines.filter((l) => l.userId === null).map((l) => l.text)).toEqual(['방장님이 들어왔어요', '손님님이 들어왔어요']);
// newcomer gets the history at once
const c = await guest(s.base, '셋째');
const cc = await new Client(s.base, c.cookie).connect();
cc.send({ t: 'join', code });
const log = (await cc.waitFor((m) => m.t === 'chatlog')) as Extract<ServerMessage, { t: 'chatlog' }>;
expect(log.lines.map((l) => l.text)).toEqual(['방장님이 들어왔어요', '손님님이 들어왔어요', '안녕 하세요', 'ㅎㅇ']);
// host leaves → system lines
ca.send({ t: 'leave' });
await cb.waitFor((m) => m.t === 'chat' && m.line.text === '방장이 손님님으로 바뀌었어요');
expect(chatOf(cb).some((l) => l.text === '방장님이 나갔어요')).toBe(true);
// not in a room → refused
ca.send({ t: 'chat', text: '아무도 없나' });
expect((await errorOf(ca)).message).toContain('방에 들어가 있지 않아요');
});
test('chat flood guard is off by default and limits only when the admin turns it on', async () => {
const { a, ca, cb } = await setup();
for (let i = 0; i < 30; i++) ca.send({ t: 'chat', text: `도배${i}` });
await cb.waitFor((m) => m.t === 'chat' && m.line.text === '도배29');
expect(ca.messages.some((m) => m.t === 'error')).toBe(false);
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: true, chatRatePerSec: 1, chatBurst: 3 }, a.id);
for (let i = 0; i < 6; i++) ca.send({ t: 'chat', text: `또${i}` });
expect((await errorOf(ca)).message).toContain('너무 빨리');
await sleep(100);
expect(chatOf(cb).filter((l) => l.text.startsWith('또')).length).toBe(3);
});
test('lobby song count follows catalog changes made by another process', async () => {
const { ca } = await setup();
const before = (await nextRoom(ca)).pool;
const cat = new Catalog(s.db);
const [id] = cat.upsert({ title: '새로찾은곡', artists: [{ name: '누군가' }], year: 2015, genres: [], source: 't', ref: 'new' });
cat.autoLevel(id, 'all', 3);
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'y' WHERE id = ?").run(id);
s.rooms.recountAll();
expect((await nextRoom(ca, (r) => r.pool.playable === before.playable + 1)).pool.total).toBe(before.total + 1);
});
});

View File

@@ -0,0 +1,319 @@
/**
* 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);
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 null;
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();
}
}
}

View File

@@ -10,6 +10,8 @@ import { createHttpApp, type HttpDeps } from './http/app';
import { Gateway, type WsData } from './ws/gateway';
import { Audit, Roles } from './admin/roles';
import { SettingsStore } from './admin/settings';
import { RoomManager } from './rooms/manager';
import { toPublicUser } from './auth/users';
/** A guest who closed the site and stayed away this long is deleted (docs/02). */
export const GUEST_IDLE_MS = 24 * 3600_000;
@@ -43,15 +45,35 @@ export function startServer(opts: StartOptions) {
const roles = new Roles(db, config.superadminDiscordIds);
const audit = new Audit(db);
const startedAt = Date.now();
const gateway = new Gateway({ log, onClose: (id) => users.touch(id) });
const genreNames = new Map(db.query<{ id: string; name: string }, []>('SELECT id, name FROM genres').all().map((g) => [g.id, g.name]));
const rooms = new RoomManager({
db,
user: (id) => {
const u = users.get(id);
return u ? toPublicUser(u) : null;
},
genreName: (id) => genreNames.get(id) ?? id,
log: (msg, extra) => log('info', msg, extra),
});
const gateway = new Gateway({
log,
onClose: (id) => users.touch(id),
rooms,
chatGuard: () => {
const site = settings.getSite();
return { on: site.chatFloodGuard, ratePerSec: site.chatRatePerSec, burst: site.chatBurst };
},
});
const removeGuest = (id: string) => {
const r = rooms.roomOf(id);
if (r) rooms.removePlayer(r, id, 'closed');
gateway.disconnectUser(id);
if (users.deleteGuest(id)) log('info', 'guest removed', { user: id });
};
/** Guests who closed the site and stayed away a day are deleted. */
const purgeIdleGuests = (now = Date.now()) => {
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) if (!gateway.isOnline(id)) removeGuest(id);
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) if (!gateway.isOnline(id) && !rooms.roomOf(id)) removeGuest(id);
};
let ready = true;
@@ -66,17 +88,21 @@ export function startServer(opts: StartOptions) {
sessions,
roles,
settings,
rooms,
db,
ipOf,
discordExchange: opts.discordExchange,
health: () => ({ ok: ready, connections: gateway.connectionCount }),
health: () => ({ ok: ready, connections: gateway.connectionCount, rooms: rooms.rooms.size }),
removeGuest,
admin: {
audit,
db,
checkEmbed: opts.checkEmbed,
onCatalogChange: () => rooms.recountAll(),
disconnectUser: (id) => gateway.disconnectUser(id),
stats: () => ({
connections: gateway.connectionCount,
rooms: { total: rooms.rooms.size, playing: [...rooms.rooms.values()].filter((r) => r.status === 'playing').length },
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
}),
@@ -113,6 +139,15 @@ export function startServer(opts: StartOptions) {
},
});
const roomSweeper = setInterval(() => rooms.sweep(), 10_000);
// The collector runs in its own process, so lobbies re-count now and then to show newly matched songs.
const roomRecount = setInterval(() => {
try {
rooms.recountAll();
} catch (e) {
log('warn', 'room recount failed', { err: String(e) });
}
}, 60_000);
const sweeper = setInterval(() => {
try {
sessions.purgeExpired();
@@ -125,12 +160,14 @@ export function startServer(opts: StartOptions) {
const stop = async () => {
ready = false;
clearInterval(sweeper);
clearInterval(roomSweeper);
clearInterval(roomRecount);
gateway.shutdown();
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
db.close();
};
return { server, stop, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
return { server, stop, users, sessions, db, gateway, settings, roles, rooms, purgeIdleGuests };
}
async function serveFile(root: string, pathname: string): Promise<Response> {

View File

@@ -0,0 +1,93 @@
/**
* Which songs a room's settings select (docs/04, docs/12 Q7·Q9).
* - 장르: same group "또는", different groups "그리고"; empty = 전체
* - 난이도 N: a song qualifies when any applicable scope has level N: 'all', each chosen genre, each decade the year range touches
* - 재생 가능: listening modes need a confirmed (matched, embeddable) YouTube video; the lyrics mode needs lyrics
*/
import type { Database } from 'bun:sqlite';
import type { RoomConfig } from '@mq/shared';
type Args = (string | number)[];
function where(db: Database, c: RoomConfig): { sql: string; args: Args } {
const w: string[] = ['s.deleted_at IS NULL', 's.hidden = 0'];
const args: Args = [];
if (c.genres.length) {
const groups = new Map<string, string[]>();
const known = db.query<{ id: string; grp: string }, []>('SELECT id, grp FROM genres').all();
for (const g of c.genres) {
const grp = known.find((k) => k.id === g)?.grp;
if (!grp) continue;
groups.set(grp, [...(groups.get(grp) ?? []), g]);
}
for (const ids of groups.values()) {
w.push(`EXISTS (SELECT 1 FROM song_genres g WHERE g.song_id = s.id AND g.genre_id IN (${ids.map(() => '?').join(',')}))`);
args.push(...ids);
}
}
if (c.yearFrom) (w.push('s.year >= ?'), args.push(c.yearFrom));
if (c.yearTo) (w.push('s.year <= ?'), args.push(c.yearTo));
const scopes = ['all', ...c.genres.map((g) => `genre:${g}`)];
if (c.yearFrom || c.yearTo) {
const from = Math.floor((c.yearFrom ?? 1950) / 10) * 10;
const to = Math.floor((c.yearTo ?? new Date().getFullYear()) / 10) * 10;
for (let d = from; d <= to; d += 10) scopes.push(`decade:${d}`);
}
w.push(`EXISTS (SELECT 1 FROM song_levels l WHERE l.song_id = s.id AND l.level = ? AND l.scope IN (${scopes.map(() => '?').join(',')}))`);
args.push(c.level, ...scopes);
if (c.mode === 'artist') {
if (!c.artistIds.length) w.push('0');
else {
w.push(`EXISTS (SELECT 1 FROM song_artists a WHERE a.song_id = s.id AND a.artist_id IN (${c.artistIds.map(() => '?').join(',')}))`);
args.push(...c.artistIds);
}
}
return { sql: w.join(' AND '), args };
}
function playable(c: RoomConfig): string {
return c.mode === 'lyrics' ? 'EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id)' : "s.youtube_status = 'matched' AND s.embeddable = 1";
}
/** playable = songs a game can use now; total = also those still waiting for a YouTube match (lyrics mode: same). */
export function countPool(db: Database, c: RoomConfig): { playable: number; total: number } {
const { sql, args } = where(db, c);
const r = db
.query<{ total: number; playable: number | null }, Args>(`SELECT COUNT(*) total, SUM(${playable(c)}) playable FROM songs s WHERE ${sql}`)
.get(...args)!;
return { total: r.total, playable: r.playable ?? 0 };
}
/** Playable song ids for a game (stage 5 shuffles and picks from these), excluding already played ones. */
export function poolIds(db: Database, c: RoomConfig, exclude: number[] = []): number[] {
const { sql, args } = where(db, c);
const ex = exclude.length ? ` AND s.id NOT IN (${exclude.map(() => '?').join(',')})` : '';
return db
.query<{ id: number }, Args>(`SELECT s.id FROM songs s WHERE ${sql} AND ${playable(c)}${ex}`)
.all(...args, ...exclude)
.map((r) => r.id);
}
/** Year span of the catalog, for the 연도 slider. */
export function yearBounds(db: Database): { min: number; max: number } {
const r = db.query<{ min: number | null; max: number | null }, []>('SELECT MIN(year) min, MAX(year) max FROM songs WHERE deleted_at IS NULL AND year IS NOT NULL').get()!;
return { min: r.min ?? 1980, max: Math.max(r.max ?? 0, new Date().getFullYear()) };
}
/** 가수 선택 search (docs/04 가수노래): name or alias, with song counts. */
export function searchArtists(db: Database, q: string, limit = 20) {
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
return db
.query<{ id: number; name: string; songs: number }, [string, string, number]>(
`SELECT a.id, a.name, COUNT(DISTINCT sa.song_id) songs FROM artists a
JOIN song_artists sa ON sa.artist_id = a.id JOIN songs s ON s.id = sa.song_id AND s.deleted_at IS NULL
WHERE a.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM artist_aliases x WHERE x.artist_id = a.id AND x.alias LIKE ? ESCAPE '\\')
GROUP BY a.id ORDER BY songs DESC, a.name LIMIT ?`,
)
.all(like, like, limit);
}
export function artistsByIds(db: Database, ids: number[]) {
if (!ids.length) return [];
return db.query<{ id: number; name: string }, number[]>(`SELECT id, name FROM artists WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
}

View File

@@ -5,20 +5,28 @@
import type { Server, ServerWebSocket } from 'bun';
import { ClientMessage, MAX_CLIENT_MESSAGE_BYTES, PROTOCOL, type ServerMessage } from '@mq/shared';
import type { LogFn } from '../server';
import type { RoomManager } from '../rooms/manager';
import { TokenBucket } from './rate-limit';
export interface WsData {
userId: string;
connId: number;
/** The room this socket is in (docs/04). */
roomCode?: string;
}
export interface GatewayDeps {
log: LogFn;
onClose?: (userId: string) => void;
rooms: RoomManager;
/** Chat flood guard (docs/12 채팅): off by default, the admin turns it on in site settings. */
chatGuard?: () => { on: boolean; ratePerSec: number; burst: number };
}
export class Gateway {
private conns = new Map<string, Set<ServerWebSocket<WsData>>>();
private nextId = 1;
private buckets = new Map<number, TokenBucket>();
constructor(private d: GatewayDeps) {}
@@ -57,7 +65,7 @@ export class Gateway {
this.conns.set(ws.data.userId, set);
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now() });
},
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer) => {
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer): void => {
const text = typeof raw === 'string' ? raw : raw.toString();
if (text.length > MAX_CLIENT_MESSAGE_BYTES) return this.send(ws, { t: 'error', message: '메시지가 너무 길어요.' });
let json: unknown;
@@ -69,12 +77,41 @@ export class Gateway {
const parsed = ClientMessage.safeParse(json);
if (!parsed.success) return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
const m = parsed.data;
const rooms = this.d.rooms;
const err = (e: string | null): void => {
if (e) this.send(ws, { t: 'error', message: e });
};
switch (m.t) {
case 'ping':
return this.send(ws, { t: 'pong', c: m.c, s: Date.now() });
case 'join':
return err(rooms.join(ws, m.code, m.password));
case 'leave':
return rooms.leave(ws);
case 'config':
return err(rooms.setConfig(ws, m.patch));
case 'password':
return err(rooms.setPassword(ws, m.value));
case 'ready':
return err(rooms.ready(ws, m.on));
case 'kick':
return err(rooms.kick(ws, m.userId));
case 'host':
return err(rooms.giveHost(ws, m.userId));
case 'chat': {
const g = this.d.chatGuard?.();
if (g?.on) {
let b = this.buckets.get(ws.data.connId);
if (!b) this.buckets.set(ws.data.connId, (b = new TokenBucket(g.ratePerSec, g.burst)));
if (!b.take()) return this.send(ws, { t: 'error', message: '채팅을 너무 빨리 보내고 있어요. 잠깐 쉬었다 보내 주세요.' });
}
return err(rooms.chat(ws, m.text, m.n));
}
}
},
close: (ws: ServerWebSocket<WsData>) => {
this.buckets.delete(ws.data.connId);
this.d.rooms.detach(ws);
const set = this.conns.get(ws.data.userId);
set?.delete(ws);
if (set && set.size === 0) {