feat(bot): remove cluster-local DM channel cache

This commit is contained in:
spiral
2022-06-14 23:11:55 -04:00
parent f0b5749d5c
commit 65e2bb0234
2 changed files with 9 additions and 28 deletions

View File

@@ -11,8 +11,6 @@ namespace PluralKit.Bot;
public class PrivateChannelService
{
private static readonly Dictionary<ulong, ulong> _channelsCache = new();
private readonly IMetrics _metrics;
private readonly ILogger _logger;
private readonly ModelRepository _repo;
@@ -27,42 +25,32 @@ public class PrivateChannelService
public async Task TrySavePrivateChannel(MessageCreateEvent evt)
{
if (evt.GuildId != null) return;
if (_channelsCache.TryGetValue(evt.Author.Id, out _)) return;
await SaveDmChannel(evt.Author.Id, evt.ChannelId);
if (evt.GuildId == null) await SaveDmChannel(evt.Author.Id, evt.ChannelId);
}
public async Task<ulong> GetOrCreateDmChannel(ulong userId)
{
if (_channelsCache.TryGetValue(userId, out var cachedChannelId))
{
_metrics.Measure.Meter.Mark(BotMetrics.LocalDMCacheHits);
return cachedChannelId;
}
var channelId = await _repo.GetDmChannel(userId);
if (channelId == null)
if (channelId != null)
{
_metrics.Measure.Meter.Mark(BotMetrics.DMCacheMisses);
var channel = await _rest.CreateDm(userId);
channelId = channel.Id;
_metrics.Measure.Meter.Mark(BotMetrics.DatabaseDMCacheHits);
return channelId.Value;
}
_metrics.Measure.Meter.Mark(BotMetrics.DatabaseDMCacheHits);
_metrics.Measure.Meter.Mark(BotMetrics.DMCacheMisses);
var channel = await _rest.CreateDm(userId);
// spawn off saving the channel as to not block the current thread
// todo: don't save to database again if we just fetched it from there
_ = SaveDmChannel(userId, channelId.Value);
_ = SaveDmChannel(userId, channel.Id);
return channelId.Value;
return channel.Id;
}
private async Task SaveDmChannel(ulong userId, ulong channelId)
{
try
{
_channelsCache.Add(userId, channelId);
await _repo.UpdateAccount(userId, new() { DmChannel = channelId });
}
catch (Exception e)