forked from zhuanggenhua/BoardGame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
2054 lines (1804 loc) · 73.9 KB
/
Copy pathserver.ts
File metadata and controls
2054 lines (1804 loc) · 73.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 游戏服务器入口
*
* Koa + socket.io 架构:
* - REST 路由:create/join/leave/destroy/claim-seat/getMatch/leaderboard
* - /game namespace:GameTransportServer(游戏状态同步)
* - /lobby-socket:大厅事件(保持不变)
* - 默认 namespace:重赛/聊天(保持不变)
*/
import 'dotenv/config';
import http from 'node:http';
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import { Server as IOServer, Socket as IOSocket } from 'socket.io';
import msgpackParser from 'socket.io-msgpack-parser';
import { nanoid } from 'nanoid';
import { connectDB } from './src/server/db';
import { sanitizeChatText } from './src/server/chatUtils';
import { MAX_CHAT_MESSAGES } from './src/shared/chat';
import { MatchRecord } from './src/server/models/MatchRecord';
import { GAME_SERVER_MANIFEST } from './src/games/manifest.server';
import { mongoStorage } from './src/server/storage/MongoStorage';
import { hybridStorage } from './src/server/storage/HybridStorage';
import { runStartupCleanupTasks, type StartupCleanupTask } from './src/server/storage/startupCleanup';
import { createClaimSeatHandler, claimSeatUtils } from './src/server/claimSeat';
import { evaluateEmptyRoomJoinGuard } from './src/server/joinGuard';
import { areAllSeatsOccupied, hasOccupiedPlayers, isSeatOccupied, isSupportedPlayerCount } from './src/server/matchOccupancy';
import {
createMatchWithOwnerConflictRetry,
decideDuplicateOwnerRoomAction,
DUPLICATE_OWNER_DISCONNECT_GRACE_MS,
planDuplicateOwnerRoomCreate,
} from './src/server/duplicateOwnerRooms';
import { buildUgcServerGames } from './src/server/ugcRegistration';
import { GameTransportServer } from './src/engine/transport/server';
import type { GameEngineConfig } from './src/engine/transport/server';
import type { MatchMetadata, MatchStorage } from './src/engine/transport/storage';
import { resolveMatchStatus } from './src/engine/transport/storage';
import logger, { gameLogger } from './server/logger';
import { createTrainingDataRecorderFromEnv } from './server/trainingDataRecorder';
import { requestLogger, errorHandler } from './server/middleware/logging';
// ============================================================================
// 事件常量(与前端保持一致)
// ============================================================================
const LOBBY_EVENTS = {
SUBSCRIBE_LOBBY: 'lobby:subscribe',
UNSUBSCRIBE_LOBBY: 'lobby:unsubscribe',
LOBBY_UPDATE: 'lobby:update',
MATCH_CREATED: 'lobby:matchCreated',
MATCH_UPDATED: 'lobby:matchUpdated',
MATCH_ENDED: 'lobby:matchEnded',
HEARTBEAT: 'lobby:heartbeat',
} as const;
const REMATCH_EVENTS = {
JOIN_MATCH: 'rematch:join',
LEAVE_MATCH: 'rematch:leave',
VOTE: 'rematch:vote',
STATE_UPDATE: 'rematch:stateUpdate',
TRIGGER_RESET: 'rematch:triggerReset',
DEBUG_NEW_ROOM: 'debug:newRoom',
} as const;
const MATCH_CHAT_EVENTS = {
JOIN: 'matchChat:join',
LEAVE: 'matchChat:leave',
SEND: 'matchChat:send',
MESSAGE: 'matchChat:message',
HISTORY: 'matchChat:history',
} as const;
// ============================================================================
// 重赛投票状态
// ============================================================================
interface RematchVoteState {
votes: Record<string, boolean>;
ready: boolean;
revision: number;
}
const rematchStateByMatch = new Map<string, RematchVoteState>();
const matchSubscribers = new Map<string, Set<string>>();
// 对局聊天历史缓存(内存,对局结束后自动清理)
interface ChatHistoryMessage {
id: string;
matchId: string;
senderId?: string;
senderName: string;
text: string;
createdAt: string;
}
const chatHistoryByMatch = new Map<string, ChatHistoryMessage[]>();
const LOBBY_ROOM = 'lobby:subscribers';
const LOBBY_ALL = 'all';
const LOBBY_ALL_ROOM = `${LOBBY_ROOM}:${LOBBY_ALL}`;
const LOBBY_HEARTBEAT_INTERVAL = 15000;
// ============================================================================
// 游戏注册
// ============================================================================
const ENABLED_GAME_ENTRIES = GAME_SERVER_MANIFEST.filter(
(entry) => entry.manifest.type === 'game' && entry.manifest.enabled
);
const SUPPORTED_GAMES: string[] = [];
type SupportedGame = string;
type LobbyGameId = SupportedGame | typeof LOBBY_ALL;
const normalizeGameName = (name?: string) => (name || '').toLowerCase();
const isSupportedGame = (gameName: string): gameName is SupportedGame => {
return (SUPPORTED_GAMES as readonly string[]).includes(gameName);
};
const registerSupportedGames = (gameIds: string[]) => {
const normalized = gameIds.map((id) => normalizeGameName(id)).filter((id) => id.length > 0);
SUPPORTED_GAMES.splice(0, SUPPORTED_GAMES.length, ...normalized);
};
// ============================================================================
// 环境配置
// ============================================================================
const isProd = process.env.NODE_ENV === 'production';
let JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
if (isProd) {
throw new Error('[Server] JWT_SECRET 必须在生产环境配置');
}
JWT_SECRET = 'boardgame-secret-key-change-in-production';
logger.warn('[Server] JWT_SECRET 未配置,使用开发默认值');
}
const RAW_WEB_ORIGINS = (process.env.WEB_ORIGINS || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const DEFAULT_APP_WEB_ORIGINS = [
'http://localhost',
'https://localhost',
'capacitor://localhost',
] as const;
const RAW_APP_WEB_ORIGINS = (process.env.APP_WEB_ORIGINS || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const DEV_CORS_ORIGINS = [
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:5174',
'http://localhost:4173',
'http://localhost:6174',
'http://127.0.0.1:3000',
'http://127.0.0.1:5173',
'http://127.0.0.1:5174',
'http://127.0.0.1:4173',
'http://127.0.0.1:6174',
];
const APP_CORS_ORIGINS = RAW_APP_WEB_ORIGINS.length > 0
? RAW_APP_WEB_ORIGINS
: [...DEFAULT_APP_WEB_ORIGINS];
const CORS_ORIGINS = Array.from(new Set([
...(RAW_WEB_ORIGINS.length > 0 ? RAW_WEB_ORIGINS : DEV_CORS_ORIGINS),
...APP_CORS_ORIGINS,
]));
const isDevLoopbackOrigin = (origin?: string) => !isProd && /^http:\/\/(localhost|127\.0\.0\.1):\d+$/i.test(origin ?? '');
const isAllowedCorsOrigin = (origin?: string) => {
if (!origin) return true;
return CORS_ORIGINS.includes(origin) || isDevLoopbackOrigin(origin);
};
const USE_PERSISTENT_STORAGE = process.env.USE_PERSISTENT_STORAGE !== 'false';
const GAME_SERVER_PORT = Number(process.env.GAME_SERVER_PORT) || 18000;
const SOCKET_IO_ALLOW_POLLING = process.env.SOCKET_IO_ALLOW_POLLING;
const SOCKET_IO_SERVER_TRANSPORTS =
SOCKET_IO_ALLOW_POLLING === 'true'
? ['websocket', 'polling']
: SOCKET_IO_ALLOW_POLLING === 'false'
? ['websocket']
: process.env.NODE_ENV === 'production'
? ['websocket']
: ['websocket', 'polling'];
const DEFAULT_TRAINING_DATA_MIN_MATCH_DURATION_MS = 10 * 60 * 1000;
const TRAINING_DATA_MIN_MATCH_DURATION_MS = (() => {
const raw = process.env.TRAINING_DATA_MIN_MATCH_DURATION_MS;
if (!raw) return DEFAULT_TRAINING_DATA_MIN_MATCH_DURATION_MS;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed)) {
return DEFAULT_TRAINING_DATA_MIN_MATCH_DURATION_MS;
}
return Math.max(0, parsed);
})();
// ============================================================================
// 归档逻辑
// ============================================================================
const storage: MatchStorage = hybridStorage;
type OwnerMatchLookupStorage = {
findMatchesByOwnerKey: (ownerKey: string) => Promise<Array<{ matchID: string; gameName: string }>>;
};
const supportsOwnerMatchLookup = (value: MatchStorage): value is MatchStorage & OwnerMatchLookupStorage => {
return typeof (value as Partial<OwnerMatchLookupStorage>).findMatchesByOwnerKey === 'function';
};
const archiveMatchResult = async ({
matchID,
gameName,
gameover,
}: {
matchID: string;
gameName: string;
gameover?: { winner?: string | number };
}) => {
if (!USE_PERSISTENT_STORAGE) {
return;
}
try {
const existing = await MatchRecord.findOne({ matchID });
if (existing) return;
const { metadata, state: storedState } = await storage.fetch(matchID, { metadata: true, state: true });
const winnerSeatID = gameover?.winner !== undefined ? String(gameover.winner) : undefined;
const resultType = winnerSeatID ? 'win' : 'draw';
const players: Array<{ id: string; name: string; result: string; ownerKey?: string }> = [];
let winnerOwnerKey: string | undefined;
if (metadata?.players) {
for (const [seatId, pdata] of Object.entries(metadata.players)) {
const name = pdata?.name || `Player ${seatId}`;
const ownerKey = pdata?.ownerKey;
// 用 ownerKey 作为真实 ID,fallback 到 name
const playerId = ownerKey || name;
const isWinner = seatId === winnerSeatID;
if (isWinner) winnerOwnerKey = playerId;
players.push({
id: playerId,
name,
result: isWinner ? 'win' : resultType === 'draw' ? 'draw' : 'loss',
ownerKey,
});
}
}
// 从最终状态中提取操作日志
const matchState = storedState?.G as { sys?: { actionLog?: { entries?: unknown[] } } } | undefined;
const actionLog = matchState?.sys?.actionLog?.entries ?? undefined;
await MatchRecord.create({
matchID,
gameName,
players,
winnerID: winnerOwnerKey,
actionLog,
createdAt: new Date(metadata?.createdAt || Date.now()),
endedAt: new Date(),
});
logger.info(`[Archive] 归档对局 matchID=${matchID}`);
} catch (err) {
logger.error('[Archive] 归档失败:', err);
}
};
// ============================================================================
// 构建游戏引擎配置
// ============================================================================
const buildServerEngines = async (): Promise<{ engines: GameEngineConfig[]; gameIds: string[] }> => {
const engines: GameEngineConfig[] = [];
const manifestGameIds = new Set<string>();
const gameIds: string[] = [];
for (const entry of ENABLED_GAME_ENTRIES) {
const { manifest, engineConfig } = entry;
const normalizedId = normalizeGameName(manifest.id);
if (manifestGameIds.has(normalizedId)) {
throw new Error(`[GameManifest] 游戏 ID 重复: ${manifest.id}`);
}
manifestGameIds.add(normalizedId);
gameIds.push(normalizedId);
// 直接使用 engineConfig(不再从 __adapterConfig 提取)
engines.push(engineConfig);
}
if (USE_PERSISTENT_STORAGE) {
// 纯内存模式不依赖 Mongo,跳过 UGC 数据库查询,保证无库也能起服务。
const { engineConfigs: ugcEngines, gameIds: ugcGameIds } = await buildUgcServerGames({
existingGameIds: manifestGameIds,
});
ugcEngines.forEach((cfg) => engines.push(cfg));
ugcGameIds.forEach((id) => gameIds.push(id));
}
return { engines, gameIds };
};
// ============================================================================
// 初始化
// ============================================================================
if (USE_PERSISTENT_STORAGE) {
await connectDB();
} else {
logger.info('[GameServer] 当前以纯内存模式启动,跳过 Mongo / UGC / 排行榜归档');
}
const { engines: SERVER_ENGINES, gameIds: SERVER_GAME_IDS } = await buildServerEngines();
registerSupportedGames(SERVER_GAME_IDS);
// 创建 Koa 应用
const app = new Koa();
// 全局错误处理(必须在所有中间件之前)
app.use(errorHandler);
// 请求日志
app.use(requestLogger);
const httpServer = http.createServer(app.callback());
// 创建 socket.io 服务器(统一实例,多 namespace)
// 使用 MessagePack 序列化替代 JSON,减少 20-30% 传输体积
const io = new IOServer(httpServer, {
parser: msgpackParser,
transports: SOCKET_IO_SERVER_TRANSPORTS,
cors: {
origin: (origin, callback) => {
if (isAllowedCorsOrigin(origin)) {
callback(null, true);
return;
}
callback(new Error(`CORS: origin ${origin ?? 'unknown'} not allowed`));
},
methods: ['GET', 'POST'],
credentials: true,
},
// 心跳配置:适当放宽以减少后台标签页的误断线
// 默认 pingInterval=25s + pingTimeout=20s = 45s 断线
// 调整为 pingInterval=30s + pingTimeout=60s = 90s 断线
// 给后台标签页更多缓冲时间(Chrome 节流 timer 到 1 次/分钟)
pingInterval: 30000,
pingTimeout: 60000,
// WebSocket 帧压缩:在 msgpack 基础上再压缩 60-70%(重复字段名/结构)
// 限制窗口大小以控制内存开销(每连接约 15KB 而非默认 32KB)
perMessageDeflate: {
threshold: 1024, // 超过 1KB 才压缩,避免小消息反而变大
zlibDeflateOptions: { windowBits: 13 }, // 8KB 窗口(默认 15 = 32KB)
zlibInflateOptions: { windowBits: 13 },
},
});
// 创建游戏传输服务器
const trainingDataRecorder = createTrainingDataRecorderFromEnv(process.env);
const gameTransport = new GameTransportServer({
io,
storage,
games: SERVER_ENGINES,
trainingDataRecorder,
trainingDataMinMatchDurationMs: TRAINING_DATA_MIN_MATCH_DURATION_MS,
rulesVersion: process.env.npm_package_version ?? null,
offlineGraceMs: 300000, // 5 分钟:给断线玩家充足的重连时间
authenticate: async (matchID, playerID, credentials, metadata) => {
if (!credentials) return false;
const playerMeta = metadata.players[playerID];
if (!playerMeta?.credentials) return false;
return playerMeta.credentials === credentials;
},
onGameOver: (matchID, gameName, gameover) => {
// 记录游戏结束日志
const winner = gameover?.winner !== undefined ? String(gameover.winner) : null;
gameLogger.matchEnded(matchID, gameName, winner, 0); // duration 需要从 metadata 计算
// 归档对局结果
void archiveMatchResult({ matchID, gameName, gameover: gameover as { winner?: string | number } });
// 通知大厅更新(房间仍存在,标记为 gameover,大厅列表显示为已结束)
const game = normalizeGameName(gameName);
if (game && isSupportedGame(game)) {
scheduleLobbySnapshot(game, `gameover: ${matchID}`);
}
},
});
// claim-seat handler
const claimSeatHandler = createClaimSeatHandler({
db: {
fetch: async (matchID: string, opts: { metadata?: boolean; state?: boolean }) => {
const result = await storage.fetch(matchID, opts);
return result as unknown as { metadata?: unknown; state?: unknown };
},
setMetadata: async (matchID: string, metadata: unknown) => {
await storage.setMetadata(matchID, metadata as MatchMetadata);
},
} as unknown as Parameters<typeof createClaimSeatHandler>[0]['db'],
auth: {
generateCredentials: () => nanoid(21),
},
jwtSecret: JWT_SECRET,
});
// ============================================================================
// CORS 中间件
// ============================================================================
app.use(async (ctx, next) => {
const requestOrigin = ctx.get('origin');
const allowedOrigins = new Set(CORS_ORIGINS);
const isDevOrigin = !isProd && /^http:\/\/(localhost|127\.0\.0\.1):\d+$/i.test(requestOrigin);
if (requestOrigin && (allowedOrigins.has(requestOrigin) || isDevOrigin)) {
ctx.set('Access-Control-Allow-Origin', requestOrigin);
ctx.set('Vary', 'Origin');
ctx.set('Access-Control-Allow-Credentials', 'true');
}
ctx.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
ctx.set(
'Access-Control-Allow-Headers',
ctx.get('access-control-request-headers') || 'Content-Type, Authorization',
);
if (ctx.method === 'OPTIONS') {
ctx.status = 204;
return;
}
await next();
});
// 全局错误处理中间件(必须在所有业务中间件之前)
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
const status = (err as { status?: number }).status ?? 500;
const message = err instanceof Error ? err.message : 'Internal Server Error';
ctx.status = status;
ctx.body = { error: message };
// 非 4xx 错误打印日志
if (status >= 500) {
logger.error(`[Server] ${ctx.method} ${ctx.path} → ${status}:`, message);
}
}
});
// Body parser(全局启用)
app.use(bodyParser());
// ============================================================================
// 辅助函数
// ============================================================================
const resolveOwnerFromRequest = (
ctx: Koa.Context,
setupData: Record<string, unknown>,
requestedPlayerName?: string,
): { ownerKey: string; ownerType: 'user' | 'guest'; ownerName?: string } => {
const authHeader = ctx.get('authorization');
const rawToken = claimSeatUtils.parseBearerToken(authHeader);
const payload = rawToken ? claimSeatUtils.verifyGameToken(rawToken, JWT_SECRET) : null;
const normalizedRequestedPlayerName = typeof requestedPlayerName === 'string' && requestedPlayerName.trim()
? requestedPlayerName.trim()
: undefined;
if (rawToken && !payload?.userId) {
ctx.throw(401, 'Invalid token');
return { ownerKey: 'user:invalid', ownerType: 'user' };
}
if (payload?.userId) {
return {
ownerKey: `user:${payload.userId}`,
ownerType: 'user',
ownerName: normalizedRequestedPlayerName ?? (payload.username?.trim() || undefined),
};
}
const guestId =
typeof setupData.guestId === 'string' && setupData.guestId.trim()
? setupData.guestId.trim()
: undefined;
if (!guestId) {
ctx.throw(400, 'guestId is required');
return { ownerKey: 'guest:invalid', ownerType: 'guest' };
}
return {
ownerKey: `guest:${guestId}`,
ownerType: 'guest',
ownerName: normalizedRequestedPlayerName,
};
};
const resolveOwnerKeyFromMetadata = (metadata?: MatchMetadata | null): string | undefined => {
const setupData = metadata?.setupData as { ownerKey?: string } | undefined;
return setupData?.ownerKey;
};
const isEmptyRoomByMetadata = (metadata?: MatchMetadata | null): boolean => {
if (!metadata?.players) return false;
return !hasOccupiedPlayers(metadata.players as Record<string, { name?: string; credentials?: string; isConnected?: boolean | null }>);
};
const resolveJoinSeat = (
players: MatchMetadata['players'],
requestedPlayerID?: string,
): { playerID?: string; reason?: 'player_not_found' | 'seat_occupied' | 'room_full' } => {
if (requestedPlayerID) {
const requestedSeat = players[requestedPlayerID];
if (!requestedSeat) {
return { reason: 'player_not_found' };
}
if (isSeatOccupied(requestedSeat)) {
return { reason: 'seat_occupied' };
}
return { playerID: requestedPlayerID };
}
const openSeat = Object.entries(players)
.sort(([a], [b]) => Number(a) - Number(b))
.find(([, seat]) => !isSeatOccupied(seat));
if (!openSeat) {
return { reason: 'room_full' };
}
return { playerID: openSeat[0] };
};
type MatchCreateSetupData = Record<string, unknown> & {
ownerKey: string;
ownerType: 'user' | 'guest';
firstPlayerId?: string;
turnOrder?: string[];
prevMatchID?: string;
};
const cleanupMatchRoom = async (
matchID: string,
metadata?: MatchMetadata | null,
emitRemoval = false,
): Promise<void> => {
await storage.wipe(matchID);
gameTransport.unloadMatch(matchID, { disconnectSockets: true });
const game = normalizeGameName(metadata?.gameName);
if (emitRemoval && game && isSupportedGame(game)) {
emitMatchEnded(game, matchID);
} else {
matchGameIndex.delete(matchID);
}
matchSubscribers.delete(matchID);
rematchStateByMatch.delete(matchID);
chatHistoryByMatch.delete(matchID);
};
const cleanupMissingOwnerRoom = async (
matchID: string,
metadata?: MatchMetadata | null,
context?: string,
emitRemoval = false,
): Promise<boolean> => {
if (!isEmptyRoomByMetadata(metadata)) return false;
const ownerKey = resolveOwnerKeyFromMetadata(metadata);
if (ownerKey) return false;
await cleanupMatchRoom(matchID, metadata, emitRemoval);
logger.warn(`[RoomCleanup] reason=missing_owner context=${context ?? 'unknown'} matchID=${matchID}`);
return true;
};
// ============================================================================
// REST 路由
// ============================================================================
import Router from '@koa/router';
const router = new Router();
// GET /games — 健康检查端点(用于 E2E 测试)
router.get('/games', async (ctx) => {
ctx.body = {
status: 'ok',
games: SUPPORTED_GAMES,
timestamp: Date.now()
};
});
// POST /games/:name/create — 创建对局
router.get('/internal/rooms', async (ctx) => {
const requestedGame = typeof ctx.query.gameName === 'string'
? normalizeGameName(ctx.query.gameName)
: '';
if (requestedGame) {
if (!isSupportedGame(requestedGame)) {
ctx.throw(400, `Game ${ctx.query.gameName} not found`);
}
ctx.body = { items: await getLobbySnapshot(requestedGame) };
return;
}
ctx.body = { items: await getLobbySnapshotAll() };
});
router.delete('/internal/rooms/:matchID', async (ctx) => {
const matchID = String(ctx.params.matchID || '').trim();
if (!matchID) {
ctx.throw(400, 'Missing matchID');
}
const deleted = await destroyLobbyRoom(matchID);
ctx.body = { deleted, matchID };
});
router.post('/internal/rooms/bulk-delete', async (ctx) => {
const body = ctx.request.body as { ids?: unknown } | undefined;
const ids = Array.isArray(body?.ids)
? body.ids
.filter((value): value is string => typeof value === 'string')
.map(value => value.trim())
.filter(Boolean)
: [];
const uniqueIds = Array.from(new Set(ids));
let deleted = 0;
for (const matchID of uniqueIds) {
const ok = await destroyLobbyRoom(matchID);
if (ok) {
deleted++;
}
}
ctx.body = { requested: uniqueIds.length, deleted };
});
router.post('/games/:name/create', async (ctx) => {
const gameName = normalizeGameName(ctx.params.name);
if (!gameName || !isSupportedGame(gameName)) {
ctx.throw(404, `Game ${ctx.params.name} not found`);
}
const gameEntry = GAME_SERVER_MANIFEST.find((entry) => normalizeGameName(entry.manifest.id) === gameName);
const gameEngine = gameEntry?.engineConfig;
const body = ctx.request.body as Record<string, unknown> | undefined;
const numPlayers = Number(body?.numPlayers ?? 2);
// 当前策略:默认不自动删除活跃旧房,只有前端确认后才带 forceReplaceOwnerRoom 重试。
const forceReplaceOwnerRoom = body?.forceReplaceOwnerRoom === true;
const requestedOwnerName = typeof body?.playerName === 'string' && body.playerName.trim()
? body.playerName.trim()
: undefined;
const minPlayers = gameEngine?.minPlayers ?? 2;
const maxPlayers = gameEngine?.maxPlayers ?? 2;
const playerOptions = gameEntry?.manifest.playerOptions;
if (!isSupportedPlayerCount(numPlayers, minPlayers, maxPlayers, playerOptions)) {
ctx.throw(400, 'Invalid numPlayers');
}
const rawSetupData =
body?.setupData && typeof body.setupData === 'object'
? (body.setupData as Record<string, unknown>)
: {};
const { ownerKey, ownerType, ownerName } = resolveOwnerFromRequest(ctx, rawSetupData, requestedOwnerName);
const setupData: MatchCreateSetupData = { ...rawSetupData, ownerKey, ownerType };
const matchID = nanoid(11);
const seed = nanoid(16);
const playerIds = Array.from({ length: numPlayers }, (_, i) => String(i));
// 清理客户端不应直接控制的先手字段(只允许通过 prevMatchID 间接设置)
delete setupData.firstPlayerId;
delete setupData.turnOrder;
// 重赛先手轮换:从上一局状态中提取先手信息
if (typeof setupData.prevMatchID === 'string') {
try {
const prevMatch = await storage.fetch(setupData.prevMatchID, { state: true });
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 跨游戏通用提取,state 结构不固定
const prevCore = (prevMatch.state as any)?.G?.core;
if (prevCore) {
// 双人:轮换先手;多人:随机打乱顺序
if (numPlayers === 2) {
// 通用提取:activePlayerId / currentPlayer / turnOrder[0]
const prev = prevCore.startingPlayerId ?? prevCore.activePlayerId ?? prevCore.currentPlayer
?? (Array.isArray(prevCore.turnOrder) ? prevCore.turnOrder[0] : undefined);
if (typeof prev === 'string') {
// 下一局先手 = 上一局非先手玩家
const next = playerIds.find(id => id !== prev) ?? playerIds[0];
setupData.firstPlayerId = next;
}
} else {
// 多人:随机打乱 playerIds 顺序作为 turnOrder 提示
const shuffled = [...playerIds];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
setupData.turnOrder = shuffled;
}
}
} catch {
// 上一局不存在或已过期,忽略
}
delete setupData.prevMatchID;
}
if (ownerKey) {
const ownerMatches = supportsOwnerMatchLookup(storage)
? await storage.findMatchesByOwnerKey(ownerKey)
: [];
if (ownerMatches.length > 0) {
const existingMatches = await Promise.all(ownerMatches.map(async (match) => {
const { metadata: existingMetadata } = await storage.fetch(match.matchID, { metadata: true });
return {
...match,
metadata: existingMetadata,
decision: decideDuplicateOwnerRoomAction(existingMetadata, {
disconnectGraceMs: DUPLICATE_OWNER_DISCONNECT_GRACE_MS,
}),
};
}));
const createPlan = planDuplicateOwnerRoomCreate(existingMatches, {
forceReplaceActive: forceReplaceOwnerRoom,
});
if (createPlan.action === 'block') {
const activeMatch = createPlan.activeMatch;
logger.info('duplicate_owner_room_blocked', {
ownerKey,
ownerType: ownerType ?? 'unknown',
matchID: activeMatch.matchID,
gameName: activeMatch.gameName,
reason: activeMatch.decision.reason,
canForceReplace: true,
});
ctx.status = 409;
ctx.body = {
error: 'ACTIVE_MATCH_EXISTS',
gameName: activeMatch.gameName,
matchID: activeMatch.matchID,
canForceReplace: true,
};
return;
}
const cleanableMatches = createPlan.cleanupMatches;
if (cleanableMatches.length > 0) {
logger.info(forceReplaceOwnerRoom ? 'force_cleanup_duplicate_owner_rooms' : 'cleanup_duplicate_owner_rooms', {
ownerKey,
ownerType: ownerType ?? 'unknown',
count: cleanableMatches.length,
matches: cleanableMatches.map((match) => ({
matchID: match.matchID,
gameName: match.gameName,
reason: match.decision.reason,
})),
});
await Promise.all(cleanableMatches.map(async (match) => {
await cleanupMatchRoom(match.matchID, match.metadata, true);
}));
}
}
}
// 初始化游戏状态
const setupResult = await gameTransport.setupMatch(matchID, gameName, playerIds, seed, setupData);
if (!setupResult) {
ctx.throw(500, 'Failed to setup match');
return;
}
const { state: initialState, randomCursor } = setupResult;
// 构建 metadata(每个座位包含 id 字段)
const players: Record<string, { id: number; name?: string; credentials?: string; isConnected?: boolean }> = {};
for (let i = 0; i < playerIds.length; i++) {
players[playerIds[i]] = { id: i };
}
const metadata: MatchMetadata = {
gameName,
players,
createdAt: Date.now(),
updatedAt: Date.now(),
setupData,
status: 'waiting',
};
let ownerCredentials: string | undefined;
if (ownerName) {
ownerCredentials = nanoid(21);
metadata.players['0'] = {
...metadata.players['0'],
name: ownerName,
credentials: ownerCredentials,
isConnected: false,
};
}
const createMatchData = {
initialState: {
G: initialState,
_stateID: 0,
randomSeed: seed,
randomCursor,
},
metadata,
};
const createPersistResult = await createMatchWithOwnerConflictRetry({
createMatch: async () => {
await storage.createMatch(matchID, createMatchData);
},
fetchConflictMetadata: async (conflictMatchID) => {
const { metadata: conflictMetadata } = await storage.fetch(conflictMatchID, { metadata: true });
return conflictMetadata;
},
cleanupConflictMatch: async (conflictMatchID, conflictMetadata) => {
await cleanupMatchRoom(conflictMatchID, conflictMetadata, true);
},
forceReplaceActive: forceReplaceOwnerRoom,
onForceCleanup: async ({ attempt, conflict }) => {
logger.info('force_cleanup_duplicate_owner_rooms_race', {
ownerKey,
ownerType: ownerType ?? 'unknown',
matchID: conflict.matchID,
gameName: conflict.gameName,
attempt,
});
},
});
if (createPersistResult.action === 'conflict') {
ctx.status = 409;
ctx.body = {
error: 'ACTIVE_MATCH_EXISTS',
gameName: createPersistResult.conflict.gameName,
matchID: createPersistResult.conflict.matchID,
canForceReplace: true,
};
return;
}
ctx.body = {
matchID,
ownerPlayerID: ownerCredentials ? '0' : undefined,
ownerCredentials,
};
setTimeout(() => void handleMatchCreated(matchID, gameName), 100);
});
// POST /games/:name/:matchID/join — 加入对局
router.post('/games/:name/:matchID/join', async (ctx) => {
const gameName = normalizeGameName(ctx.params.name);
const matchID = ctx.params.matchID;
const body = ctx.request.body as {
playerID?: string;
playerName?: string;
data?: Record<string, unknown>;
} | undefined;
const requestedPlayerID = typeof body?.playerID === 'string' && body.playerID.trim()
? body.playerID.trim()
: undefined;
const playerName = body?.playerName;
if (!playerName?.trim()) {
ctx.throw(403, 'playerName is required');
return;
}
const result = await storage.fetch(matchID, { state: true, metadata: true });
if (!result.metadata) {
ctx.throw(404, `Match ${matchID} not found`);
return;
}
// 密码校验
const setupData = result.metadata.setupData as { password?: string } | undefined;
const roomPassword = setupData?.password;
const password = body?.data?.password;
if (roomPassword && roomPassword !== password) {
ctx.throw(403, 'Incorrect password');
return;
}
// 空房间加入守卫
const guestId = typeof body?.data?.guestId === 'string' ? body.data.guestId : undefined;
const guard = evaluateEmptyRoomJoinGuard({
metadata: result.metadata as unknown as Parameters<typeof evaluateEmptyRoomJoinGuard>[0]['metadata'],
state: result.state as unknown as Parameters<typeof evaluateEmptyRoomJoinGuard>[0]['state'],
authHeader: ctx.get('authorization'),
guestId,
jwtSecret: JWT_SECRET,
});
if (!guard.allowed) {
if (guard.reason === 'missing_owner') {
const cleaned = await cleanupMissingOwnerRoom(matchID, result.metadata, 'join', true);
if (cleaned) {
ctx.throw(404, 'Match not found');
return;
}
}
ctx.throw(guard.status ?? 403, guard.message ?? 'Only match owner can rejoin');
return;
}
// 分配凭证
const joinSeat = resolveJoinSeat(result.metadata.players, requestedPlayerID);
if (!joinSeat.playerID) {
if (joinSeat.reason === 'player_not_found') {
ctx.throw(404, `Player ${requestedPlayerID} not found`);
return;
}
if (joinSeat.reason === 'seat_occupied') {
ctx.throw(409, `Seat ${requestedPlayerID} is occupied`);
return;
}
ctx.throw(409, 'Room is full');
return;
}
const playerID = joinSeat.playerID;
const credentials = nanoid(21);
const metadata = result.metadata;
// 解析真实用户标识
const authHeader = ctx.get('authorization');
const rawToken = claimSeatUtils.parseBearerToken(authHeader);
const jwtPayload = rawToken ? claimSeatUtils.verifyGameToken(rawToken, JWT_SECRET) : null;
let playerOwnerKey: string | undefined;
if (jwtPayload?.userId) {
playerOwnerKey = `user:${jwtPayload.userId}`;
} else if (guestId) {
playerOwnerKey = `guest:${guestId}`;
}
metadata.players[playerID] = {
...metadata.players[playerID],
name: playerName.trim(),
credentials,
...(playerOwnerKey ? { ownerKey: playerOwnerKey } : {}),
};
metadata.updatedAt = Date.now();
// 状态机:所有座位都有玩家时,从 waiting → playing
if (metadata.status === 'waiting' || !metadata.status) {
if (areAllSeatsOccupied(metadata.players)) {
metadata.status = 'playing';
}
}
await storage.setMetadata(matchID, metadata);
gameTransport.updateMatchMetadata(matchID, metadata);
ctx.body = { playerID, playerCredentials: credentials };
setTimeout(() => void handleMatchJoined(matchID, gameName), 100);
});
// POST /games/:name/:matchID/leave — 离开对局(释放座位)
router.post('/games/:name/:matchID/leave', async (ctx) => {
const gameName = normalizeGameName(ctx.params.name);
const matchID = ctx.params.matchID;
const body = ctx.request.body as { playerID?: string; credentials?: string } | undefined;
const playerID = body?.playerID;
const credentials = body?.credentials;
if (!playerID) {
ctx.throw(403, 'playerID is required');
return;
}
if (!credentials) {
ctx.throw(403, 'credentials is required');
return;
}
const result = await storage.fetch(matchID, { metadata: true });
if (!result.metadata) {
ctx.throw(404, `Match ${matchID} not found`);
return;
}
const metadata = result.metadata;
const playerMeta = metadata.players[playerID];
if (!playerMeta) {
ctx.throw(404, `Player ${playerID} not found`);