Skip to content

Commit

Permalink
simple uuid query cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Fallen-Breath committed Aug 20, 2024
1 parent 5c0a592 commit f4a97a0
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/main/java/me/fallenbreath/velocitywhitelist/MojangAPI.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.fallenbreath.velocitywhitelist;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.slf4j.Logger;

Expand All @@ -10,6 +11,7 @@
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

Expand All @@ -22,12 +24,26 @@ private static class ResponseObject
public String id;
}

private record QueryCacheEntry(QueryResult result, long timestampMs)
{
}

public record QueryResult(UUID uuid, String playerName)
{
}

private static final int QUERY_CACHE_TTL_MS = 5 * 60 * 1000; // 5min
private static final int QUERY_CACHE_CAPACITY = 100;
private static final List<QueryCacheEntry> queryCache = Lists.newLinkedList();

public static Optional<QueryResult> queryPlayerByName(Logger logger, String name)
{
synchronized (queryCache)
{
long now = System.currentTimeMillis();
queryCache.removeIf(e -> now - e.timestampMs > QUERY_CACHE_TTL_MS);
}

// TODO: use http proxy from my fork
// TODO: simple expiring lru cache?
String url = "https://api.mojang.com/users/profiles/minecraft/" + name;
Expand All @@ -47,7 +63,19 @@ public static Optional<QueryResult> queryPlayerByName(Logger logger, String name
{
return Optional.empty();
}
return Utils.tryParseUuid(obj.id).map(uuid -> new QueryResult(uuid, obj.name));
var ret = Utils.tryParseUuid(obj.id).map(uuid -> new QueryResult(uuid, obj.name));

ret.ifPresent(result -> {
synchronized (queryCache)
{
queryCache.add(new QueryCacheEntry(result, System.currentTimeMillis()));
while (queryCache.size() > QUERY_CACHE_CAPACITY)
{
queryCache.remove(0);
}
}
});
return ret;
}
catch (IOException | InterruptedException | IllegalArgumentException e)
{
Expand Down

0 comments on commit f4a97a0

Please sign in to comment.