diff --git a/common/src/main/java/net/draycia/carbon/common/users/MojangProfileResolver.java b/common/src/main/java/net/draycia/carbon/common/users/MojangProfileResolver.java index 3b5880ac..cbdc61e0 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/MojangProfileResolver.java +++ b/common/src/main/java/net/draycia/carbon/common/users/MojangProfileResolver.java @@ -54,14 +54,16 @@ public final class MojangProfileResolver implements ProfileResolver { private final ExecutorService executorService; private final Map> pendingUuidLookups = new HashMap<>(); private final Map> pendingUsernameLookups = new HashMap<>(); + private final ProfileCache cache; @Inject - private MojangProfileResolver(final Logger logger) { + private MojangProfileResolver(final Logger logger, final ProfileCache cache) { this.client = HttpClient.newHttpClient(); this.gson = new GsonBuilder() .registerTypeAdapter(UUID.class, new UUIDTypeAdapter()) .create(); this.executorService = Executors.newFixedThreadPool(2, ConcurrentUtil.carbonThreadFactory(logger, "MojangProfileResolver")); + this.cache = cache; } @Override @@ -69,6 +71,9 @@ public final class MojangProfileResolver implements ProfileResolver { if (username.length() > 25 || username.length() < 1) { // Invalid names return CompletableFuture.completedFuture(null); } + if (this.cache.hasCachedEntry(username)) { + return CompletableFuture.completedFuture(this.cache.cachedId(username)); + } return this.pendingUuidLookups.computeIfAbsent(username, $ -> { final CompletableFuture<@Nullable BasicLookupResponse> mojangLookup = CompletableFuture.supplyAsync(() -> { try { @@ -83,6 +88,7 @@ public final class MojangProfileResolver implements ProfileResolver { mojangLookup.whenComplete((result, $$$) -> { synchronized (this) { + this.cache.cache(result == null ? null : result.id(), username); this.pendingUuidLookups.remove(username); } }); @@ -98,6 +104,9 @@ public final class MojangProfileResolver implements ProfileResolver { @Override public synchronized CompletableFuture<@Nullable String> resolveName(final UUID uuid) { + if (this.cache.hasCachedEntry(uuid)) { + return CompletableFuture.completedFuture(this.cache.cachedName(uuid)); + } return this.pendingUsernameLookups.computeIfAbsent(uuid, $ -> { final CompletableFuture<@Nullable BasicLookupResponse> mojangLookup = CompletableFuture.supplyAsync(() -> { try { @@ -112,6 +121,7 @@ public final class MojangProfileResolver implements ProfileResolver { mojangLookup.whenComplete((result, $$$) -> { synchronized (this) { + this.cache.cache(uuid, result == null ? null : result.name()); this.pendingUsernameLookups.remove(uuid); } }); diff --git a/common/src/main/java/net/draycia/carbon/common/users/ProfileCache.java b/common/src/main/java/net/draycia/carbon/common/users/ProfileCache.java new file mode 100644 index 00000000..75958776 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/users/ProfileCache.java @@ -0,0 +1,191 @@ +/* + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; + +@DefaultQualifier(NonNull.class) +@Singleton +public final class ProfileCache { + + private static final long REMOVE_AFTER = Duration.ofDays(7).toMillis(); + private static final long REMOVE_NULL_IDS_AFTER = Duration.ofHours(1).toMillis(); + + private final Gson gson; + private final Path cacheFile; + private final Map byId; + private final Map byName; + private final Set entries; + + private record CacheEntry(@Nullable UUID uuid, @Nullable String name, long updated) { + + } + + @Inject + private ProfileCache(final @ForCarbon Path dataDirectory) { + this.gson = new GsonBuilder() + .registerTypeAdapter(UUID.class, new UUIDSerializerGson()) + .create(); + this.cacheFile = dataDirectory.resolve("users/profile_cache.json"); + this.byId = new HashMap<>(); + this.byName = new HashMap<>(); + this.entries = new HashSet<>(); + this.load(); + } + + public synchronized @Nullable String cachedName(final UUID id) { + final @Nullable CacheEntry entry = this.byId.get(id); + if (entry == null) { + return null; + } else if (entry.updated() < cutoff()) { + return null; + } + return entry.name(); + } + + public synchronized @Nullable UUID cachedId(final String name) { + final @Nullable CacheEntry entry = this.byName.get(name); + if (entry == null) { + return null; + } else if (entry.updated() < cutoff()) { + return null; + } + return entry.uuid(); + } + + public synchronized boolean hasCachedEntry(final String name) { + final @Nullable CacheEntry entry = this.byName.get(name); + if (entry == null) { + return false; + } + return entry.updated() >= cutoff(); + } + + public synchronized boolean hasCachedEntry(final UUID uuid) { + final @Nullable CacheEntry entry = this.byId.get(uuid); + if (entry == null) { + return false; + } + return entry.updated() >= cutoff(); + } + + public synchronized void cache(final @Nullable UUID uuid, final @Nullable String name) { + final @Nullable CacheEntry r1 = uuid == null ? null : this.byId.remove(uuid); + final @Nullable CacheEntry r2 = name == null ? null : this.byName.remove(name); + if (r1 != null) { + this.entries.remove(r1); + } + if (r2 != null) { + this.entries.remove(r2); + } + final CacheEntry entry = new CacheEntry(uuid, name, System.currentTimeMillis()); + this.entries.add(entry); + if (entry.name() != null) { + this.byName.put(entry.name(), entry); + } + if (entry.uuid() != null) { + this.byId.put(entry.uuid(), entry); + } + } + + private synchronized void cleanup() { + final long cutoff = cutoff(); + final long nullIdCutoff = nullIdCutoff(); + for (final Iterator iterator = this.entries.iterator(); iterator.hasNext(); ) { + final CacheEntry entry = iterator.next(); + if (entry.updated() < cutoff || entry.uuid() == null && entry.updated() < nullIdCutoff) { + iterator.remove(); + if (entry.uuid() != null) { + this.byId.remove(entry.uuid()); + } + if (entry.name() != null) { + this.byName.remove(entry.name()); + } + } + } + } + + private static long nullIdCutoff() { + return System.currentTimeMillis() - REMOVE_NULL_IDS_AFTER; + } + + private static long cutoff() { + return System.currentTimeMillis() - REMOVE_AFTER; + } + + private synchronized void load() { + this.entries.clear(); + this.byId.clear(); + this.byName.clear(); + if (!Files.exists(this.cacheFile)) { + return; + } + try { + try (final BufferedReader reader = Files.newBufferedReader(this.cacheFile)) { + final Set load = this.gson.fromJson(reader, new TypeToken>() {}.getType()); + this.entries.addAll(load); + for (final CacheEntry entry : this.entries) { + if (entry.name() != null) { + this.byName.put(entry.name(), entry); + } + if (entry.uuid() != null) { + this.byId.put(entry.uuid(), entry); + } + } + } + } catch (final IOException ex) { + throw new RuntimeException("Failed to load cache", ex); + } + } + + public synchronized void save() { + this.cleanup(); + try { + Files.createDirectories(this.cacheFile.getParent()); + try (final BufferedWriter writer = Files.newBufferedWriter(this.cacheFile)) { + this.gson.toJson(this.entries, writer); + } + } catch (final IOException ex) { + throw new RuntimeException("Failed to save cache", ex); + } + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java b/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java index 2678eee6..36a5f09e 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java +++ b/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java @@ -25,7 +25,6 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; -// todo caching, should be able to cache both username & uuid after either one is requested @DefaultQualifier(NonNull.class) public interface ProfileResolver { 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 1069466e..d6e1d2da 100644 --- a/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java +++ b/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaper.java @@ -37,6 +37,7 @@ import net.draycia.carbon.common.listeners.RadiusListener; import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messaging.MessagingManager; import net.draycia.carbon.common.users.CarbonPlayerCommon; +import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.ProfileResolver; import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.util.CloudUtils; @@ -133,6 +134,9 @@ public final class CarbonChatPaper implements CarbonChat { Bukkit.getScheduler().runTaskTimerAsynchronously(this.plugin, () -> PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager, this.logger), saveDelay, saveDelay); + Bukkit.getScheduler().runTaskTimerAsynchronously(this.plugin, + () -> this.injector.getInstance(ProfileCache.class).save(), 20 * 60 * 15, 20 * 60 * 15); + // Load channels ((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages); @@ -153,6 +157,7 @@ public final class CarbonChatPaper implements CarbonChat { } void onDisable() { + this.injector.getInstance(ProfileCache.class).save(); this.injector.getInstance(ProfileResolver.class).shutdown(); this.userManager.shutdown(); this.injector.getInstance(ExecutionCoordinatorHolder.class).shutdown(); diff --git a/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java b/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java index fb44fa55..b14e4ce0 100644 --- a/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java +++ b/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java @@ -22,6 +22,7 @@ package net.draycia.carbon.paper.listeners; import com.google.inject.Inject; import java.util.Optional; import net.draycia.carbon.api.CarbonChat; +import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.paper.users.CarbonPlayerPaper; import org.apache.logging.log4j.Logger; @@ -39,18 +40,22 @@ public class PaperPlayerJoinListener implements Listener { private final CarbonChat carbonChat; private final Logger logger; + private final ProfileCache profileCache; @Inject public PaperPlayerJoinListener( final CarbonChat carbonChat, - final Logger logger + final Logger logger, + final ProfileCache profileCache ) { this.carbonChat = carbonChat; this.logger = logger; + this.profileCache = profileCache; } @EventHandler(priority = EventPriority.HIGH) public void onJoin(final PlayerJoinEvent event) { + this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName()); this.carbonChat.server().userManager().user(event.getPlayer().getUniqueId()).thenAccept(result -> { Optional.ofNullable(result.displayName()).ifPresent(displayName -> { final Player player = event.getPlayer();