컴퓨터 방 자동 정리 + 게스트 계정 삭제(로그아웃·하루 미접속) + 테스트 10분→1분

- 방 화면을 벗어나면(홈·규칙) detach: 자리·접속 상태는 유지, 방 접속 수에서 빠짐
- 컴퓨터가 있는 방: 사람이 모두 [방 나가기]하면 바로 닫고, 아무도 안 보면 대기실·끝난 방 1분, 게임 중 30분 뒤 정리
- 게스트 로그아웃 = 계정 삭제(자리·전적·세션·소켓), 사이트를 닫고 24시간 지난 게스트도 1분 주기로 삭제
- users.last_seen_at을 요청·소켓 종료 때 갱신(이전엔 갱신 안 됨), 003 마이그레이션에서 기존 게스트 시계 초기화
- 테스트: 무작위 대국 시드를 playoutSeeds()로 평소 1/10, test:full은 전부. bun test --parallel=4, 테스트 서버 종료 대기 1s→50ms

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-07 17:10:52 +09:00
parent 373231b553
commit 39223bacdd
49 changed files with 629 additions and 155 deletions

View File

@@ -248,6 +248,91 @@ describe('playing with bots', () => {
});
});
describe('practice rooms close once nobody is there', () => {
function finishedPractice() {
const h = harness();
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
room.act('A', 1, { type: 'resign' });
expect(room.status).toBe('finished');
return { ...h, room, a };
}
test('leaving on purpose (only computers left) closes the room right away', () => {
const { room, manager, store } = finishedPractice();
room.leave('A');
expect(manager.get(room.code)).toBeUndefined();
expect(store.openRooms()).toHaveLength(0);
expect(manager.activeRoomFor('A')).toBeNull();
});
test('leaving mid-game also closes it', () => {
const h = harness();
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
room.join(h.conn('A'), 'player');
room.start('A');
room.leave('A');
expect(h.manager.get(room.code)).toBeUndefined();
});
test('going to another page (seat kept) or closing the site: closed a minute later by the sweep', () => {
const { room, a, manager, clock, conn } = finishedPractice();
room.disconnect(a);
manager.sweep();
expect(manager.get(room.code)).toBe(room); // a refresh reconnects within seconds
clock.advance(30_000);
room.join(conn('A'), 'player');
room.disconnect(room.conns.get('A')!);
clock.advance(59_000);
manager.sweep();
expect(manager.get(room.code)).toBe(room); // the minute counts from the last disconnect
clock.advance(1_000);
manager.sweep();
expect(manager.get(room.code)).toBeUndefined();
});
test('a running practice game with nobody connected waits 30 minutes', () => {
const h = harness();
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
room.start('A');
room.disconnect(a);
h.clock.advance(29 * 60_000);
h.manager.sweep();
expect(h.manager.get(room.code)).toBe(room);
h.clock.advance(60_000);
h.manager.sweep();
expect(h.manager.get(room.code)).toBeUndefined();
});
test('rooms without computers keep the old timeouts; someone still connected keeps any room', () => {
const h = harness();
const room = h.create('A');
const a = h.conn('A');
room.join(a, 'player');
room.join(h.conn('B'), 'player');
room.leave('B');
expect(h.manager.get(room.code)).toBe(room);
const practice = h.manager.createPractice('C', 'omok') as Room;
rooms.push(practice);
practice.join(h.conn('C'), 'player');
h.clock.advance(5 * 60_000);
h.manager.sweep();
expect(h.manager.get(practice.code)).toBe(practice);
room.disconnect(a);
h.clock.advance(5 * 60_000);
h.manager.sweep();
expect(h.manager.get(room.code)).toBe(room); // empty lobby: 10 minutes
});
});
describe('restore after restart', () => {
test('bots stay seated, have no reconnect grace, and the driver re-plans their move', () => {
const { manager, conn, store, clock, users } = harness();

View File

@@ -10,6 +10,9 @@ export const MAX_ROOMS = 2000;
export const MAX_ROOMS_PER_USER = 3;
const EMPTY_LOBBY_TTL = 10 * 60_000;
const FINISHED_TTL = 30 * 60_000;
/** Rooms with computer players nobody is looking at: closed this long after the last person went away. */
const PRACTICE_IDLE_TTL = 60_000;
const PRACTICE_GAME_TTL = 30 * 60_000;
export interface ManagerDeps {
store: RoomStore;
@@ -42,6 +45,10 @@ export class RoomManager {
log: this.deps.log,
settings: this.deps.settings,
botDelay: this.deps.botDelay,
onEmpty: (room, why) => {
// Everyone left a room with computer players on purpose: nobody can come back to it, close it now.
if (why === 'leave' && this.byCode.get(room.code) === room && room.hasBots() && !room.hasPeopleSeated()) this.close(room);
},
onSeatChange: (room, userId, seated) => {
if (isBotId(userId)) return;
const set = this.seatIndex.get(userId) ?? new Set<string>();
@@ -150,6 +157,11 @@ export class RoomManager {
}
}
/** Frees every seat the user holds (account removed). */
leaveAll(userId: string): void {
for (const code of [...(this.seatIndex.get(userId) ?? [])]) this.byCode.get(code)?.leave(userId);
}
publicRooms(gameId: string | null): { code: string; gameId: string; host: string; seated: number; max: number; options: unknown }[] {
return this.all()
// Rooms with computer players are practice rooms: never listed, never filled by quick play.
@@ -198,6 +210,13 @@ export class RoomManager {
for (const room of this.all()) {
if (room.conns.size > 0) continue;
const idle = now - room.lastActiveAt;
if (room.hasBots()) {
// Practice rooms are private and only for the people who made them: once nobody is looking, close soon.
const empty = now - (room.emptySince ?? now);
const ttl = room.status === 'playing' || room.status === 'paused' ? PRACTICE_GAME_TTL : PRACTICE_IDLE_TTL;
if (empty >= ttl) this.close(room);
continue;
}
const closable =
(room.status === 'lobby' && idle > EMPTY_LOBBY_TTL) ||
(room.status === 'finished' && idle > FINISHED_TTL) ||

View File

@@ -76,7 +76,8 @@ export interface RoomDeps {
users: { publicUser(id: string): PublicUser | null };
now?: () => number;
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
onEmpty?: (room: Room) => void;
/** The last connection went away: `leave` = someone left on purpose, `disconnect` = a socket dropped or the page was left. */
onEmpty?: (room: Room, why: 'leave' | 'disconnect') => void;
onSeatChange?: (room: Room, userId: string, seated: boolean) => void;
/** Admin settings (docs/14-admin.md). Optional so unit tests can run without them. */
settings?: { game(id: string): EffectiveGame | null; getSite(): SiteSettings };
@@ -97,6 +98,8 @@ export class Room {
spectators = new Set<string>();
presence = new Map<string, Presence>();
conns = new Map<string, Conn>();
/** Seated people still on the site but away from the room page (no room messages; still count as connected). */
detached = new Map<string, Conn>();
kicked = new Set<string>();
/** Players who left during a game; their seat is freed when the game ends. */
leftDuringGame = new Set<string>();
@@ -108,6 +111,8 @@ export class Room {
game: GameSlot | null = null;
chatLog: Extract<ServerMessage, { t: 'chat' }>[] = [];
lastActiveAt: number;
/** When the last connection went away (null while someone is connected). */
emptySince: number | null;
private timer: ReturnType<typeof setTimeout> | null = null;
/** Log entries of streaming actions not yet written (flushed with the next snapshot). */
private pendingLogs: LogEntry[] = [];
@@ -130,6 +135,7 @@ export class Room {
this.seats = new Array(config.maxPlayers).fill(null);
this.now = deps.now ?? Date.now;
this.lastActiveAt = this.now();
this.emptySince = this.now();
const room = this;
this.bots = new BotDriver(
{
@@ -205,6 +211,11 @@ export class Room {
return this.seats.some((s) => !!s && isBotId(s.userId));
}
/** A person still holds a seat (not counting people who already left a running game). */
hasPeopleSeated(): boolean {
return this.seats.some((s) => !!s && !isBotId(s.userId) && !this.leftDuringGame.has(s.userId));
}
// ---------------------------------------------------------------- snapshot
snapshot(): RoomSnapshot {
@@ -409,6 +420,8 @@ export class Room {
this.leftDuringGame.delete(u);
this.presence.set(u, { connected: true, since: now, joinedAt: prev?.joinedAt || now });
this.conns.set(u, conn);
this.detached.delete(u);
this.emptySince = null;
if (wasSeated && prev && !prev.connected && this.inGame(u)) {
this.notice('reconnected', `${this.nick(u)}님이 다시 연결됐어요.`);
}
@@ -422,11 +435,25 @@ export class Room {
return null;
}
/**
* Left the room page but still on the site (홈, 규칙…): no more room messages and the room no longer counts the
* connection, but the seat stays and the person still counts as connected (no "연결 끊김", no auto moves).
*/
detach(conn: Conn): void {
const u = conn.userId;
if (this.conns.get(u) !== conn) return;
if (this.spectators.has(u)) return this.disconnect(conn);
this.conns.delete(u);
this.detached.set(u, conn);
if (this.conns.size === 0) this.becameEmpty('disconnect');
}
/** Connection dropped (not an intentional leave). */
disconnect(conn: Conn): void {
const u = conn.userId;
if (this.conns.get(u) !== conn) return;
this.conns.delete(u);
if (this.detached.get(u) === conn) this.detached.delete(u);
else if (this.conns.get(u) === conn) this.conns.delete(u);
else return;
const p = this.presence.get(u);
if (p) {
p.connected = false;
@@ -440,12 +467,13 @@ export class Room {
}
this.broadcastRoom();
this.scheduleTimer();
if (this.conns.size === 0) this.deps.onEmpty?.(this);
if (this.conns.size === 0) this.becameEmpty('disconnect');
}
leave(userId: string): void {
const conn = this.conns.get(userId);
this.conns.delete(userId);
this.detached.delete(userId);
this.spectators.delete(userId);
this.presence.delete(userId);
const seat = this.seatOf(userId);
@@ -471,7 +499,12 @@ export class Room {
this.persist({ actorId: userId, kind: 'leave', data: null });
this.broadcastRoom();
conn?.send({ t: 'bye', reason: 'closed' });
if (this.conns.size === 0) this.deps.onEmpty?.(this);
if (this.conns.size === 0) this.becameEmpty('leave');
}
private becameEmpty(why: 'leave' | 'disconnect'): void {
this.emptySince ??= this.now();
this.deps.onEmpty?.(this, why);
}
private pickNewHost(): void {