2024-08-22 11:54:50 +00:00
|
|
|
using BotSharp.Abstraction.Infrastructures;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Rougamo;
|
|
|
|
|
using Rougamo.Context;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Infrastructures;
|
|
|
|
|
|
|
|
|
|
public class SharpCacheAttribute : MoAttribute
|
|
|
|
|
{
|
|
|
|
|
public static IServiceProvider Services { get; set; } = null!;
|
|
|
|
|
|
|
|
|
|
private int _minutes;
|
2024-08-23 01:13:43 +00:00
|
|
|
|
2024-08-25 13:44:02 +00:00
|
|
|
public SharpCacheAttribute(int minutes = 60)
|
2024-08-22 11:54:50 +00:00
|
|
|
{
|
|
|
|
|
_minutes = minutes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override void OnEntry(MethodContext context)
|
|
|
|
|
{
|
2024-08-25 13:44:02 +00:00
|
|
|
var settings = Services.GetRequiredService<SharpCacheSettings>();
|
|
|
|
|
if (!settings.Enabled)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-22 11:54:50 +00:00
|
|
|
var cache = Services.GetRequiredService<ICacheService>();
|
|
|
|
|
|
2024-08-25 13:44:02 +00:00
|
|
|
var key = GetCacheKey(settings, context);
|
2024-08-22 11:54:50 +00:00
|
|
|
var value = cache.GetAsync(key, context.TaskReturnType).Result;
|
|
|
|
|
if (value != null)
|
|
|
|
|
{
|
|
|
|
|
context.ReplaceReturnValue(this, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override void OnSuccess(MethodContext context)
|
|
|
|
|
{
|
2024-08-25 13:44:02 +00:00
|
|
|
var settings = Services.GetRequiredService<SharpCacheSettings>();
|
|
|
|
|
if (!settings.Enabled)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-22 11:54:50 +00:00
|
|
|
var cache = Services.GetRequiredService<ICacheService>();
|
|
|
|
|
|
|
|
|
|
if (context.ReturnValue != null)
|
|
|
|
|
{
|
2024-08-25 13:44:02 +00:00
|
|
|
var key = GetCacheKey(settings, context);
|
2024-08-22 11:54:50 +00:00
|
|
|
cache.SetAsync(key, context.ReturnValue, new TimeSpan(0, _minutes, 0)).Wait();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-25 13:44:02 +00:00
|
|
|
private string GetCacheKey(SharpCacheSettings settings, MethodContext context)
|
2024-08-22 11:54:50 +00:00
|
|
|
{
|
2024-08-25 13:44:02 +00:00
|
|
|
var key = settings.Prefix + "-" + context.Method.Name;
|
2024-08-22 11:54:50 +00:00
|
|
|
foreach (var arg in context.Arguments)
|
|
|
|
|
{
|
|
|
|
|
if (arg is null)
|
|
|
|
|
{
|
|
|
|
|
key += "-" + "<NULL>";
|
|
|
|
|
}
|
|
|
|
|
else if (arg is ICacheKey withCacheKey)
|
|
|
|
|
{
|
|
|
|
|
key += "-" + withCacheKey.GetCacheKey();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
key += "-" + arg.ToString();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return key;
|
|
|
|
|
}
|
|
|
|
|
}
|