add guild, user and scoresaber account caching

This commit is contained in:
Lee 2024-06-27 13:00:45 +01:00
parent d5ee54d011
commit b36bdae5de
6 changed files with 71 additions and 24 deletions

@ -85,10 +85,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId> <artifactId>spring-boot-starter-websocket</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Libraries --> <!-- Libraries -->
<dependency> <dependency>
@ -114,6 +110,11 @@
<artifactId>httpclient5</artifactId> <artifactId>httpclient5</artifactId>
<version>5.3.1</version> <version>5.3.1</version>
</dependency> </dependency>
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
<version>0.5.11</version>
</dependency>
<!-- Test Dependencies --> <!-- Test Dependencies -->
<dependency> <dependency>

@ -7,7 +7,6 @@ import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import java.io.File; import java.io.File;
@ -15,7 +14,7 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.Objects; import java.util.Objects;
@EnableScheduling @EnableCaching @EnableScheduling
@SpringBootApplication @SpringBootApplication
@Log4j2(topic = "Ember") @Log4j2(topic = "Ember")
public class BatApplication { public class BatApplication {

@ -5,11 +5,14 @@ import cc.fascinated.bat.common.EmbedUtils;
import cc.fascinated.bat.model.BatGuild; import cc.fascinated.bat.model.BatGuild;
import cc.fascinated.bat.model.BatUser; import cc.fascinated.bat.model.BatUser;
import cc.fascinated.bat.service.DiscordService; import cc.fascinated.bat.service.DiscordService;
import cc.fascinated.bat.service.GuildService;
import cc.fascinated.bat.service.UserService;
import lombok.NonNull; import lombok.NonNull;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.interactions.commands.SlashCommandInteraction; import net.dv8tion.jda.api.interactions.commands.SlashCommandInteraction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@ -17,8 +20,14 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class BotStatsCommand extends BatCommand { public class BotStatsCommand extends BatCommand {
public BotStatsCommand() { private final GuildService guildService;
private final UserService userService;
@Autowired
public BotStatsCommand(@NonNull GuildService guildService, @NonNull UserService userService) {
super("botstats", "Shows the bot statistics"); super("botstats", "Shows the bot statistics");
this.guildService = guildService;
this.userService = userService;
} }
@Override @Override
@ -29,7 +38,9 @@ public class BotStatsCommand extends BatCommand {
"**Bot Statistics**\n" + "**Bot Statistics**\n" +
"➜ Guilds: %s\n".formatted(jda.getGuilds().size()) + "➜ Guilds: %s\n".formatted(jda.getGuilds().size()) +
"➜ Users: %s\n".formatted(jda.getUsers().size()) + "➜ Users: %s\n".formatted(jda.getUsers().size()) +
"➜ Gateway Ping: %sms".formatted(jda.getGatewayPing()) "➜ Gateway Ping: %sms\n".formatted(jda.getGatewayPing()) +
"➜ Cached Guilds: %s\n".formatted(guildService.getGuilds().size()) +
"➜ Cached Users: %s".formatted(userService.getUsers().size())
).build()).queue(); ).build()).queue();
} }
} }

