Files
joke-app/apps/server/src/server.ts
EJClaw 84d64b27f2 컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업
- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위
- 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말)
- humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60)
- 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로
- 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수
- 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕]
- 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:46:13 +09:00

223 lines
8.7 KiB
TypeScript

/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
import { existsSync, readFileSync } from 'node:fs';
import { join, normalize } from 'node:path';
import type { Server } from 'bun';
import { GAMES } from '@bg/games';
import { botProfile } from '@bg/shared';
import { Llm } from './ai/llm';
import type { Config } from './config';
import { openDb } from './db';
import { SESSION_COOKIE, Sessions } from './auth/sessions';
import { Users, toPublicUser } from './auth/users';
import { createHttpApp, type HttpDeps } from './http/app';
import { RoomManager } from './rooms/manager';
import { createLuckSeeder } from './rooms/luck';
import type { BotDelayInput } from './rooms/bots';
import { RoomStore } from './rooms/store';
import { Replays } from './rooms/replay';
import { Gateway, type WsData } from './ws/gateway';
import { Audit, Roles } from './admin/roles';
import { SettingsStore } from './admin/settings';
/** A guest who closed the site and stayed away this long is deleted. */
export const GUEST_IDLE_MS = 24 * 3600_000;
export type LogFn = (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
export const jsonLog: LogFn = (level, msg, extra) => {
const line = JSON.stringify({ t: new Date().toISOString(), level, msg, ...extra });
if (level === 'error') console.error(line);
else console.log(line);
};
export interface StartOptions {
config: Config;
log?: LogFn;
staticDir?: string | null;
discordExchange?: HttpDeps['discordExchange'];
/** Computer players' thinking time (tests shorten it). */
botDelay?: (input: BotDelayInput) => number;
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
stopWaitMs?: number;
/** Computers' luck on a worker thread (docs/04 §5.1); default on. */
luck?: boolean;
}
export function startServer(opts: StartOptions) {
const { config } = opts;
const log = opts.log ?? jsonLog;
const db = openDb(config.dbPath);
const users = new Users(db);
const sessions = new Sessions(db);
const store = new RoomStore(db);
const publicUser = (id: string) => {
const bot = botProfile(id);
if (bot) return bot;
const u = users.get(id);
return u ? toPublicUser(u) : null;
};
const settings = new SettingsStore(db, GAMES);
const roles = new Roles(db, config.superadminDiscordIds);
const audit = new Audit(db);
const startedAt = Date.now();
// Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8).
const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null;
if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok }));
const luck = opts.luck === false ? null : createLuckSeeder({ log });
const rooms = new RoomManager({
store,
games: GAMES,
users: { publicUser },
log,
settings,
botDelay: opts.botDelay,
ai,
luckSeed: luck ? (job) => luck.seed(job) : undefined,
offlineSince: (id): number | null => gateway.offlineSince(id),
});
const restored = rooms.restoreAll();
log('info', 'rooms restored', restored);
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id), build: () => build });
const removeGuest = (id: string) => {
rooms.leaveAll(id);
gateway.closeUser(id);
if (users.deleteGuest(id)) log('info', 'guest removed', { user: id });
};
/** Still on the site (socket open) or still holding a seat: not idle. */
const guestKept = (id: string) => gateway.isOnline(id) || !!rooms.activeRoomFor(id);
/** Guests who closed the site and stayed away a day are deleted (docs/05 §4). */
const purgeIdleGuests = (now = Date.now()) => {
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) {
if (guestKept(id)) continue;
removeGuest(id);
}
};
let ready = true;
const ipOf = (req: Request) =>
(config.trustProxy ? req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() : undefined) ||
server?.requestIP(req)?.address ||
'unknown';
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = staticDir && existsSync(staticDir);
// The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh.
const build = serveStatic ? webBuildId(staticDir!) : null;
const app = createHttpApp({
config,
build,
users,
sessions,
rooms,
replays: new Replays(db, GAMES, { publicUser }),
ipOf,
discordExchange: opts.discordExchange,
health: () => ({
ok: ready,
rooms: rooms.all().length,
connections: gateway.connectionCount,
...(ai ? { ai: { model: ai.stats.model, available: ai.available(), ok: ai.stats.ok, failed: ai.stats.failed, avgMs: ai.stats.avgMs } } : {}),
}),
roles,
settings,
removeGuest,
admin: {
audit,
games: GAMES,
disconnectUser: (id) => gateway.disconnectUser(id),
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
stats: () => {
const all = rooms.all();
const day = Date.now() - 24 * 3600_000;
return {
connections: gateway.connectionCount,
rooms: { total: all.length, lobby: all.filter((r) => r.status === 'lobby').length, playing: all.filter((r) => r.status === 'playing').length },
games: db.query<{ total: number; today: number }, [number]>('SELECT COUNT(*) AS total, SUM(started_at > ?) AS today FROM games').get(day),
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
};
},
},
});
const server: Server<WsData> = Bun.serve<WsData>({
port: config.port,
async fetch(req, srv) {
const url = new URL(req.url);
if (url.pathname === '/ws') {
const origin = req.headers.get('origin');
if (!origin || !config.allowedOrigins.includes(origin)) return new Response('forbidden origin', { status: 403 });
const cookie = req.headers.get('cookie') ?? '';
const token = cookie
.split(';')
.map((s) => s.trim())
.find((s) => s.startsWith(`${SESSION_COOKIE}=`))
?.slice(SESSION_COOKIE.length + 1);
const userId = token ? sessions.resolve(decodeURIComponent(token)) : null;
if (!userId) return new Response('unauthorized', { status: 401 });
return gateway.upgrade(req, srv, userId);
}
if (url.pathname.startsWith('/api/') || url.pathname === '/healthz') return app.fetch(req);
if (url.pathname.startsWith('/internal/')) return new Response('not found', { status: 404 });
if (serveStatic) return serveFile(staticDir!, url.pathname);
return new Response('not found', { status: 404 });
},
websocket: {
...gateway.handlers,
idleTimeout: 40,
sendPings: true,
perMessageDeflate: true,
maxPayloadLength: 64 * 1024,
},
});
const sweeper = setInterval(() => {
try {
rooms.sweep();
sessions.purgeExpired();
purgeIdleGuests();
store.purgeOldLogs();
} catch (err) {
log('error', 'sweep failed', { err: String(err) });
}
}, 60_000);
const stop = async () => {
ready = false;
clearInterval(sweeper);
gateway.shutdown();
rooms.shutdown();
luck?.stop();
// Bun's stop() promise can stay pending after server-initiated WS closes even though the
// listener is already closed, so bound the wait.
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
db.close();
};
return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
}
/** The build id the web build wrote into its index.html (`<meta name="bg-build">`, vite.config.ts), or null. */
export function webBuildId(root: string): string | null {
try {
return /<meta name="bg-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
} catch {
return null;
}
}
async function serveFile(root: string, pathname: string): Promise<Response> {
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
const candidate = join(root, safe);
if (candidate.startsWith(root) && !candidate.endsWith('/')) {
const f = Bun.file(candidate);
if (await f.exists()) {
const immutable = safe.startsWith('/assets/');
return new Response(f, { headers: { 'Cache-Control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' } });
}
}
// SPA fallback.
return new Response(Bun.file(join(root, 'index.html')), { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8' } });
}