Add ProfileCache

This commit is contained in:
Jason Penilla committed 2023-03-21 13:22:36 -07:00
1 parent 34c8f60530
commit 46fcd4e351
5 files changed
+213 -3

No files matched your search

@@ -54,14 +54,16 @@ public final class MojangProfileResolver implements ProfileResolver {
private final ExecutorService executorService;
private final Map<String, CompletableFuture<@Nullable BasicLookupResponse>> pendingUuidLookups = new HashMap<>();
private final Map<UUID, CompletableFuture<@Nullable BasicLookupResponse>> 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);
}
});
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<UUID, CacheEntry> byId;
private final Map<String, CacheEntry> byName;
private final Set<CacheEntry> 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<CacheEntry> 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<CacheEntry> load = this.gson.fromJson(reader, new TypeToken<Set<CacheEntry>>() {}.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);
}
}
}
@@ -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 {