Added in memory caching

This commit is contained in:
barelyprofessional
2024-08-17 23:45:29 +08:00
parent b390368713
commit 71b46d73d2
10 changed files with 428 additions and 70 deletions

View File

@@ -0,0 +1,27 @@
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetWsClient.Models.Events;
namespace KfChatDotNetBot.Commands;
public class CacheClearCommand : ICommand
{
public List<Regex> Patterns => [
new Regex("^cache clear")
];
public string HelpText => "Clear the cache";
public bool HideFromHelp => true;
public UserRight RequiredRight => UserRight.Admin;
public async Task RunCommand(ChatBot botInstance, MessageModel message, UserDbModel user, GroupCollection arguments, CancellationToken ctx)
{
var cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
foreach (var cacheKey in cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
botInstance.SendChatMessage("Cache wiped", true);
}
}

View File

@@ -18,6 +18,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="NLog" Version="5.3.2" /> <PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="PuppeteerSharp" Version="18.0.5" /> <PackageReference Include="PuppeteerSharp" Version="18.0.5" />
<PackageReference Include="System.Runtime.Caching" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.4" /> <PackageReference Include="System.Text.Json" Version="8.0.4" />
</ItemGroup> </ItemGroup>

View File

@@ -0,0 +1,266 @@
// <auto-generated />
using System;
using KfChatDotNetBot;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240817151151_SettingsCache")]
partial class SettingsCache
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.ChipsggBetDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<double>("Amount")
.HasColumnType("REAL");
b.Property<string>("BetId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("Created")
.HasColumnType("TEXT");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("TEXT");
b.Property<float>("CurrencyPrice")
.HasColumnType("REAL");
b.Property<string>("GameTitle")
.IsRequired()
.HasColumnType("TEXT");
b.Property<float>("Multiplier")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("Updated")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Win")
.HasColumnType("INTEGER");
b.Property<double>("Winnings")
.HasColumnType("REAL");
b.HasKey("Id");
b.ToTable("ChipsggBets");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.HowlggBetsDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("Bet")
.HasColumnType("INTEGER");
b.Property<int>("BetId")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("Date")
.HasColumnType("TEXT");
b.Property<string>("Game")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("GameId")
.HasColumnType("INTEGER");
b.Property<long>("Profit")
.HasColumnType("INTEGER");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("HowlggBets");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.JuicerDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<float>("Amount")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("JuicedAt")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Juicers");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.RainbetBetsDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("BetId")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("BetSeenAt")
.HasColumnType("TEXT");
b.Property<string>("GameName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<float>("Multiplier")
.HasColumnType("REAL");
b.Property<float>("Payout")
.HasColumnType("REAL");
b.Property<string>("PublicId")
.HasColumnType("TEXT");
b.Property<int>("RainbetUserId")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<float>("Value")
.HasColumnType("REAL");
b.HasKey("Id");
b.ToTable("RainbetBets");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.SettingDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<double>("CacheDuration")
.HasColumnType("REAL");
b.Property<string>("Default")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Regex")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Settings");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.TwitchViewCountDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<double>("ServerTime")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("Time")
.HasColumnType("TEXT");
b.Property<string>("Topic")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Viewers")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("TwitchViewCounts");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.UserDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("Ignored")
.HasColumnType("INTEGER");
b.Property<int>("KfId")
.HasColumnType("INTEGER");
b.Property<string>("KfUsername")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserRight")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("KfChatDotNetBot.Models.DbModels.JuicerDbModel", b =>
{
b.HasOne("KfChatDotNetBot.Models.DbModels.UserDbModel", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
/// <inheritdoc />
public partial class SettingsCache : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<double>(
name: "CacheDuration",
table: "Settings",
type: "REAL",
nullable: false,
defaultValue: 0.0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CacheDuration",
table: "Settings");
}
}
}

View File

@@ -169,6 +169,9 @@ namespace KfChatDotNetBot.Migrations
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<double>("CacheDuration")
.HasColumnType("REAL");
b.Property<string>("Default") b.Property<string>("Default")
.HasColumnType("TEXT"); .HasColumnType("TEXT");

View File

@@ -9,5 +9,5 @@ public class BuiltInSettingsModel
public required string Description { get; set; } public required string Description { get; set; }
public string? Default { get; set; } public string? Default { get; set; }
public required bool IsSecret { get; set; } public required bool IsSecret { get; set; }
public required TimeSpan CacheDuration { get; set; } = TimeSpan.Zero;
} }

