채팅을 따로 분리해 속도 제한 없이: 방 채팅·마피아·라이어·그림 맞히기(그리기 전) 채팅의 줄 간격 제한(chat-pace)과 브라우저 대기열을 없애 치는 대로 바로 보냄. 서버 연결당 공용 한도(초당 20개)를 채팅·입력 중 신호가 같이 써서 빠르게 치면 15번째 줄부터 조용히 사라지던 문제도: 채팅은 별도 한도(초당 50, 최대 200, 매크로 도배 방지용)로 분리. 게임 채팅은 보내는 동안 게임 버튼을 잠그지 않음(pending 미설정)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -57,11 +57,10 @@ describe('마피아 room flow', () => {
|
||||
expect(all).not.toContain(`"role":"mafia"`);
|
||||
}
|
||||
// Rate limit (validate gets the server clock), and the system-only phase timer cannot be sent by clients.
|
||||
// A quick run of lines all goes through; only a flood is refused.
|
||||
for (let i = 0; i < 5; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` });
|
||||
expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(5);
|
||||
room.act(mafia, 2, { type: 'chat', channel: 'mafia', text: '또' });
|
||||
expect(conns[mafia]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 2, reason: '조금 천천히 보내 주세요.' });
|
||||
// No pace limit: a long run of lines in the same instant all goes through.
|
||||
for (let i = 0; i < 20; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` });
|
||||
expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(20);
|
||||
expect(conns[mafia]!.msgs.some((m) => m.t === 'reject')).toBe(false);
|
||||
room.act(town[0]!, 3, { type: 'phaseTimeout' });
|
||||
expect(conns[town[0]!]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 3, reason: '잘못된 요청이에요.' });
|
||||
expect(state().phase.kind).toBe('night');
|
||||
|
||||
@@ -228,18 +228,15 @@ describe('윷놀이 room rules', () => {
|
||||
});
|
||||
|
||||
describe('Room chat (2026-10-13)', () => {
|
||||
test('a quick burst of lines all goes through; a flood is still stopped', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
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');
|
||||
for (let i = 0; i < 6; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull();
|
||||
expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.');
|
||||
clock.advance(300);
|
||||
expect(room.chat('A', '0.3초 뒤')).toBeNull();
|
||||
expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.');
|
||||
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(['줄 0', '줄 1', '줄 2', '줄 3', '줄 4', '줄 5', '0.3초 뒤']);
|
||||
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('typing at a person\'s pace (a line every 0.4 s) never waits', () => {
|
||||
|
||||
@@ -14,7 +14,6 @@ import { BotBrain, type BotActivity } from '../ai/brain';
|
||||
import type { Llm } from '../ai/llm';
|
||||
import type { LogEntry, RoomStore } from './store';
|
||||
import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings';
|
||||
import { chatNext, chatWait } from '@bg/games/chat-pace';
|
||||
|
||||
export interface Conn {
|
||||
userId: string;
|
||||
@@ -152,8 +151,6 @@ export class Room {
|
||||
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private recentCs = new Map<string, number[]>();
|
||||
private lastChatAt = new Map<string, number>();
|
||||
/** Room chat pace per person (`chat-pace.ts`). */
|
||||
private chatPace = new Map<string, number>();
|
||||
/** When each person last said they were typing (to drop repeats within a second). */
|
||||
private typingAt = new Map<string, number>();
|
||||
private consecutiveErrors = 0;
|
||||
@@ -813,10 +810,8 @@ export class Room {
|
||||
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
|
||||
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
|
||||
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
|
||||
// No pace limit: every line goes out as soon as it is typed (the socket's own flood guard still applies).
|
||||
const now = this.now();
|
||||
// Quick lines in a row all go through at once; only a flood stops.
|
||||
if (chatWait(this.chatPace.get(userId), now) > 0) return '조금 천천히 보내 주세요.';
|
||||
this.chatPace.set(userId, chatNext(this.chatPace.get(userId), now));
|
||||
this.typingAt.delete(userId);
|
||||
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
||||
if (!clean) return null;
|
||||
|
||||
@@ -216,6 +216,24 @@ describe('M1 integration scenarios', () => {
|
||||
expect(h.res.status).toBe(200);
|
||||
});
|
||||
|
||||
test('10b. chat has its own budget: a fast run of lines (with 입력 중 signals) all arrives and leaves game moves untouched', async () => {
|
||||
const s = start();
|
||||
const a = await client(s, '빠른손');
|
||||
const code = await createRoom(s, a);
|
||||
await join(a, code);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
a.send({ t: 'typing', on: true, ch: 'room' });
|
||||
a.send({ t: 'chat', text: `줄 ${i}` });
|
||||
a.send({ t: 'typing', on: false, ch: 'room' });
|
||||
}
|
||||
await a.next('chat', (m) => m.text === '줄 59');
|
||||
expect(a.messages.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(Array.from({ length: 60 }, (_, i) => `줄 ${i}`));
|
||||
// The general budget is still full: a burst of 30 pings all answered.
|
||||
for (let i = 0; i < 30; i++) a.send({ t: 'ping', ts: i });
|
||||
await sleep(200);
|
||||
expect(a.messages.filter((m) => m.t === 'pong').length).toBe(30);
|
||||
});
|
||||
|
||||
test('11. malformed / oversized / schema-invalid messages', async () => {
|
||||
const s = start();
|
||||
const a = await client(s, '이상한값');
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface WsData {
|
||||
userId: string;
|
||||
connId: number;
|
||||
bucket: TokenBucket;
|
||||
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
|
||||
chatBucket: TokenBucket;
|
||||
strikes: number;
|
||||
room: string | null;
|
||||
conn: Conn | null;
|
||||
@@ -26,6 +28,21 @@ export interface GatewayDeps {
|
||||
}
|
||||
|
||||
export const MAX_CONNS_PER_USER = 5;
|
||||
|
||||
/**
|
||||
* Chat budget per socket: far above any typing speed (a line costs up to three messages: 입력 중 on, the line, off),
|
||||
* only a script flooding the room is cut off.
|
||||
*/
|
||||
const CHAT_RATE_PER_SEC = 50;
|
||||
const CHAT_BURST = 200;
|
||||
|
||||
/** Room chat, game chat (마피아·라이어 게임·그림 맞히기 `act` with `type: 'chat'`) and the "입력 중" signal. */
|
||||
function isChatMessage(m: unknown): boolean {
|
||||
if (typeof m !== 'object' || m === null) return false;
|
||||
const { t, a } = m as { t?: unknown; a?: unknown };
|
||||
if (t === 'chat' || t === 'typing') return true;
|
||||
return t === 'act' && typeof a === 'object' && a !== null && (a as { type?: unknown }).type === 'chat';
|
||||
}
|
||||
const MAX_BUFFERED = 1024 * 1024;
|
||||
|
||||
export class Gateway {
|
||||
@@ -47,7 +64,7 @@ export class Gateway {
|
||||
upgrade(req: Request, server: Server<WsData>, userId: string): Response | undefined {
|
||||
if (this.closing) return new Response('restarting', { status: 503 });
|
||||
if ((this.byUser.get(userId)?.size ?? 0) >= MAX_CONNS_PER_USER) return new Response('too many connections', { status: 429 });
|
||||
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), strikes: 0, room: null, conn: null };
|
||||
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST), strikes: 0, room: null, conn: null };
|
||||
if (server.upgrade(req, { data })) return undefined;
|
||||
return new Response('upgrade failed', { status: 400 });
|
||||
}
|
||||
@@ -96,23 +113,28 @@ export class Gateway {
|
||||
ws.close(1009, 'message too big');
|
||||
return;
|
||||
}
|
||||
if (!ws.data.bucket.take()) {
|
||||
let json: unknown;
|
||||
let badJson = false;
|
||||
try {
|
||||
json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
|
||||
} catch {
|
||||
badJson = true;
|
||||
}
|
||||
const bucket = !badJson && isChatMessage(json) ? ws.data.chatBucket : ws.data.bucket;
|
||||
if (!bucket.take()) {
|
||||
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
|
||||
return;
|
||||
}
|
||||
let parsed: ClientMessage;
|
||||
try {
|
||||
const json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
|
||||
const r = ClientMessage.safeParse(json);
|
||||
if (!r.success) {
|
||||
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
parsed = r.data;
|
||||
} catch {
|
||||
if (badJson) {
|
||||
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
const r = ClientMessage.safeParse(json);
|
||||
if (!r.success) {
|
||||
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
const parsed: ClientMessage = r.data;
|
||||
try {
|
||||
this.dispatch(ws, parsed);
|
||||
} catch (err) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { create } from 'zustand';
|
||||
import { socket, useRoom } from '../net/socket';
|
||||
import { useChatOutbox, useTypingSignal } from '../lib/chat-input';
|
||||
import { useTypingSignal } from '../lib/chat-input';
|
||||
import { useStickToBottom } from '../lib/useStickToBottom';
|
||||
import { BotActivity } from './BotActivity';
|
||||
import { ChatMessage, sameRun } from './ChatMessage';
|
||||
@@ -16,7 +16,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
const [text, setText] = useState('');
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t }));
|
||||
const send = (t: string) => socket.send({ t: 'chat', text: t });
|
||||
const typing = useTypingSignal('room', room.chatEnabled);
|
||||
const lastId = chat.at(-1)?.id ?? 0;
|
||||
useEffect(() => {
|
||||
|
||||
@@ -15,7 +15,7 @@ import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
import { useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -426,7 +426,7 @@ const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : n
|
||||
function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const send = useChatOutbox((t: string) => act({ type: 'chat', text: t }));
|
||||
const send = (t: string) => act({ type: 'chat', text: t });
|
||||
const lines: Line[] = [
|
||||
...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })),
|
||||
...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })),
|
||||
|
||||
@@ -15,7 +15,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
import { useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -458,8 +458,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
const [text, setText] = useState('');
|
||||
const [seen, setSeen] = useState<Record<string, number>>({});
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
// Lines typed quickly all go out at once (only a flood waits; the game refuses faster ones).
|
||||
const send = useChatOutbox<{ channel: Channel; text: string }>((m) => act({ type: 'chat', ...m }));
|
||||
// Every line goes out the moment it is typed (no pace limit).
|
||||
const send = (m: { channel: Channel; text: string }) => act({ type: 'chat', ...m });
|
||||
const cur: Channel = tabs.includes(tab) ? tab : 'day';
|
||||
// Day → 전체; night → the first private channel I may write in (only on my own screen).
|
||||
const phaseKey = `${v.day}-${v.phase.kind}`;
|
||||
|
||||
@@ -1,50 +1,13 @@
|
||||
/**
|
||||
* Chat input helpers shared by the room chat and the games with their own chat (마피아, 라이어 게임).
|
||||
* Chat input helper shared by the room chat and the games with their own chat (마피아, 라이어 게임).
|
||||
*
|
||||
* - `useChatOutbox`: every line typed is sent right away, in order. Only past the server's chat pace (`chat-pace.ts`,
|
||||
* a burst of lines and then several a second) do lines wait in a small queue instead of being refused ("조금 천천히").
|
||||
* Chat lines are sent the moment Enter is pressed — no queue and no pace limit.
|
||||
* - `useTypingSignal`: tells the others "입력 중" while there is text in the box (renewed every 2 s, cleared when the
|
||||
* box is emptied or the line is sent, and when the box goes away).
|
||||
*/
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { CHAT_BURST, CHAT_INTERVAL_MS, chatNext, chatWait } from '@bg/games/chat-pace';
|
||||
import { socket } from '../net/socket';
|
||||
|
||||
const MAX_QUEUE = 10;
|
||||
// A little under the server's pace, so lines bunched up on the way (network jitter) are not refused there.
|
||||
const BURST = CHAT_BURST - 1;
|
||||
const INTERVAL = CHAT_INTERVAL_MS + 40;
|
||||
|
||||
export function useChatOutbox<T = string>(send: (item: T) => void) {
|
||||
const queue = useRef<T[]>([]);
|
||||
const next = useRef<number | undefined>(undefined);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const sendRef = useRef(send);
|
||||
sendRef.current = send;
|
||||
const pump = useCallback(() => {
|
||||
timer.current = null;
|
||||
while (queue.current.length) {
|
||||
const now = Date.now();
|
||||
const wait = chatWait(next.current, now, BURST, INTERVAL);
|
||||
if (wait > 0) {
|
||||
timer.current = setTimeout(pump, wait);
|
||||
return;
|
||||
}
|
||||
next.current = chatNext(next.current, now, INTERVAL);
|
||||
sendRef.current(queue.current.shift()!);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
|
||||
return useCallback(
|
||||
(item: T) => {
|
||||
if (queue.current.length >= MAX_QUEUE) return;
|
||||
queue.current.push(item);
|
||||
if (!timer.current) pump();
|
||||
},
|
||||
[pump],
|
||||
);
|
||||
}
|
||||
|
||||
const RENEW_MS = 2000;
|
||||
|
||||
export function useTypingSignal(ch: 'room' | 'game', enabled = true) {
|
||||
|
||||
@@ -238,13 +238,17 @@ class GameSocket {
|
||||
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. */
|
||||
/**
|
||||
* 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(() => {
|
||||
|
||||
Reference in New Issue
Block a user