|
| 1 | +using System.Text.Json; |
| 2 | + |
| 3 | +using Azure.Messaging.ServiceBus; |
| 4 | + |
| 5 | +using Microsoft.Extensions.Caching.Hybrid; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | + |
| 8 | +namespace Arbiter.Messaging.ServiceBus.Cache; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Processes <see cref="CacheExpireMessage"/> messages from a Service Bus topic subscription and expires the |
| 12 | +/// matching entries from the local <see cref="HybridCache"/>. |
| 13 | +/// </summary> |
| 14 | +public sealed partial class CacheExpireProcessor : ServiceBusProcessorBase |
| 15 | +{ |
| 16 | + private readonly HybridCache _hybridCache; |
| 17 | + private readonly CacheExpireOptions _options; |
| 18 | + private readonly ILogger<CacheExpireProcessor> _logger; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Initializes a new instance of the <see cref="CacheExpireProcessor"/> class. |
| 22 | + /// </summary> |
| 23 | + /// <param name="processor">The Service Bus processor used to receive messages.</param> |
| 24 | + /// <param name="logger">The logger used to write processing messages.</param> |
| 25 | + /// <param name="hybridCache">The hybrid cache to expire.</param> |
| 26 | + /// <param name="options">The cache expiration options.</param> |
| 27 | + /// <exception cref="ArgumentNullException">When <paramref name="hybridCache"/> or <paramref name="options"/> is null.</exception> |
| 28 | + public CacheExpireProcessor( |
| 29 | + ServiceBusProcessor processor, |
| 30 | + ILogger<CacheExpireProcessor> logger, |
| 31 | + HybridCache hybridCache, |
| 32 | + CacheExpireOptions options) |
| 33 | + : base(processor, logger) |
| 34 | + { |
| 35 | + ArgumentNullException.ThrowIfNull(hybridCache); |
| 36 | + ArgumentNullException.ThrowIfNull(options); |
| 37 | + |
| 38 | + _hybridCache = hybridCache; |
| 39 | + _options = options; |
| 40 | + _logger = logger; |
| 41 | + } |
| 42 | + |
| 43 | + /// <inheritdoc /> |
| 44 | + /// <remarks> |
| 45 | + /// Message settlement is handled automatically by the processor (<see cref="ServiceBusProcessorOptions.AutoCompleteMessages" />); |
| 46 | + /// returning successfully completes the message, while throwing abandons it for redelivery. A message with an |
| 47 | + /// unparsable body is non-retryable and is dead-lettered explicitly rather than retried until the delivery count is exhausted. |
| 48 | + /// </remarks> |
| 49 | + protected override async Task ProcessMessageAsync(ProcessMessageEventArgs args) |
| 50 | + { |
| 51 | + ArgumentNullException.ThrowIfNull(args); |
| 52 | + |
| 53 | + CacheExpireMessage? message; |
| 54 | + |
| 55 | + try |
| 56 | + { |
| 57 | + message = args.ReadFromJson<CacheExpireMessage>(); |
| 58 | + } |
| 59 | + catch (JsonException ex) |
| 60 | + { |
| 61 | + // non-retryable: a malformed body never succeeds, so dead-letter immediately instead of |
| 62 | + // abandoning until MaxDeliveryCount is reached |
| 63 | + LogDeadLetteringMessage(_logger, ex, args.Message.MessageId); |
| 64 | + |
| 65 | + await args.DeadLetterMessageAsync( |
| 66 | + args.Message, |
| 67 | + deadLetterReason: "DeserializationFailed", |
| 68 | + deadLetterErrorDescription: ex.Message, |
| 69 | + args.CancellationToken).ConfigureAwait(false); |
| 70 | + |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + if (message is null) |
| 75 | + return; |
| 76 | + |
| 77 | + // skip messages this application published; it already expired its own local cache |
| 78 | + if (!string.IsNullOrEmpty(message.SourceId) |
| 79 | + && string.Equals(message.SourceId, _options.SourceId, StringComparison.Ordinal)) |
| 80 | + { |
| 81 | + LogSkippingOwnMessage(_logger, message.SourceId); |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + if (!string.IsNullOrEmpty(message.Key)) |
| 86 | + await _hybridCache.RemoveAsync(message.Key, args.CancellationToken).ConfigureAwait(false); |
| 87 | + |
| 88 | + foreach (var tag in message.Tags) |
| 89 | + { |
| 90 | + if (!string.IsNullOrEmpty(tag)) |
| 91 | + await _hybridCache.RemoveByTagAsync(tag, args.CancellationToken).ConfigureAwait(false); |
| 92 | + } |
| 93 | + |
| 94 | + LogExpiredCache(_logger, message.Key, message.Tags.Count); |
| 95 | + } |
| 96 | + |
| 97 | + [LoggerMessage(Level = LogLevel.Debug, Message = "Skipping cache expiration message from own source '{SourceId}'")] |
| 98 | + private static partial void LogSkippingOwnMessage(ILogger logger, string sourceId); |
| 99 | + |
| 100 | + [LoggerMessage(Level = LogLevel.Warning, Message = "Dead-lettering cache expiration message '{MessageId}' with unparsable body")] |
| 101 | + private static partial void LogDeadLetteringMessage(ILogger logger, Exception exception, string messageId); |
| 102 | + |
| 103 | + [LoggerMessage(Level = LogLevel.Debug, Message = "Expired local cache for key '{Key}' and {TagCount} tag(s)")] |
| 104 | + private static partial void LogExpiredCache(ILogger logger, string? key, int tagCount); |
| 105 | +} |
0 commit comments