Skip to content

Commit

Permalink
Error handling mechanism for adding UUID to query player names
Browse files Browse the repository at this point in the history
  • Loading branch information
Suisuroru committed Nov 30, 2024
1 parent aa7c21f commit ba1d4a4
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions Xplat/src/main/java/vazkii/botania/data/UuidNameProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@
public class UuidNameProvider {

private static final Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
private static final Map<String, FailureEntry> failureTimes = new ConcurrentHashMap<>();
private static final Duration CACHE_DURATION = Duration.ofMinutes(15);
private static final int MAX_FAILURES = 5;

public static String getPlayerNameFromUUID(String uuid) {
CacheEntry entry = cache.get(uuid);
if (entry != null && !entry.isExpired()) {
boolean isCacheExpired = entry == null || entry.isExpired();

if (!isCacheExpired) {
return entry.name;
}

Expand All @@ -38,17 +42,45 @@ public static String getPlayerNameFromUUID(String uuid) {
in.close();

JsonObject jsonObject = JsonParser.parseString(content.toString()).getAsJsonObject();
String name = jsonObject.get("name").getAsString();
if (jsonObject.has("name")) {
String name = jsonObject.get("name").getAsString();

cache.put(uuid, new CacheEntry(name));
cache.put(uuid, new CacheEntry(name));
failureTimes.remove(uuid); // Reset failure count on success

return name;
return name;
} else {
recordFailureTime(uuid);
FailureEntry failureEntry = failureTimes.getOrDefault(uuid, new FailureEntry());
if (failureEntry.failures >= MAX_FAILURES) {
if (isCacheExpired) {
cache.remove(uuid);
}
return uuid;
}
return null;
}
} catch (Exception e) {
e.printStackTrace();
recordFailureTime(uuid);

FailureEntry failureEntry = failureTimes.getOrDefault(uuid, new FailureEntry());
if (failureEntry.failures >= MAX_FAILURES) {
if (isCacheExpired) {
cache.remove(uuid);
}
return uuid;
}
return null;
}
}

private static void recordFailureTime(String uuid) {
FailureEntry failureEntry = failureTimes.computeIfAbsent(uuid, k -> new FailureEntry());
failureEntry.failures++;
failureEntry.lastFailureTime = Instant.now();
}

private static class CacheEntry {
final String name;
final Instant creationTime;
Expand All @@ -62,4 +94,9 @@ boolean isExpired() {
return Instant.now().isAfter(creationTime.plus(CACHE_DURATION));
}
}

private static class FailureEntry {
int failures = 0;
Instant lastFailureTime = Instant.now();
}
}

0 comments on commit ba1d4a4

Please sign in to comment.