Fix settings loading and add helpers for JPA

This commit is contained in:
anthorob committed 2022-03-20 16:56:33 -04:00
1 parent 90c2f8fba7
commit 832fc0ff3d
5 files changed
+73 -49

No files matched your search

@@ -18,6 +18,7 @@ import netneutrality.db.entities.OGuild;
import netneutrality.db.entities.OGuildSetting; import netneutrality.db.entities.OGuildSetting;
import netneutrality.handler.ratelimiter.IMessageRateLimiter; import netneutrality.handler.ratelimiter.IMessageRateLimiter;
import netneutrality.handler.ratelimiter.MessageRateLimiterImpl; import netneutrality.handler.ratelimiter.MessageRateLimiterImpl;
import netneutrality.thread.ThreadManager;
import netneutrality.utils.JpaUtils; import netneutrality.utils.JpaUtils;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import org.hibernate.Session; import org.hibernate.Session;
@@ -71,7 +72,8 @@ public class GuildManager {
this.rateLimiter = new MessageRateLimiterImpl(); this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this); managers.put(guild.getId(), this);
reloadBlacklistCache(true); reloadBlacklistCache();
reloadSettingsCache();
} }
private GuildManager(String guildId) { private GuildManager(String guildId) {
@@ -84,7 +86,8 @@ public class GuildManager {
this.rateLimiter = new MessageRateLimiterImpl(); this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this); managers.put(guild.getId(), this);
reloadBlacklistCache(true); reloadBlacklistCache();
reloadSettingsCache();
} }
public static GuildManager getManager(Guild guild) { public static GuildManager getManager(Guild guild) {
@@ -148,28 +151,31 @@ public class GuildManager {
public void setSettingValue(Settings setting, String value) { public void setSettingValue(Settings setting, String value) {
Session session = sessionFactory.openSession(); Session session = sessionFactory.openSession();
session.load(guildEntity, guildEntity.getGuildId()); JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
if (value == null || value.isEmpty()) {
value = setting.getDefaultValue();
}
OGuildSetting oGuildSetting = guildEntity.getSettingByName(setting.getName()); OGuildSetting oGuildSetting = guildEntity.getSettingByName(setting.getName());
session.beginTransaction(); session.beginTransaction();
if (value == null || setting.getDefaultValue().equals(value)) {
if (oGuildSetting != null) {
session.delete(oGuildSetting);
}
} else {
if (oGuildSetting == null) { if (oGuildSetting == null) {
oGuildSetting = new OGuildSetting(); oGuildSetting = new OGuildSetting();
oGuildSetting.setGuild(guildEntity); oGuildSetting.setGuild(guildEntity);
oGuildSetting.setName(setting.getName()); oGuildSetting.setName(setting.getName());
oGuildSetting.setValue(value); oGuildSetting.setValue(value);
session.save(oGuildSetting); session.save(oGuildSetting);
} else { } else {
oGuildSetting.setValue(value); oGuildSetting.setValue(value);
session.update(oGuildSetting); session.update(oGuildSetting);
} }
}
session.getTransaction().commit(); session.getTransaction().commit();
reloadSettingsCache(false); reloadSettingsCache(false);
session.close(); session.close();
} }
@@ -178,67 +184,50 @@ public class GuildManager {
if (toggle == isDebugEnabled()) if (toggle == isDebugEnabled())
return; return;
Session session = sessionFactory.openSession(); JpaUtils.updateWithTransaction(guildEntity, () -> guildEntity.setDebug(toggle));
session.beginTransaction();
guildEntity.setDebug(toggle);
session.update(guildEntity);
session.getTransaction().commit();
session.close();
} }
public static boolean reloadSettingsForGuild(String guildId) { public boolean reloadSettingsCache(boolean close) {
GuildManager manager = GuildManager.getManager(guildId);
manager.reloadSettingsCache(true);
return true;
}
public static boolean reloadSettingsForGuild(Guild guild) {
GuildManager manager = GuildManager.getManager(guild.getId());
manager.reloadSettingsCache(true);
return true;
}
public void reloadSettingsCache(boolean close) {
logger.debug("Reloading settings cache for guild: " + guild.getId()); logger.debug("Reloading settings cache for guild: " + guild.getId());
settingsCache.clear(); settingsCache.clear();
Session session = sessionFactory.openSession(); JpaUtils.getWithSession(guildEntity, close, () -> {
JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
Set<OGuildSetting> settingSet = guildEntity.getGuildSettings(); Set<OGuildSetting> settingSet = guildEntity.getGuildSettings();
for (OGuildSetting setting : settingSet) { for (OGuildSetting setting : settingSet) {
settingsCache.put(setting.getName(), setting.getValue()); settingsCache.put(setting.getName(), setting.getValue());
} }
});
if (close) return true;
session.close(); }
public boolean reloadSettingsCache() {
return reloadSettingsCache(true);
} }
public void reloadBlacklistCache(boolean close) { public void reloadBlacklistCache(boolean close) {
logger.debug("Reloading blacklist cache for guild: " + guild.getId()); logger.debug("Reloading blacklist cache for guild: " + guild.getId());
blacklistCache.clear(); blacklistCache.clear();
Session session = sessionFactory.openSession(); JpaUtils.getWithSession(guildEntity, close, () -> {
JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
Set<OBlacklist> oBlacklistSet = guildEntity.getBlacklists(); Set<OBlacklist> oBlacklistSet = guildEntity.getBlacklists();
for (OBlacklist bl : oBlacklistSet) { for (OBlacklist bl : oBlacklistSet) {
if (bl.getEnabled()) { if (bl.getEnabled()) {
blacklistCache.add(bl.getWord()); blacklistCache.add(bl.getWord());
} }
} }
});
}
if (close) public void reloadBlacklistCache() {
session.close(); reloadBlacklistCache(true);
} }
public void checkAndLogMessage(Message message, Member member, TextChannel channel) { public void checkAndLogMessage(Message message, Member member, TextChannel channel) {
if (isLoggingEnabled()) { if (isLoggingEnabled()) {
DBController.get("message", DBMessage.class).log(this, channel, member, message); ThreadManager.getExecutor("log-messages").submit(() -> DBController.get("message", DBMessage.class).log(this, channel, member, message));
} }
} }
@@ -254,6 +243,7 @@ public class GuildManager {
logger.debug("Guild[{}] doesn't exist in DB, creating entity..", guildId); logger.debug("Guild[{}] doesn't exist in DB, creating entity..", guildId);
session.beginTransaction(); session.beginTransaction();
entity = new OGuild(); entity = new OGuild();
entity.setGuildId(guildId); entity.setGuildId(guildId);
session.save(entity); session.save(entity);
@@ -18,7 +18,7 @@ public class WebModule {
private final OkHttpClient client = new OkHttpClient(); private final OkHttpClient client = new OkHttpClient();
private Response response; private Response response;
//private final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.43"; //private final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.43";
private final String userAgent = "NetNeutrality/1.0 (Discord bot, [email protected])"; private static final String userAgent = "NetNeutrality/1.0 (Discord bot, [email protected])";
public WebModule(String url) { public WebModule(String url) {
@@ -70,9 +70,9 @@ public class ActionHandler extends AbstractHandler {
Guild guild = NetNeutrality.getJDA().getGuildById(guildId); Guild guild = NetNeutrality.getJDA().getGuildById(guildId);
boolean ok; boolean ok;
if (guild == null) if (guild == null)
ok = GuildManager.reloadSettingsForGuild(guildId); ok = GuildManager.getManager(guildId).reloadSettingsCache();
else else
ok = GuildManager.reloadSettingsForGuild(guild); ok = GuildManager.getManager(guild).reloadSettingsCache();
json.put("status", String.valueOf(ok)); json.put("status", String.valueOf(ok));
@@ -22,7 +22,6 @@ public class ThreadManager {
public static ExecutorService getExecutor(String name) { public static ExecutorService getExecutor(String name) {
return executors.computeIfAbsent(name, s -> Executors.newSingleThreadExecutor(new BaseThreadFactory(name))); return executors.computeIfAbsent(name, s -> Executors.newSingleThreadExecutor(new BaseThreadFactory(name)));
} }
public static ExecutorService getExecutor(String name, ExecutorType type) { public static ExecutorService getExecutor(String name, ExecutorType type) {
@@ -9,6 +9,7 @@ import io.sentry.Breadcrumb;
import io.sentry.Sentry; import io.sentry.Sentry;
import io.sentry.SentryLevel; import io.sentry.SentryLevel;
import netneutrality.core.GuildManager; import netneutrality.core.GuildManager;
import netneutrality.core.SessionManager;
import netneutrality.db.entities.OGuild; import netneutrality.db.entities.OGuild;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException; import org.hibernate.ObjectNotFoundException;
@@ -22,21 +23,55 @@ public class JpaUtils {
try { try {
session.load(object, id); session.load(object, id);
} catch (HibernateException exception) { } catch (HibernateException exception) {
if (object instanceof OGuild oGuild) {
if (exception instanceof ObjectNotFoundException) { if (exception instanceof ObjectNotFoundException) {
Sentry.addBreadcrumb(Breadcrumb.error("ObjectNotFoundException")); Sentry.addBreadcrumb(Breadcrumb.error("ObjectNotFoundException"));
if (object instanceof OGuild oGuild) {
String cachedId = oGuild.getGuildId(); String cachedId = oGuild.getGuildId();
Sentry.captureMessage("Trying to load Guild[" + cachedId + "] while deleted from database, reloading..", SentryLevel.ERROR); Sentry.captureMessage("Trying to load Guild[" + cachedId + "] while deleted from database, reloading entity..", SentryLevel.ERROR);
GuildManager guildManager = GuildManager.getManager(cachedId); GuildManager guildManager = GuildManager.getManager(cachedId);
guildManager.reloadEntity(); guildManager.reloadEntity();
guildManager.getBlacklistCache().clear(); guildManager.getBlacklistCache().clear();
Sentry.captureMessage("Guild[" + cachedId + "] reloaded", SentryLevel.INFO); Sentry.captureMessage("Guild[" + cachedId + "] reloaded", SentryLevel.INFO);
} }
} }
session.close();
session.close();
throw exception; throw exception;
} }
} }
public static void updateWithTransaction(Object persistantEntity, Runnable runnable) {
Session session = SessionManager.getSessionFactory().openSession();
session.beginTransaction();
runnable.run();
session.update(persistantEntity);
session.getTransaction().commit();
session.close();
}
public static void getWithSession(OGuild oGuild, Runnable runnable) {
getWithSession(oGuild, oGuild.getGuildId(), runnable);
}
public static void getWithSession(OGuild oGuild, boolean close, Runnable runnable) {
getWithSession(oGuild, oGuild.getGuildId(), close, runnable);
}
public static void getWithSession(Object persistantEntity, Serializable id, Runnable runnable) {
getWithSession(persistantEntity, id, true, runnable);
}
public static void getWithSession(Object persistantEntity, Serializable id, boolean close, Runnable runnable) {
Session session = SessionManager.getSessionFactory().openSession();
tryLoad(session, persistantEntity, id);
runnable.run();
if (close)
session.close();
}
} }