mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-01 14:38:48 +00:00
Initial work on user rewrite
Only JSONUserManager and Paper platform work currently
This commit is contained in:
22 files changed
+456
-305
No files matched your search
@@ -50,6 +50,7 @@ import net.kyori.adventure.text.Component;
|
||||
import net.kyori.moonshine.Moonshine;
|
||||
import net.kyori.moonshine.exception.scan.UnscannableMethodException;
|
||||
import net.kyori.moonshine.message.IMessageRenderer;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
@@ -60,11 +61,12 @@ public final class CarbonCommonModule extends AbstractModule {
|
||||
@Singleton
|
||||
public UserManager<CarbonPlayerCommon> userManager(
|
||||
final ConfigFactory configFactory,
|
||||
final Injector injector
|
||||
final Injector injector,
|
||||
final Logger logger
|
||||
) {
|
||||
return switch (Objects.requireNonNull(configFactory.primaryConfig()).storageType()) {
|
||||
case MYSQL -> MySQLUserManager.manager(configFactory.primaryConfig().databaseSettings());
|
||||
case PSQL -> PostgreSQLUserManager.manager(configFactory.primaryConfig().databaseSettings());
|
||||
case MYSQL -> MySQLUserManager.manager(configFactory.primaryConfig().databaseSettings(), logger);
|
||||
case PSQL -> PostgreSQLUserManager.manager(configFactory.primaryConfig().databaseSettings(), logger);
|
||||
default -> injector.getInstance(JSONUserManager.class);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package net.draycia.carbon.common.users;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public interface ProfileResolver {
|
||||
|
||||
CompletableFuture<@Nullable UUID> resolveUUID(String username);
|
||||
|
||||
CompletableFuture<@Nullable String> resolveName(UUID uuid);
|
||||
|
||||
void shutdown();
|
||||
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package net.draycia.carbon.common.users;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.draycia.carbon.api.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.api.users.UserManager;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
import static net.kyori.adventure.text.Component.text;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public class ProxiedCachingUserManager implements UserManager<CarbonPlayerCommon> {
|
||||
|
||||
private final Map<UUID, CarbonPlayerCommon> userCache = new ConcurrentHashMap<>();
|
||||
private final UserManager<CarbonPlayerCommon> proxiedUserManager;
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ProxiedCachingUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager, final CarbonChat carbonChat) {
|
||||
this.proxiedUserManager = proxiedUserManager;
|
||||
this.carbonChat = carbonChat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
|
||||
|
||||
if (cachedPlayer != null) {
|
||||
return new ComponentPlayerResult<>(cachedPlayer, Component.empty());
|
||||
}
|
||||
|
||||
final ComponentPlayerResult<CarbonPlayerCommon> result = this.proxiedUserManager.carbonPlayer(uuid).join();
|
||||
|
||||
if (result.player() != null) {
|
||||
this.userCache.put(uuid, result.player());
|
||||
|
||||
return new ComponentPlayerResult<>(result.player(), Component.empty());
|
||||
}
|
||||
|
||||
final @Nullable String name = this.carbonChat.server().resolveName(uuid).join();
|
||||
|
||||
if (name != null) {
|
||||
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
|
||||
|
||||
this.userCache.put(uuid, player);
|
||||
|
||||
return new ComponentPlayerResult<>(player, Component.empty());
|
||||
}
|
||||
|
||||
return new ComponentPlayerResult<>(null, text("Name not found for uuid!"));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) {
|
||||
return this.proxiedUserManager.savePlayer(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
|
||||
return this.proxiedUserManager.saveAndInvalidatePlayer(player);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.draycia.carbon.common.users;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.draycia.carbon.api.users.CarbonPlayer;
|
||||
import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.api.users.UserManager;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.util.ComponentMessageThrowable;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public interface UserManagerInternal<C extends CarbonPlayer> extends UserManager<C> {
|
||||
|
||||
void shutdown();
|
||||
|
||||
CompletableFuture<Void> save(C player);
|
||||
|
||||
CompletableFuture<Void> loggedOut(UUID uuid);
|
||||
|
||||
@Override
|
||||
default CompletableFuture<ComponentPlayerResult<C>> savePlayer(final C player) {
|
||||
return this.save(player)
|
||||
.thenApply($ -> new ComponentPlayerResult<>(player, Component.empty()))
|
||||
.exceptionally(thr -> new ComponentPlayerResult<>(null, ComponentMessageThrowable.getOrConvertMessage(thr)));
|
||||
}
|
||||
|
||||
}
|
||||
+30
-4
@@ -19,12 +19,21 @@
|
||||
*/
|
||||
package net.draycia.carbon.common.users.db;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.api.users.UserManager;
|
||||
import net.draycia.carbon.common.users.CarbonPlayerCommon;
|
||||
import net.draycia.carbon.common.users.UserManagerInternal;
|
||||
import net.draycia.carbon.common.util.ConcurrentUtil;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
@@ -34,15 +43,20 @@ import org.jdbi.v3.core.statement.Update;
|
||||
import static net.kyori.adventure.text.Component.empty;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public abstract class AbstractUserManager implements UserManager<CarbonPlayerCommon> {
|
||||
public abstract class DatabaseUserManager implements UserManagerInternal<CarbonPlayerCommon> {
|
||||
|
||||
protected final Jdbi jdbi;
|
||||
|
||||
protected final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
|
||||
protected final QueriesLocator locator;
|
||||
protected final ExecutorService executor;
|
||||
private final Logger logger;
|
||||
|
||||
protected AbstractUserManager(final Jdbi jdbi, final QueriesLocator locator) {
|
||||
protected DatabaseUserManager(final Jdbi jdbi, final QueriesLocator locator, final Logger logger) {
|
||||
this.jdbi = jdbi;
|
||||
this.locator = locator;
|
||||
this.executor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "DatabaseUserManager"));
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -71,8 +85,20 @@ public abstract class AbstractUserManager implements UserManager<CarbonPlayerCom
|
||||
}
|
||||
// TODO: save ignoredplayers
|
||||
return new ComponentPlayerResult<>(player, empty());
|
||||
}));
|
||||
}), this.executor);
|
||||
}
|
||||
|
||||
abstract protected Update bindPlayerArguments(final Update update, final CarbonPlayerCommon player);
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
for (final UUID id : List.copyOf(this.userCache.keySet())) {
|
||||
try {
|
||||
this.loggedOut(id).join();
|
||||
} catch (final Exception ex) {
|
||||
this.logger.warn("Exception saving data for player with uuid " + id);
|
||||
}
|
||||
}
|
||||
ConcurrentUtil.shutdownExecutor(this.executor, TimeUnit.MILLISECONDS, 500);
|
||||
}
|
||||
}
|
||||
+23
-12
@@ -21,9 +21,6 @@ package net.draycia.carbon.common.users.db.mysql;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -37,13 +34,14 @@ import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.common.config.DatabaseSettings;
|
||||
import net.draycia.carbon.common.users.CarbonPlayerCommon;
|
||||
import net.draycia.carbon.common.users.SaveOnChange;
|
||||
import net.draycia.carbon.common.users.db.AbstractUserManager;
|
||||
import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
|
||||
import net.draycia.carbon.common.users.db.DBType;
|
||||
import net.draycia.carbon.common.users.db.DatabaseUserManager;
|
||||
import net.draycia.carbon.common.users.db.KeyArgumentFactory;
|
||||
import net.draycia.carbon.common.users.db.QueriesLocator;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
@@ -57,16 +55,15 @@ import static net.kyori.adventure.text.Component.text;
|
||||
|
||||
// TODO: Dispatch updates using messaging system when users are modified
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public final class MySQLUserManager extends AbstractUserManager implements SaveOnChange {
|
||||
public final class MySQLUserManager extends DatabaseUserManager implements SaveOnChange {
|
||||
|
||||
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
private MySQLUserManager(final Jdbi jdbi) {
|
||||
super(jdbi, new QueriesLocator(DBType.MYSQL));
|
||||
private MySQLUserManager(final Jdbi jdbi, final Logger logger) {
|
||||
super(jdbi, new QueriesLocator(DBType.MYSQL), logger);
|
||||
}
|
||||
|
||||
public static MySQLUserManager manager(
|
||||
final DatabaseSettings databaseSettings
|
||||
final DatabaseSettings databaseSettings,
|
||||
final Logger logger
|
||||
) {
|
||||
try {
|
||||
//Class.forName("org.postgresql.Driver");
|
||||
@@ -103,7 +100,7 @@ public final class MySQLUserManager extends AbstractUserManager implements SaveO
|
||||
.registerRowMapper(new MySQLPlayerRowMapper())
|
||||
.installPlugin(new SqlObjectPlugin());
|
||||
|
||||
return new MySQLUserManager(jdbi);
|
||||
return new MySQLUserManager(jdbi, logger);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -145,7 +142,12 @@ public final class MySQLUserManager extends AbstractUserManager implements SaveO
|
||||
}));
|
||||
|
||||
return new ComponentPlayerResult<>(playerResult, empty());
|
||||
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
|
||||
}, this.executor).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<CarbonPlayerCommon> user(UUID uuid) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -226,4 +228,13 @@ public final class MySQLUserManager extends AbstractUserManager implements SaveO
|
||||
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.removeLeftChannel(id, channel));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> save(CarbonPlayerCommon player) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> loggedOut(UUID uuid) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
+22
-12
@@ -21,9 +21,6 @@ package net.draycia.carbon.common.users.db.postgresql;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -36,13 +33,14 @@ import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.common.config.DatabaseSettings;
|
||||
import net.draycia.carbon.common.users.CarbonPlayerCommon;
|
||||
import net.draycia.carbon.common.users.SaveOnChange;
|
||||
import net.draycia.carbon.common.users.db.AbstractUserManager;
|
||||
import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
|
||||
import net.draycia.carbon.common.users.db.DBType;
|
||||
import net.draycia.carbon.common.users.db.DatabaseUserManager;
|
||||
import net.draycia.carbon.common.users.db.KeyArgumentFactory;
|
||||
import net.draycia.carbon.common.users.db.QueriesLocator;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
@@ -58,15 +56,13 @@ import static net.kyori.adventure.text.Component.text;
|
||||
|
||||
// TODO: Dispatch updates using messaging system when users are modified
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public final class PostgreSQLUserManager extends AbstractUserManager implements SaveOnChange {
|
||||
public final class PostgreSQLUserManager extends DatabaseUserManager implements SaveOnChange {
|
||||
|
||||
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
private PostgreSQLUserManager(final Jdbi jdbi) {
|
||||
super(jdbi, new QueriesLocator(DBType.POSTGRESQL));
|
||||
private PostgreSQLUserManager(final Jdbi jdbi, final Logger logger) {
|
||||
super(jdbi, new QueriesLocator(DBType.POSTGRESQL), logger);
|
||||
}
|
||||
|
||||
public static PostgreSQLUserManager manager(final DatabaseSettings databaseSettings) {
|
||||
public static PostgreSQLUserManager manager(final DatabaseSettings databaseSettings, final Logger logger) {
|
||||
try {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
Flyway.configure().getPluginRegister().REGISTERED_PLUGINS.add(new PostgreSQLDatabaseType());
|
||||
@@ -98,7 +94,7 @@ public final class PostgreSQLUserManager extends AbstractUserManager implements
|
||||
.installPlugin(new SqlObjectPlugin())
|
||||
.installPlugin(new PostgresPlugin());
|
||||
|
||||
return new PostgreSQLUserManager(jdbi);
|
||||
return new PostgreSQLUserManager(jdbi, logger);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -148,7 +144,12 @@ public final class PostgreSQLUserManager extends AbstractUserManager implements
|
||||
return new ComponentPlayerResult<>(player, text(""));
|
||||
}
|
||||
});
|
||||
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
|
||||
}, this.executor).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<CarbonPlayerCommon> user(UUID uuid) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -229,4 +230,13 @@ public final class PostgreSQLUserManager extends AbstractUserManager implements
|
||||
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.removeLeftChannel(id, channel));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> save(CarbonPlayerCommon player) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> loggedOut(UUID uuid) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
@@ -27,51 +27,51 @@ import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.draycia.carbon.api.CarbonChat;
|
||||
import net.draycia.carbon.api.CarbonChatProvider;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.api.users.UserManager;
|
||||
import net.draycia.carbon.common.ForCarbon;
|
||||
import net.draycia.carbon.common.serialisation.gson.ChatChannelSerializerGson;
|
||||
import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson;
|
||||
import net.draycia.carbon.common.users.CarbonPlayerCommon;
|
||||
import net.draycia.carbon.common.users.UserManagerInternal;
|
||||
import net.draycia.carbon.common.util.ConcurrentUtil;
|
||||
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
|
||||
import net.kyori.adventure.util.ComponentMessageThrowable;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
import static net.kyori.adventure.text.Component.empty;
|
||||
import static net.kyori.adventure.text.Component.text;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
public class JSONUserManager implements UserManager<CarbonPlayerCommon> {
|
||||
public class JSONUserManager implements UserManagerInternal<CarbonPlayerCommon> {
|
||||
|
||||
private static final String EMPTY_USER_UUID = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6";
|
||||
private final Logger logger;
|
||||
private final Gson serializer;
|
||||
private final Path userDirectory;
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
|
||||
private final Map<UUID, CompletableFuture<CarbonPlayerCommon>> cache = new HashMap<>();
|
||||
private final ExecutorService executor;
|
||||
private final String emptyUserJson;
|
||||
|
||||
@Inject
|
||||
public JSONUserManager(
|
||||
final @ForCarbon Path dataDirectory,
|
||||
final Injector injector,
|
||||
final Logger logger,
|
||||
final CarbonChat carbonChat
|
||||
final Logger logger
|
||||
) throws IOException {
|
||||
this.logger = logger;
|
||||
this.userDirectory = dataDirectory.resolve("users");
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
Files.createDirectories(this.userDirectory);
|
||||
|
||||
@@ -81,59 +81,78 @@ public class JSONUserManager implements UserManager<CarbonPlayerCommon> {
|
||||
.registerTypeAdapter(UUID.class, injector.getInstance(UUIDSerializerGson.class))
|
||||
.setPrettyPrinting()
|
||||
.create();
|
||||
|
||||
this.emptyUserJson = this.serializer.toJson(new CarbonPlayerCommon("username", UUID.fromString(EMPTY_USER_UUID)));
|
||||
|
||||
this.executor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "JSONUserManager"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
|
||||
public synchronized CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
|
||||
return this.user(uuid)
|
||||
.thenApply(user -> new ComponentPlayerResult<>(user, empty()))
|
||||
.exceptionally(thr -> new ComponentPlayerResult<>(null, ComponentMessageThrowable.getOrConvertMessage(thr)));
|
||||
}
|
||||
|
||||
if (cachedPlayer != null) {
|
||||
return new ComponentPlayerResult<>(cachedPlayer, empty());
|
||||
}
|
||||
@Override
|
||||
public synchronized CompletableFuture<CarbonPlayerCommon> user(final UUID uuid) {
|
||||
return this.cache.computeIfAbsent(uuid, $ -> {
|
||||
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
|
||||
final Path userFile = this.userFile(uuid);
|
||||
|
||||
final Path userFile = this.userDirectory.resolve(uuid + ".json");
|
||||
if (Files.exists(userFile)) {
|
||||
try {
|
||||
final @Nullable CarbonPlayerCommon player =
|
||||
this.serializer.fromJson(Files.newBufferedReader(userFile), CarbonPlayerCommon.class);
|
||||
|
||||
if (Files.exists(userFile)) {
|
||||
try {
|
||||
final @Nullable CarbonPlayerCommon player =
|
||||
this.serializer.fromJson(Files.newBufferedReader(userFile), CarbonPlayerCommon.class);
|
||||
if (player == null) {
|
||||
throw new IllegalStateException("Player file found but was empty.");
|
||||
}
|
||||
player.leftChannels().removeIf(channel -> CarbonChatProvider.carbonChat()
|
||||
.channelRegistry()
|
||||
.get(channel) == null);
|
||||
|
||||
if (player == null) {
|
||||
return new ComponentPlayerResult<CarbonPlayerCommon>(null, text("Player file found but was empty."));
|
||||
return player;
|
||||
} catch (final IOException exception) {
|
||||
throw new RuntimeException(exception);
|
||||
}
|
||||
player.leftChannels().removeIf(channel -> CarbonChatProvider.carbonChat()
|
||||
.channelRegistry()
|
||||
.get(channel) == null);
|
||||
this.userCache.put(uuid, player);
|
||||
|
||||
return new ComponentPlayerResult<>(player, empty());
|
||||
} catch (final IOException exception) {
|
||||
return new ComponentPlayerResult<CarbonPlayerCommon>(null, text(exception.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
final String name = Objects.requireNonNull(
|
||||
this.carbonChat.server().resolveName(uuid).join());
|
||||
return new CarbonPlayerCommon(null /* Username will be resolved when requested */, uuid);
|
||||
}, this.executor);
|
||||
|
||||
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
|
||||
// Don't keep failed requests so they can be retried on the next request
|
||||
// The caller is expected to handle the error
|
||||
future.whenComplete((result, $$$) -> {
|
||||
if (result == null) {
|
||||
synchronized (this) {
|
||||
this.cache.remove(uuid);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.userCache.put(uuid, player);
|
||||
return future;
|
||||
});
|
||||
}
|
||||
|
||||
return new ComponentPlayerResult<>(player, empty());
|
||||
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
|
||||
private Path userFile(final UUID id) {
|
||||
return this.userDirectory.resolve(id + ".json");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final Path userFile = this.userDirectory.resolve(player.uuid() + ".json");
|
||||
public CompletableFuture<Void> save(final CarbonPlayerCommon player) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
final Path userFile = this.userFile(player.uuid());
|
||||
|
||||
try {
|
||||
final String json = this.serializer.toJson(player);
|
||||
|
||||
if (json == null || json.isBlank()) {
|
||||
return new ComponentPlayerResult<>(null, text("No data to save - toJson returned null or blank."));
|
||||
throw new IllegalStateException("No data to save - toJson returned null or blank.");
|
||||
|
||||
// quick and dirty check to not create files for/save default data
|
||||
} else if (json.equals(this.emptyUserJson.replace(EMPTY_USER_UUID, player.uuid().toString()))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Files.exists(userFile)) {
|
||||
@@ -143,24 +162,36 @@ public class JSONUserManager implements UserManager<CarbonPlayerCommon> {
|
||||
Files.writeString(userFile, json,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.TRUNCATE_EXISTING);
|
||||
|
||||
return new ComponentPlayerResult<>(player, text(String.format("Saving player data for [%s], [%s]",
|
||||
player.username(), player.uuid())));
|
||||
} catch (final IOException exception) {
|
||||
this.logger.error("Exception caught while saving data for player [{}]", player.username());
|
||||
exception.printStackTrace();
|
||||
return new ComponentPlayerResult<>(null, text(exception.getMessage()));
|
||||
throw new RuntimeException("Exception while saving data for player [%s]".formatted(player.username()), exception);
|
||||
}
|
||||
});
|
||||
}, this.executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
|
||||
return this.savePlayer(player).thenApply(result -> {
|
||||
this.userCache.remove(player.uuid());
|
||||
|
||||
return result;
|
||||
});
|
||||
return this.loggedOut(player.uuid()).thenApply($ -> new ComponentPlayerResult<>(player, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
for (final UUID id : List.copyOf(this.cache.keySet())) {
|
||||
try {
|
||||
this.loggedOut(id).join();
|
||||
} catch (final Exception ex) {
|
||||
this.logger.warn("Exception saving data for player with uuid " + id);
|
||||
}
|
||||
}
|
||||
ConcurrentUtil.shutdownExecutor(this.executor, TimeUnit.MILLISECONDS, 500);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized CompletableFuture<Void> loggedOut(final UUID uuid) {
|
||||
final CompletableFuture<@Nullable CarbonPlayerCommon> remove = this.cache.remove(uuid);
|
||||
final @Nullable CarbonPlayerCommon join = remove.join();
|
||||
if (remove.isDone() && join != null) { // don't need to save if it never finished loading
|
||||
return this.save(join);
|
||||
}
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package net.draycia.carbon.common.util;
|
||||
|
||||
import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
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 ConcurrentUtil {
|
||||
|
||||
private ConcurrentUtil() {
|
||||
}
|
||||
|
||||
public static void shutdownExecutor(final ExecutorService service, final TimeUnit timeoutUnit, final long timeoutLength) {
|
||||
service.shutdown();
|
||||
boolean didShutdown;
|
||||
try {
|
||||
didShutdown = service.awaitTermination(timeoutLength, timeoutUnit);
|
||||
} catch (final InterruptedException ignore) {
|
||||
didShutdown = false;
|
||||
}
|
||||
if (!didShutdown) {
|
||||
service.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public static ThreadFactory carbonThreadFactory(final Logger logger, final String name) {
|
||||
return new ThreadFactoryBuilder()
|
||||
.setDaemon(true)
|
||||
.setNameFormat("CarbonChat " + name + " Thread #%d")
|
||||
.setUncaughtExceptionHandler((thread, thr) -> logger.warn("Uncaught exception on thread {}", thread.getName(), thr))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,10 +22,11 @@ package net.draycia.carbon.common.util;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.draycia.carbon.api.CarbonServer;
|
||||
import net.draycia.carbon.api.users.ComponentPlayerResult;
|
||||
import net.draycia.carbon.api.users.UserManager;
|
||||
import net.draycia.carbon.common.users.CarbonPlayerCommon;
|
||||
import net.draycia.carbon.common.users.UserManagerInternal;
|
||||
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
|
||||
@@ -35,56 +36,27 @@ public final class PlayerUtils {
|
||||
private PlayerUtils() {
|
||||
}
|
||||
|
||||
public static List<CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>>> saveLoggedInPlayers(
|
||||
public static List<CompletableFuture<Void>> saveLoggedInPlayers(
|
||||
final CarbonServer carbonServer,
|
||||
final UserManager<CarbonPlayerCommon> userManager
|
||||
final UserManager<CarbonPlayerCommon> userManager,
|
||||
final Logger logger
|
||||
) {
|
||||
return carbonServer.players().stream()
|
||||
.map(player -> savePlayer(carbonServer, userManager, (WrappedCarbonPlayer) player))
|
||||
.map(player -> savePlayer(userManager, (WrappedCarbonPlayer) player, logger))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(
|
||||
final CarbonServer carbonServer,
|
||||
public static CompletableFuture<Void> savePlayer(
|
||||
final UserManager<CarbonPlayerCommon> userManager,
|
||||
final WrappedCarbonPlayer player
|
||||
final WrappedCarbonPlayer player,
|
||||
final Logger logger
|
||||
) {
|
||||
final var saveResult =
|
||||
userManager.savePlayer(player.carbonPlayerCommon());
|
||||
|
||||
saveResult.thenAccept(result -> {
|
||||
if (result.player() == null) {
|
||||
carbonServer.console().sendMessage(result.reason());
|
||||
}
|
||||
});
|
||||
|
||||
saveResult.exceptionally(exception -> {
|
||||
exception.getCause().printStackTrace();
|
||||
((UserManagerInternal<CarbonPlayerCommon>) userManager).save(player.carbonPlayerCommon());
|
||||
saveResult.exceptionally(thr -> {
|
||||
logger.warn("Exception saving data for player {} with UUID {}", player.username(), player.uuid(), thr);
|
||||
return null;
|
||||
});
|
||||
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
public static CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(
|
||||
final CarbonServer carbonServer,
|
||||
final UserManager<CarbonPlayerCommon> userManager,
|
||||
final WrappedCarbonPlayer player
|
||||
) {
|
||||
final var saveResult =
|
||||
userManager.saveAndInvalidatePlayer(player.carbonPlayerCommon());
|
||||
|
||||
saveResult.thenAccept(result -> {
|
||||
if (result.player() == null) {
|
||||
carbonServer.console().sendMessage(result.reason());
|
||||
}
|
||||
});
|
||||
|
||||
saveResult.exceptionally(exception -> {
|
||||
exception.getCause().printStackTrace();
|
||||
return null;
|
||||
});
|
||||
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user