diff --git a/PluralKit.Bot/BotMetrics.cs b/PluralKit.Bot/BotMetrics.cs index 42d8b64b..94dd0f6e 100644 --- a/PluralKit.Bot/BotMetrics.cs +++ b/PluralKit.Bot/BotMetrics.cs @@ -22,6 +22,27 @@ public static class BotMetrics Context = "Bot" }; + public static MeterOptions LocalDMCacheHits => new() + { + Name = "Cluster local DM Cache Hits", + MeasurementUnit = Unit.Calls, + Context = "Bot" + }; + + public static MeterOptions DatabaseDMCacheHits => new() + { + Name = "Database DM Cache Hits", + MeasurementUnit = Unit.Calls, + Context = "Bot" + }; + + public static MeterOptions DMCacheMisses => new() + { + Name = "DM Cache Misses", + MeasurementUnit = Unit.Calls, + Context = "Bot" + }; + public static MeterOptions CommandsRun => new() { Name = "Commands run", diff --git a/PluralKit.Bot/Services/PrivateChannelService.cs b/PluralKit.Bot/Services/PrivateChannelService.cs index e5b4fa3c..3c2781e7 100644 --- a/PluralKit.Bot/Services/PrivateChannelService.cs +++ b/PluralKit.Bot/Services/PrivateChannelService.cs @@ -1,3 +1,5 @@ +using App.Metrics; + using Serilog; using Myriad.Gateway; @@ -11,11 +13,13 @@ public class PrivateChannelService { private static readonly Dictionary _channelsCache = new(); + private readonly IMetrics _metrics; private readonly ILogger _logger; private readonly ModelRepository _repo; private readonly DiscordApiClient _rest; - public PrivateChannelService(ILogger logger, ModelRepository repo, DiscordApiClient rest) + public PrivateChannelService(IMetrics metrics, ILogger logger, ModelRepository repo, DiscordApiClient rest) { + _metrics = metrics; _logger = logger; _repo = repo; _rest = rest; @@ -32,16 +36,23 @@ public class PrivateChannelService public async Task 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) { + _metrics.Measure.Meter.Mark(BotMetrics.DMCacheMisses); var channel = await _rest.CreateDm(userId); channelId = channel.Id; } + _metrics.Measure.Meter.Mark(BotMetrics.DatabaseDMCacheHits); + // 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); return channelId.Value;