Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

De-static RPCService #69

Merged
merged 2 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class IceAdapter implements Callable<Integer>, AutoCloseable, FafRpcCallb
private IceOptions iceOptions;

private GPGNetServer gpgNetServer;
private RPCService rpcService;

private final ExecutorService executor = ExecutorHolder.getExecutor();
private static final Lock lockGameSession = new ReentrantLock();
Expand Down Expand Up @@ -61,8 +62,12 @@ public void start() {

PeerIceModule.setForceRelay(iceOptions.isForceRelay());
gpgNetServer = new GPGNetServer();

This comment was marked as resolved.

gpgNetServer.init(iceOptions.getGpgnetPort(), iceOptions.getLobbyPort());
RPCService.init(iceOptions.getRpcPort(), this);
rpcService = new RPCService();
gpgNetServer.init(iceOptions.getGpgnetPort(), iceOptions.getLobbyPort(), rpcService);
rpcService.init(iceOptions.getRpcPort(), gpgNetServer, this);

PeerIceModule.setForceRelay(iceOptions.isForceRelay());
PeerIceModule.setRpcService(rpcService);

debug().startupComplete();
}
Expand All @@ -88,7 +93,7 @@ public void onConnectToPeer(String remotePlayerLogin, int remotePlayerId, boolea
if (gpgNetServer.isConnected()
&& gpgNetServer.getGameState().isPresent()
&& (gpgNetServer.getGameState().get() == GameState.LAUNCHING
|| GPGNetServer.getGameState().get() == GameState.ENDED)) {
|| gpgNetServer.getGameState().get() == GameState.ENDED)) {
log.warn("Game ended or in progress, ABORTING connectToPeer");
return;
}
Expand Down Expand Up @@ -146,7 +151,7 @@ public static void close(int status) {

onFAShutdown(); // will close gameSession aswell
INSTANCE.gpgNetServer.close();
RPCService.close();
INSTANCE.rpcService.close();

This comment was marked as resolved.

Debug.close();
TrayIcon.close();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
Expand All @@ -28,6 +29,7 @@ public class GPGNetServer implements AutoCloseable {

private int gpgnetPort;
private int lobbyPort;
private RPCService rpcService;
private ServerSocket serverSocket;
private volatile GPGNetClient currentClient;

Expand All @@ -39,18 +41,16 @@ public void sendToGpgNet(String header, Object... args) {
gpgNetClient.getLobbyFuture().thenRun(() -> gpgNetClient.sendGpgnetMessage(header, args)));
}

@Setter
private volatile LobbyInitMode lobbyInitMode = LobbyInitMode.NORMAL;

public static LobbyInitMode getLobbyInitMode() {
return INSTANCE.lobbyInitMode;
}

public static void setLobbyInitMode(LobbyInitMode mode) {
INSTANCE.lobbyInitMode = mode;
}

public void init(int gpgnetPort, int lobbyPort) {
public void init(int gpgnetPort, int lobbyPort, RPCService rpcService) {
INSTANCE = this;
this.rpcService = rpcService;

if (gpgnetPort == 0) {
this.gpgnetPort = NetworkToolbox.findFreeTCPPort(20000, 65536);
Expand Down Expand Up @@ -103,7 +103,7 @@ private GPGNetClient(Socket socket) {
}
listenerThread = Thread.startVirtualThread(this::listenerThread);

RPCService.onConnectionStateChanged("Connected");
rpcService.onConnectionStateChanged("Connected");
log.info("GPGNetClient has connected");
}

Expand Down Expand Up @@ -145,7 +145,7 @@ private void processGpgnetMessage(String command, List<Object> args) {
"Received GPGNet message: {} {}",
command,
args.stream().map(Object::toString).collect(Collectors.joining(" ")));
RPCService.onGpgNetMessageReceived(command, args);
rpcService.onGpgNetMessageReceived(command, args);
}

/**
Expand Down Expand Up @@ -227,7 +227,7 @@ private void onGpgnetConnectionLost() {
clientFuture = new CompletableFuture<>();
}

RPCService.onConnectionStateChanged("Disconnected");
rpcService.onConnectionStateChanged("Disconnected");

IceAdapter.onFAShutdown();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.ice4j.TransportAddress;
import org.ice4j.ice.*;
Expand All @@ -28,6 +29,9 @@
@Getter
@Slf4j
public class PeerIceModule {
@Setter
private static RPCService rpcService;

private static boolean ALLOW_HOST = true;
private static boolean ALLOW_REFLEXIVE = true;
private static boolean ALLOW_RELAY = true;
Expand Down Expand Up @@ -85,7 +89,7 @@ public PeerIceModule(Peer peer) {
*/
private void setState(IceState newState) {
this.iceState = newState;
RPCService.onIceConnectionStateChanged(IceAdapter.getId(), peer.getRemoteId(), iceState.getMessage());
rpcService.onIceConnectionStateChanged(IceAdapter.getId(), peer.getRemoteId(), iceState.getMessage());
debug().peerStateChanged(this.peer);
}

Expand Down Expand Up @@ -200,7 +204,7 @@ a, new LongTermCredential(iceServer.getTurnUsername(), iceServer.getTurnCredenti
.map(it -> it.type().toString() + "(" + it.protocol() + ")")
.collect(Collectors.joining(", ")));
setState(AWAITING_CANDIDATES);
RPCService.onIceMsg(localCandidatesMessage);
rpcService.onIceMsg(localCandidatesMessage);

// Make sure to abort the connection process and reinitiate when we haven't received an answer to our offer in 6
// seconds, candidate packet was probably lost
Expand Down Expand Up @@ -358,7 +362,7 @@ private void startIce() {

// We are connected
connected = true;
RPCService.onConnected(IceAdapter.getId(), peer.getRemoteId(), true);
rpcService.onConnected(IceAdapter.getId(), peer.getRemoteId(), true);
setState(CONNECTED);

if (component.getSelectedPair().getLocalCandidate().getType() == CandidateType.RELAYED_CANDIDATE) {
Expand Down Expand Up @@ -403,7 +407,7 @@ public void onConnectionLost() {
if (connected) {
connected = false;
log.warn("{} ICE connection has been lost for peer", getLogPrefix());
RPCService.onConnected(IceAdapter.getId(), peer.getRemoteId(), false);
rpcService.onConnected(IceAdapter.getId(), peer.getRemoteId(), false);
}

setState(DISCONNECTED);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class RPCHandler {
private final Lock lockStatus = new ReentrantLock();
private final int rpcPort;
private final FafRpcCallbacks callbacks;
private final GPGNetServer gpgNetServer;

public void hostGame(String mapName) {
callbacks.onHostGame(mapName);
Expand All @@ -55,7 +56,7 @@ public void disconnectFromPeer(long remotePlayerId) {
}

public void setLobbyInitMode(String lobbyInitMode) {
GPGNetServer.setLobbyInitMode(LobbyInitMode.getByName(lobbyInitMode));
gpgNetServer.setLobbyInitMode(LobbyInitMode.getByName(lobbyInitMode));
log.debug("LobbyInitMode set to {}", lobbyInitMode);
}

Expand Down Expand Up @@ -95,7 +96,7 @@ public void setIceServers(List<Map<String, Object>> iceServers) {
@SneakyThrows
public String status() {
IceStatus.IceGPGNetState gpgpnet = new IceStatus.IceGPGNetState(
GPGNetServer.getGpgnetPort(), GPGNetServer.isConnected(), GPGNetServer.getGameStateString(), "-");
gpgNetServer.getGpgnetPort(), gpgNetServer.isConnected(), gpgNetServer.getGameStateString(), "-");

List<IceStatus.IceRelay> relays = new ArrayList<>();
GameSession gameSession = IceAdapter.getGameSession();
Expand Down Expand Up @@ -155,10 +156,10 @@ public String status() {
.mapToInt(s -> s.getTurnAddresses().size()
+ s.getStunAddresses().size())
.sum(),
GPGNetServer.getLobbyPort(),
GPGNetServer.getLobbyInitMode().getName(),
gpgNetServer.getLobbyPort(),
gpgNetServer.getLobbyInitMode().getName(),
new IceStatus.IceOptions(
IceAdapter.getId(), IceAdapter.getLogin(), rpcPort, GPGNetServer.getGpgnetPort()),
IceAdapter.getId(), IceAdapter.getLogin(), rpcPort, gpgNetServer.getGpgnetPort()),
gpgpnet,
relays.toArray(new IceStatus.IceRelay[relays.size()]));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,30 @@
import com.nbarraille.jjsonrpc.TcpServer;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;

/**
* Handles communication between client and adapter, opens a server for the client to connect to
*/
@Slf4j
public class RPCService {
public class RPCService implements AutoCloseable {

private static final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
private static TcpServer tcpServer;
private static volatile boolean skipRPCMessages = false;

public static void init(int port, FafRpcCallbacks callbacks) {
public void init(int port, GPGNetServer gpgNetServer, FafRpcCallbacks callbacks) {
Debug.RPC_PORT = port;
log.info("Creating RPC server on port {}", port);

RPCHandler rpcHandler = new RPCHandler(port, callbacks);
RPCHandler rpcHandler = new RPCHandler(port, callbacks, gpgNetServer);
tcpServer = new TcpServer(port, rpcHandler);
tcpServer.start();

debug().rpcStarted(tcpServer.getFirstPeer());
tcpServer.getFirstPeer().thenAccept(firstPeer -> {
firstPeer.onConnectionLost(() -> {
GameState gameState = GPGNetServer.getGameState().orElse(null);
GameState gameState = gpgNetServer.getGameState().orElse(null);
if (gameState == GameState.LAUNCHING) {
skipRPCMessages = true;
log.warn("Lost connection to first RPC Peer. GameState: LAUNCHING, NOT STOPPING!");
Expand All @@ -58,19 +57,19 @@ public static void init(int port, FafRpcCallbacks callbacks) {
});
}

public static void onConnectionStateChanged(String newState) {
public void onConnectionStateChanged(String newState) {
if (!skipRPCMessages) {
getPeerOrWait().sendNotification("onConnectionStateChanged", Arrays.asList(newState));
}
}

public static void onGpgNetMessageReceived(String header, List<Object> chunks) {
public void onGpgNetMessageReceived(String header, List<Object> chunks) {
if (!skipRPCMessages) {
getPeerOrWait().sendNotification("onGpgNetMessageReceived", Arrays.asList(header, chunks));
}
}

public static void onIceMsg(CandidatesMessage candidatesMessage) {
public void onIceMsg(CandidatesMessage candidatesMessage) {
if (!skipRPCMessages) {
try {
getPeerOrWait()
Expand All @@ -86,15 +85,15 @@ public static void onIceMsg(CandidatesMessage candidatesMessage) {
}
}

public static void onIceConnectionStateChanged(long localPlayerId, long remotePlayerId, String state) {
public void onIceConnectionStateChanged(long localPlayerId, long remotePlayerId, String state) {
if (!skipRPCMessages) {
getPeerOrWait()
.sendNotification(
"onIceConnectionStateChanged", Arrays.asList(localPlayerId, remotePlayerId, state));
}
}

public static void onConnected(long localPlayerId, long remotePlayerId, boolean connected) {
public void onConnected(long localPlayerId, long remotePlayerId, boolean connected) {
if (!skipRPCMessages) {
getPeerOrWait().sendNotification("onConnected", Arrays.asList(localPlayerId, remotePlayerId, connected));
}
Expand All @@ -105,7 +104,7 @@ public static void onConnected(long localPlayerId, long remotePlayerId, boolean
*
* @return the currently connected peer (the client)
*/
public static JJsonPeer getPeerOrWait() {
public JJsonPeer getPeerOrWait() {
try {
return tcpServer.getFirstPeer().get();
} catch (Exception e) {
Expand All @@ -114,11 +113,8 @@ public static JJsonPeer getPeerOrWait() {
return null;
}

public static CompletableFuture<JJsonPeer> getPeerFuture() {
return tcpServer.getFirstPeer();
}

public static void close() {
@Override
public void close() {
tcpServer.stop();
}
}
Loading