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

72 lines
2.3 KiB
C#
Raw Normal View History

2021-01-17 23:05:00 -05:00
using System;
2022-12-28 15:17:48 -05:00
using System.Text.Json;
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);
2022-12-28 15:17:48 -05:00
void AddUser(TwitterUser user);
2021-02-02 22:49:37 -05:00
}
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()
2023-03-03 10:37:42 -05:00
.SetSize(1000)//Size amount
2021-01-17 23:05:00 -05:00
//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.
2022-12-29 13:02:38 -05:00
.SetSlidingExpiration(TimeSpan.FromMinutes(10))
2021-01-17 23:05:00 -05:00
// Remove from cache after this time, regardless of sliding expiration
2022-12-29 13:02:38 -05:00
.SetAbsoluteExpiration(TimeSpan.FromDays(1));
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-29 09:58:08 -05:00
SizeLimit = 3000 //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();
}
2022-12-28 15:17:48 -05:00
public TwitterUser Extract(JsonElement result)
{
return _twitterService.Extract(result);
}
public void PurgeUser(string username)
{
_userCache.Remove(username);
}
2022-12-28 15:17:48 -05:00
public void AddUser(TwitterUser user)
{
_userCache.Set(user.Acct, user, _cacheEntryOptions);
}
2021-01-17 23:05:00 -05:00
}
}