refactor: Move to ConfigLib, use lombok (#563)

* refactor: move to configlib, adjust config structure

* fix: huskclaims typos

* fix: don't generate `server.yml` in local mode

* fix: NPE with server name
This commit is contained in:
William authored and GitHub committed 2024-02-12 16:54:23 +00:00
1 parent c55631a30d
commit 1723aa44fc
84 files changed
+4334 -4832

No files matched your search

@@ -157,7 +157,10 @@ public abstract class Broker {
protected String getSubChannelId() {
final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor());
try {
return plugin.getKey(plugin.getSettings().getClusterId().toLowerCase(Locale.ENGLISH), version).asString();
return plugin.getKey(
plugin.getSettings().getCrossServer().getClusterId().toLowerCase(Locale.ENGLISH),
version
).asString();
} catch (InvalidKeyException e) {
plugin.log(Level.SEVERE, "Cluster ID specified in config contains invalid characters");
}
@@ -19,96 +19,197 @@
package net.william278.huskhomes.network;
import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.util.Pool;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.CrossServerSettings.RedisSettings;
/**
* Redis PubSub broker implementation.
*/
public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool;
private final Subscriber subscriber;
public RedisBroker(@NotNull HuskHomes plugin) {
super(plugin);
this.subscriber = new Subscriber(this, getSubChannelId());
}
@Blocking
@Override
public void initialize() throws IllegalStateException {
super.initialize();
// Establish a connection with the Redis server
final Pool<Jedis> jedisPool = getJedisPool(plugin.getSettings().getCrossServer().getRedis());
try {
jedisPool.getResource().ping();
} catch (JedisException e) {
throw new IllegalStateException("Failed to establish connection with Redis. "
+ "Please check the supplied credentials in the config file", e);
}
final String password = plugin.getSettings().getRedisPassword();
final String host = plugin.getSettings().getRedisHost();
final int port = plugin.getSettings().getRedisPort();
final boolean useSSL = plugin.getSettings().useRedisSsl();
this.jedisPool = password.isEmpty() ? new JedisPool(new JedisPoolConfig(), host, port, 0, useSSL)
: new JedisPool(new JedisPoolConfig(), host, port, 0, password, useSSL);
new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start();
plugin.log(Level.INFO, "Initialized Redis connection pool");
// Subscribe using a thread (rather than a task)
subscriber.enable(jedisPool);
new Thread(subscriber::subscribe, "huskhomes:redis_subscriber").start();
}
@NotNull
private Runnable getSubscriber() {
return () -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(@NotNull String channel, @NotNull String encodedMessage) {
if (!channel.equals(getSubChannelId())) {
return;
}
private static Pool<Jedis> getJedisPool(@NotNull RedisSettings settings) {
// Get the Redis connection settings
final String password = settings.getPassword();
final String host = settings.getHost();
final int port = settings.getPort();
final boolean useSSL = settings.isUseSsl();
final Message message;
try {
message = plugin.getGson().fromJson(encodedMessage, Message.class);
} catch (Exception e) {
plugin.log(Level.WARNING, "Failed to decode message from Redis: " + e.getMessage());
return;
}
// Create the jedis pool
final JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(0);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
if (message.getScope() == Message.Scope.PLAYER) {
plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message));
return;
}
// Check if sentinels are to be used
final RedisSettings.SentinelSettings sentinel = settings.getSentinel();
Set<String> redisSentinelNodes = new HashSet<>(sentinel.getNodes());
if (!redisSentinelNodes.isEmpty()) {
final String sentinelPassword = sentinel.getPassword();
return new JedisSentinelPool(sentinel.getMasterName(), redisSentinelNodes, password.isEmpty()
? null : password, sentinelPassword.isEmpty() ? null : sentinelPassword);
}
if (message.getTarget().equals(plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> handle(receiver, message));
}
}
}, getSubChannelId());
}
};
// Otherwise, use the standard Jedis pool
return password.isEmpty()
? new JedisPool(config, host, port, 0, useSSL)
: new JedisPool(config, host, port, 0, password, useSSL);
}
@Override
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
plugin.runAsync(() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(getSubChannelId(), plugin.getGson().toJson(message));
}
});
plugin.runAsync(() -> subscriber.send(message));
}
@Override
@Blocking
public void close() {
super.close();
if (jedisPool != null) {
jedisPool.close();
subscriber.disable();
}
@AllArgsConstructor
private static class Subscriber extends JedisPubSub {
private static final int RECONNECTION_TIME = 8000;
private final RedisBroker broker;
private final String channel;
private Pool<Jedis> jedisPool;
private boolean enabled;
private boolean reconnected;
private Subscriber(@NotNull RedisBroker broker, @NotNull String channel) {
this.broker = broker;
this.channel = channel;
}
private void enable(@NotNull Pool<Jedis> jedisPool) {
this.jedisPool = jedisPool;
this.enabled = true;
}
@Blocking
private void disable() {
this.enabled = false;
if (jedisPool != null && !jedisPool.isClosed()) {
jedisPool.close();
}
this.unsubscribe();
}
@Blocking
public void send(@NotNull Message message) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(channel, broker.plugin.getGson().toJson(message));
}
}
@Blocking
private void subscribe() {
while (enabled && !Thread.interrupted() && jedisPool != null && !jedisPool.isClosed()) {
try (Jedis jedis = jedisPool.getResource()) {
if (reconnected) {
broker.plugin.log(Level.INFO, "Redis connection is alive again");
}
// Subscribe to channel and lock the thread
jedis.subscribe(this, channel);
} catch (Throwable t) {
// Thread was unlocked due error
onThreadUnlock(t);
}
}
}
private void onThreadUnlock(@NotNull Throwable t) {
if (!enabled) {
return;
}
if (reconnected) {
broker.plugin.log(Level.WARNING, "Redis Server connection lost. Attempting reconnect in %ss..."
.formatted(RECONNECTION_TIME / 1000), t);
}
try {
this.unsubscribe();
} catch (Throwable ignored) {
// empty catch
}
// Make an instant subscribe if occurs any error on initialization
if (!reconnected) {
reconnected = true;
} else {
try {
Thread.sleep(RECONNECTION_TIME);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void onMessage(@NotNull String channel, @NotNull String encoded) {
final Message message;
try {
message = broker.plugin.getGson().fromJson(encoded, Message.class);
} catch (Exception e) {
broker.plugin.log(Level.WARNING, "Failed to decode message from Redis: " + e.getMessage());
return;
}
if (message.getScope() == Message.Scope.PLAYER) {
broker.plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> broker.handle(receiver, message));
return;
}
if (message.getTarget().equals(broker.plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
broker.plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> broker.handle(receiver, message));
}
}
}