2019-10-27 12:09:07 +00:00
using System ;
using System.Collections.Concurrent ;
using System.Linq ;
using System.Net.Http ;
using System.Threading.Tasks ;
2020-04-17 21:10:01 +00:00
2020-06-14 20:19:12 +00:00
using App.Metrics ;
2021-11-22 00:42:35 +00:00
using Myriad.Cache ;
2020-12-22 12:15:26 +00:00
using Myriad.Rest ;
using Myriad.Rest.Types.Requests ;
using Myriad.Types ;
2019-10-27 12:09:07 +00:00
using Serilog ;
namespace PluralKit.Bot
{
public class WebhookCacheService
{
public static readonly string WebhookName = "PluralKit Proxy Webhook" ;
2020-12-22 12:15:26 +00:00
private readonly DiscordApiClient _rest ;
private readonly ConcurrentDictionary < ulong , Lazy < Task < Webhook > > > _webhooks ;
2019-10-27 12:09:07 +00:00
2020-08-29 11:46:27 +00:00
private readonly IMetrics _metrics ;
private readonly ILogger _logger ;
2021-11-22 00:42:35 +00:00
private readonly IDiscordCache _cache ;
2019-10-27 12:09:07 +00:00
2021-11-22 00:42:35 +00:00
public WebhookCacheService ( ILogger logger , IMetrics metrics , DiscordApiClient rest , IDiscordCache cache )
2019-10-27 12:09:07 +00:00
{
2020-06-14 20:19:12 +00:00
_metrics = metrics ;
2020-12-22 12:15:26 +00:00
_rest = rest ;
2021-11-22 00:42:35 +00:00
_cache = cache ;
2019-10-27 12:09:07 +00:00
_logger = logger . ForContext < WebhookCacheService > ( ) ;
2020-12-22 12:15:26 +00:00
_webhooks = new ConcurrentDictionary < ulong , Lazy < Task < Webhook > > > ( ) ;
2019-10-27 12:09:07 +00:00
}
2021-08-27 15:03:47 +00:00
2020-12-22 12:15:26 +00:00
public async Task < Webhook > GetWebhook ( ulong channelId )
2019-10-27 12:09:07 +00:00
{
// We cache the webhook through a Lazy<Task<T>>, this way we make sure to only create one webhook per channel
// If the webhook is requested twice before it's actually been found, the Lazy<T> wrapper will stop the
// webhook from being created twice.
2020-12-22 12:15:26 +00:00
Lazy < Task < Webhook > > GetWebhookTaskInner ( )
2020-06-11 14:13:18 +00:00
{
2020-12-22 12:15:26 +00:00
Task < Webhook > Factory ( ) = > GetOrCreateWebhook ( channelId ) ;
return _webhooks . GetOrAdd ( channelId , new Lazy < Task < Webhook > > ( Factory ) ) ;
2020-06-11 14:13:18 +00:00
}
var lazyWebhookValue = GetWebhookTaskInner ( ) ;
2021-08-27 15:03:47 +00:00
2020-06-11 14:13:18 +00:00
// If we've cached a failed Task, we need to clear it and try again
// This is so errors don't become "sticky" and *they* in turn get cached (not good)
// although, keep in mind this block gets hit the call *after* the task failed (since we only await it below)
if ( lazyWebhookValue . IsValueCreated & & lazyWebhookValue . Value . IsFaulted )
{
2020-12-22 12:15:26 +00:00
_logger . Warning ( lazyWebhookValue . Value . Exception , "Cached webhook task for {Channel} faulted with below exception" , channelId ) ;
2021-08-27 15:03:47 +00:00
2020-06-11 14:13:18 +00:00
// Specifically don't recurse here so we don't infinite-loop - if this one errors too, it'll "stick"
// until next time this function gets hit (which is okay, probably).
2020-12-22 12:15:26 +00:00
_webhooks . TryRemove ( channelId , out _ ) ;
2020-06-11 14:13:18 +00:00
lazyWebhookValue = GetWebhookTaskInner ( ) ;
}
2019-10-27 12:09:07 +00:00
// It's possible to "move" a webhook to a different channel after creation
// Here, we ensure it's actually still pointing towards the proper channel, and if not, wipe and refetch one.
var webhook = await lazyWebhookValue . Value ;
2020-12-22 12:15:26 +00:00
if ( webhook . ChannelId ! = channelId & & webhook . ChannelId ! = 0 )
return await InvalidateAndRefreshWebhook ( channelId , webhook ) ;
2019-10-27 12:09:07 +00:00
return webhook ;
}
2020-12-22 12:15:26 +00:00
public async Task < Webhook > InvalidateAndRefreshWebhook ( ulong channelId , Webhook webhook )
2019-10-27 12:09:07 +00:00
{
2020-12-22 12:15:26 +00:00
// note: webhook.ChannelId may not be the same as channelId >.>
2021-06-10 12:21:05 +00:00
_logger . Debug ( "Refreshing webhook for channel {Channel}" , webhook . ChannelId ) ;
2021-08-27 15:03:47 +00:00
2019-10-27 12:09:07 +00:00
_webhooks . TryRemove ( webhook . ChannelId , out _ ) ;
2020-12-22 12:15:26 +00:00
return await GetWebhook ( channelId ) ;
2019-10-27 12:09:07 +00:00
}
2020-12-22 12:15:26 +00:00
private async Task < Webhook ? > GetOrCreateWebhook ( ulong channelId )
2019-10-27 12:09:07 +00:00
{
2020-12-22 12:15:26 +00:00
_logger . Debug ( "Webhook for channel {Channel} not found in cache, trying to fetch" , channelId ) ;
2020-06-14 20:19:12 +00:00
_metrics . Measure . Meter . Mark ( BotMetrics . WebhookCacheMisses ) ;
2021-08-27 15:03:47 +00:00
2020-12-22 12:15:26 +00:00
_logger . Debug ( "Finding webhook for channel {Channel}" , channelId ) ;
var webhooks = await FetchChannelWebhooks ( channelId ) ;
2020-07-05 11:38:18 +00:00
// If the channel has a webhook created by PK, just return that one
2021-11-22 00:42:35 +00:00
var ourUserId = await _cache . GetOwnUser ( ) ;
var ourWebhook = webhooks . FirstOrDefault ( hook = > IsWebhookMine ( ourUserId , hook ) ) ;
2020-07-05 11:38:18 +00:00
if ( ourWebhook ! = null )
return ourWebhook ;
2021-08-27 15:03:47 +00:00
2020-07-05 11:38:18 +00:00
// We don't have one, so we gotta create a new one
// but first, make sure we haven't hit the webhook cap yet...
2020-12-22 12:15:26 +00:00
if ( webhooks . Length > = 10 )
2020-07-05 11:38:18 +00:00
throw new PKError ( "This channel has the maximum amount of possible webhooks (10) already created. A server admin must delete one or more webhooks so PluralKit can create one for proxying." ) ;
2021-08-27 15:03:47 +00:00
2020-12-22 12:15:26 +00:00
return await DoCreateWebhook ( channelId ) ;
2020-07-05 11:38:18 +00:00
}
2020-12-22 12:15:26 +00:00
private async Task < Webhook [ ] > FetchChannelWebhooks ( ulong channelId )
2020-07-05 11:38:18 +00:00
{
try
{
2020-12-22 12:15:26 +00:00
return await _rest . GetChannelWebhooks ( channelId ) ;
2020-07-05 11:38:18 +00:00
}
catch ( HttpRequestException e )
{
_logger . Warning ( e , "Error occurred while fetching webhook list" ) ;
// This happens sometimes when Discord returns a malformed request for the webhook list
// Nothing we can do than just assume that none exist.
2020-12-22 12:15:26 +00:00
return new Webhook [ 0 ] ;
2019-10-27 12:09:07 +00:00
}
}
2021-08-27 15:03:47 +00:00
2020-12-22 12:15:26 +00:00
private async Task < Webhook > DoCreateWebhook ( ulong channelId )
2019-10-27 12:09:07 +00:00
{
2020-12-22 12:15:26 +00:00
_logger . Information ( "Creating new webhook for channel {Channel}" , channelId ) ;
return await _rest . CreateWebhook ( channelId , new CreateWebhookRequest ( WebhookName ) ) ;
2019-10-27 12:09:07 +00:00
}
2021-11-22 00:42:35 +00:00
private bool IsWebhookMine ( ulong userId , Webhook arg ) = > arg . User ? . Id = = userId & & arg . Name = = WebhookName ;
2019-10-27 12:09:07 +00:00
public int CacheSize = > _webhooks . Count ;
}
2019-05-16 23:23:09 +00:00
}