// GameRoomDO — 경기당 1개 (리그 1:1 & 커스텀 N인 공용). WebSocket Hibernation 사용. import { DurableObject } from "cloudflare:workers"; import { RoomLogic } from "./room-logic.js"; import { DEFAULT_RULES, sanitizeRules } from "./rules.js"; import { applyLeagueResult, recordCustom } from "./db.js"; const QUIET = new Set(["board", "attack", "ping"]); export class GameRoomDO extends DurableObject { constructor(ctx, env) { super(ctx, env); this.logic = null; // 클라이언트 keepalive: DO 를 깨우지 않고 런타임이 바로 응답한다. ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"t":"ping"}', '{"t":"pong"}')); } async load() { if (this.logic) return this.logic; const j = await this.ctx.storage.get("room"); if (j) this.logic = RoomLogic.fromJSON(j); return this.logic; } async save() { if (this.logic) await this.ctx.storage.put("room", this.logic.toJSON()); } async fetch(req) { const url = new URL(req.url); if (url.pathname === "/init") { const body = await req.json(); const cur = await this.load(); if (cur && cur.players.size > 0) return Response.json({ ok: false, reason: "exists" }, { status: 409 }); this.logic = new RoomLogic({ id: body.id, kind: body.kind, code: body.code ?? null, allowed: body.allowed ?? null, ft: body.ft, }); if (body.kind === "custom") this.logic.rules = sanitizeRules(body.rules ?? {}, DEFAULT_RULES); this.logic.matchId = crypto.randomUUID(); this.logic.createdAt = Date.now(); await this.save(); // 아무도 안 들어오면 10분 뒤 정리 await this.ctx.storage.setAlarm(Date.now() + 10 * 60_000); return Response.json({ ok: true }); } if (url.pathname === "/info") { const l = await this.load(); if (!l || l.finished) return Response.json({ exists: false }); return Response.json({ exists: true, kind: l.kind, players: l.players.size, phase: l.phase, rules: l.rules }); } if (url.pathname === "/ws") { if (req.headers.get("Upgrade") !== "websocket") return new Response("websocket only", { status: 426 }); const l = await this.load(); if (!l) return new Response("no such room", { status: 404 }); const uid = req.headers.get("x-uid"); const info = JSON.parse(decodeURIComponent(req.headers.get("x-info") || "%7B%7D")); const pair = new WebSocketPair(); const [client, server] = Object.values(pair); // 같은 유저의 이전 소켓은 정리 (재접속) for (const old of this.ctx.getWebSockets(uid)) { try { old.serializeAttachment({ uid, replaced: true }); old.close(4000, "replaced"); } catch {} } this.ctx.acceptWebSocket(server, [uid]); server.serializeAttachment({ uid }); const res = l.join(uid, info); if (!res.ok) { server.send(JSON.stringify({ t: "error", msg: res.reason, fatal: true })); server.close(4001, "rejected"); } await this.flush(); return new Response(null, { status: 101, webSocket: client }); } return new Response("not found", { status: 404 }); } async webSocketMessage(ws, data) { const l = await this.load(); const att = ws.deserializeAttachment(); if (!l || !att || att.replaced) return; let m; try { m = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data)); } catch { return; } l.handle(att.uid, m); await this.flush(!QUIET.has(m.t)); } async webSocketClose(ws) { await this.onGone(ws); } async webSocketError(ws) { await this.onGone(ws); } async onGone(ws) { const l = await this.load(); const att = ws.deserializeAttachment(); if (!l || !att || att.replaced) return; const others = this.ctx.getWebSockets(att.uid).filter((s) => s !== ws && s.readyState === 1); if (!others.length) l.disconnect(att.uid); await this.flush(); } async alarm() { const l = await this.load(); if (!l) return; if (l.players.size === 0) { await this.ctx.storage.deleteAll(); this.logic = null; return; } l.tick(); await this.flush(); } /** outbox 전송 + effects 처리 + 저장 + 다음 알람. */ async flush(persist = true) { const l = this.logic; if (!l) return; // 효과를 먼저 처리해야 match_end(trDelta 포함)가 순서대로 나간다. for (let guard = 0; guard < 4; guard++) { const { out, effects } = l.drain(); this.deliver(out); if (!effects.length) break; for (const e of effects) await this.applyEffect(l, e); } if (persist) await this.save(); const wake = l.nextWake(); if (l.players.size === 0) { await this.ctx.storage.setAlarm(Date.now() + 60_000); } else if (wake) { await this.ctx.storage.setAlarm(wake); } } deliver(out) { if (!out.length) return; const sockets = this.ctx.getWebSockets(); for (const o of out) { const payload = JSON.stringify(o.msg); for (const ws of sockets) { const att = ws.deserializeAttachment(); if (!att || att.replaced) continue; if (o.to !== null && att.uid !== o.to) continue; if (o.except && att.uid === o.except) continue; try { ws.send(payload); } catch {} } } } async applyEffect(l, e) { const db = this.env.DB; if (e.type === "league_end") { let result = null; try { result = await applyLeagueResult(db, { matchId: l.matchId, winner: e.winner, loser: e.loser, score: e.score }); } catch (err) { console.error("league_end failed", err); } l.lastEnd = {}; for (const uid of [e.winner, e.loser]) { const msg = { t: "match_end", winner: e.winner, score: e.score, trDelta: result?.[uid]?.trDelta ?? null, before: result?.[uid]?.before ?? null, after: result?.[uid]?.after ?? null, }; l.lastEnd[uid] = msg; l.send(uid, msg); } } else if (e.type === "custom_end") { try { await recordCustom(db, { matchId: l.matchId, standings: e.standings, size: e.size }); } catch (err) { console.error("custom_end failed", err); } l.matchId = crypto.randomUUID(); // 리매치는 새 경기 } } }