- lib/motion: useMotionSettled에서 12초 상한을 없앰(명시한 maxMs만) - 서버: 클라이언트 settled(seq)를 받으면 그 사람의 제한 시간을 연출에 걸린 만큼 늦춤(보고 전에는 최대 15초×속도, 보고한 적 없는 화면·컴퓨터·실시간 게임은 예전 그대로), 마감이 바뀌면 deadline 메시지 - 바퀴벌레 포커: 게임을 끝낸 판정은 패배 배너까지 다 끝난 뒤에 끝 화면 - 증강 윷놀이: 선택 창 열림을 후보 묶음마다 따로, 이의있음! 재선택 창은 이의있음! 화면이 사라진 뒤에 - e2e/motion.e2e.ts: 30초 움직임·바퀴벌레 포커 마지막 판정·이의있음! 재선택·다빈치 ×1/8 회귀 확인, 방 타이머 단위 테스트 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
393 lines
14 KiB
TypeScript
393 lines
14 KiB
TypeScript
/**
|
||
* WebSocket client with auto-reconnect, seq ordering, ping/clock sync (docs/03 §4–§8).
|
||
* Room/game state lives in the zustand store below; components only read it.
|
||
*/
|
||
import { create } from 'zustand';
|
||
import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite';
|
||
import { toast } from '../store/toast';
|
||
import { markOutdated, noteServerBuild } from '../lib/update';
|
||
import { setGameSpeed } from '../lib/motion';
|
||
import { setChatSound } from '../lib/feedback';
|
||
|
||
export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline';
|
||
|
||
export interface ChatLine {
|
||
id: number;
|
||
from: PublicUser | null;
|
||
text: string;
|
||
at: number;
|
||
/** Arrived just now (not resent history on joining): plays the chat sound. */
|
||
live: boolean;
|
||
}
|
||
|
||
export interface GameState {
|
||
seq: number;
|
||
/**
|
||
* The room's game number this view belongs to. The server sends the new room before a new game's first state,
|
||
* so this is read from the room when the state arrives. The room page remounts the board when it changes, so
|
||
* nothing a board remembers (the last effect / move it showed) leaks into the next game.
|
||
*/
|
||
gameNo: number;
|
||
view: unknown;
|
||
active: string[];
|
||
deadline: number | null;
|
||
events: unknown[];
|
||
}
|
||
|
||
interface RoomStore {
|
||
status: ConnStatus;
|
||
me: PublicUser | null;
|
||
code: string | null;
|
||
room: RoomView | null;
|
||
roomSeq: number;
|
||
game: GameState | null;
|
||
result: GameResultView | null;
|
||
chat: ChatLine[];
|
||
emotes: { id: number; from: string; emote: string }[];
|
||
/** People typing right now: user id → where and until when (ms, local clock). */
|
||
typing: Record<string, { ch: 'room' | 'game'; until: number }>;
|
||
pending: number | null;
|
||
slow: boolean;
|
||
rttMs: number | null;
|
||
clockOffset: number;
|
||
joinError: string | null;
|
||
kicked: boolean;
|
||
}
|
||
|
||
/** A "입력 중" signal lasts this long unless renewed (the typer renews it every couple of seconds). */
|
||
const TYPING_MS = 5000;
|
||
const withoutTyping = (t: RoomStore['typing'], id: string | undefined): RoomStore['typing'] => {
|
||
if (!id || !(id in t)) return t;
|
||
const { [id]: _gone, ...rest } = t;
|
||
return rest;
|
||
};
|
||
|
||
export const useRoom = create<RoomStore>(() => ({
|
||
status: 'idle',
|
||
me: null,
|
||
code: null,
|
||
room: null,
|
||
roomSeq: -1,
|
||
game: null,
|
||
result: null,
|
||
chat: [],
|
||
emotes: [],
|
||
typing: {},
|
||
pending: null,
|
||
slow: false,
|
||
rttMs: null,
|
||
clockOffset: 0,
|
||
joinError: null,
|
||
kicked: false,
|
||
}));
|
||
|
||
const BACKOFF = [500, 1000, 2000, 4000, 8000];
|
||
const MAX_BACKOFF = 10_000;
|
||
const PING_EVERY = 10_000;
|
||
const PONG_TIMEOUT = 5_000;
|
||
|
||
class GameSocket {
|
||
private ws: WebSocket | null = null;
|
||
private attempt = 0;
|
||
private retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private pingTimer: ReturnType<typeof setInterval> | null = null;
|
||
private pongTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private pendingTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private offsets: number[] = [];
|
||
private wanted = false;
|
||
private cs = Date.now();
|
||
private chatId = 1;
|
||
private onMessageHooks = new Set<(m: ServerMessage) => void>();
|
||
|
||
constructor() {
|
||
if (typeof window !== 'undefined') {
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.visibilityState === 'visible') this.kick();
|
||
});
|
||
window.addEventListener('online', () => this.kick());
|
||
window.addEventListener('offline', () => useRoom.setState({ status: 'offline' }));
|
||
}
|
||
}
|
||
|
||
/** Start (or keep) a connection. Safe to call repeatedly. */
|
||
start(): void {
|
||
this.wanted = true;
|
||
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) return;
|
||
this.open();
|
||
}
|
||
|
||
stop(): void {
|
||
this.wanted = false;
|
||
this.clearTimers();
|
||
this.ws?.close();
|
||
this.ws = null;
|
||
useRoom.setState({ status: 'idle' });
|
||
}
|
||
|
||
/** Reconnect immediately if we should be connected but are not. */
|
||
private kick(): void {
|
||
if (!this.wanted) return;
|
||
if (!this.ws || this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSING) {
|
||
if (this.retryTimer) clearTimeout(this.retryTimer);
|
||
this.retryTimer = null;
|
||
this.open();
|
||
} else if (this.ws.readyState === WebSocket.OPEN) {
|
||
this.ping();
|
||
}
|
||
}
|
||
|
||
private open(): void {
|
||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||
const ws = new WebSocket(`${proto}//${location.host}/ws`);
|
||
this.ws = ws;
|
||
useRoom.setState({ status: this.attempt === 0 ? 'connecting' : 'reconnecting' });
|
||
ws.onopen = () => {
|
||
this.attempt = 0;
|
||
this.pingTimer = setInterval(() => this.ping(), PING_EVERY);
|
||
};
|
||
ws.onmessage = (e) => {
|
||
let m: ServerMessage;
|
||
try {
|
||
m = JSON.parse(String(e.data));
|
||
} catch {
|
||
return;
|
||
}
|
||
this.handle(m);
|
||
for (const h of this.onMessageHooks) h(m);
|
||
};
|
||
ws.onclose = (e) => {
|
||
if (this.ws !== ws) return;
|
||
this.clearTimers();
|
||
this.ws = null;
|
||
const st = useRoom.getState().status;
|
||
if (!this.wanted || st === 'replaced' || useRoom.getState().kicked) return;
|
||
if (e.code === 4401 || e.code === 1008) {
|
||
// Not logged in (session expired): stop and let the page ask for a nickname.
|
||
useRoom.setState({ status: 'idle' });
|
||
this.wanted = false;
|
||
window.dispatchEvent(new Event('bg:unauthorized'));
|
||
return;
|
||
}
|
||
if (this.attempt >= 1) {
|
||
// Repeated failures may mean the session is gone (the upgrade got a 401).
|
||
fetch('/api/me', { credentials: 'same-origin' })
|
||
.then((r) => r.json())
|
||
.then((d: { me: unknown }) => {
|
||
if (d.me === null) {
|
||
this.wanted = false;
|
||
useRoom.setState({ status: 'idle' });
|
||
window.dispatchEvent(new Event('bg:unauthorized'));
|
||
}
|
||
})
|
||
.catch(() => {});
|
||
}
|
||
this.scheduleReconnect();
|
||
};
|
||
}
|
||
|
||
private scheduleReconnect(extraDelay = 0): void {
|
||
const base = BACKOFF[this.attempt] ?? MAX_BACKOFF;
|
||
const jitter = base * (0.7 + Math.random() * 0.6);
|
||
this.attempt++;
|
||
useRoom.setState({ status: navigator.onLine === false ? 'offline' : 'reconnecting' });
|
||
this.retryTimer = setTimeout(() => {
|
||
this.retryTimer = null;
|
||
if (this.wanted) this.open();
|
||
}, jitter + extraDelay);
|
||
}
|
||
|
||
private clearTimers(): void {
|
||
if (this.pingTimer) clearInterval(this.pingTimer);
|
||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||
this.pingTimer = null;
|
||
this.pongTimer = null;
|
||
}
|
||
|
||
private ping(): void {
|
||
if (this.ws?.readyState !== WebSocket.OPEN || this.pongTimer) return;
|
||
this.send({ t: 'ping', ts: Date.now() });
|
||
this.pongTimer = setTimeout(() => {
|
||
this.pongTimer = null;
|
||
// Dead connection: force a reconnect.
|
||
this.ws?.close();
|
||
}, PONG_TIMEOUT);
|
||
}
|
||
|
||
send(m: unknown): boolean {
|
||
if (this.ws?.readyState !== WebSocket.OPEN) return false;
|
||
this.ws.send(JSON.stringify(m));
|
||
return true;
|
||
}
|
||
|
||
subscribe(fn: (m: ServerMessage) => void): () => void {
|
||
this.onMessageHooks.add(fn);
|
||
return () => this.onMessageHooks.delete(fn);
|
||
}
|
||
|
||
// ------------------------------------------------------------- room commands
|
||
|
||
join(code: string, as: 'player' | 'spectator' = 'player'): void {
|
||
const cur = useRoom.getState();
|
||
if (cur.code !== code) {
|
||
useRoom.setState({ code, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, joinError: null, kicked: false, pending: null });
|
||
}
|
||
this.start();
|
||
this.send({ t: 'join', code, as });
|
||
}
|
||
|
||
leave(): void {
|
||
this.send({ t: 'leave' });
|
||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null });
|
||
}
|
||
|
||
/** Left the room page (홈, 규칙…) without leaving: the seat stays, but the room no longer counts us as there. */
|
||
detach(code: string): void {
|
||
if (useRoom.getState().code !== code) return;
|
||
this.send({ t: 'detach' });
|
||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null });
|
||
}
|
||
|
||
/**
|
||
* Sends a game action; returns false when not connected. A game's chat line (`type: 'chat'`) is sent on its own:
|
||
* it does not mark the board as waiting, so typing never locks the game's buttons and lines never wait on each other.
|
||
*/
|
||
act(a: unknown): boolean {
|
||
const cs = ++this.cs;
|
||
if (!this.send({ t: 'act', cs, a })) {
|
||
toast('연결이 끊겨 있어요. 다시 연결되면 해 주세요.', 'error');
|
||
return false;
|
||
}
|
||
if ((a as { type?: unknown } | null)?.type === 'chat') return true;
|
||
useRoom.setState({ pending: cs, slow: false });
|
||
if (this.pendingTimer) clearTimeout(this.pendingTimer);
|
||
this.pendingTimer = setTimeout(() => {
|
||
if (useRoom.getState().pending === cs) {
|
||
useRoom.setState({ slow: true });
|
||
this.ping();
|
||
}
|
||
}, 2000);
|
||
return true;
|
||
}
|
||
|
||
/** Server time estimate. */
|
||
now(): number {
|
||
return Date.now() + useRoom.getState().clockOffset;
|
||
}
|
||
|
||
// ------------------------------------------------------------- inbound
|
||
|
||
private handle(m: ServerMessage): void {
|
||
const st = useRoom.getState();
|
||
switch (m.t) {
|
||
case 'welcome': {
|
||
if (m.protocol !== PROTOCOL) markOutdated();
|
||
else noteServerBuild(m.build);
|
||
useRoom.setState({ status: 'open', me: m.me });
|
||
this.offsets = [m.serverTime - Date.now()];
|
||
useRoom.setState({ clockOffset: this.offsets[0]! });
|
||
// Re-join the room we were in (reconnect path).
|
||
if (st.code && !st.kicked) this.send({ t: 'join', code: st.code, as: 'player' });
|
||
break;
|
||
}
|
||
case 'room':
|
||
if (m.seq >= st.roomSeq || m.room.code !== st.room?.code) {
|
||
if (m.room.gameSpeed !== undefined) setGameSpeed(m.room.gameSpeed);
|
||
if (m.room.chatSound !== undefined) setChatSound(m.room.chatSound);
|
||
useRoom.setState({ room: m.room, roomSeq: m.seq, joinError: null });
|
||
if (m.room.status === 'playing' && st.result) useRoom.setState({ result: null });
|
||
}
|
||
break;
|
||
case 'state': {
|
||
if (st.game && m.seq < st.game.seq) break; // stale
|
||
const patch: Partial<RoomStore> = {
|
||
game: { seq: m.seq, gameNo: st.room?.gameNo ?? 0, view: m.view, active: m.active, deadline: m.deadline, events: m.events },
|
||
};
|
||
if (m.cs !== undefined && m.cs === st.pending) {
|
||
patch.pending = null;
|
||
patch.slow = false;
|
||
}
|
||
useRoom.setState(patch);
|
||
break;
|
||
}
|
||
case 'deadline':
|
||
// A player's screen finished animating: their clock started, so the deadline moved (same view).
|
||
if (st.game) useRoom.setState({ game: { ...st.game, deadline: m.deadline } });
|
||
break;
|
||
case 'reject':
|
||
if (m.cs === st.pending) useRoom.setState({ pending: null, slow: false });
|
||
toast(m.reason, 'error');
|
||
break;
|
||
case 'result':
|
||
useRoom.setState({ result: m.result });
|
||
break;
|
||
case 'chat':
|
||
useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at, live: !m.replay }].slice(-100), typing: withoutTyping(st.typing, m.from?.id) });
|
||
break;
|
||
case 'typing':
|
||
if (m.on) {
|
||
const until = Date.now() + TYPING_MS;
|
||
useRoom.setState({ typing: { ...st.typing, [m.from]: { ch: m.ch, until } } });
|
||
setTimeout(() => {
|
||
const cur = useRoom.getState().typing[m.from];
|
||
if (cur && cur.until <= Date.now()) useRoom.setState((s) => ({ typing: withoutTyping(s.typing, m.from) }));
|
||
}, TYPING_MS + 50);
|
||
} else useRoom.setState({ typing: withoutTyping(st.typing, m.from) });
|
||
break;
|
||
case 'emote': {
|
||
const id = this.chatId++;
|
||
useRoom.setState({ emotes: [...st.emotes, { id, from: m.from, emote: m.id }].slice(-10) });
|
||
setTimeout(() => useRoom.setState((s) => ({ emotes: s.emotes.filter((e) => e.id !== id) })), 2500);
|
||
break;
|
||
}
|
||
case 'notice':
|
||
toast(m.message);
|
||
break;
|
||
case 'error':
|
||
if (m.code === 'room-not-found' || m.code === 'join-failed') useRoom.setState({ joinError: m.message });
|
||
else toast(m.message, 'error');
|
||
break;
|
||
case 'pong': {
|
||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||
this.pongTimer = null;
|
||
const now = Date.now();
|
||
const rtt = now - m.ts;
|
||
const offset = m.serverTime + rtt / 2 - now;
|
||
this.offsets = [...this.offsets, offset].slice(-5);
|
||
const sorted = [...this.offsets].sort((a, b) => a - b);
|
||
useRoom.setState({ rttMs: rtt, clockOffset: sorted[Math.floor(sorted.length / 2)]! });
|
||
if (st.slow && st.pending) {
|
||
// Connection is alive but our action got no answer: resync instead of resending.
|
||
this.send({ t: 'sync' });
|
||
useRoom.setState({ pending: null, slow: false });
|
||
}
|
||
break;
|
||
}
|
||
case 'bye':
|
||
if (m.reason === 'restart') {
|
||
toast('서버를 업데이트하고 있어요. 잠시 후 자동으로 다시 연결돼요.');
|
||
this.attempt = 0;
|
||
this.ws?.close();
|
||
// onclose schedules a reconnect; add 1–3s so clients don't all return at once.
|
||
this.ws = null;
|
||
this.clearTimers();
|
||
this.scheduleReconnect(1000 + Math.random() * 2000);
|
||
} else if (m.reason === 'replaced') {
|
||
useRoom.setState({ status: 'replaced' });
|
||
} else if (m.reason === 'kicked') {
|
||
useRoom.setState({ kicked: true, joinError: '방장이 방에서 내보냈어요.' });
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
/** "Use here" after another tab took over. */
|
||
reclaim(): void {
|
||
useRoom.setState({ status: 'connecting' });
|
||
this.wanted = true;
|
||
this.attempt = 0;
|
||
this.open();
|
||
}
|
||
}
|
||
|
||
export const socket = new GameSocket();
|