@ -2,25 +2,29 @@ package cc.fascinated.bat.service;
import cc.fascinated.bat.model.BatGuild; import cc.fascinated.bat.model.BatGuild;
import cc.fascinated.bat.repository.GuildRepository; import cc.fascinated.bat.repository.GuildRepository;
import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.*;
import java.util.Optional;
/** /**
* @author Fascinated (fascinated7) * @author Fascinated (fascinated7)
*/ */
@Service @Log4j2 @Service @Log4j2 @Getter
@DependsOn("discordService") @DependsOn("discordService")
public class GuildService extends ListenerAdapter { public class GuildService extends ListenerAdapter {
/**
* The cached guilds
*/
private final Map<String, BatGuild> guilds = new HashMap<>();
/** /**
* The guild repository to use * The guild repository to use
*/ */
@ -38,12 +42,17 @@ public class GuildService extends ListenerAdapter {
* @param id The ID of the guild * @param id The ID of the guild
* @return The guild * @return The guild
*/ */
@Cacheable(cacheNames = "guilds", key = "#id")
public BatGuild getGuild(@NonNull String id) { public BatGuild getGuild(@NonNull String id) {
if (guilds.containsKey(id)) {
return guilds.get(id);
}
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Optional<BatGuild> optionalGuild = guildRepository.findById(id); Optional<BatGuild> optionalGuild = guildRepository.findById(id);
if (optionalGuild.isPresent()) { if (optionalGuild.isPresent()) {
return optionalGuild.get(); BatGuild guild = optionalGuild.get();
guilds.put(id, guild);
return guild;
} }
BatGuild guild = guildRepository.save(new BatGuild(id)); BatGuild guild = guildRepository.save(new BatGuild(id));
log.info("Created guild \"{}\" in {}ms", id, System.currentTimeMillis() - start); log.info("Created guild \"{}\" in {}ms", id, System.currentTimeMillis() - start);
@ -55,7 +64,6 @@ public class GuildService extends ListenerAdapter {
* *
* @param guild The guild to save * @param guild The guild to save
*/ */
@CachePut(cacheNames = "guilds", key = "#guild.id")
public void saveGuild(@NonNull BatGuild guild) { public void saveGuild(@NonNull BatGuild guild) {
guildRepository.save(guild); guildRepository.save(guild);
} }
@ -66,7 +74,11 @@ public class GuildService extends ListenerAdapter {
* @return all guilds * @return all guilds
*/ */
public List<BatGuild> getAllGuilds() { public List<BatGuild> getAllGuilds() {
return guildRepository.findAll(); List<BatGuild> guilds = new ArrayList<>();
for (Guild guild : DiscordService.JDA.getGuilds()) {
guilds.add(getGuild(guild.getId()));
}
return guilds;
} }
@Override @Override

@ -12,8 +12,8 @@ import com.google.gson.JsonObject;
import lombok.NonNull; import lombok.NonNull;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import net.jodah.expiringmap.ExpiringMap;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
@ -24,6 +24,8 @@ import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service @Log4j2(topic = "ScoreSaber Service") @Service @Log4j2(topic = "ScoreSaber Service")
public class ScoreSaberService extends TextWebSocketHandler { public class ScoreSaberService extends TextWebSocketHandler {
@ -31,6 +33,13 @@ public class ScoreSaberService extends TextWebSocketHandler {
private static final String GET_PLAYER_ENDPOINT = SCORESABER_API + "player/%s/full"; private static final String GET_PLAYER_ENDPOINT = SCORESABER_API + "player/%s/full";
private static final String GET_PLAYER_SCORES_ENDPOINT = SCORESABER_API + "player/%s/scores?limit=100&sort=%s&page=%s&withMetadata=true"; private static final String GET_PLAYER_SCORES_ENDPOINT = SCORESABER_API + "player/%s/scores?limit=100&sort=%s&page=%s&withMetadata=true";
/**
* The cached accounts.
*/
private final Map<String, ScoreSaberAccountToken> cachedAccounts = ExpiringMap.builder()
.expiration(5, TimeUnit.MINUTES)
.build();
@Autowired @Autowired
public ScoreSaberService() { public ScoreSaberService() {
connectWebSocket(); connectWebSocket();
@ -45,6 +54,10 @@ public class ScoreSaberService extends TextWebSocketHandler {
* @throws cc.fascinated.bat.exception.RateLimitException If the ScoreSaber rate limit is reached. * @throws cc.fascinated.bat.exception.RateLimitException If the ScoreSaber rate limit is reached.
*/ */
public ScoreSaberAccountToken getAccount(String id) { public ScoreSaberAccountToken getAccount(String id) {
if (cachedAccounts.containsKey(id)) {
return cachedAccounts.get(id);
}
ScoreSaberAccountToken account = WebRequest.getAsEntity(String.format(GET_PLAYER_ENDPOINT, id), ScoreSaberAccountToken.class); ScoreSaberAccountToken account = WebRequest.getAsEntity(String.format(GET_PLAYER_ENDPOINT, id), ScoreSaberAccountToken.class);
if (account == null) { // Check if the account doesn't exist. if (account == null) { // Check if the account doesn't exist.
log.info("Account with id '{}' not found.", id); log.info("Account with id '{}' not found.", id);
@ -56,6 +69,7 @@ public class ScoreSaberService extends TextWebSocketHandler {
if (account.isInactive()) { if (account.isInactive()) {
throw new BadRequestException("Account with id '%s' is inactive.".formatted(id)); throw new BadRequestException("Account with id '%s' is inactive.".formatted(id));
} }
cachedAccounts.put(id, account);
return account; return account;
} }

@ -2,22 +2,28 @@ package cc.fascinated.bat.service;
import cc.fascinated.bat.model.BatUser; import cc.fascinated.bat.model.BatUser;
import cc.fascinated.bat.repository.UserRepository; import cc.fascinated.bat.repository.UserRepository;
import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
/** /**
* @author Fascinated (fascinated7) * @author Fascinated (fascinated7)
*/ */
@Service @Log4j2 @Service @Log4j2 @Getter
@DependsOn("discordService") @DependsOn("discordService")
public class UserService { public class UserService {
/**
* The cached users
*/
private final Map<String, BatUser> users = new HashMap<>();
/** /**
* The user repository to use * The user repository to use
*/ */
@ -34,12 +40,17 @@ public class UserService {
* @param id The ID of the user * @param id The ID of the user
* @return The user * @return The user
*/ */
@Cacheable(cacheNames = "users", key = "#id")
public BatUser getUser(@NonNull String id) { public BatUser getUser(@NonNull String id) {
if (users.containsKey(id)) {
return users.get(id);
}
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Optional<BatUser> optionalUser = userRepository.findById(id); Optional<BatUser> optionalUser = userRepository.findById(id);
if (optionalUser.isPresent()) { if (optionalUser.isPresent()) {
return optionalUser.get(); BatUser user = optionalUser.get();
users.put(id, user);
return user;
} }
BatUser user = userRepository.save(new BatUser(id)); BatUser user = userRepository.save(new BatUser(id));
log.info("Created user \"{}\" in {}ms", id, System.currentTimeMillis() - start); log.info("Created user \"{}\" in {}ms", id, System.currentTimeMillis() - start);
@ -51,7 +62,6 @@ public class UserService {
* *
* @param user The user to save * @param user The user to save
*/ */
@CachePut(cacheNames = "users", key = "#user.id")
public void saveUser(@NonNull BatUser user) { public void saveUser(@NonNull BatUser user) {
userRepository.save(user); userRepository.save(user);
} }