cloutier--bird.makeup/src/BirdsiteLive.Twitter/CachedTwitterService.cs

61 lines
2 KiB
C#
Raw Normal View History

2021-01-17 23:05:00 -05:00
using System;
2022-12-28 10:23:46 -05:00
using System.Threading.Tasks;
2022-02-03 19:01:21 -05:00
using BirdsiteLive.Common.Settings;
2021-01-17 23:05:00 -05:00
using BirdsiteLive.Twitter.Models;
using Microsoft.Extensions.Caching.Memory;
namespace BirdsiteLive.Twitter
{
2021-02-02 22:49:37 -05:00
public interface ICachedTwitterUserService : ITwitterUserService
{
void PurgeUser(string username);
}
public class CachedTwitterUserService : ICachedTwitterUserService
2021-01-17 23:05:00 -05:00
{
private readonly ITwitterUserService _twitterService;
2021-01-17 23:05:00 -05:00
2022-02-03 19:01:21 -05:00
private readonly MemoryCache _userCache;
private readonly MemoryCacheEntryOptions _cacheEntryOptions = new MemoryCacheEntryOptions()
2021-01-17 23:05:00 -05:00
.SetSize(1)//Size amount
//Priority on removing when reaching size limit (memory pressure)
2022-12-28 10:37:04 -05:00
.SetPriority(CacheItemPriority.Low)
2021-01-17 23:05:00 -05:00
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromHours(24))
// Remove from cache after this time, regardless of sliding expiration
2021-02-03 01:04:32 -05:00
.SetAbsoluteExpiration(TimeSpan.FromDays(7));
2021-01-17 23:05:00 -05:00
#region Ctor
2022-02-03 19:01:21 -05:00
public CachedTwitterUserService(ITwitterUserService twitterService, InstanceSettings settings)
2021-01-17 23:05:00 -05:00
{
_twitterService = twitterService;
2022-02-03 19:01:21 -05:00
_userCache = new MemoryCache(new MemoryCacheOptions()
{
2022-12-28 10:37:04 -05:00
SizeLimit = 5000 //TODO make this use number of entries in db
2022-02-03 19:01:21 -05:00
});
2021-01-17 23:05:00 -05:00
}
#endregion
2022-12-28 10:23:46 -05:00
public async Task<TwitterUser> GetUserAsync(string username)
2021-01-17 23:05:00 -05:00
{
if (!_userCache.TryGetValue(username, out TwitterUser user))
{
2022-12-28 10:23:46 -05:00
user = await _twitterService.GetUserAsync(username);
2021-01-27 03:27:04 -05:00
if(user != null) _userCache.Set(username, user, _cacheEntryOptions);
2021-01-17 23:05:00 -05:00
}
return user;
}
2022-02-03 19:45:25 -05:00
public bool IsUserApiRateLimited()
{
return _twitterService.IsUserApiRateLimited();
}
public void PurgeUser(string username)
{
_userCache.Remove(username);
}
2021-01-17 23:05:00 -05:00
}
}