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

183
apps/web/src/net/socket.ts Normal file
View File

@@ -0,0 +1,183 @@
/**
* One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1).
*/
import { create } from 'zustand';
import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
interface RoomState {
status: Status;
code: string | null;
room: RoomView | null;
/** serverNow ≈ Date.now() + offset */
offset: number;
rtt: number | null;
/** Join failed with this message (wrong password, unknown room…). */
joinError: string | null;
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere';
/** Room chat in seq order (docs/06), last CHAT_KEEP lines. */
chat: ChatLine[];
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
pending: { n: string; text: string }[];
}
const CHAT_KEEP = 200;
/** The room this tab was last in: tells "the server restarted and the room is gone" apart from a wrong code. */
const LAST_ROOM_KEY = 'mq:lastRoom';
export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.';
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] }));
let ws: WebSocket | null = null;
let retry = 0;
let password: string | undefined;
let pingTimer: ReturnType<typeof setInterval> | null = null;
/** A join is on its way: the next error is the join's answer. */
let joining = false;
let nonce = 0;
function lastRoom(): string | null {
try {
return sessionStorage.getItem(LAST_ROOM_KEY);
} catch {
return null;
}
}
function setLastRoom(code: string | null): void {
try {
if (code) sessionStorage.setItem(LAST_ROOM_KEY, code);
else sessionStorage.removeItem(LAST_ROOM_KEY);
} catch {
/* private mode */
}
}
function sendJoin(code: string): void {
joining = true;
send({ t: 'join', code, password });
}
const samples: { sent: number; received: number; server: number }[] = [];
function send(m: unknown): void {
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m));
}
function syncClock(): void {
for (let i = 0; i < 5; i++) setTimeout(() => send({ t: 'ping', c: Date.now() }), i * 150);
}
function onMessage(m: ServerMessage): void {
switch (m.t) {
case 'welcome': {
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
retry = 0;
syncClock();
const code = useRoom.getState().code;
if (code) sendJoin(code);
return;
}
case 'pong': {
samples.push({ sent: m.c, received: Date.now(), server: m.s });
if (samples.length > 10) samples.shift();
let best: { offset: number; rtt: number } | null = null;
for (const s of samples) {
const rtt = s.received - s.sent;
const offset = s.server - (s.sent + rtt / 2);
if (!best || rtt < best.rtt) best = { offset, rtt };
}
if (best) useRoom.setState({ offset: best.offset, rtt: best.rtt });
return;
}
case 'room':
if (m.room.code === useRoom.getState().code) {
joining = false;
setLastRoom(m.room.code);
useRoom.setState({ room: m.room, joinError: null, left: null });
}
return;
case 'left':
if (m.code === useRoom.getState().code) {
setLastRoom(null);
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
}
return;
case 'chatlog':
// (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone.
if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] });
return;
case 'chat':
if (m.code === useRoom.getState().code) {
const st = useRoom.getState();
useRoom.setState({
chat: [...st.chat, m.line].slice(-CHAT_KEEP),
pending: m.line.n ? st.pending.filter((p) => p.n !== m.line.n) : st.pending,
});
}
return;
case 'notice':
toast(m.text);
return;
case 'error': {
const st = useRoom.getState();
if (joining && st.code) {
joining = false;
// The room was there a moment ago (this tab was in it): the server restarted and rooms live in memory (docs/04 결정 1).
// Kept after that, so a refresh still explains it.
const gone = m.message.includes('찾을 수 없') && lastRoom() === st.code;
useRoom.setState({ room: null, joinError: gone ? ROOM_GONE_TEXT : m.message });
} else toast(m.message, 'error');
return;
}
}
}
function connect(): void {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${proto}://${location.host}/ws`);
useRoom.setState({ status: retry ? 'reconnecting' : 'connecting' });
ws.onmessage = (e) => onMessage(JSON.parse(String(e.data)) as ServerMessage);
ws.onclose = () => {
ws = null;
if (useRoom.getState().status === 'idle') return;
useRoom.setState({ status: 'reconnecting' });
const wait = Math.min(10_000, 500 * 2 ** retry++);
setTimeout(() => useRoom.getState().status !== 'idle' && connect(), wait);
};
}
export const socket = {
start(): void {
if (ws) return;
connect();
pingTimer ??= setInterval(syncClock, 30_000);
},
stop(): void {
useRoom.setState({ status: 'idle' });
ws?.close();
ws = null;
if (pingTimer) clearInterval(pingTimer);
pingTimer = null;
},
join(code: string, pw?: string): void {
password = pw;
const st = useRoom.getState();
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) });
socket.start();
sendJoin(code);
},
leave(): void {
send({ t: 'leave' });
setLastRoom(null);
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
},
chat(text: string): void {
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
useRoom.setState((st) => ({ pending: [...st.pending, { n, text }] }));
send({ t: 'chat', text, n });
},
send,
};
/** Server clock (ms) for countdowns and synced playback. */
export const serverNow = () => Date.now() + useRoom.getState().offset;