usermanager cleanup

This commit is contained in:
Jason Penilla committed 2023-03-23 13:01:47 -07:00
1 parent 0251440600
commit 0c283d0918
5 files changed
+205 -201

No files matched your search

@@ -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 <https://www.gnu.org/licenses/>.
*/
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<C extends CarbonPlayer> implements UserManagerInternal<C> {
protected final Logger logger;
protected final ExecutorService executor;
protected final ReentrantLock cacheLock;
protected final Map<UUID, CompletableFuture<C>> 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<UUID, CompletableFuture<Void>> collect = List.copyOf(this.cache.keySet()).stream()
.collect(Collectors.toMap(Function.identity(), this::loggedOut));
for (final Map.Entry<UUID, CompletableFuture<Void>> 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<Void> loggedOut(final UUID uuid) {
this.cacheLock.lock();
try {
final @Nullable CompletableFuture<C> 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<CarbonPlayerCommon> future) {
future.whenComplete((result, thr) -> {
if (result == null || thr != null) {
this.cacheLock.lock();
try {
this.cache.remove(uuid);
} finally {
this.cacheLock.unlock();
}
}
});
}
}
@@ -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<CarbonPlayerCommon> {
public abstract class DatabaseUserManager extends CachingUserManager<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 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<Void> save(final CarbonPlayerCommon player) {
public final CompletableFuture<Void> 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<CarbonP
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);
}
}
@@ -21,8 +21,6 @@ package net.draycia.carbon.common.users.db.mysql;
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.Optional;
import java.util.UUID;
@@ -54,12 +52,8 @@ import org.jdbi.v3.sqlobject.SqlObjectPlugin;
@DefaultQualifier(NonNull.class)
public final class MySQLUserManager extends DatabaseUserManager {
private final ProfileResolver profileResolver;
private final Map<UUID, CompletableFuture<CarbonPlayerCommon>> 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<CarbonPlayerCommon> user(final UUID uuid) {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
return this.userCache.computeIfAbsent(uuid, key -> {
public CompletableFuture<CarbonPlayerCommon> user(final UUID uuid) {
this.cacheLock.lock();
try {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
return this.jdbi.withHandle(handle -> {
final Optional<CarbonPlayerCommon> 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<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);
}
}
@@ -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<UUID, CompletableFuture<CarbonPlayerCommon>> 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<CarbonPlayerCommon> user(final UUID uuid) {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
public CompletableFuture<CarbonPlayerCommon> user(final UUID uuid) {
this.cacheLock.lock();
try {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> 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<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);
}
}
@@ -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<CarbonPlayerCommon> {
public class JSONUserManager extends CachingUserManager<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 ProfileResolver profileResolver;
private final Map<UUID, CompletableFuture<CarbonPlayerCommon>> cache = new HashMap<>();
private final ExecutorService executor;
private final String emptyUserJson;
@Inject
@@ -69,7 +61,7 @@ public class JSONUserManager implements UserManagerInternal<CarbonPlayerCommon>
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<CarbonPlayerCommon>
.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<CarbonPlayerCommon> user(final UUID uuid) {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
final Path userFile = this.userFile(uuid);
public CompletableFuture<CarbonPlayerCommon> user(final UUID uuid) {
this.cacheLock.lock();
try {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> 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<CarbonPlayerCommon>
}, 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<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);
}
}