Skip to content

Commit

Permalink
feat(gateway): fully integrated gateway v3 into the rest of the codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
seailz committed Sep 25, 2023
1 parent 5f8866c commit c5d150f
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 708 deletions.
59 changes: 11 additions & 48 deletions src/main/java/com/seailz/discordjar/DiscordJar.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import com.seailz.discordjar.command.listeners.slash.SubCommandListener;
import com.seailz.discordjar.events.DiscordListener;
import com.seailz.discordjar.events.EventDispatcher;
import com.seailz.discordjar.gateway.GatewayFactory;
import com.seailz.discordjar.gateway.Gateway;
import com.seailz.discordjar.gateway.GatewayTransportCompressionType;
import com.seailz.discordjar.http.HttpOnlyApplication;
import com.seailz.discordjar.model.api.APIRelease;
Expand Down Expand Up @@ -49,6 +49,7 @@
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.socket.CloseStatus;

import java.io.IOException;
import java.lang.annotation.Annotation;
Expand Down Expand Up @@ -82,7 +83,7 @@ public class DiscordJar {
/**
* Used to manage the gateway connection
*/
private GatewayFactory gatewayFactory;
private Gateway gatewayFactory;
/**
* Stores the logger
*/
Expand Down Expand Up @@ -144,7 +145,6 @@ public class DiscordJar {
private Status status;

public int gatewayConnections = 0;
public List<GatewayFactory> gatewayFactories = new ArrayList<>();
private final List<String> memberCachingDisabledGuilds = new ArrayList<>();
private final GatewayTransportCompressionType gatewayTransportCompressionType;
private final APIVersion apiVersion;
Expand Down Expand Up @@ -298,7 +298,11 @@ public DiscordJar(String token, EnumSet<Intent> intents, APIVersion version, boo
this.numShards = numShards;

if (!httpOnly) {
this.gatewayFactory = new GatewayFactory(this, debug, shardId, numShards, gwCompressionType);
this.gatewayFactory = Gateway.builder(this)
.setShardCount(numShards)
.setShardId(shardId)
.setTransportCompressionType(gwCompressionType)
.build();
}

}
Expand Down Expand Up @@ -343,43 +347,10 @@ protected void initiateNoShutdown() {
}, "djar-shutdown-prevention").start();
}

public GatewayFactory getGateway() {
public Gateway getGateway() {
return gatewayFactory;
}

/**
* Kills the gateway connection and destroys the {@link GatewayFactory} instance.
* This method will also initiate garbage collection to avoid memory leaks. This probably shouldn't be used unless in {@link #restartGateway()}.
*/
public void killGateway() {
try {
if (gatewayFactory != null) gatewayFactory.killConnection();
} catch (IOException ignored) {}
gatewayFactory = null;
// init garbage collection to avoid memory leaks
System.gc();
}

/**
* Restarts the gateway connection and creates a new {@link GatewayFactory} instance.
* This will invalidate and destroy the old {@link GatewayFactory} instance.
* This method will also initiate garbage collection to avoid memory leaks.
*
* @see GatewayFactory
* @see #killGateway()
*/
public void restartGateway() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {}
killGateway();
try {
gatewayFactory = new GatewayFactory(this, debug, shardId, numShards, gatewayTransportCompressionType);
gatewayFactories.add(gatewayFactory);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}

protected void initiateShutdownHooks() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Expand All @@ -389,11 +360,7 @@ protected void initiateShutdownHooks() {
throw new RuntimeException(e);
}
if (gatewayFactory != null) {
try {
gatewayFactory.killConnectionNicely();
} catch (IOException e) {
throw new RuntimeException(e);
}
gatewayFactory.disconnect(CloseStatus.GOING_AWAY);
}
}, "djar--shutdown-hook"));
}
Expand All @@ -418,10 +385,6 @@ public void updateVoiceState(VoiceState state) {
}
}

public void setGatewayFactory(GatewayFactory gatewayFactory) {
this.gatewayFactory = gatewayFactory;
}

public List<Bucket> getBuckets() {
return buckets;
}
Expand Down Expand Up @@ -1556,7 +1519,7 @@ public EnumSet<CacheType> getCacheTypes() {
* <br>The time is in milliseconds.
*/
public List<Long> getGatewayPingHistory() {
return GatewayFactory.pingHistoryMs;
return Gateway.pingHistoryMs;
}

/**
Expand Down
17 changes: 14 additions & 3 deletions src/main/java/com/seailz/discordjar/gateway/Gateway.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.seailz.discordjar.model.api.version.APIVersion;
import com.seailz.discordjar.model.application.Intent;
import com.seailz.discordjar.model.guild.Member;
import com.seailz.discordjar.model.status.Status;
import com.seailz.discordjar.utils.URLS;
import com.seailz.discordjar.utils.rest.DiscordRequest;
import com.seailz.discordjar.utils.rest.DiscordResponse;
Expand Down Expand Up @@ -43,14 +44,15 @@ public class Gateway {
private WebSocket socket;
private boolean resumedConnection = false;
private ReconnectInfo resumeInfo;
private long lastSequenceNumber = -1;
public static long lastSequenceNumber = -1;
private boolean readyForMessages = false;
private HeartLogic heartbeatManager;
public static Date lastHeartbeatSent = new Date();
public static List<Long> pingHistoryMs = new ArrayList<>();
private final List<Consumer<VoiceState>> onVoiceStateUpdateListeners = new ArrayList<>();
private final List<Consumer<VoiceServerUpdate>> onVoiceServerUpdateListeners = new ArrayList<>();
public final HashMap<String, GatewayFactory.MemberChunkStorageWrapper> memberRequestChunks = new HashMap<>();
public final HashMap<String, Gateway.MemberChunkStorageWrapper> memberRequestChunks = new HashMap<>();
private Status status = null;

protected Gateway(DiscordJar bot, int shardCount, int shardId, GatewayTransportCompressionType compressionType) {
this.bot = bot;
Expand Down Expand Up @@ -362,7 +364,7 @@ public void requestGuildMembers(RequestGuildMembersAction action, CompletableFut

queueMessage(payload);

memberRequestChunks.put(action.getNonce(), new GatewayFactory.MemberChunkStorageWrapper(new ArrayList<>(), future));
memberRequestChunks.put(action.getNonce(), new Gateway.MemberChunkStorageWrapper(new ArrayList<>(), future));
}

public void sendVoicePayload(String guildId, String channelId, boolean selfMute, boolean selfDeaf) {
Expand Down Expand Up @@ -393,6 +395,15 @@ public List<Consumer<VoiceServerUpdate>> getOnVoiceServerUpdateListeners() {
return onVoiceServerUpdateListeners;
}

/**
* Do not use this method - it is for internal use only.
* @param status The status to set.
*/
@Deprecated
public void setStatus(Status status) {
this.status = status;
}

public record MemberChunkStorageWrapper(List<Member> members, CompletableFuture<List<Member>> future) {
public void addMember(Member member) {
members.add(member);
Expand Down
Loading

0 comments on commit c5d150f

Please sign in to comment.