diff --git a/common/src/main/java/net/draycia/carbon/common/util/ConcurrentUtil.java b/common/src/main/java/net/draycia/carbon/common/util/ConcurrentUtil.java
index b6819152..eefcdda7 100644
--- a/common/src/main/java/net/draycia/carbon/common/util/ConcurrentUtil.java
+++ b/common/src/main/java/net/draycia/carbon/common/util/ConcurrentUtil.java
@@ -21,6 +21,7 @@ package net.draycia.carbon.common.util;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
@@ -54,4 +55,12 @@ public final class ConcurrentUtil {
.build();
}
+ public static ScheduledExecutorService createPeriodicTasksPool(final Logger logger) {
+ return new ExceptionLoggingScheduledThreadPoolExecutor(
+ 1,
+ carbonThreadFactory(logger, "Periodic Tasks"),
+ logger
+ );
+ }
+
}
diff --git a/common/src/main/java/net/draycia/carbon/common/util/ExceptionLoggingScheduledThreadPoolExecutor.java b/common/src/main/java/net/draycia/carbon/common/util/ExceptionLoggingScheduledThreadPoolExecutor.java
new file mode 100644
index 00000000..660fc9ea
--- /dev/null
+++ b/common/src/main/java/net/draycia/carbon/common/util/ExceptionLoggingScheduledThreadPoolExecutor.java
@@ -0,0 +1,73 @@
+/*
+ * CarbonChat
+ *
+ * Copyright (c) 2023 Josua Parks (Vicarious)
+ * Contributors
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+package net.draycia.carbon.common.util;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import org.apache.logging.log4j.Logger;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
+@DefaultQualifier(NonNull.class)
+public final class ExceptionLoggingScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
+
+ private final Logger logger;
+
+ public ExceptionLoggingScheduledThreadPoolExecutor(final int corePoolSize, final ThreadFactory threadFactory, final Logger logger) {
+ super(corePoolSize, threadFactory);
+ this.logger = logger;
+ }
+
+ @Override
+ public ScheduledFuture> schedule(final Runnable command, final long delay, final TimeUnit unit) {
+ return super.schedule(new ExceptionLoggingRunnable(command, this.logger), delay, unit);
+ }
+
+ @Override
+ public ScheduledFuture schedule(final Callable callable, final long delay, final TimeUnit unit) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public ScheduledFuture> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) {
+ return super.scheduleAtFixedRate(new ExceptionLoggingRunnable(command, this.logger), initialDelay, period, unit);
+ }
+
+ @Override
+ public ScheduledFuture> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay, final TimeUnit unit) {
+ return super.scheduleWithFixedDelay(new ExceptionLoggingRunnable(command, this.logger), initialDelay, delay, unit);
+ }
+
+ private record ExceptionLoggingRunnable(Runnable wrapped, Logger logger) implements Runnable {
+ @Override
+ public void run() {
+ try {
+ this.wrapped.run();
+ } catch (final Throwable thr) {
+ this.logger.error("Error executing task '{}'", this.wrapped, thr);
+ Exceptions.rethrow(thr);
+ }
+ }
+ }
+
+}
diff --git a/common/src/main/java/net/draycia/carbon/common/util/Exceptions.java b/common/src/main/java/net/draycia/carbon/common/util/Exceptions.java
new file mode 100644
index 00000000..289aa35f
--- /dev/null
+++ b/common/src/main/java/net/draycia/carbon/common/util/Exceptions.java
@@ -0,0 +1,52 @@
+/*
+ * CarbonChat
+ *
+ * Copyright (c) 2023 Josua Parks (Vicarious)
+ * Contributors
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+package net.draycia.carbon.common.util;
+
+import java.util.function.Consumer;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
+@DefaultQualifier(NonNull.class)
+public final class Exceptions {
+
+ private Exceptions() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public static RuntimeException rethrow(final Throwable t) throws X {
+ throw (X) t;
+ }
+
+ public static Consumer sneaky(final CheckedConsumer consumer) {
+ return t -> {
+ try {
+ consumer.accept(t);
+ } catch (final Throwable thr) {
+ rethrow(thr);
+ }
+ };
+ }
+
+ @FunctionalInterface
+ public interface CheckedConsumer {
+ void accept(T t) throws X;
+ }
+
+}
diff --git a/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabric.java b/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabric.java
index 47a6a007..48fe7d3a 100644
--- a/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabric.java
+++ b/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabric.java
@@ -24,6 +24,8 @@ import com.google.inject.Injector;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.CarbonServer;
@@ -37,6 +39,7 @@ import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.CloudUtils;
+import net.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.fabric.callback.ChatCallback;
@@ -47,7 +50,6 @@ import net.draycia.carbon.fabric.listeners.FabricPlayerJoinListener;
import net.draycia.carbon.fabric.listeners.FabricPlayerLeaveListener;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
-import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.message.v1.ServerMessageDecoratorEvent;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader;
@@ -87,6 +89,7 @@ public final class CarbonChatFabric implements ModInitializer, CarbonChat {
public static ResourceKey CHAT_TYPE = ResourceKey.create(Registries.CHAT_TYPE, new ResourceLocation("carbon", "chat"));
private @MonotonicNonNull MessagingManager messagingManager = null;
+ private @MonotonicNonNull ScheduledExecutorService periodicTasks;
@Override
public void onInitialize() {
@@ -106,7 +109,15 @@ public final class CarbonChatFabric implements ModInitializer, CarbonChat {
this.registerChatListener();
this.registerServerLifecycleListeners();
this.registerPlayerStatusListeners();
- this.registerTickListeners();
+
+ this.periodicTasks = ConcurrentUtil.createPeriodicTasksPool(this.logger);
+
+ this.periodicTasks.scheduleAtFixedRate(
+ () -> PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager, this.logger), 5, 5, TimeUnit.MINUTES);
+ this.periodicTasks.scheduleAtFixedRate(
+ () -> this.injector.getInstance(ProfileCache.class).save(), 15, 15, TimeUnit.MINUTES);
+ this.periodicTasks.scheduleAtFixedRate(
+ () -> this.userManager.cleanup(), 30, 30, TimeUnit.SECONDS);
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
@@ -131,6 +142,7 @@ public final class CarbonChatFabric implements ModInitializer, CarbonChat {
ServerLifecycleEvents.SERVER_STARTING.register(server -> this.minecraftServer = server);
ServerLifecycleEvents.SERVER_STOPPING.register($ -> PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager, this.logger).forEach(CompletableFuture::join));
ServerLifecycleEvents.SERVER_STOPPED.register(server -> {
+ ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500);
this.injector.getInstance(ProfileCache.class).save();
this.injector.getInstance(ProfileResolver.class).shutdown();
this.userManager.shutdown();
@@ -144,24 +156,6 @@ public final class CarbonChatFabric implements ModInitializer, CarbonChat {
ServerPlayConnectionEvents.JOIN.register(this.injector.getInstance(FabricPlayerJoinListener.class));
}
- private void registerTickListeners() {
- final long cleanupDelay = 30 * 20; // 30 seconds
- final long saveDelay = 5 * 60 * 20; // 5 minutes
- final long saveProfilesDelay = 15 * 60 * 20; // 15 minutes
-
- ServerTickEvents.END_SERVER_TICK.register(server -> {
- if (server.getTickCount() != 0 && server.getTickCount() % cleanupDelay == 0) {
- this.userManager.cleanup();
- }
- if (server.getTickCount() != 0 && server.getTickCount() % saveDelay == 0) {
- PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager, this.logger);
- }
- if (server.getTickCount() != 0 && server.getTickCount() % saveProfilesDelay == 0) {
- this.injector.getInstance(ProfileCache.class).save();
- }
- });
- }
-
@Override
public UUID serverId() {
return this.serverId;
diff --git a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerJoinListener.java b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerJoinListener.java
index b835e29a..862d0229 100644
--- a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerJoinListener.java
+++ b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerJoinListener.java
@@ -22,6 +22,7 @@ package net.draycia.carbon.fabric.listeners;
import com.google.inject.Inject;
import java.util.List;
import net.draycia.carbon.common.config.ConfigFactory;
+import net.draycia.carbon.common.users.ProfileCache;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket;
@@ -34,15 +35,19 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class FabricPlayerJoinListener implements ServerPlayConnectionEvents.Join {
- private ConfigFactory configFactory;
+ private final ProfileCache profileCache;
+ private final ConfigFactory configFactory;
@Inject
- public FabricPlayerJoinListener(final ConfigFactory configFactory) {
+ public FabricPlayerJoinListener(final ConfigFactory configFactory, final ProfileCache profileCache) {
this.configFactory = configFactory;
+ this.profileCache = profileCache;
}
@Override
public void onPlayReady(final ServerGamePacketListenerImpl handler, final PacketSender sender, final MinecraftServer server) {
+ this.profileCache.cache(handler.getPlayer().getUUID(), handler.getPlayer().getGameProfile().getName());
+
final @Nullable List suggestions = this.configFactory.primaryConfig().customChatSuggestions();
if (suggestions == null || suggestions.isEmpty()) {
diff --git a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerLeaveListener.java b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerLeaveListener.java
index 51be4d2a..3387417e 100644
--- a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerLeaveListener.java
+++ b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricPlayerLeaveListener.java
@@ -20,42 +20,35 @@
package net.draycia.carbon.fabric.listeners;
import com.google.inject.Inject;
-import net.draycia.carbon.api.CarbonChat;
-import net.draycia.carbon.api.users.UserManager;
-import net.draycia.carbon.common.users.CarbonPlayerCommon;
+import net.draycia.carbon.fabric.FabricUserManager;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
+import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class FabricPlayerLeaveListener implements ServerPlayConnectionEvents.Disconnect {
- private final CarbonChat carbonChat;
- private final UserManager userManager;
+ private final FabricUserManager userManager;
+ private final Logger logger;
@Inject
public FabricPlayerLeaveListener(
- final CarbonChat carbonChat,
- final UserManager userManager
+ final Logger logger,
+ final FabricUserManager userManager
) {
- this.carbonChat = carbonChat;
+ this.logger = logger;
this.userManager = userManager;
}
@Override
public void onPlayDisconnect(final ServerGamePacketListenerImpl handler, final MinecraftServer server) {
- // todo
- /*
- this.carbonChat.server().userManager().carbonPlayer(handler.getPlayer().getUUID()).thenAccept(result -> {
- if (result.player() == null) {
- return;
- }
-
- PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerFabric) result.player());
+ this.userManager.loggedOut(handler.getPlayer().getGameProfile().getId()).exceptionally(thr -> {
+ this.logger.warn("Exception saving data for player " + handler.getPlayer().getGameProfile().getName() + " with uuid " + handler.getPlayer().getGameProfile().getId());
+ return null;
});
- */
}
}
diff --git a/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java b/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java
index b181a7cd..adbbada8 100644
--- a/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java
+++ b/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java
@@ -25,9 +25,7 @@ import github.scarsz.discordsrv.DiscordSRV;
import java.nio.file.Path;
import java.util.Set;
import java.util.UUID;
-import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
@@ -87,7 +85,7 @@ public final class CarbonChatPaper implements CarbonChat {
private @MonotonicNonNull MessagingManager messagingManager = null;
- private @MonotonicNonNull ScheduledExecutorService executor = null;
+ private @MonotonicNonNull ScheduledExecutorService periodicTasks = null;
CarbonChatPaper() {
}
@@ -112,8 +110,7 @@ public final class CarbonChatPaper implements CarbonChat {
this.dataDirectory = dataDirectory;
this.packetService();
- this.executor = Executors.newSingleThreadScheduledExecutor(ConcurrentUtil.carbonThreadFactory(this.logger,
- "CarbonChatPaper"));
+ this.periodicTasks = ConcurrentUtil.createPeriodicTasksPool(this.logger);
}
void onEnable() {
@@ -136,15 +133,12 @@ public final class CarbonChatPaper implements CarbonChat {
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
- // Player data saving
- this.executor.scheduleAtFixedRate(
+ this.periodicTasks.scheduleAtFixedRate(
() -> PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager, this.logger), 5, 5, TimeUnit.MINUTES);
-
- this.executor.scheduleAtFixedRate(
+ this.periodicTasks.scheduleAtFixedRate(
() -> this.injector.getInstance(ProfileCache.class).save(), 15, 15, TimeUnit.MINUTES);
-
- Bukkit.getScheduler().runTaskTimerAsynchronously(this.plugin,
- () -> this.userManager.cleanup(), 30 * 20, 30 * 20);
+ this.periodicTasks.scheduleAtFixedRate(
+ () -> this.userManager.cleanup(), 30, 30, TimeUnit.SECONDS);
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
@@ -166,8 +160,7 @@ public final class CarbonChatPaper implements CarbonChat {
}
void onDisable() {
- ConcurrentUtil.shutdownExecutor(this.executor, TimeUnit.MILLISECONDS, 500);
-
+ ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500);
this.injector.getInstance(ProfileCache.class).save();
this.injector.getInstance(ProfileResolver.class).shutdown();
this.userManager.shutdown();