-
Notifications
You must be signed in to change notification settings - Fork 7
Migrate away from Vert.X #175
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
Open
nateweisz
wants to merge
7
commits into
main
Choose a base branch
from
174-migrate-away-vertx
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
52875fe
Initial work on it
nateweisz aa2fbab
Fixed missing Guild Features and works now!
nateweisz 846ad27
Spotless
nateweisz e44792c
Satisfy sonar
nateweisz 6bafbce
Satisfy sonar
nateweisz cf94021
disable test
nateweisz 2e5eaf4
disable test
nateweisz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
gateway/src/main/java/com/javadiscord/jdi/internal/gateway/GatewayWebSocketClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package com.javadiscord.jdi.internal.gateway; | ||
|
||
import java.net.URI; | ||
import java.util.function.Consumer; | ||
|
||
import org.java_websocket.WebSocket; | ||
import org.java_websocket.client.WebSocketClient; | ||
import org.java_websocket.framing.Framedata; | ||
import org.java_websocket.handshake.ServerHandshake; | ||
|
||
public class GatewayWebSocketClient extends WebSocketClient { | ||
private final Runnable onSuccess; | ||
private final Consumer<Exception> onFailure; | ||
private Consumer<String> onReceive = (message) -> {}; | ||
private Runnable onClose = () -> {}; | ||
private Consumer<Framedata> frameHandler = (framedata) -> {}; | ||
|
||
public GatewayWebSocketClient( | ||
URI serverUri, Runnable onSuccess, Consumer<Exception> onFailure | ||
) { | ||
super(serverUri); | ||
this.onSuccess = onSuccess; | ||
this.onFailure = onFailure; | ||
} | ||
|
||
@Override | ||
public void onOpen(ServerHandshake serverHandshake) { | ||
onSuccess.run(); | ||
} | ||
|
||
@Override | ||
public void onMessage(String s) { | ||
onReceive.accept(s); | ||
} | ||
|
||
@Override | ||
public void onClose(int i, String s, boolean b) { | ||
onClose.run(); | ||
} | ||
|
||
@Override | ||
public void onError(Exception e) { | ||
onFailure.accept(e); | ||
} | ||
|
||
@Override | ||
public void onWebsocketPing(WebSocket conn, Framedata f) { | ||
frameHandler.accept(f); | ||
} | ||
|
||
@Override | ||
public void onWebsocketPong(WebSocket conn, Framedata f) { | ||
frameHandler.accept(f); | ||
} | ||
|
||
public void setOnReceive(Consumer<String> onReceive) { | ||
this.onReceive = onReceive; | ||
} | ||
|
||
public void setOnClose(Runnable onClose) { | ||
this.onClose = onClose; | ||
} | ||
|
||
public void setFrameHandler(Consumer<Framedata> frameHandler) { | ||
this.frameHandler = frameHandler; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,28 @@ | ||
package com.javadiscord.jdi.internal.gateway; | ||
|
||
import java.net.URI; | ||
|
||
import com.javadiscord.jdi.internal.cache.Cache; | ||
import com.javadiscord.jdi.internal.gateway.handlers.heartbeat.HeartbeatService; | ||
import com.javadiscord.jdi.internal.gateway.identify.IdentifyRequest; | ||
|
||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import io.vertx.core.Vertx; | ||
import io.vertx.core.buffer.Buffer; | ||
import io.vertx.core.http.WebSocket; | ||
import io.vertx.core.http.WebSocketClient; | ||
import io.vertx.core.http.WebSocketConnectOptions; | ||
import io.vertx.core.http.WebSocketFrame; | ||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.java_websocket.client.WebSocketClient; | ||
import org.java_websocket.framing.CloseFrame; | ||
import org.java_websocket.framing.Framedata; | ||
import org.java_websocket.framing.PingFrame; | ||
import org.java_websocket.framing.PongFrame; | ||
|
||
public class WebSocketManager { | ||
private static final Logger LOGGER = LogManager.getLogger(WebSocketManager.class); | ||
private final GatewaySetting gatewaySetting; | ||
private final IdentifyRequest identifyRequest; | ||
private final Vertx vertx; | ||
private final WebSocketRetryHandler retryHandler; | ||
private final Cache cache; | ||
private WebSocket webSocket; | ||
private WebSocketClient webSocketClient; | ||
private GatewayWebSocketClient client; | ||
private HeartbeatService heartbeatService; | ||
private boolean retryAllowed; | ||
|
||
|
@@ -32,66 +31,61 @@ public WebSocketManager( | |
) { | ||
this.gatewaySetting = gatewaySetting; | ||
this.identifyRequest = identifyRequest; | ||
this.vertx = Vertx.vertx(); | ||
this.retryHandler = new WebSocketRetryHandler(vertx); | ||
this.retryHandler = new WebSocketRetryHandler(); | ||
this.cache = cache; | ||
} | ||
|
||
public void start(ConnectionMediator connectionMediator) { | ||
heartbeatService = new HeartbeatService(connectionMediator); | ||
retryAllowed = true; | ||
|
||
String gatewayURL = connectionMediator.getConnectionDetails().getGatewayURL(); | ||
|
||
WebSocketConnectOptions webSocketConnectOptions = | ||
new WebSocketConnectOptions() | ||
.addHeader("Origin", "localhost") | ||
.setAbsoluteURI( | ||
client = | ||
new GatewayWebSocketClient( | ||
URI.create( | ||
"%s/?v=%d&encoding=%s" | ||
.formatted( | ||
gatewayURL, | ||
gatewaySetting.getApiVersion(), | ||
gatewaySetting.getEncoding() | ||
) | ||
) | ||
.setSsl(true); | ||
|
||
webSocketClient = vertx.createWebSocketClient(); | ||
retryAllowed = true; | ||
webSocketClient.connect(webSocketConnectOptions) | ||
.onSuccess( | ||
webSocket -> { | ||
), | ||
() -> { | ||
// Success | ||
LOGGER.info("Connected to Discord"); | ||
|
||
this.webSocket = webSocket; | ||
|
||
WebSocketHandler webSocketHandler = | ||
new WebSocketHandler(connectionMediator, cache, heartbeatService); | ||
|
||
webSocketHandler.handle(webSocket); | ||
webSocketHandler.handle(client); | ||
|
||
webSocket.frameHandler(frame -> frameHandler(frame, webSocketHandler)); | ||
client.setFrameHandler(frame -> frameHandler(frame, webSocketHandler)); | ||
|
||
if (retryHandler.hasRetried()) { | ||
retryHandler.clear(); | ||
sendResumeEvent(webSocket, connectionMediator); | ||
sendResumeEvent(connectionMediator); | ||
} else { | ||
sendIdentify(webSocket, identifyRequest); | ||
sendIdentify(client, identifyRequest); | ||
} | ||
} | ||
) | ||
.onFailure( | ||
error -> { | ||
LOGGER.warn("Failed to connect to {} {}", gatewayURL, error.getCause()); | ||
}, | ||
(exception) -> { | ||
// Error | ||
LOGGER.warn( | ||
"An error occurred in the gateway's connection: {} {}", gatewayURL, | ||
exception.getCause() | ||
); | ||
if (retryAllowed) { | ||
retryHandler.retry(() -> restart(connectionMediator)); | ||
} | ||
} | ||
); | ||
client.connect(); | ||
} | ||
|
||
private void frameHandler(WebSocketFrame frame, WebSocketHandler webSocketHandler) { | ||
if (frame.isClose()) { | ||
webSocketHandler.handleClose(frame.closeStatusCode(), frame.closeReason()); | ||
private void frameHandler(Framedata frame, WebSocketHandler webSocketHandler) { | ||
if (frame instanceof PingFrame) { | ||
client.sendFrame(new PongFrame()); | ||
} else if (frame instanceof CloseFrame closeFrame) { | ||
webSocketHandler.handleClose(closeFrame.getCloseCode(), closeFrame.getMessage()); | ||
} | ||
} | ||
|
||
|
@@ -102,54 +96,56 @@ public void restart(ConnectionMediator connectionMediator) { | |
} | ||
|
||
public void stop() { | ||
if (webSocket != null && !webSocket.isClosed()) { | ||
webSocket.close(); | ||
if (client != null && !client.isClosed()) { | ||
try { | ||
client.closeBlocking(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe add some logging if it succeeded |
||
} catch (InterruptedException e) { | ||
LOGGER.error("Failed to close websocket client: {}", e.getMessage()); | ||
Thread.currentThread().interrupt(); | ||
} | ||
} | ||
|
||
if (heartbeatService != null) { | ||
heartbeatService.stop(); | ||
} | ||
webSocketClient.close() | ||
.onSuccess(res -> LOGGER.info("Web socket client has been shutdown")) | ||
.onFailure(err -> LOGGER.error("Failed to shutdown web socket client", err)); | ||
|
||
retryAllowed = false; | ||
vertx.close() | ||
.onSuccess(res -> LOGGER.info("Gateway has shutdown")) | ||
.onFailure(err -> LOGGER.error("Failed to shutdown gateway", err)); | ||
} | ||
|
||
public WebSocket getWebSocket() { | ||
return webSocket; | ||
public WebSocketClient getWebSocket() { | ||
return client; | ||
} | ||
|
||
private static void sendIdentify(WebSocket webSocket, IdentifyRequest identifyRequest) { | ||
private static void sendIdentify( | ||
org.java_websocket.client.WebSocketClient client, | ||
IdentifyRequest identifyRequest | ||
) { | ||
try { | ||
webSocket.write( | ||
Buffer.buffer((new ObjectMapper().writeValueAsString(identifyRequest))) | ||
client.send( | ||
new ObjectMapper().writeValueAsString(identifyRequest) | ||
); | ||
} catch (JsonProcessingException e) { | ||
LOGGER.error("Failed to send identify request, restarting bot"); | ||
} | ||
} | ||
|
||
private void sendResumeEvent(WebSocket webSocket, ConnectionMediator connectionMediator) { | ||
private void sendResumeEvent(ConnectionMediator connectionMediator) { | ||
String botToken = identifyRequest.getD().getToken(); | ||
String sessionId = connectionMediator.getConnectionDetails().getSessionId(); | ||
int sequence = connectionMediator.getConnectionDetails().getSequence(); | ||
int opcode = GatewayOpcode.RESUME; | ||
webSocket.write( | ||
Buffer.buffer( | ||
client.send( | ||
""" | ||
{ | ||
"op": %d, | ||
"d": { | ||
"token": "%s", | ||
"session_id": "%s", | ||
"seq": %d | ||
} | ||
} | ||
""" | ||
{ | ||
"op": %d, | ||
"d": { | ||
"token": "%s", | ||
"session_id": "%s", | ||
"seq": %d | ||
} | ||
} | ||
""" | ||
.formatted(opcode, botToken, sessionId, sequence) | ||
) | ||
.formatted(opcode, botToken, sessionId, sequence) | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is
i
,s
andb
? Maybe give them better names and why arent they passed down toonClose
like the other methods?