View File

@@ -16,4 +16,6 @@ public class SettingDbModel
public string? Default { get; set; } = null; public string? Default { get; set; } = null;
// Prevents the value from being revealed to Sneedchat when queried by an admin // Prevents the value from being revealed to Sneedchat when queried by an admin
public bool IsSecret { get; set; } = false; public bool IsSecret { get; set; } = false;
// Number of seconds to cache in memory, 0 to not cache
public double CacheDuration { get; set; } = 0;
} }

View File

@@ -26,7 +26,8 @@ public static class BuiltIn
Regex = builtIn.Regex, Regex = builtIn.Regex,
Description = builtIn.Description, Description = builtIn.Description,
Default = builtIn.Default, Default = builtIn.Default,
IsSecret = builtIn.IsSecret IsSecret = builtIn.IsSecret,
CacheDuration = builtIn.CacheDuration.TotalSeconds
}); });
continue; continue;
} }
@@ -36,6 +37,7 @@ public static class BuiltIn
setting.Description = builtIn.Description; setting.Description = builtIn.Description;
setting.Default = builtIn.Default; setting.Default = builtIn.Default;
setting.IsSecret = builtIn.IsSecret; setting.IsSecret = builtIn.IsSecret;
setting.CacheDuration = builtIn.CacheDuration.TotalSeconds;
} }
logger.Info("Saving changes to the DB"); logger.Info("Saving changes to the DB");
await db.SaveChangesAsync(); await db.SaveChangesAsync();
@@ -101,7 +103,8 @@ public static class BuiltIn
Description = Description =
"Pusher WebSocket endpoint URL", "Pusher WebSocket endpoint URL",
Default = "wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679?protocol=7&client=js&version=7.6.0&flash=false", Default = "wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679?protocol=7&client=js&version=7.6.0&flash=false",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -110,7 +113,8 @@ public static class BuiltIn
Description = Description =
"Kiwi Farms chat WebSocket endpoint", "Kiwi Farms chat WebSocket endpoint",
Default = "wss://kiwifarms.st:9443/chat.ws", Default = "wss://kiwifarms.st:9443/chat.ws",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -119,7 +123,8 @@ public static class BuiltIn
Description = Description =
"List of Pusher channels to subscribe to", "List of Pusher channels to subscribe to",
Default = null, Default = null,
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -128,7 +133,8 @@ public static class BuiltIn
Description = Description =
"Kiwi Farms Keno Kasino room ID", "Kiwi Farms Keno Kasino room ID",
Default = "15", Default = "15",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -137,7 +143,8 @@ public static class BuiltIn
Description = Description =
"Proxy to use for all outgoing requests. Null to disable", "Proxy to use for all outgoing requests. Null to disable",
Default = null, Default = null,
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -146,7 +153,8 @@ public static class BuiltIn
Description = Description =
"Kiwi Farms chat reconnect timeout", "Kiwi Farms chat reconnect timeout",
Default = "30", Default = "30",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -155,7 +163,8 @@ public static class BuiltIn
Description = Description =
"Pusher reconnect timeout", "Pusher reconnect timeout",
Default = "30", Default = "30",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -164,7 +173,8 @@ public static class BuiltIn
Description = Description =
"Whether to enable detection for the presence of GambaSesh", "Whether to enable detection for the presence of GambaSesh",
Default = "true", Default = "true",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromMinutes(5)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -173,7 +183,8 @@ public static class BuiltIn
Description = Description =
"GambaSesh's uer ID for the purposes of detection", "GambaSesh's uer ID for the purposes of detection",
Default = "168162", Default = "168162",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -182,7 +193,8 @@ public static class BuiltIn
Description = Description =
"Kick Icon to use for relaying chat messages", "Kick Icon to use for relaying chat messages",
Default = "https://i.postimg.cc/Qtw4nCPG/kick16.png", Default = "https://i.postimg.cc/Qtw4nCPG/kick16.png",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -191,7 +203,8 @@ public static class BuiltIn
Description = Description =
"Domain to use when retrieving a session token", "Domain to use when retrieving a session token",
Default = "kiwifarms.st", Default = "kiwifarms.st",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -200,7 +213,8 @@ public static class BuiltIn
Description = Description =
"Username to use when authenticating with Kiwi Farms", "Username to use when authenticating with Kiwi Farms",
Default = null, Default = null,
IsSecret = true IsSecret = true,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -209,7 +223,8 @@ public static class BuiltIn
Description = Description =
"Password to use when authenticating with Kiwi Farms", "Password to use when authenticating with Kiwi Farms",
Default = null, Default = null,
IsSecret = true IsSecret = true,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -218,7 +233,8 @@ public static class BuiltIn
Description = Description =
"Path to download the Chromium install used for the token grabber", "Path to download the Chromium install used for the token grabber",
Default = "chromium_install", Default = "chromium_install",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -227,7 +243,8 @@ public static class BuiltIn
Description = Description =
"BossmanJack's Twitch channel ID", "BossmanJack's Twitch channel ID",
Default = "114122847", Default = "114122847",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -236,7 +253,8 @@ public static class BuiltIn
Description = Description =
"BossmanJack's Twitch channel username", "BossmanJack's Twitch channel username",
Default = "thebossmanjack", Default = "thebossmanjack",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -245,7 +263,8 @@ public static class BuiltIn
Description = Description =
"Enable to prevent messages from actually being sent to chat.", "Enable to prevent messages from actually being sent to chat.",
Default = "false", Default = "false",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -254,7 +273,8 @@ public static class BuiltIn
Description = Description =
"Token to use when authenticating with Discord. Set to null to disable.", "Token to use when authenticating with Discord. Set to null to disable.",
Default = null, Default = null,
IsSecret = true IsSecret = true,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -263,7 +283,8 @@ public static class BuiltIn
Description = Description =
"BossmanJack's Discord user ID", "BossmanJack's Discord user ID",
Default = "554123642246529046", Default = "554123642246529046",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -271,7 +292,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "URL for the 16px Twitch icon", Description = "URL for the 16px Twitch icon",
Default = "https://i.postimg.cc/QMFVV2Xk/twitch16.png", Default = "https://i.postimg.cc/QMFVV2Xk/twitch16.png",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -279,7 +301,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "URL for the 16px Discord icon", Description = "URL for the 16px Discord icon",
Default = "https://i.postimg.cc/cLmQrp89/discord16.png", Default = "https://i.postimg.cc/cLmQrp89/discord16.png",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -287,7 +310,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Bossman's Shuffle Username", Description = "Bossman's Shuffle Username",
Default = "TheBossmanJack", Default = "TheBossmanJack",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -295,7 +319,8 @@ public static class BuiltIn
Regex = @"\d+", Regex = @"\d+",
Description = "Cooldown (in seconds) until you can get juiced again", Description = "Cooldown (in seconds) until you can get juiced again",
Default = "3600", Default = "3600",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromMinutes(5)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -303,7 +328,8 @@ public static class BuiltIn
Regex = @"\d+", Regex = @"\d+",
Description = "Amount of $KKK to juice", Description = "Amount of $KKK to juice",
Default = "50", Default = "50",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromMinutes(5)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -311,7 +337,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Last successfully retrieved forum token (will be refreshed automatically if expired)", Description = "Last successfully retrieved forum token (will be refreshed automatically if expired)",
Default = null, Default = null,
IsSecret = true IsSecret = true,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -319,7 +346,8 @@ public static class BuiltIn
Regex = "true|false", Regex = "true|false",
Description = "Whether to enable Kick functionality (Pusher websocket mainly)", Description = "Whether to enable Kick functionality (Pusher websocket mainly)",
Default = "true", Default = "true",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -327,7 +355,8 @@ public static class BuiltIn
Regex = @"\d+", Regex = @"\d+",
Description = "How much to divide the Howlgg bets/profit by to get the real value", Description = "How much to divide the Howlgg bets/profit by to get the real value",
Default = "1650", Default = "1650",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel() new BuiltInSettingsModel()
{ {
@@ -335,7 +364,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Green color used for showing positive values in chat", Description = "Green color used for showing positive values in chat",
Default = "#3dd179", Default = "#3dd179",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel() new BuiltInSettingsModel()
{ {
@@ -343,7 +373,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Red color used for showing negative values in chat", Description = "Red color used for showing negative values in chat",
Default = "#f1323e", Default = "#f1323e",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel() new BuiltInSettingsModel()
{ {
@@ -351,7 +382,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Bossman's username on Jackpot", Description = "Bossman's username on Jackpot",
Default = "TheBossmanJack", Default = "TheBossmanJack",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -359,7 +391,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Bossman's rainbet public ID", Description = "Bossman's rainbet public ID",
Default = "Ir04170wLulcjtePCL7P6lmeOlepRaNp", Default = "Ir04170wLulcjtePCL7P6lmeOlepRaNp",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -367,7 +400,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "URL for your FlareSolverr service API", Description = "URL for your FlareSolverr service API",
Default = "http://localhost:8191/", Default = "http://localhost:8191/",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -375,7 +409,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Proxy in use specifically for FlareSolverr", Description = "Proxy in use specifically for FlareSolverr",
Default = null, Default = null,
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
}, },
new BuiltInSettingsModel new BuiltInSettingsModel
{ {
@@ -383,7 +418,8 @@ public static class BuiltIn
Regex = ".+", Regex = ".+",
Description = "Bossman's Chips.gg username", Description = "Bossman's Chips.gg username",
Default = "TheBossmanJack", Default = "TheBossmanJack",
IsSecret = false IsSecret = false,
CacheDuration = TimeSpan.FromHours(1)
} }
]; ];

View File

@@ -1,14 +1,23 @@
using KfChatDotNetBot.Models.DbModels; using KfChatDotNetBot.Models.DbModels;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Runtime.Caching;
using NLog; using NLog;
namespace KfChatDotNetBot.Settings; namespace KfChatDotNetBot.Settings;
public static class Helpers public static class Helpers
{ {
public static async Task<SettingValue> GetValue(string key, bool caseInsensitive = false) public static async Task<SettingValue> GetValue(string key, bool caseInsensitive = false, bool bypassCache = false)
{ {
var logger = LogManager.GetCurrentClassLogger(); var logger = LogManager.GetCurrentClassLogger();
var cache = MemoryCache.Default;
if (!bypassCache && cache.Contains(key))
{
var cachedSetting = cache.Get(key) as SettingDbModel;
var value = cachedSetting.Value;
if (cachedSetting.Value == "null") value = null;
return new SettingValue(value, cachedSetting, true);
}
await using var db = new ApplicationDbContext(); await using var db = new ApplicationDbContext();
logger.Trace($"Retrieving value for {key}"); logger.Trace($"Retrieving value for {key}");
@@ -30,51 +39,27 @@ public static class Helpers
throw new KeyNotFoundException($"{key} does not exist"); throw new KeyNotFoundException($"{key} does not exist");
} }
cache.Set(key, setting, new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.UtcNow.AddSeconds(setting.CacheDuration)});
if (setting.Value == "null") if (setting.Value == "null")
{ {
logger.Debug($"{key}'s value is null so returning SettingValue(null)"); logger.Debug($"{key}'s value is null so returning SettingValue(null)");
return new SettingValue(null, null); return new SettingValue(null, setting, false);
} }
logger.Debug($"Returning '{setting.Value}' as {typeof(SettingValue)}"); logger.Debug($"Cache Miss! Returning '{setting.Value}' as {typeof(SettingValue)}");
return new SettingValue(setting.Value, setting); return new SettingValue(setting.Value, setting, false);
} }
public static async Task<Dictionary<string, SettingValue>> GetMultipleValues(string[] keys, bool caseInsensitive = false) public static async Task<Dictionary<string, SettingValue>> GetMultipleValues(string[] keys, bool caseInsensitive = false, bool bypassCache = false)
{ {
var logger = LogManager.GetCurrentClassLogger(); var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Trace($"Getting values for keys {string.Join(", ", keys)}"); logger.Trace($"Getting values for keys {string.Join(", ", keys)}");
Dictionary<string, SettingValue> values = new Dictionary<string, SettingValue>(); Dictionary<string, SettingValue> values = new Dictionary<string, SettingValue>();
foreach (var key in keys) foreach (var key in keys)
{ {
SettingDbModel? setting; values.Add(key, await GetValue(key, caseInsensitive, bypassCache));
if (caseInsensitive)
{
// String comparison doesn't work on EF core if I recall correctly
#pragma warning disable CA1862
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key.ToLower() == key.ToLower());
#pragma warning restore CA1862
}
else
{
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
}
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
if (setting.Value == "null")
{
logger.Debug($"{key}'s value is null so returning SettingValue(null)");
values.Add(key, new SettingValue(null, null));
continue;
}
values.Add(key, new SettingValue(setting.Value, setting));
} }
return values; return values;
@@ -108,6 +93,8 @@ public static class Helpers
setting.Value = stringValue; setting.Value = stringValue;
await db.SaveChangesAsync(); await db.SaveChangesAsync();
var cache = MemoryCache.Default;
if (cache.Contains(key)) cache.Remove(key);
} }
public static async Task SetValueAsList<T>(string key, List<T> values, char separator = ',') public static async Task SetValueAsList<T>(string key, List<T> values, char separator = ',')
@@ -127,6 +114,8 @@ public static class Helpers
setting.Value = joinedValue; setting.Value = joinedValue;
await db.SaveChangesAsync(); await db.SaveChangesAsync();
var cache = MemoryCache.Default;
if (cache.Contains(key)) cache.Remove(key);
} }
public static async Task SetValueAsKeyValuePairs<T>(string key, Dictionary<string, T> data, char delimiter = ',', public static async Task SetValueAsKeyValuePairs<T>(string key, Dictionary<string, T> data, char delimiter = ',',
@@ -151,6 +140,8 @@ public static class Helpers
setting.Value = value; setting.Value = value;
await db.SaveChangesAsync(); await db.SaveChangesAsync();
var cache = MemoryCache.Default;
if (cache.Contains(key)) cache.Remove(key);
} }
public static async Task SetValueAsBoolean(string key, bool value) public static async Task SetValueAsBoolean(string key, bool value)
@@ -169,5 +160,7 @@ public static class Helpers
setting.Value = value ? "true" : "false"; setting.Value = value ? "true" : "false";
await db.SaveChangesAsync(); await db.SaveChangesAsync();
var cache = MemoryCache.Default;
if (cache.Contains(key)) cache.Remove(key);
} }
} }

View File

@@ -2,8 +2,9 @@ using KfChatDotNetBot.Models.DbModels;
namespace KfChatDotNetBot.Settings; namespace KfChatDotNetBot.Settings;
public class SettingValue(string? value, SettingDbModel? dbEntry) public class SettingValue(string? value, SettingDbModel dbEntry, bool cached)
{ {
public string? Value { get; set; } = value; public string? Value { get; set; } = value;
public SettingDbModel? DbEntry { get; set; } = dbEntry; public SettingDbModel DbEntry { get; set; } = dbEntry;
public bool Cached { get; set; } = cached;
} }