| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using NexMediator.Abstractions.Exceptions; |
| | | 3 | | using NexMediator.Abstractions.Interfaces; |
| | | 4 | | |
| | | 5 | | namespace NexMediator.Pipeline.Behaviors; |
| | | 6 | | /// <summary> |
| | | 7 | | /// A pipeline behavior that adds caching to supported requests. |
| | | 8 | | /// Also supports cache invalidation for requests implementing <see cref="IInvalidateCacheableRequest"/>. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <typeparam name="TRequest">The type of the request.</typeparam> |
| | | 11 | | /// <typeparam name="TResponse">The type of the response.</typeparam> |
| | | 12 | | public class CachingBehavior<TRequest, TResponse> : INexPipelineBehavior<TRequest, TResponse> |
| | | 13 | | where TRequest : INexRequest<TResponse> |
| | | 14 | | { |
| | | 15 | | private readonly ICache _cache; |
| | | 16 | | private readonly ILogger<CachingBehavior<TRequest, TResponse>> _logger; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Creates a new instance of <see cref="CachingBehavior{TRequest, TResponse}"/>. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="cache">The cache service.</param> |
| | | 22 | | /// <param name="logger">The logger instance.</param> |
| | 24 | 23 | | public CachingBehavior(ICache cache, ILogger<CachingBehavior<TRequest, TResponse>> logger) |
| | 24 | 24 | | { |
| | 24 | 25 | | _cache = cache ?? throw new ArgumentNullException(nameof(cache)); |
| | 23 | 26 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 22 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | | 30 | | public async Task<TResponse> Handle( |
| | | 31 | | TRequest request, |
| | | 32 | | RequestHandlerDelegate<TResponse> next, |
| | | 33 | | CancellationToken cancellationToken) |
| | 11 | 34 | | { |
| | | 35 | | //Invalidate cache for requests that require it |
| | 11 | 36 | | if (request is IInvalidateCacheableRequest inv) |
| | 0 | 37 | | { |
| | 0 | 38 | | foreach (var key in inv.KeysToInvalidate) |
| | 0 | 39 | | await _cache.RemoveAsync(key, cancellationToken); |
| | 0 | 40 | | foreach (var prefix in inv.PrefixesToInvalidate) |
| | 0 | 41 | | await _cache.RemoveByPrefixAsync(prefix, cancellationToken); |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | //Proceed with caching logic |
| | 11 | 45 | | if (request is not ICacheableRequest<TResponse> cacheable) |
| | 1 | 46 | | { |
| | 1 | 47 | | return await next(); |
| | | 48 | | } |
| | | 49 | | |
| | 10 | 50 | | var cacheKey = cacheable.CacheKey; |
| | 10 | 51 | | TResponse? cached = default; |
| | | 52 | | |
| | | 53 | | try |
| | 10 | 54 | | { |
| | 10 | 55 | | cached = await _cache.GetAsync<TResponse>(cacheKey, cancellationToken); |
| | 9 | 56 | | } |
| | 1 | 57 | | catch (Exception ex) |
| | 1 | 58 | | { |
| | 1 | 59 | | _logger.LogWarning(ex, "Cache read failed for key {CacheKey}", cacheKey); |
| | 1 | 60 | | } |
| | | 61 | | |
| | 10 | 62 | | if (cached != null) |
| | 2 | 63 | | { |
| | 2 | 64 | | _logger.LogDebug("Cache hit for {RequestType} [Key: {CacheKey}]", typeof(TRequest).Name, cacheKey); |
| | 2 | 65 | | return cached; |
| | | 66 | | } |
| | | 67 | | |
| | 8 | 68 | | _logger.LogDebug("Cache miss for {RequestType} [Key: {CacheKey}]", typeof(TRequest).Name, cacheKey); |
| | | 69 | | |
| | 8 | 70 | | var response = await next(); |
| | | 71 | | |
| | 8 | 72 | | if (response == null) |
| | 0 | 73 | | { |
| | 0 | 74 | | throw new NexMediatorException($"Handler returned null for request type {typeof(TRequest).Name}"); |
| | | 75 | | } |
| | | 76 | | |
| | 8 | 77 | | int? ttl = cacheable.Expiration.HasValue |
| | 8 | 78 | | ? (int)cacheable.Expiration.Value.TotalSeconds |
| | 8 | 79 | | : null; |
| | | 80 | | |
| | | 81 | | try |
| | 8 | 82 | | { |
| | 8 | 83 | | await _cache.SetAsync(cacheKey, response, ttl, cancellationToken); |
| | 7 | 84 | | _logger.LogDebug( |
| | 7 | 85 | | "Response cached for {RequestType} [Key: {CacheKey}, TTL: {TTL}s]", |
| | 7 | 86 | | typeof(TRequest).Name, cacheKey, ttl); |
| | 7 | 87 | | } |
| | 1 | 88 | | catch (Exception ex) |
| | 1 | 89 | | { |
| | 1 | 90 | | _logger.LogWarning(ex, "Cache write failed for key {CacheKey}", cacheKey); |
| | 1 | 91 | | } |
| | | 92 | | |
| | 8 | 93 | | return response; |
| | 11 | 94 | | } |
| | | 95 | | } |