diff --git a/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java new file mode 100644 index 00000000..4c0b76bd --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java @@ -0,0 +1,105 @@ +/* + * 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.users; + +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.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Function; +import java.util.stream.Collectors; +import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.common.util.ConcurrentUtil; +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; + +@DefaultQualifier(NonNull.class) +public abstract class CachingUserManager implements UserManagerInternal { + + protected final Logger logger; + protected final ExecutorService executor; + protected final ReentrantLock cacheLock; + protected final Map> cache; + + protected CachingUserManager(final Logger logger, final ExecutorService executorService) { + this.logger = logger; + this.executor = executorService; + this.cacheLock = new ReentrantLock(); + this.cache = new HashMap<>(); + } + + @Override + public void shutdown() { + this.cacheLock.lock(); + try { + final Map> collect = List.copyOf(this.cache.keySet()).stream() + .collect(Collectors.toMap(Function.identity(), this::loggedOut)); + for (final Map.Entry> entry : collect.entrySet()) { + try { + entry.getValue().join(); + } catch (final Exception ex) { + this.logger.warn("Exception saving data for player with uuid " + entry.getKey()); + } + } + ConcurrentUtil.shutdownExecutor(this.executor, TimeUnit.MILLISECONDS, 500); + } finally { + this.cacheLock.unlock(); + } + } + + @Override + public CompletableFuture loggedOut(final UUID uuid) { + this.cacheLock.lock(); + try { + final @Nullable CompletableFuture remove = this.cache.remove(uuid); + if (remove != null && remove.isDone()) { // don't need to save if it never finished loading + final @Nullable C join = remove.join(); + if (join != null) { + return this.save(join); + } + } + return CompletableFuture.completedFuture(null); + } finally { + this.cacheLock.unlock(); + } + } + + // Don't keep failed requests, so they can be retried on the next request + // The caller is expected to handle the error + protected void attachPostLoad(final UUID uuid, final CompletableFuture future) { + future.whenComplete((result, thr) -> { + if (result == null || thr != null) { + this.cacheLock.lock(); + try { + this.cache.remove(uuid); + } finally { + this.cacheLock.unlock(); + } + } + }); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/users/db/DatabaseUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/db/DatabaseUserManager.java index 95a16abf..361ba592 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/db/DatabaseUserManager.java +++ b/common/src/main/java/net/draycia/carbon/common/users/db/DatabaseUserManager.java @@ -19,17 +19,12 @@ */ 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.common.users.CachingUserManager; import net.draycia.carbon.common.users.CarbonPlayerCommon; -import net.draycia.carbon.common.users.UserManagerInternal; +import net.draycia.carbon.common.users.ProfileResolver; import net.draycia.carbon.common.util.ConcurrentUtil; import net.kyori.adventure.key.Key; import org.apache.logging.log4j.Logger; @@ -40,24 +35,21 @@ import org.jdbi.v3.core.statement.PreparedBatch; import org.jdbi.v3.core.statement.Update; @DefaultQualifier(NonNull.class) -public abstract class DatabaseUserManager implements UserManagerInternal { +public abstract class DatabaseUserManager extends CachingUserManager { protected final Jdbi jdbi; - - protected final Map userCache = Collections.synchronizedMap(new HashMap<>()); protected final QueriesLocator locator; - protected final ExecutorService executor; - private final Logger logger; + protected final ProfileResolver profileResolver; - protected DatabaseUserManager(final Jdbi jdbi, final QueriesLocator locator, final Logger logger) { + protected DatabaseUserManager(final Jdbi jdbi, final QueriesLocator locator, final Logger logger, final ProfileResolver profileResolver) { + super(logger, Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "DatabaseUserManager"))); this.jdbi = jdbi; this.locator = locator; - this.executor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "DatabaseUserManager")); - this.logger = logger; + this.profileResolver = profileResolver; } @Override - final public CompletableFuture save(final CarbonPlayerCommon player) { + public final CompletableFuture save(final CarbonPlayerCommon player) { return CompletableFuture.runAsync(() -> this.jdbi.withHandle(handle -> { if (!this.modifiedPlayerObject(player)) { return CompletableFuture.completedFuture(null); @@ -98,16 +90,4 @@ public abstract class DatabaseUserManager implements UserManagerInternal> cache = new HashMap<>(); - private MySQLUserManager(final Jdbi jdbi, final Logger logger, final ProfileResolver profileResolver) { - super(jdbi, new QueriesLocator(DBType.MYSQL), logger); - this.profileResolver = profileResolver; + super(jdbi, new QueriesLocator(DBType.MYSQL), logger, profileResolver); } public static MySQLUserManager manager( @@ -107,10 +101,11 @@ public final class MySQLUserManager extends DatabaseUserManager { } @Override - public synchronized CompletableFuture user(final UUID uuid) { - return this.cache.computeIfAbsent(uuid, $ -> { - final CompletableFuture future = CompletableFuture.supplyAsync(() -> { - return this.userCache.computeIfAbsent(uuid, key -> { + public CompletableFuture user(final UUID uuid) { + this.cacheLock.lock(); + try { + return this.cache.computeIfAbsent(uuid, $ -> { + final CompletableFuture future = CompletableFuture.supplyAsync(() -> { return this.jdbi.withHandle(handle -> { final Optional carbonPlayerCommon = handle.createQuery(this.locator.query("select-player")) .bind("id", uuid) @@ -145,21 +140,15 @@ public final class MySQLUserManager extends DatabaseUserManager { }); return carbonPlayerCommon.get(); }); - }); - }, this.executor); + }, this.executor); - // 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.attachPostLoad(uuid, future); + + return future; }); - - return future; - }); + } finally { + this.cacheLock.unlock(); + } } @Override @@ -176,14 +165,4 @@ public final class MySQLUserManager extends DatabaseUserManager { .bind("spying", player.spying()); } - @Override - public CompletableFuture 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); - } - } diff --git a/common/src/main/java/net/draycia/carbon/common/users/db/postgresql/PostgreSQLUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/db/postgresql/PostgreSQLUserManager.java index 4a1d5c9d..f51ce04b 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/db/postgresql/PostgreSQLUserManager.java +++ b/common/src/main/java/net/draycia/carbon/common/users/db/postgresql/PostgreSQLUserManager.java @@ -21,8 +21,6 @@ package net.draycia.carbon.common.users.db.postgresql; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import java.util.HashMap; -import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -55,12 +53,8 @@ import org.jdbi.v3.sqlobject.SqlObjectPlugin; @DefaultQualifier(NonNull.class) public final class PostgreSQLUserManager extends DatabaseUserManager { - private final ProfileResolver profileResolver; - private final Map> cache = new HashMap<>(); - private PostgreSQLUserManager(final Jdbi jdbi, final Logger logger, final ProfileResolver profileResolver) { - super(jdbi, new QueriesLocator(DBType.POSTGRESQL), logger); - this.profileResolver = profileResolver; + super(jdbi, new QueriesLocator(DBType.POSTGRESQL), logger, profileResolver); } public static PostgreSQLUserManager manager( @@ -104,67 +98,58 @@ public final class PostgreSQLUserManager extends DatabaseUserManager { } @Override - public synchronized CompletableFuture user(final UUID uuid) { - return this.cache.computeIfAbsent(uuid, $ -> { - final CompletableFuture future = CompletableFuture.supplyAsync(() -> { - final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid); + public CompletableFuture user(final UUID uuid) { + this.cacheLock.lock(); + try { + return this.cache.computeIfAbsent(uuid, $ -> { + final CompletableFuture future = CompletableFuture.supplyAsync(() -> { + return this.jdbi.withHandle(handle -> { + try { + final @Nullable CarbonPlayerCommon carbonPlayerCommon = handle.createQuery(this.locator.query("select-player")) + .bind("id", uuid) + .mapTo(CarbonPlayerCommon.class) + .first(); - if (cachedPlayer != null) { - return cachedPlayer; - } + handle.createQuery(this.locator.query("select-ignores")) + .bind("id", uuid) + .mapTo(UUID.class) + .forEach(ignoredPlayer -> carbonPlayerCommon.ignoring(ignoredPlayer, true)); - return this.jdbi.withHandle(handle -> { - try { - final @Nullable CarbonPlayerCommon carbonPlayerCommon = handle.createQuery(this.locator.query("select-player")) - .bind("id", uuid) - .mapTo(CarbonPlayerCommon.class) - .first(); + handle.createQuery(this.locator.query("select-leftchannels")) + .bind("id", uuid) + .mapTo(Key.class) + .forEach(channel -> { + final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat() + .channelRegistry() + .get(channel); + if (chatChannel == null) { + return; + } + carbonPlayerCommon.leftChannels().add(channel); + }); + return carbonPlayerCommon; + } catch (final IllegalStateException exception) { + // Player doesn't exist in the DB, create them! + final String name = Objects.requireNonNull( + this.profileResolver.resolveName(uuid).join()); - handle.createQuery(this.locator.query("select-ignores")) - .bind("id", uuid) - .mapTo(UUID.class) - .forEach(ignoredPlayer -> carbonPlayerCommon.ignoring(ignoredPlayer, true)); + final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid); - handle.createQuery(this.locator.query("select-leftchannels")) - .bind("id", uuid) - .mapTo(Key.class) - .forEach(channel -> { - final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat() - .channelRegistry() - .get(channel); - if (chatChannel == null) { - return; - } - carbonPlayerCommon.leftChannels().add(channel); - }); - return carbonPlayerCommon; - } catch (final IllegalStateException exception) { - // Player doesn't exist in the DB, create them! - final String name = Objects.requireNonNull( - this.profileResolver.resolveName(uuid).join()); + this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player) + .execute(); - final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid); + return player; + } + }); + }, this.executor); - this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player) - .execute(); + this.attachPostLoad(uuid, future); - return player; - } - }); - }, this.executor); - - // 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); - } - } + return future; }); - - return future; - }); + } finally { + this.cacheLock.unlock(); + } } @Override @@ -181,14 +166,4 @@ public final class PostgreSQLUserManager extends DatabaseUserManager { .bind("spying", player.spying()); } - @Override - public CompletableFuture 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); - } - } diff --git a/common/src/main/java/net/draycia/carbon/common/users/json/JSONUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/json/JSONUserManager.java index 93a1a2bf..6d13ab75 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/json/JSONUserManager.java +++ b/common/src/main/java/net/draycia/carbon/common/users/json/JSONUserManager.java @@ -27,22 +27,17 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -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.CarbonChatProvider; import net.draycia.carbon.api.channels.ChatChannel; 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.CachingUserManager; import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.ProfileResolver; -import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.util.ConcurrentUtil; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.apache.logging.log4j.Logger; @@ -51,15 +46,12 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) -public class JSONUserManager implements UserManagerInternal { +public class JSONUserManager extends CachingUserManager { 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 ProfileResolver profileResolver; - private final Map> cache = new HashMap<>(); - private final ExecutorService executor; private final String emptyUserJson; @Inject @@ -69,7 +61,7 @@ public class JSONUserManager implements UserManagerInternal final Logger logger, final ProfileResolver profileResolver ) throws IOException { - this.logger = logger; + super(logger, Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "JSONUserManager"))); this.userDirectory = dataDirectory.resolve("users"); this.profileResolver = profileResolver; @@ -83,52 +75,47 @@ public class JSONUserManager implements UserManagerInternal .create(); this.emptyUserJson = this.serializer.toJson(new CarbonPlayerCommon("username", UUID.fromString(EMPTY_USER_UUID))); - - this.executor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "JSONUserManager")); } @Override - public synchronized CompletableFuture user(final UUID uuid) { - return this.cache.computeIfAbsent(uuid, $ -> { - final CompletableFuture future = CompletableFuture.supplyAsync(() -> { - final Path userFile = this.userFile(uuid); + public CompletableFuture user(final UUID uuid) { + this.cacheLock.lock(); + try { + return this.cache.computeIfAbsent(uuid, $ -> { + final CompletableFuture future = CompletableFuture.supplyAsync(() -> { + final Path userFile = this.userFile(uuid); - 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."); + if (player == null) { + throw new IllegalStateException("Player file found but was empty."); + } + player.profileResolver = this.profileResolver; + player.leftChannels().removeIf(channel -> CarbonChatProvider.carbonChat() + .channelRegistry() + .get(channel) == null); + + return player; + } catch (final IOException exception) { + throw new RuntimeException(exception); } - player.profileResolver = this.profileResolver; - player.leftChannels().removeIf(channel -> CarbonChatProvider.carbonChat() - .channelRegistry() - .get(channel) == null); - - return player; - } catch (final IOException exception) { - throw new RuntimeException(exception); } - } - final CarbonPlayerCommon player = new CarbonPlayerCommon(null /* Username will be resolved when requested */, uuid); - player.profileResolver = this.profileResolver; - return player; - }, this.executor); + final CarbonPlayerCommon player = new CarbonPlayerCommon(null /* Username will be resolved when requested */, uuid); + player.profileResolver = this.profileResolver; + return player; + }, this.executor); - // 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.attachPostLoad(uuid, future); + + return future; }); - - return future; - }); + } finally { + this.cacheLock.unlock(); + } } private Path userFile(final UUID id) { @@ -164,26 +151,4 @@ public class JSONUserManager implements UserManagerInternal }, this.executor); } - @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 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); - } - }