M9: 게임 기록 다시 보기
- 서버: 끝난 게임을 공개된 시드 + room_log 행동으로 다시 돌려 플레이어별 view 장면을 만든다 (rooms/replay.ts, 장면은 view 차이만 전송: shared/view-patch.ts). 행동 로그의 at = 적용한 정확한 시각, start 로그에 stateVersion. GET /api/me/games, GET /api/replays/:gamePk(그 판 플레이어만, no-store), RoomView.lastGamePk. 로그가 지워졌거나 규칙 버전이 바뀌었거나 결과가 다르면 한국어 안내(410). - 웹: 다시 보기 화면(/replay/:gamePk, 게임 Board/Side 읽기 전용, 처음/이전/재생·멈춤/다음/끝, 슬라이더), 내 정보의 내 게임 기록 목록, 결과 화면의 [처음부터 다시 보기]. - 테스트: 모든 게임을 Room으로 끝까지 둔 뒤 다시 만든 상태·결과·장면이 같은지, 권한, view-patch, e2e/replay.e2e.ts. - 문서: docs/09 §8, docs/07 §10. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
288
apps/server/src/rooms/replay.ts
Normal file
288
apps/server/src/rooms/replay.ts
Normal file
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Game replays (docs/09 §8): a finished game is rebuilt from its revealed seed and the action log
|
||||
* (`room_log` act/auto entries) by running the pure game module again, then rendered with the same
|
||||
* per-viewer `view` the player saw while playing. The seed and the raw log never leave the server.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { SeededRng, seedFromHex, type AnyGameDefinition, type GameResult } from '@bg/engine';
|
||||
import { diffView, type MyGameSummary, type PublicUser, type ReplayData, type ReplayFrame } from '@bg/shared';
|
||||
|
||||
/** room_log rows are purged after this long (store.purgeOldLogs). */
|
||||
export const LOG_RETENTION_MS = 90 * 24 * 3600_000;
|
||||
/** Rebuilt replays are kept briefly (people step through right after opening one); bounded in count and size. */
|
||||
const CACHE_ENTRIES = 32;
|
||||
const CACHE_CHARS = 16_000_000;
|
||||
const CACHE_TTL_MS = 10 * 60_000;
|
||||
|
||||
export interface ReplayInput {
|
||||
seedHex: string;
|
||||
options: unknown;
|
||||
players: string[];
|
||||
startedAt: number;
|
||||
gameNo: number;
|
||||
/** act/auto log entries of this game in seq order. */
|
||||
actions: { actorId: string; kind: string; data: unknown; at: number }[];
|
||||
}
|
||||
|
||||
type Step = { state: unknown; action: ReplayInput['actions'][number] | null; events: unknown[] };
|
||||
|
||||
/**
|
||||
* Re-runs a game exactly as the room did: setup with the seed and start time, then every logged action with
|
||||
* the RNG continuing and the time it was applied at (the room logs that exact `now`).
|
||||
*/
|
||||
function* replaySteps(def: AnyGameDefinition, input: ReplayInput): Generator<Step> {
|
||||
const rng = SeededRng.fromSeed(seedFromHex(input.seedHex));
|
||||
let state = def.setup({ players: input.players, options: input.options, rng, now: input.startedAt, gameNo: input.gameNo });
|
||||
yield { state, action: null, events: [{ type: 'gameStarted' }] };
|
||||
for (const a of input.actions) {
|
||||
const next = def.apply(state, a.actorId, a.data, { rng, now: a.at });
|
||||
state = next.state;
|
||||
yield { state, action: a, events: next.events };
|
||||
}
|
||||
}
|
||||
|
||||
/** Final state of a rebuilt game. */
|
||||
export function rebuildGame(def: AnyGameDefinition, input: ReplayInput): unknown {
|
||||
let state: unknown;
|
||||
for (const step of replaySteps(def, input)) state = step.state;
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Frames for one viewer. Streamed actions (drawing strokes) are folded into the next frame, as their effect
|
||||
* reaches clients through `syncView` (the whole drawing). Views are sent as deltas against the previous frame.
|
||||
* The work is cut into slices of about `sliceMs` so a long game (마작: ~300 ms in total) never blocks the
|
||||
* rooms sharing this thread for long.
|
||||
*/
|
||||
export async function buildFrames(
|
||||
def: AnyGameDefinition,
|
||||
input: ReplayInput,
|
||||
viewer: string,
|
||||
sliceMs = 8,
|
||||
): Promise<{ frames: ReplayFrame[]; final: unknown }> {
|
||||
const frames: ReplayFrame[] = [];
|
||||
const render = (s: unknown) => (def.syncView ? def.syncView(s, viewer) : def.view(s, viewer));
|
||||
let prevView: unknown;
|
||||
let final: unknown;
|
||||
let slice = performance.now();
|
||||
for (const { state, action: a, events } of replaySteps(def, input)) {
|
||||
final = state;
|
||||
if (performance.now() - slice > sliceMs) {
|
||||
await new Promise((r) => setImmediate(r));
|
||||
slice = performance.now();
|
||||
}
|
||||
if (a && a.kind === 'act' && def.isStreamAction?.(a.data)) continue;
|
||||
const view = render(state);
|
||||
const active = def.result(state) ? [] : def.activePlayers(state);
|
||||
if (!a) frames.push({ at: input.startedAt, actor: null, events, active, view });
|
||||
else {
|
||||
const patch = diffView(prevView, view);
|
||||
frames.push({ at: a.at, actor: a.actorId, ...(a.kind === 'auto' ? { auto: true } : {}), events, active, ...(patch ? { patch } : {}) });
|
||||
}
|
||||
prevView = view;
|
||||
}
|
||||
return { frames, final };
|
||||
}
|
||||
|
||||
interface GameRow {
|
||||
id: string;
|
||||
room_id: string;
|
||||
game_no: number;
|
||||
game_id: string;
|
||||
options_json: string;
|
||||
seed: string | null;
|
||||
started_at: number;
|
||||
ended_at: number | null;
|
||||
end_reason: string | null;
|
||||
result_json: string | null;
|
||||
}
|
||||
|
||||
export type ReplayResult = { ok: true; body: string } | { ok: false; status: 400 | 403 | 404 | 409 | 410; error: string };
|
||||
|
||||
export class Replays {
|
||||
private cache = new Map<string, { body: string; at: number }>();
|
||||
private cacheChars = 0;
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private inflight = new Map<string, Promise<Awaited<ReturnType<typeof buildFrames>>>>();
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(
|
||||
private db: Database,
|
||||
private games: Record<string, AnyGameDefinition>,
|
||||
private users: { publicUser(id: string): PublicUser | null },
|
||||
now?: () => number,
|
||||
) {
|
||||
this.now = now ?? Date.now;
|
||||
}
|
||||
|
||||
/** My finished games, newest first. `before` is the last gamePk of the previous page. */
|
||||
listForUser(userId: string, before: string | null, limit: number): { games: MyGameSummary[]; next: string | null } {
|
||||
const rows = this.db
|
||||
.query<GameRow & { rank: number | null }, [string, string, number]>(
|
||||
`SELECT g.id, g.room_id, g.game_no, g.game_id, g.options_json, g.seed, g.started_at, g.ended_at, g.end_reason, g.result_json, gp.rank
|
||||
FROM game_players gp JOIN games g ON g.id = gp.game_pk
|
||||
WHERE gp.user_id = ? AND g.ended_at IS NOT NULL AND g.id < ?
|
||||
ORDER BY g.id DESC LIMIT ?`,
|
||||
)
|
||||
.all(userId, before ?? '~', limit + 1);
|
||||
const page = rows.slice(0, limit);
|
||||
const others = new Map<string, { user_id: string; rank: number | null }[]>();
|
||||
if (page.length) {
|
||||
const marks = page.map(() => '?').join(',');
|
||||
const list = this.db
|
||||
.query<{ game_pk: string; user_id: string; rank: number | null }, string[]>(
|
||||
`SELECT game_pk, user_id, rank FROM game_players WHERE game_pk IN (${marks}) ORDER BY rank IS NULL, rank, seat`,
|
||||
)
|
||||
.all(...page.map((r) => r.id));
|
||||
for (const p of list) {
|
||||
const arr = others.get(p.game_pk) ?? [];
|
||||
arr.push(p);
|
||||
others.set(p.game_pk, arr);
|
||||
}
|
||||
}
|
||||
const cutoff = this.now() - LOG_RETENTION_MS;
|
||||
const games = page.map((r): MyGameSummary => {
|
||||
const result = r.result_json ? (JSON.parse(r.result_json) as GameResult) : null;
|
||||
return {
|
||||
gamePk: r.id,
|
||||
gameId: r.game_id,
|
||||
startedAt: r.started_at,
|
||||
endedAt: r.ended_at!,
|
||||
endReason: r.end_reason ?? 'normal',
|
||||
myRank: r.rank,
|
||||
players: (others.get(r.id) ?? []).map((p) => ({
|
||||
nickname: this.users.publicUser(p.user_id)?.nickname ?? '알 수 없음',
|
||||
rank: p.rank,
|
||||
me: p.user_id === userId,
|
||||
})),
|
||||
summary: result?.summary ?? '',
|
||||
// Cheap check for the list; the replay request itself rebuilds and verifies the game.
|
||||
replayable: !!r.seed && !!this.games[r.game_id] && r.started_at > cutoff,
|
||||
};
|
||||
});
|
||||
return { games, next: rows.length > limit ? page[page.length - 1]!.id : null };
|
||||
}
|
||||
|
||||
async get(gamePk: string, userId: string): Promise<ReplayResult> {
|
||||
const g = this.db
|
||||
.query<GameRow, [string]>(
|
||||
'SELECT id, room_id, game_no, game_id, options_json, seed, started_at, ended_at, end_reason, result_json FROM games WHERE id = ?',
|
||||
)
|
||||
.get(gamePk);
|
||||
if (!g) return { ok: false, status: 404, error: '게임 기록을 찾을 수 없어요.' };
|
||||
const seats = this.db.query<{ user_id: string }, [string]>('SELECT user_id FROM game_players WHERE game_pk = ?').all(gamePk);
|
||||
// game_players is written when the game ends; before that nobody (not even players) can open a replay.
|
||||
if (g.ended_at === null || !g.seed || !g.result_json) return { ok: false, status: 409, error: '게임이 끝난 뒤에 다시 볼 수 있어요.' };
|
||||
if (!seats.some((s) => s.user_id === userId)) return { ok: false, status: 403, error: '이 게임에 참여한 사람만 다시 볼 수 있어요.' };
|
||||
|
||||
const key = `${gamePk}:${userId}`;
|
||||
const hit = this.cache.get(key);
|
||||
if (hit) {
|
||||
this.cache.delete(key);
|
||||
if (this.now() - hit.at < CACHE_TTL_MS) {
|
||||
this.cache.set(key, hit);
|
||||
return { ok: true, body: hit.body };
|
||||
}
|
||||
this.cacheChars -= hit.body.length;
|
||||
}
|
||||
|
||||
const gone = { ok: false as const, status: 410 as const, error: '기록이 남아 있지 않아 다시 볼 수 없어요. (90일이 지난 게임은 다시 볼 수 없어요.)' };
|
||||
const def = this.games[g.game_id];
|
||||
if (!def) return gone;
|
||||
const log = this.db
|
||||
.query<{ actor_id: string | null; kind: string; data_json: string; at: number }, [string, number]>(
|
||||
'SELECT actor_id, kind, data_json, at FROM room_log WHERE room_id = ? AND game_no = ? ORDER BY seq',
|
||||
)
|
||||
.all(g.room_id, g.game_no);
|
||||
const startIdx = log.findIndex((e) => e.kind === 'start');
|
||||
const endIdx = log.findIndex((e, i) => i > startIdx && e.kind === 'finish');
|
||||
if (startIdx < 0 || endIdx < 0) return gone;
|
||||
const start = JSON.parse(log[startIdx]!.data_json) as { players: string[]; stateVersion?: number };
|
||||
// Games logged before stateVersion was recorded all ran at version 1. Actions logged under other
|
||||
// rules cannot be re-applied safely (a state migration does not translate actions).
|
||||
if ((start.stateVersion ?? 1) !== def.stateVersion) {
|
||||
return { ok: false, status: 410, error: '그 뒤로 게임 규칙이 바뀌어서 이 게임은 다시 볼 수 없어요.' };
|
||||
}
|
||||
const viewer = this.playerIdOf(userId, start.players, seats.map((s) => s.user_id));
|
||||
if (!viewer) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||
const input: ReplayInput = {
|
||||
seedHex: g.seed,
|
||||
options: JSON.parse(g.options_json),
|
||||
players: start.players,
|
||||
startedAt: g.started_at,
|
||||
gameNo: g.game_no,
|
||||
actions: log
|
||||
.slice(startIdx + 1, endIdx)
|
||||
.filter((e) => (e.kind === 'act' || e.kind === 'auto') && e.actor_id !== null)
|
||||
.map((e) => ({ actorId: e.actor_id!, kind: e.kind, data: JSON.parse(e.data_json), at: e.at })),
|
||||
};
|
||||
|
||||
// Rebuilds run one at a time (each already yields between slices); identical requests share one rebuild.
|
||||
let job = this.inflight.get(key);
|
||||
if (!job) {
|
||||
job = this.queue.then(() => buildFrames(def, input, viewer));
|
||||
this.queue = job.catch(() => {});
|
||||
this.inflight.set(key, job);
|
||||
const done = () => this.inflight.delete(key);
|
||||
job.then(done, done);
|
||||
}
|
||||
let built: Awaited<ReturnType<typeof buildFrames>>;
|
||||
try {
|
||||
built = await job;
|
||||
} catch {
|
||||
return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||
}
|
||||
// The rebuilt game must end exactly as recorded; otherwise the replay would show a different game.
|
||||
const result = JSON.parse(g.result_json) as GameResult;
|
||||
const rebuilt = def.result(built.final);
|
||||
const matches = g.end_reason === 'void' ? rebuilt === null : JSON.stringify(rebuilt) === g.result_json;
|
||||
if (!matches) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||
|
||||
const ids = this.idMap(start.players, seats.map((s) => s.user_id));
|
||||
const players: Record<string, PublicUser> = {};
|
||||
for (const p of start.players) {
|
||||
const u = this.users.publicUser(ids.get(p) ?? p);
|
||||
players[p] = u ? { ...u, id: p } : { id: p, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
}
|
||||
const data: ReplayData = {
|
||||
gamePk,
|
||||
gameId: g.game_id,
|
||||
options: input.options,
|
||||
startedAt: g.started_at,
|
||||
endedAt: g.ended_at,
|
||||
me: viewer,
|
||||
players,
|
||||
result,
|
||||
frames: built.frames,
|
||||
};
|
||||
const body = JSON.stringify(data);
|
||||
this.cache.set(key, { body, at: this.now() });
|
||||
this.cacheChars += body.length;
|
||||
while (this.cache.size > CACHE_ENTRIES || (this.cacheChars > CACHE_CHARS && this.cache.size > 1)) {
|
||||
const [k, v] = this.cache.entries().next().value!;
|
||||
this.cache.delete(k);
|
||||
this.cacheChars -= v.body.length;
|
||||
}
|
||||
return { ok: true, body };
|
||||
}
|
||||
|
||||
/**
|
||||
* In-game player id → current user id. A guest who later linked Discord into an existing member has their
|
||||
* game_players row moved to the member id while the game state keeps the old id; pair those up when the
|
||||
* leftover is unambiguous.
|
||||
*/
|
||||
private idMap(players: string[], current: string[]): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
const cur = new Set(current);
|
||||
const missing = players.filter((p) => !cur.has(p));
|
||||
const extra = current.filter((u) => !players.includes(u));
|
||||
for (const p of players) if (cur.has(p)) map.set(p, p);
|
||||
if (missing.length === 1 && extra.length === 1) map.set(missing[0]!, extra[0]!);
|
||||
return map;
|
||||
}
|
||||
|
||||
private playerIdOf(userId: string, players: string[], current: string[]): string | null {
|
||||
for (const [p, u] of this.idMap(players, current)) if (u === userId) return p;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user