network: reworked client-server events (related to triggers dialog problem from #11173) (#11189)

* added bad connection mode to test client works on slow network, use -Dxmage.badconnection;
* added bad connection protection in events processing due event type;
* split events to different types (can be ignored, must be synced, etc);
* removed some unused server events.
This commit is contained in:
Oleg Agafonov 2023-09-21 18:40:52 +04:00 committed by GitHub
parent fa8e93a29d
commit 342979a55a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 299 additions and 202 deletions

View file

@ -16,6 +16,7 @@ import mage.client.util.audio.AudioManager;
import mage.client.util.object.SaveObjectUtil;
import mage.interfaces.callback.CallbackClient;
import mage.interfaces.callback.ClientCallback;
import mage.interfaces.callback.ClientCallbackType;
import mage.remote.ActionData;
import mage.remote.Session;
import mage.view.*;
@ -24,8 +25,7 @@ import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.UUID;
import java.util.*;
/**
* @author BetaSteward_at_googlemail.com
@ -34,38 +34,76 @@ public class CallbackClientImpl implements CallbackClient {
private static final Logger logger = Logger.getLogger(CallbackClientImpl.class);
private final MageFrame frame;
private int messageId = 0;
private int gameInformMessageId = 0;
private final Map<ClientCallbackType, Integer> lastMessages;
public CallbackClientImpl(MageFrame frame) {
this.frame = frame;
this.lastMessages = new HashMap<>();
Arrays.stream(ClientCallbackType.values()).forEach(t -> this.lastMessages.put(t, 0));
}
@Override
public synchronized void processCallback(final ClientCallback callback) {
callback.decompressData();
// put replay related code here
SaveObjectUtil.saveObject(callback.getData(), callback.getMethod().toString());
// all GUI related code must be executed in swing thread
SwingUtilities.invokeLater(() -> {
try {
logger.debug(callback.getMessageId() + " -- " + callback.getMethod());
logger.debug("message " + callback.getMessageId() + " - " + callback.getMethod().getType() + " - " + callback.getMethod());
// process bad connection (events can income in wrong order, so outdated data must be ignored)
// - table/dialog events like game start, game end, choose dialog - must be processed anyway
// - messages events like chat, inform, error - must be processed anyway
// - update events like opponent priority - can be ignored
if (!callback.getMethod().getType().equals(ClientCallbackType.CLIENT_SIDE_EVENT)) {
int lastAnyMessageId = this.lastMessages.values().stream().mapToInt(x -> x).max().orElse(0);
if (lastAnyMessageId > callback.getMessageId()) {
// un-synced message
if (callback.getMethod().getType().mustIgnoreOnOutdated()) {
// ignore
logger.warn(String.format("ignore un-synced message %d - %s - %s, possible reason: slow connection/performance",
callback.getMessageId(),
callback.getMethod().getType(),
callback.getMethod()
));
return;
} else {
// process it anyway
logger.debug(String.format("processing un-synced message %d - %s - %s, possible reason: slow connection/performance",
callback.getMessageId(),
callback.getMethod().getType(),
callback.getMethod()
));
}
}
// keep track of synced messages only
if (!callback.getMethod().getType().canProcessInAnyOrder()) {
this.lastMessages.put(callback.getMethod().getType(), callback.getMessageId());
}
}
switch (callback.getMethod()) {
case START_GAME: {
TableClientMessage message = (TableClientMessage) callback.getData();
GameManager.instance.setCurrentPlayerUUID(message.getPlayerId());
gameStarted(message.getGameId(), message.getPlayerId());
gameStarted(callback.getMessageId(), message.getGameId(), message.getPlayerId());
break;
}
case START_TOURNAMENT: {
TableClientMessage message = (TableClientMessage) callback.getData();
tournamentStarted(message.getGameId(), message.getPlayerId());
tournamentStarted(callback.getMessageId(), message.getGameId(), message.getPlayerId());
break;
}
case START_DRAFT: {
TableClientMessage message = (TableClientMessage) callback.getData();
draftStarted(message.getGameId(), message.getPlayerId());
draftStarted(callback.getMessageId(), message.getGameId(), message.getPlayerId());
break;
}
@ -149,7 +187,7 @@ public class CallbackClientImpl implements CallbackClient {
case REPLAY_INIT: {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
panel.init((GameView) callback.getData());
panel.init(callback.getMessageId(), (GameView) callback.getData());
}
break;
}
@ -157,7 +195,7 @@ public class CallbackClientImpl implements CallbackClient {
case REPLAY_DONE: {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
panel.endMessage(null, null, (String) callback.getData(), callback.getMessageId());
panel.endMessage(callback.getMessageId(), null, null, (String) callback.getData());
}
break;
}
@ -165,7 +203,7 @@ public class CallbackClientImpl implements CallbackClient {
case REPLAY_UPDATE: {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
panel.updateGame((GameView) callback.getData());
panel.updateGame(callback.getMessageId(), (GameView) callback.getData());
}
break;
}
@ -174,7 +212,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_INIT", callback.getObjectId(), callback.getData());
panel.init((GameView) callback.getData());
panel.init(callback.getMessageId(), (GameView) callback.getData());
}
break;
}
@ -190,7 +228,7 @@ public class CallbackClientImpl implements CallbackClient {
String logFileName = "game-" + gameId + ".json";
S3Uploader.upload(logFileName, gameId.toString());
}
panel.endMessage(message.getGameView(), message.getOptions(), message.getMessage(), callback.getMessageId());
panel.endMessage(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage());
}
break;
}
@ -205,7 +243,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_ASK", callback.getObjectId(), message);
panel.ask(message.getMessage(), message.getGameView(), callback.getMessageId(), message.getOptions());
panel.ask(callback.getMessageId(), message.getGameView(), message.getMessage(), message.getOptions());
}
break;
}
@ -216,8 +254,8 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_TARGET", callback.getObjectId(), message);
panel.pickTarget(message.getGameView(), message.getOptions(), message.getMessage(),
message.getCardsView1(), message.getTargets(), message.isFlag(), callback.getMessageId());
panel.pickTarget(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage(),
message.getCardsView1(), message.getTargets(), message.isFlag());
}
break;
}
@ -227,7 +265,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_SELECT", callback.getObjectId(), message);
panel.select(message.getGameView(), message.getOptions(), message.getMessage(), callback.getMessageId());
panel.select(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage());
}
break;
}
@ -237,7 +275,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_CHOOSE_ABILITY", callback.getObjectId(), callback.getData());
panel.pickAbility(abilityPickerView.getGameView(), null, abilityPickerView);
panel.pickAbility(callback.getMessageId(), abilityPickerView.getGameView(), null, abilityPickerView);
}
break;
}
@ -247,7 +285,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_CHOOSE_PILE", callback.getObjectId(), message);
panel.pickPile(message.getGameView(), message.getOptions(), message.getMessage(), message.getCardsView1(), message.getCardsView2());
panel.pickPile(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage(), message.getCardsView1(), message.getCardsView2());
}
break;
}
@ -257,7 +295,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_CHOOSE_CHOICE", callback.getObjectId(), message);
panel.getChoice(message.getGameView(), message.getOptions(), message.getChoice(), callback.getObjectId());
panel.getChoice(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getChoice(), callback.getObjectId());
}
break;
}
@ -267,7 +305,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_PLAY_MANA", callback.getObjectId(), message);
panel.playMana(message.getGameView(), message.getOptions(), message.getMessage(), callback.getMessageId());
panel.playMana(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage());
}
break;
}
@ -277,7 +315,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_PLAY_XMANA", callback.getObjectId(), message);
panel.playXMana(message.getGameView(), message.getOptions(), message.getMessage(), callback.getMessageId());
panel.playXMana(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMessage());
}
break;
}
@ -287,8 +325,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_GET_AMOUNT", callback.getObjectId(), message);
panel.getAmount(message.getGameView(), message.getOptions(), message.getMin(), message.getMax(), message.getMessage());
panel.getAmount(callback.getMessageId(), message.getGameView(), message.getOptions(), message.getMin(), message.getMax(), message.getMessage());
}
break;
}
@ -298,8 +335,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_GET_MULTI_AMOUNT", callback.getObjectId(), message);
panel.getMultiAmount(message.getMessages(), message.getGameView(), message.getOptions(), message.getMin(), message.getMax());
panel.getMultiAmount(callback.getMessageId(), message.getGameView(), message.getMessages(), message.getOptions(), message.getMin(), message.getMax());
}
break;
}
@ -308,7 +344,7 @@ public class CallbackClientImpl implements CallbackClient {
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_UPDATE", callback.getObjectId(), callback.getData());
panel.updateGame((GameView) callback.getData(), true, null, null); // update after undo wtf?!
panel.updateGame(callback.getMessageId(), (GameView) callback.getData(), true, null, null); // update after undo wtf?! // TODO: clean dialogs?!
}
break;
}
@ -337,20 +373,12 @@ public class CallbackClientImpl implements CallbackClient {
}
case GAME_INFORM: {
if (callback.getMessageId() > gameInformMessageId) {
{
GameClientMessage message = (GameClientMessage) callback.getData();
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_INFORM", callback.getObjectId(), message);
panel.inform(message.getMessage(), message.getGameView(), callback.getMessageId());
}
}
// no longer needed because phase skip handling on server side now
} else {
logger.warn(new StringBuilder("message out of sequence - ignoring").append("MessageId = ").append(callback.getMessageId()).append(" method = ").append(callback.getMethod()));
GameClientMessage message = (GameClientMessage) callback.getData();
GamePanel panel = MageFrame.getGame(callback.getObjectId());
if (panel != null) {
appendJsonEvent("GAME_INFORM", callback.getObjectId(), message);
panel.inform(callback.getMessageId(), message.getGameView(), message.getMessage());
}
gameInformMessageId = messageId;
break;
}
@ -432,14 +460,10 @@ public class CallbackClientImpl implements CallbackClient {
}
default: {
// TODO: add exception here and process miss events like TOURNAMENT_UPDATE
break;
}
}
// sync message for server side events only
if (!callback.getMethod().isClientSideMessage()) {
messageId = callback.getMessageId();
}
} catch (Exception ex) {
handleException(ex);
}
@ -466,50 +490,50 @@ public class CallbackClientImpl implements CallbackClient {
switch (usedPanel.getChatType()) {
case GAME:
usedPanel.receiveMessage("", new StringBuilder()
.append("HOTKEYS:")
.append("<br/>Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over")
.append("<br/>Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_CONFIRM)))
.append("</b> - Confirm \"Ok\", \"Yes\" or \"Done\" button")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_NEXT_TURN)))
.append("</b> - Skip current turn but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_END_STEP)))
.append("</b> - Skip to next end step but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_SKIP_STEP)))
.append("</b> - Skip current turn but stop on declare attackers/blockers")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_MAIN_STEP)))
.append("</b> - Skip to next main phase but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_YOUR_TURN)))
.append("</b> - Skip everything until your next turn")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_PRIOR_END)))
.append("</b> - Skip everything until the end step just prior to your turn")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_CANCEL_SKIP)))
.append("</b> - Undo F4/F5/F7/F9/F11")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_SWITCH_CHAT)))
.append("</b> - Switch in/out to chat text field")
/*
.append("HOTKEYS:")
.append("<br/>Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over")
.append("<br/>Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_TOGGLE_MACRO)))
.append("</b> - Toggle recording a sequence of actions to repeat. Will not pause if interrupted and can fail if a selected card changes such as when scrying top card to bottom.")
.append("<br/><b>").append(System.getProperty("os.name").contains("Mac OS X") ? "Cmd" : "Ctrl").append(" + click</b> - Hold priority while casting a spell or activating an ability")
*/
.append("<br/>")
.append("<br/>")
.append("CHAT COMMANDS:")
.append("<br/>").append("<b>/h username </b> - show player's stats (history)")
.append("<br/>").append("<b>/w username message</b> - send private message to player (whisper)")
.append("<br/>").append("<b>/pings</b> - show players and watchers ping")
.append("<br/>").append("<b>/fix</b> - fix frozen game")
.toString(),
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_CONFIRM)))
.append("</b> - Confirm \"Ok\", \"Yes\" or \"Done\" button")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_NEXT_TURN)))
.append("</b> - Skip current turn but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_END_STEP)))
.append("</b> - Skip to next end step but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_SKIP_STEP)))
.append("</b> - Skip current turn but stop on declare attackers/blockers")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_MAIN_STEP)))
.append("</b> - Skip to next main phase but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_YOUR_TURN)))
.append("</b> - Skip everything until your next turn")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_PRIOR_END)))
.append("</b> - Skip everything until the end step just prior to your turn")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_CANCEL_SKIP)))
.append("</b> - Undo F4/F5/F7/F9/F11")
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_SWITCH_CHAT)))
.append("</b> - Switch in/out to chat text field")
/*
.append("<br/><b>")
.append(KeyEvent.getKeyText(PreferencesDialog.getCurrentControlKey(PreferencesDialog.KEY_CONTROL_TOGGLE_MACRO)))
.append("</b> - Toggle recording a sequence of actions to repeat. Will not pause if interrupted and can fail if a selected card changes such as when scrying top card to bottom.")
.append("<br/><b>").append(System.getProperty("os.name").contains("Mac OS X") ? "Cmd" : "Ctrl").append(" + click</b> - Hold priority while casting a spell or activating an ability")
*/
.append("<br/>")
.append("<br/>")
.append("CHAT COMMANDS:")
.append("<br/>").append("<b>/h username </b> - show player's stats (history)")
.append("<br/>").append("<b>/w username message</b> - send private message to player (whisper)")
.append("<br/>").append("<b>/pings</b> - show players and watchers ping")
.append("<br/>").append("<b>/fix</b> - fix frozen game")
.toString(),
null, null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE);
break;
case TOURNAMENT:
@ -519,10 +543,10 @@ public class CallbackClientImpl implements CallbackClient {
case TABLES:
String serverAddress = SessionHandler.getSession().getServerHostname().orElse("");
usedPanel.receiveMessage("", new StringBuilder("Download card images by using the \"Images\" main menu.")
.append("<br/>Download icons and symbols by using the \"Symbols\" main menu.")
.append("<br/>\\list - show a list of available chat commands.")
.append("<br/>").append(IgnoreList.usage(serverAddress))
.append("<br/>Type <font color=green>\\w yourUserName profanity 0 (or 1 or 2)</font> to turn off/on the profanity filter").toString(),
.append("<br/>Download icons and symbols by using the \"Symbols\" main menu.")
.append("<br/>\\list - show a list of available chat commands.")
.append("<br/>").append(IgnoreList.usage(serverAddress))
.append("<br/>Type <font color=green>\\w yourUserName profanity 0 (or 1 or 2)</font> to turn off/on the profanity filter").toString(),
null, null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE);
break;
default:
@ -539,7 +563,7 @@ public class CallbackClientImpl implements CallbackClient {
}
}
protected void gameStarted(final UUID gameId, final UUID playerId) {
protected void gameStarted(final int messageId, final UUID gameId, final UUID playerId) {
try {
frame.showGame(gameId, playerId);
logger.info("Game " + gameId + " started for player " + playerId);
@ -552,7 +576,7 @@ public class CallbackClientImpl implements CallbackClient {
}
}
protected void draftStarted(UUID draftId, UUID playerId) {
protected void draftStarted(int messageId, UUID draftId, UUID playerId) {
try {
frame.showDraft(draftId);
logger.info("Draft " + draftId + " started for player " + playerId);
@ -561,7 +585,7 @@ public class CallbackClientImpl implements CallbackClient {
}
}
protected void tournamentStarted(UUID tournamentId, UUID playerId) {
protected void tournamentStarted(int messageId, UUID tournamentId, UUID playerId) {
try {
frame.showTournament(tournamentId);
AudioManager.playTournamentStarted();