Speeds up looking for users by ethAddress. Reduces load on discord server.

This commit is contained in:
Ben 2025-04-17 15:26:57 +02:00
parent 9a58da26aa
commit cd17b0c887
No known key found for this signature in database
GPG Key ID: 0F16E812E736C24B
2 changed files with 18 additions and 14 deletions

View File

@ -10,6 +10,8 @@ namespace BiblioTech.Rewards
{
private Dictionary<ulong, IGuildUser> users = new();
private Dictionary<ulong, SocketRole> roles = new();
private DateTime lastLoad = DateTime.MinValue;
private readonly SocketGuild guild;
private readonly UserRepo userRepo;
private readonly ILog log;
@ -25,9 +27,15 @@ namespace BiblioTech.Rewards
public async Task Initialize()
{
var span = DateTime.UtcNow - lastLoad;
if (span > TimeSpan.FromMinutes(10))
{
lastLoad = DateTime.UtcNow;
log.Log("Loading all users and roles...");
this.users = await LoadAllUsers(guild);
this.roles = LoadAllRoles(guild);
}
}
public IGuildUser[] Users => users.Values.ToArray();
@ -76,7 +84,6 @@ namespace BiblioTech.Rewards
private async Task<Dictionary<ulong, IGuildUser>> LoadAllUsers(SocketGuild guild)
{
log.Log("Loading all users..");
var result = new Dictionary<ulong, IGuildUser>();
var users = guild.GetUsersAsync();
await foreach (var ulist in users)

View File

@ -122,21 +122,18 @@ namespace BiblioTech
{
if (address == null) return null;
// If this becomes a performance problem, switch to in-memory cached list.
var files = Directory.GetFiles(Program.Config.UserDataPath);
foreach (var file in files)
var lower = address.Address.ToLowerInvariant();
if (string.IsNullOrEmpty(lower)) return null;
if (cache.Count == 0) LoadAllUserData();
foreach (var item in cache.Values)
{
try
if (item.CurrentAddress != null &&
item.CurrentAddress.Address.ToLowerInvariant() == lower)
{
var user = JsonConvert.DeserializeObject<UserData>(File.ReadAllText(file))!;
if (user.CurrentAddress != null &&
user.CurrentAddress.Address == address.Address)
{
return user;
return item;
}
}
catch { }
}
return null;
}