-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathTransport.ts
More file actions
765 lines (682 loc) · 20.7 KB
/
Copy pathTransport.ts
File metadata and controls
765 lines (682 loc) · 20.7 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
import { ClientEnv } from "src/client/ClientEnv";
import { z } from "zod";
import { EventBus, GameEvent } from "../core/EventBus";
import {
AllPlayers,
GameType,
Gold,
PlayerID,
Tick,
UnitType,
} from "../core/game/Game";
import { TileRef } from "../core/game/GameMap";
import {
AllPlayersStats,
batchMoveWarshipUnitIds,
ClientHashMessage,
ClientIntentMessage,
ClientJoinMessage,
ClientMessage,
ClientPingMessage,
ClientRejoinMessage,
ClientSendLiveStatsMessage,
ClientSendWinnerMessage,
GameConfig,
Intent,
LiveStats,
ServerMessage,
ServerMessageSchema,
Winner,
} from "../core/Schemas";
import { replacer } from "../core/Util";
import { getPlayToken } from "./Auth";
import { LobbyConfig } from "./ClientGameRunner";
import { showInGameAlert } from "./InGameModal";
import { LocalServer } from "./LocalServer";
import { PacedSender } from "./PacedSender";
import { translateText } from "./Utils";
import { PlayerView } from "./view";
// Spacing between batched move_warship intents. The server allows 10 intents
// per second across all types; this stays clear of that with room for the
// player's other actions.
const WARSHIP_BATCH_INTERVAL_MS = 150;
export class PauseGameIntentEvent implements GameEvent {
constructor(public readonly paused: boolean) {}
}
export class SendAllianceRequestIntentEvent implements GameEvent {
constructor(
public readonly requestor: PlayerView,
public readonly recipient: PlayerView,
) {}
}
export class SendBreakAllianceIntentEvent implements GameEvent {
constructor(
public readonly requestor: PlayerView,
public readonly recipient: PlayerView,
) {}
}
export class SendUpgradeStructureIntentEvent implements GameEvent {
constructor(
public readonly unitId: number,
public readonly unitType: UnitType,
) {}
}
export class SendAllianceRejectIntentEvent implements GameEvent {
constructor(public readonly requestor: PlayerView) {}
}
export class SendAllianceExtensionIntentEvent implements GameEvent {
constructor(public readonly recipient: PlayerView) {}
}
export class SendSpawnIntentEvent implements GameEvent {
constructor(public readonly tile: TileRef) {}
}
export class SendAttackIntentEvent implements GameEvent {
constructor(
public readonly targetID: PlayerID | null,
public readonly troops: number,
) {}
}
export class SendBoatAttackIntentEvent implements GameEvent {
constructor(
public readonly dst: TileRef,
public readonly troops: number,
) {}
}
export class BuildUnitIntentEvent implements GameEvent {
constructor(
public readonly unit: UnitType,
public readonly tile: TileRef,
public readonly rocketDirectionUp?: boolean,
) {}
}
export class SendTargetPlayerIntentEvent implements GameEvent {
constructor(public readonly targetID: PlayerID) {}
}
export class SendEmojiIntentEvent implements GameEvent {
constructor(
public readonly recipient: PlayerView | typeof AllPlayers,
public readonly emoji: number,
) {}
}
export class SendDonateGoldIntentEvent implements GameEvent {
constructor(
public readonly recipient: PlayerView,
public readonly gold: Gold | null,
) {}
}
export class SendDonateTroopsIntentEvent implements GameEvent {
constructor(
public readonly recipient: PlayerView,
public readonly troops: number | null,
) {}
}
export class SendQuickChatEvent implements GameEvent {
constructor(
public readonly recipient: PlayerView,
public readonly quickChatKey: string,
public readonly target?: PlayerID,
) {}
}
export class SendEmbargoIntentEvent implements GameEvent {
constructor(
public readonly target: PlayerView,
public readonly action: "start" | "stop",
) {}
}
export class SendEmbargoAllIntentEvent implements GameEvent {
constructor(public readonly action: "start" | "stop") {}
}
export class SendDeleteUnitIntentEvent implements GameEvent {
constructor(public readonly unitId: number) {}
}
export class CancelAttackIntentEvent implements GameEvent {
constructor(public readonly attackID: string) {}
}
export class CancelBoatIntentEvent implements GameEvent {
constructor(public readonly unitID: number) {}
}
export class SendWinnerEvent implements GameEvent {
constructor(
public readonly winner: Winner,
public readonly allPlayersStats: AllPlayersStats,
) {}
}
export class SendLiveStatsEvent implements GameEvent {
constructor(public readonly stats: LiveStats) {}
}
export class SendHashEvent implements GameEvent {
constructor(
public readonly tick: Tick,
public readonly hash: number,
) {}
}
// Emitted when the server tells us the host started a successor lobby, carrying
// the new game id to move the group to.
export class NewLobbyEvent implements GameEvent {
constructor(public readonly gameID: string) {}
}
export class MoveWarshipIntentEvent implements GameEvent {
constructor(
public readonly unitIds: number[],
public readonly tile: number,
) {}
}
export class SendKickPlayerIntentEvent implements GameEvent {
constructor(public readonly target: string) {}
}
export class SendUpdateGameConfigIntentEvent implements GameEvent {
constructor(public readonly config: Partial<GameConfig>) {}
}
export class SendToggleGameStartTimer implements GameEvent {
constructor() {}
}
export class Transport {
private socket: WebSocket | null = null;
private localServer: LocalServer;
private buffer: string[] = [];
private onconnect: () => void;
private onmessage: (msg: ServerMessage) => void;
private pingInterval: number | null = null;
private readonly warshipBatches: PacedSender;
public readonly isLocal: boolean;
constructor(
private lobbyConfig: LobbyConfig,
private eventBus: EventBus,
) {
// If gameRecord is not null, we are replaying an archived game.
// For multiplayer games, GameConfig is not known until game starts.
this.isLocal =
lobbyConfig.gameRecord !== undefined ||
lobbyConfig.gameStartInfo?.config.gameType === GameType.Singleplayer;
// The local server has no rate limiter, so only remote games need spacing.
this.warshipBatches = new PacedSender(
this.isLocal ? 0 : WARSHIP_BATCH_INTERVAL_MS,
);
this.eventBus.on(SendAllianceRequestIntentEvent, (e) =>
this.onSendAllianceRequest(e),
);
this.eventBus.on(SendAllianceRejectIntentEvent, (e) =>
this.onAllianceRejectUIEvent(e),
);
this.eventBus.on(SendAllianceExtensionIntentEvent, (e) =>
this.onSendAllianceExtensionIntent(e),
);
this.eventBus.on(SendBreakAllianceIntentEvent, (e) =>
this.onBreakAllianceRequestUIEvent(e),
);
this.eventBus.on(SendSpawnIntentEvent, (e) =>
this.onSendSpawnIntentEvent(e),
);
this.eventBus.on(SendAttackIntentEvent, (e) => this.onSendAttackIntent(e));
this.eventBus.on(SendUpgradeStructureIntentEvent, (e) =>
this.onSendUpgradeStructureIntent(e),
);
this.eventBus.on(SendBoatAttackIntentEvent, (e) =>
this.onSendBoatAttackIntent(e),
);
this.eventBus.on(SendTargetPlayerIntentEvent, (e) =>
this.onSendTargetPlayerIntent(e),
);
this.eventBus.on(SendEmojiIntentEvent, (e) => this.onSendEmojiIntent(e));
this.eventBus.on(SendDonateGoldIntentEvent, (e) =>
this.onSendDonateGoldIntent(e),
);
this.eventBus.on(SendDonateTroopsIntentEvent, (e) =>
this.onSendDonateTroopIntent(e),
);
this.eventBus.on(SendQuickChatEvent, (e) => this.onSendQuickChatIntent(e));
this.eventBus.on(SendEmbargoIntentEvent, (e) =>
this.onSendEmbargoIntent(e),
);
this.eventBus.on(SendEmbargoAllIntentEvent, (e) =>
this.onSendEmbargoAllIntent(e),
);
this.eventBus.on(BuildUnitIntentEvent, (e) => this.onBuildUnitIntent(e));
this.eventBus.on(PauseGameIntentEvent, (e) => this.onPauseGameIntent(e));
this.eventBus.on(SendWinnerEvent, (e) => this.onSendWinnerEvent(e));
this.eventBus.on(SendLiveStatsEvent, (e) => this.onSendLiveStatsEvent(e));
this.eventBus.on(SendHashEvent, (e) => this.onSendHashEvent(e));
this.eventBus.on(CancelAttackIntentEvent, (e) =>
this.onCancelAttackIntentEvent(e),
);
this.eventBus.on(CancelBoatIntentEvent, (e) =>
this.onCancelBoatIntentEvent(e),
);
this.eventBus.on(MoveWarshipIntentEvent, (e) => {
this.onMoveWarshipEvent(e);
});
this.eventBus.on(SendDeleteUnitIntentEvent, (e) =>
this.onSendDeleteUnitIntent(e),
);
this.eventBus.on(SendKickPlayerIntentEvent, (e) =>
this.onSendKickPlayerIntent(e),
);
this.eventBus.on(SendUpdateGameConfigIntentEvent, (e) =>
this.onSendUpdateGameConfigIntent(e),
);
this.eventBus.on(SendToggleGameStartTimer, (e) =>
this.onSendToggleGameStartTimer(e),
);
}
private startPing() {
if (this.isLocal) return;
this.pingInterval ??= window.setInterval(() => {
if (this.socket !== null && this.socket.readyState === WebSocket.OPEN) {
this.sendMsg({
type: "ping",
} satisfies ClientPingMessage);
}
}, 5 * 1000);
}
private stopPing() {
if (this.pingInterval) {
window.clearInterval(this.pingInterval);
this.pingInterval = null;
}
}
public connect(
onconnect: () => void,
onmessage: (message: ServerMessage) => void,
) {
if (this.isLocal) {
this.connectLocal(onconnect, onmessage);
} else {
this.connectRemote(onconnect, onmessage);
}
}
public updateCallback(
onconnect: () => void,
onmessage: (message: ServerMessage) => void,
) {
if (this.isLocal) {
this.localServer.updateCallback(onconnect, onmessage);
} else {
this.onconnect = onconnect;
this.onmessage = onmessage;
}
}
private connectLocal(
onconnect: () => void,
onmessage: (message: ServerMessage) => void,
) {
this.localServer = new LocalServer(
this.lobbyConfig,
this.lobbyConfig.gameRecord !== undefined,
this.eventBus,
);
this.localServer.updateCallback(onconnect, onmessage);
this.localServer.start();
}
private connectRemote(
onconnect: () => void,
onmessage: (message: ServerMessage) => void,
) {
this.startPing();
this.killExistingSocket();
// WS origin comes from ClientEnv (same-origin on web, audience-derived on
// the desktop app://openfront origin), not window.location.host.
const workerPath = ClientEnv.workerPath(this.lobbyConfig.gameID);
this.socket = new WebSocket(`${ClientEnv.serverWsBase()}/${workerPath}`);
this.onconnect = onconnect;
this.onmessage = onmessage;
this.socket.onopen = () => {
console.log("Connected to game server!");
if (this.socket === null) {
console.error("socket is null");
return;
}
while (this.buffer.length > 0) {
console.log("sending dropped message");
const msg = this.buffer.pop();
if (msg === undefined) {
console.warn("msg is undefined");
continue;
}
this.socket.send(msg);
}
onconnect();
};
this.socket.onmessage = (event: MessageEvent) => {
try {
const parsed = JSON.parse(event.data);
const result = ServerMessageSchema.safeParse(parsed);
if (!result.success) {
const error = z.prettifyError(result.error);
console.error("Error parsing server message", error);
return;
}
this.onmessage(result.data);
} catch (e) {
console.error("Error in onmessage handler:", e, event.data);
return;
}
};
this.socket.onerror = (err) => {
console.error("Socket encountered error: ", err, "Closing socket");
if (this.socket === null) return;
this.socket.close();
};
this.socket.onclose = (event: CloseEvent) => {
console.log(
`WebSocket closed. Code: ${event.code}, Reason: ${event.reason}`,
);
if (event.code === 1002) {
showInGameAlert(
translateText("error_modal.connection_refused", {
reason: event.reason,
}),
);
} else if (event.code !== 1000) {
console.log(`received error code ${event.code}, reconnecting`);
this.reconnect();
}
};
}
public reconnect() {
this.connect(this.onconnect, this.onmessage);
}
public turnComplete() {
if (this.isLocal) {
this.localServer.turnComplete();
}
}
async joinGame() {
this.sendMsg({
type: "join",
gameID: this.lobbyConfig.gameID,
// Note: clientID is not sent - server assigns it based on persistentID
username: this.lobbyConfig.playerName,
clanTag: this.lobbyConfig.playerClanTag ?? null,
cosmetics: this.lobbyConfig.cosmetics,
turnstileToken: this.lobbyConfig.turnstileToken,
token: await getPlayToken(),
} satisfies ClientJoinMessage);
}
async rejoinGame(lastTurn: number) {
this.sendMsg({
type: "rejoin",
gameID: this.lobbyConfig.gameID,
// Note: clientID is not sent - server looks it up from persistentID in token
lastTurn: lastTurn,
token: await getPlayToken(),
} satisfies ClientRejoinMessage);
}
leaveGame() {
this.warshipBatches.clear();
if (this.isLocal) {
this.localServer.endGame();
return;
}
this.stopPing();
if (this.socket === null) return;
if (this.socket.readyState === WebSocket.OPEN) {
console.log("on stop: leaving game");
this.killExistingSocket();
} else {
console.log(
"WebSocket is not open. Current state:",
this.socket.readyState,
);
console.error("attempting reconnect");
this.killExistingSocket();
}
}
private onSendAllianceRequest(event: SendAllianceRequestIntentEvent) {
this.sendIntent({
type: "allianceRequest",
recipient: event.recipient.id(),
});
}
private onAllianceRejectUIEvent(event: SendAllianceRejectIntentEvent) {
this.sendIntent({
type: "allianceReject",
requestor: event.requestor.id(),
});
}
private onBreakAllianceRequestUIEvent(event: SendBreakAllianceIntentEvent) {
this.sendIntent({
type: "breakAlliance",
recipient: event.recipient.id(),
});
}
private onSendAllianceExtensionIntent(
event: SendAllianceExtensionIntentEvent,
) {
this.sendIntent({
type: "allianceExtension",
recipient: event.recipient.id(),
});
}
private onSendSpawnIntentEvent(event: SendSpawnIntentEvent) {
this.sendIntent({
type: "spawn",
tile: event.tile,
});
}
private onSendAttackIntent(event: SendAttackIntentEvent) {
this.sendIntent({
type: "attack",
targetID: event.targetID,
troops: event.troops,
});
}
private onSendBoatAttackIntent(event: SendBoatAttackIntentEvent) {
this.sendIntent({
type: "boat",
troops: event.troops,
dst: event.dst,
});
}
private onSendUpgradeStructureIntent(event: SendUpgradeStructureIntentEvent) {
this.sendIntent({
type: "upgrade_structure",
unit: event.unitType,
unitId: event.unitId,
});
}
private onSendTargetPlayerIntent(event: SendTargetPlayerIntentEvent) {
this.sendIntent({
type: "targetPlayer",
target: event.targetID,
});
}
private onSendEmojiIntent(event: SendEmojiIntentEvent) {
this.sendIntent({
type: "emoji",
recipient:
event.recipient === AllPlayers ? AllPlayers : event.recipient.id(),
emoji: event.emoji,
});
}
private onSendDonateGoldIntent(event: SendDonateGoldIntentEvent) {
this.sendIntent({
type: "donate_gold",
recipient: event.recipient.id(),
gold: event.gold ? Number(event.gold) : null,
});
}
private onSendDonateTroopIntent(event: SendDonateTroopsIntentEvent) {
this.sendIntent({
type: "donate_troops",
recipient: event.recipient.id(),
troops: event.troops,
});
}
private onSendQuickChatIntent(event: SendQuickChatEvent) {
this.sendIntent({
type: "quick_chat",
recipient: event.recipient.id(),
quickChatKey: event.quickChatKey,
target: event.target,
});
}
private onSendEmbargoIntent(event: SendEmbargoIntentEvent) {
this.sendIntent({
type: "embargo",
targetID: event.target.id(),
action: event.action,
});
}
private onSendEmbargoAllIntent(event: SendEmbargoAllIntentEvent) {
this.sendIntent({
type: "embargo_all",
action: event.action,
});
}
private onBuildUnitIntent(event: BuildUnitIntentEvent) {
this.sendIntent({
type: "build_unit",
unit: event.unit,
tile: event.tile,
rocketDirectionUp: event.rocketDirectionUp,
});
}
private onPauseGameIntent(event: PauseGameIntentEvent) {
this.sendIntent({
type: "toggle_pause",
paused: event.paused,
});
}
private onSendWinnerEvent(event: SendWinnerEvent) {
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
this.sendMsg({
type: "winner",
winner: event.winner,
allPlayersStats: event.allPlayersStats,
} satisfies ClientSendWinnerMessage);
} else {
console.log(
"WebSocket is not open. Current state:",
this.socket?.readyState,
);
console.log("attempting reconnect");
}
}
private onSendLiveStatsEvent(event: SendLiveStatsEvent) {
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
this.sendMsg({
type: "live_stats",
stats: event.stats,
} satisfies ClientSendLiveStatsMessage);
}
}
private onSendHashEvent(event: SendHashEvent) {
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
this.sendMsg({
type: "hash",
turnNumber: event.tick,
hash: event.hash,
} satisfies ClientHashMessage);
} else {
console.log(
"WebSocket is not open. Current state:",
this.socket?.readyState,
);
console.log("attempting reconnect");
}
}
private onCancelAttackIntentEvent(event: CancelAttackIntentEvent) {
this.sendIntent({
type: "cancel_attack",
attackID: event.attackID,
});
}
private onCancelBoatIntentEvent(event: CancelBoatIntentEvent) {
this.sendIntent({
type: "cancel_boat",
unitID: event.unitID,
});
}
private onMoveWarshipEvent(event: MoveWarshipIntentEvent) {
for (const unitIds of batchMoveWarshipUnitIds(event.unitIds, event.tile)) {
this.warshipBatches.push(() =>
this.sendIntent({
type: "move_warship",
unitIds,
tile: event.tile,
}),
);
}
}
private onSendDeleteUnitIntent(event: SendDeleteUnitIntentEvent) {
this.sendIntent({
type: "delete_unit",
unitId: event.unitId,
});
}
private onSendKickPlayerIntent(event: SendKickPlayerIntentEvent) {
this.sendIntent({
type: "kick_player",
targetClientID: event.target,
});
}
private onSendUpdateGameConfigIntent(event: SendUpdateGameConfigIntentEvent) {
this.sendIntent({
type: "update_game_config",
config: event.config,
});
}
private onSendToggleGameStartTimer(event: SendToggleGameStartTimer) {
this.sendIntent({ type: "toggle_game_start_timer" });
}
private sendIntent(intent: Intent): boolean {
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
const msg = {
type: "intent",
intent: intent,
} satisfies ClientIntentMessage;
this.sendMsg(msg);
return true;
}
console.log(
"WebSocket is not open. Current state:",
this.socket?.readyState,
);
console.log("attempting reconnect");
return false;
}
private sendMsg(msg: ClientMessage) {
if (this.isLocal) {
// Forward message to local server
this.localServer.onMessage(msg);
return;
} else if (this.socket === null) {
// Socket missing, do nothing
return;
}
const str = JSON.stringify(msg, replacer);
if (this.socket.readyState === WebSocket.CLOSED) {
// Buffer message
console.warn("socket not ready, closing and trying later");
this.socket.close();
this.socket = null;
this.connectRemote(this.onconnect, this.onmessage);
this.buffer.push(str);
} else {
// Send the message directly
this.socket.send(str);
}
}
private killExistingSocket(): void {
if (this.socket === null) {
return;
}
// Remove all event listeners
this.socket.onmessage = null;
this.socket.onopen = null;
this.socket.onclose = null;
this.socket.onerror = null;
// Close the connection if it's still open or still connecting
try {
if (
this.socket.readyState === WebSocket.OPEN ||
this.socket.readyState === WebSocket.CONNECTING
) {
this.socket.close();
}
} catch (e) {
console.warn("Error while closing WebSocket:", e);
}
this.socket = null;
}
}