Files
music_quiz/packages/shared/src/protocol.ts

189 lines
8.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* WebSocket protocol (docs/01 "실시간 메시지"). Stage 1 only has the connection handshake and clock sync;
* room/game messages are added in later stages.
*/
import { z } from 'zod';
import { CHAT_MAX } from './types';
export const PROTOCOL = 1;
export const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024;
export const ClientMessage = z.discriminatedUnion('t', [
/** Clock sync (docs/12 Q1): the client sends its own clock, the server echoes it with the server clock. */
z.object({ t: z.literal('ping'), c: z.number() }),
// ---- rooms (docs/04, stage 4)
z.object({ t: z.literal('join'), code: z.string().regex(/^\d{6}$/), password: z.string().max(40).optional() }),
z.object({ t: z.literal('leave') }),
/** Host only: partial RoomConfig; validated with RoomConfigSchema on the server. */
z.object({ t: z.literal('config'), patch: z.record(z.string(), z.unknown()) }),
/** Host only: room password for visibility 'password' (null clears it). */
z.object({ t: z.literal('password'), value: z.string().min(1).max(40).nullable() }),
z.object({ t: z.literal('ready'), on: z.boolean() }),
z.object({ t: z.literal('kick'), userId: z.string().max(40) }),
z.object({ t: z.literal('host'), userId: z.string().max(40) }),
/** Room chat (docs/06; stage 4 = waiting room only). `n` echoes back so the sender can confirm its optimistic line. */
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX), n: z.string().max(24).optional() }),
// ---- game (docs/05, stage 5~7)
/** Host: start a game from the waiting room. */
z.object({ t: z.literal('start') }),
/** Playback report for question `n` (docs/12 Q1): ready = buffered at the position, blocked = no sound, stall = buffering, clipEnd, error = player error code. */
z.object({ t: z.literal('audio'), n: z.number().int().min(1), ev: z.enum(['ready', 'blocked', 'stall', 'clipEnd', 'error']), code: z.number().int().optional() }),
/** Vote toggles (docs/05 스킵·힌트, docs/12 Q3·Q4). */
z.object({ t: z.literal('vote'), kind: z.enum(['skip', 'hint', 'replay', 'next']) }),
z.object({ t: z.literal('typing'), on: z.boolean() }),
/** Host game controls: pause/resume, end now, 이어풀기, 다시 하기 (back to the waiting room). */
z.object({ t: z.literal('game'), action: z.enum(['pause', 'resume', 'end', 'continue', 'again']) }),
/** Host: leave this player out of this question only (not ready for 30s, docs/12 Q1). */
z.object({ t: z.literal('exclude'), userId: z.string().max(40) }),
/** Host (Discord account): save / load the quiz (docs/12 Q8). */
z.object({ t: z.literal('save'), name: z.string().trim().min(1).max(40) }),
z.object({ t: z.literal('load'), id: z.number().int().positive() }),
]);
export type ClientMessage = z.infer<typeof ClientMessage>;
export interface RoomPlayerView {
id: string;
nickname: string;
avatar: string | null;
kind: 'guest' | 'member';
ready: boolean;
online: boolean;
}
export interface RoomView {
code: string;
hostId: string;
status: 'lobby' | 'playing';
config: import('./room-config').RoomConfig;
hasPassword: boolean;
players: RoomPlayerView[];
/** 조건에 맞는 곡: playable now / including songs still waiting for a YouTube match. */
pool: { playable: number; total: number };
artists: { id: number; name: string }[];
}
/** One chat log line (docs/06 한 줄 로그). `seq` is per room; system lines have no userId. */
export interface ChatLine {
seq: number;
at: number;
userId: string | null;
nickname: string;
text: string;
/** Sender's nonce for its optimistic line. */
n?: string;
/**
* 정답 줄 + 5줄 블록 as one item (docs/06): the correct chat (or a system line when nobody got it) and `노래제목 - 가수`.
* none = skipped / time over (grey block).
*/
answer?: { text: string; none?: boolean };
}
export type GamePhase = 'prepare' | 'play' | 'reveal' | 'result';
export interface GameScore {
id: string;
nickname: string;
score: number;
correct: number;
/** Average answer time of the questions this player got (tie-break, docs/05 점수). */
avgMs: number | null;
online: boolean;
}
export interface GameHistoryItem {
n: number;
title: string;
artist: string;
year: number | null;
level: number | null;
genres: string[];
videoId: string | null;
winnerId: string | null;
winner: string | null;
ms: number | null;
how: 'correct' | 'skip' | 'timeout' | 'end';
}
/** Game state for everyone (docs/05). Never has the video id or the answer of the running question. */
export interface GameView {
phase: GamePhase;
n: number;
total: number;
mode: import('./room-config').Mode;
/** This question's players (heard it from the start); others join at the next one. */
participants: string[];
excluded: string[];
/** Not ready yet (prepare, or re-prepare after a pause), with the server time they started waiting. */
waiting: { id: string; since: number }[];
/** Everyone stopped (docs/12 Q1): buffering / no sound / the host paused. Timers do not run meanwhile. */
paused: null | { reason: 'stall' | 'blocked' | 'host'; who: string[] };
/** Server time the music (re)starts: before it the screen counts 3·2·1. */
startAt: number | null;
/** Question clock: elapsedMs + (runningSince ? serverNow - runningSince : 0); limitMs null = no limit. */
clock: { elapsedMs: number; runningSince: number | null; limitMs: number | null };
/** Seconds of the clip (null = 끝까지 with unknown length) for the progress bar. */
clipSec: number | null;
clipOver: boolean;
hint: string | null;
/** 자동 공개 at this many seconds (null = none / 직접선택). */
hintAtSec: number | null;
lyrics: string[] | null;
/** next = 바로 다음 문제, only during the reveal. */
votes: { skip: string[]; hint: string[]; replay: string[]; next: string[] };
need: { skip: number | null; hint: number | null; replay: number | null; next: number | null };
scores: GameScore[];
/** Questions of this game so far, newest last; during reveal the last one is the current question. */
history: GameHistoryItem[];
/** Server time the reveal ends. */
revealUntil: number | null;
/** 이어풀기 possible: songs left that this quiz has not played. */
left: number;
}
export type ServerMessage =
/** `build`: the web build the server serves (`<meta name="mq-build">`), null without one — a different build means "새로고침". */
| { t: 'welcome'; protocol: number; userId: string; serverNow: number; build: string | null }
| { t: 'room'; room: RoomView }
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' | 'admin' }
| { t: 'chat'; code: string; line: ChatLine }
/** 정답 줄 + 5줄 블록 in one message (docs/06). */
| { t: 'answer'; code: string; line: ChatLine }
| { t: 'game'; code: string; game: GameView | null }
/**
* Load the video muted at `startSec`, buffer, report audio ready (docs/12 Q1).
* `gain` (0..1): 소리 크기 맞추기 — the player plays at the listener's volume × gain, so songs sound equally loud.
*/
| { t: 'prepare'; code: string; n: number; videoId: string; startSec: number; endSec: number | null; gain: number }
/** Everyone unmutes and plays from `atSec` at server time `startAt`; stop at `endSec` by playback position. */
| { t: 'play'; code: string; n: number; startAt: number; atSec: number; endSec: number | null }
/** Stop now (someone is buffering / the host paused / the clip is over). */
| { t: 'pause'; code: string; n: number }
/**
* Back in a question whose music is running (refresh / reconnect): load `videoId` and play along the running timeline
* (position `atSec` at server time `startAt`); `clipStart` is where the clip began, for the progress bar.
*/
| { t: 'catchup'; code: string; n: number; videoId: string; clipStart: number; startAt: number; atSec: number; endSec: number | null; gain: number }
| { t: 'typing'; code: string; ids: string[] }
| { t: 'saved'; id: number; name: string }
/** Recent lines for someone who just joined (or came back). */
| { t: 'chatlog'; code: string; lines: ChatLine[] }
| { t: 'notice'; text: string }
| { t: 'pong'; c: number; s: number }
/** `n`: the chat nonce when a chat line was refused, so the sender drops its "보내는 중" line. */
| { t: 'error'; message: string; n?: string };
/**
* Server clock offset from ping samples (docs/12 Q1): use the sample with the smallest round trip.
* offset = server - client, so serverNow ≈ Date.now() + offset.
*/
export function clockOffset(samples: { sent: number; received: number; server: number }[]): { offset: number; rtt: number } | null {
let best: { offset: number; rtt: number } | null = null;
for (const s of samples) {
const rtt = s.received - s.sent;
if (rtt < 0) continue;
const offset = s.server - (s.sent + rtt / 2);
if (!best || rtt < best.rtt) best = { offset, rtt };
}
return best;
}