- ai/llm.ts: Ollama 클라이언트(동시 2개·대기열·시간 제한·연속 실패 시 쉬기), 꺼져 있으면 예전처럼 조용히 둔다 - ai/lines.ts: 성격 5가지(도발·허세·차분·수다·소심)×말투(존댓말/반말), 한 줄 정리(외국어·AI 말·욕·링크 거르기) - ai/brain.ts: 수 두기 전 생각 중… → 가끔 입력 중…(타자 시간) → 채팅 → 수, 사람 수에 반응, 이름 부르면 대답, 시작·끝 한마디 바퀴벌레 포커: 진실/블러핑과 건네는 말을 모델이 정함. 마피아: 계획한 대사를 모델이 자기 말로(직업 주장은 버림) - RoomView.botActivity + 화면 표시(상태 줄, 채팅 칸), AI_URL/AI_MODEL 설정, /healthz에 ai 통계 - 테스트: 클라이언트·정리·방 동작(가짜 모델), 실제 GPU 모델 브라우저 E2E(e2e/ai.e2e.ts) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
196 lines
7.8 KiB
TypeScript
196 lines
7.8 KiB
TypeScript
/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
|
|
import { existsSync } 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 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;
|
|
}
|
|
|
|
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 rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, ai, 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) });
|
|
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 app = createHttpApp({
|
|
config,
|
|
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 staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
|
|
const serveStatic = staticDir && existsSync(staticDir);
|
|
|
|
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();
|
|
// 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 };
|
|
}
|
|
|
|
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' } });
|
|
}
|