| | | 1 | | using Microsoft.Extensions.Hosting; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using StackExchange.Redis; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Transports.Redis; |
| | | 7 | | |
| | | 8 | | internal abstract class RedisSubscriberService : BackgroundService |
| | | 9 | | { |
| | | 10 | | private static readonly string GeneratedConsumerName = CreateGeneratedConsumerName(); |
| | | 11 | | |
| | | 12 | | private readonly IRedisStreamDatabase _database; |
| | | 13 | | |
| | | 14 | | /// <summary>Runs the RedisSubscriberService operation.</summary> |
| | | 15 | | protected RedisSubscriberService( |
| | | 16 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 17 | | IConnectionMultiplexer multiplexer, |
| | | 18 | | ILogger logger) |
| | | 19 | | : this( |
| | | 20 | | options, |
| | | 21 | | new RedisStreamDatabaseAdapter(multiplexer.GetDatabase(), options.Value.OperationTimeout), |
| | | 22 | | logger) |
| | | 23 | | { |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <summary>Runs the RedisSubscriberService operation.</summary> |
| | | 27 | | protected RedisSubscriberService( |
| | | 28 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 29 | | IRedisStreamDatabase database, |
| | | 30 | | ILogger logger) |
| | | 31 | | { |
| | | 32 | | Options = options.Value; |
| | | 33 | | RedisTransportOptionsValidator.ValidateCommon(Options); |
| | | 34 | | _database = database; |
| | | 35 | | Logger = logger; |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | protected RedisAsyncResponseTransportOptions Options { get; } |
| | | 39 | | protected ILogger Logger { get; } |
| | | 40 | | |
| | | 41 | | protected abstract RedisKey Stream { get; } |
| | | 42 | | protected abstract RedisValue ConsumerGroup { get; } |
| | | 43 | | protected abstract RedisSubscriberOptions SubscriberOptions { get; } |
| | | 44 | | protected abstract RedisSubscriberRole SubscriberRole { get; } |
| | | 45 | | /// <summary>Handles the delivered message.</summary> |
| | | 46 | | protected abstract Task HandleMessageAsync(RedisStreamDelivery delivery, CancellationToken cancellationToken); |
| | | 47 | | |
| | | 48 | | /// <summary>Runs this background operation until cancellation is requested.</summary> |
| | | 49 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 50 | | { |
| | | 51 | | RedisMessageDispatcher.ValidateOptions(Options, SubscriberOptions, SubscriberRole); |
| | | 52 | | |
| | | 53 | | var failures = 0; |
| | | 54 | | while (!stoppingToken.IsCancellationRequested) |
| | | 55 | | { |
| | | 56 | | try |
| | | 57 | | { |
| | | 58 | | await RunSubscriberAsync(stoppingToken).ConfigureAwait(false); |
| | | 59 | | return; |
| | | 60 | | } |
| | | 61 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 62 | | { |
| | | 63 | | return; |
| | | 64 | | } |
| | | 65 | | catch (Exception ex) when (!stoppingToken.IsCancellationRequested) |
| | | 66 | | { |
| | | 67 | | failures++; |
| | | 68 | | var retryDelay = AsyncResponseRetry.Backoff( |
| | | 69 | | failures, |
| | | 70 | | Options.SubscriberRetryBaseDelay, |
| | | 71 | | Options.SubscriberRetryMaxDelay); |
| | | 72 | | Logger.LogWarning( |
| | | 73 | | ex, |
| | | 74 | | "Redis subscriber failed for stream {Stream} ({Role}); retrying in {RetryDelay}.", |
| | | 75 | | Stream.ToString(), |
| | | 76 | | SubscriberRole, |
| | | 77 | | retryDelay); |
| | | 78 | | await Task.Delay(retryDelay, stoppingToken).ConfigureAwait(false); |
| | | 79 | | } |
| | | 80 | | } |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | private async Task RunSubscriberAsync(CancellationToken stoppingToken) |
| | | 84 | | { |
| | | 85 | | if (Options.CreateConsumerGroups) |
| | | 86 | | await EnsureConsumerGroupAsync(stoppingToken).ConfigureAwait(false); |
| | | 87 | | |
| | | 88 | | var consumerName = ResolveConsumerName(Options, SubscriberRole); |
| | | 89 | | await using var dispatcher = RedisMessageDispatcher.Create( |
| | | 90 | | HandleMessageAsync, |
| | | 91 | | _database, |
| | | 92 | | Options, |
| | | 93 | | SubscriberOptions, |
| | | 94 | | Logger, |
| | | 95 | | Stream, |
| | | 96 | | ConsumerGroup, |
| | | 97 | | SubscriberRole); |
| | | 98 | | |
| | | 99 | | Logger.LogInformation( |
| | | 100 | | "Redis subscriber started. Stream: {Stream}. Group: {ConsumerGroup}. Consumer: {ConsumerName}. Role: {Role}. |
| | | 101 | | Stream.ToString(), |
| | | 102 | | ConsumerGroup.ToString(), |
| | | 103 | | consumerName.ToString(), |
| | | 104 | | SubscriberRole, |
| | | 105 | | SubscriberOptions.AckMode); |
| | | 106 | | |
| | | 107 | | var nextPendingClaimAt = DateTimeOffset.UtcNow; |
| | | 108 | | while (!stoppingToken.IsCancellationRequested) |
| | | 109 | | { |
| | | 110 | | var processed = 0; |
| | | 111 | | |
| | | 112 | | // When the dispatcher is saturated (ACK-after-enqueue queue full) stop pulling new entries: |
| | | 113 | | // reading them would only move the backlog into the pending-entry list and spin the loop. |
| | | 114 | | // The unread entries stay as new messages in the stream until capacity frees. |
| | | 115 | | if (dispatcher.CanAcceptMore) |
| | | 116 | | { |
| | | 117 | | var utcNow = DateTimeOffset.UtcNow; |
| | | 118 | | if (utcNow >= nextPendingClaimAt) |
| | | 119 | | { |
| | | 120 | | processed += await ClaimPendingAsync(dispatcher, consumerName, stoppingToken).ConfigureAwait(false); |
| | | 121 | | nextPendingClaimAt = utcNow + SubscriberOptions.PendingClaimInterval; |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | var entries = await _database.StreamReadGroupAsync( |
| | | 125 | | Stream, |
| | | 126 | | ConsumerGroup, |
| | | 127 | | consumerName, |
| | | 128 | | SubscriberOptions.BatchSize, |
| | | 129 | | stoppingToken).ConfigureAwait(false); |
| | | 130 | | |
| | | 131 | | foreach (var entry in entries) |
| | | 132 | | { |
| | | 133 | | if (await DispatchEntryAsync(dispatcher, entry, attempt: 1, stoppingToken).ConfigureAwait(false) |
| | | 134 | | == RedisDispatchOutcome.Processed) |
| | | 135 | | { |
| | | 136 | | processed++; |
| | | 137 | | } |
| | | 138 | | } |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | // Throttle when nothing advanced — an empty stream, or every entry deferred under backpressure. |
| | | 142 | | if (processed == 0) |
| | | 143 | | await Task.Delay(SubscriberOptions.EmptyPollDelay, stoppingToken).ConfigureAwait(false); |
| | | 144 | | } |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | private async Task<RedisDispatchOutcome> DispatchEntryAsync( |
| | | 148 | | RedisMessageDispatcher dispatcher, |
| | | 149 | | StreamEntry entry, |
| | | 150 | | int attempt, |
| | | 151 | | CancellationToken cancellationToken) |
| | | 152 | | { |
| | | 153 | | RedisStreamDelivery delivery; |
| | | 154 | | try |
| | | 155 | | { |
| | | 156 | | delivery = CreateDelivery(entry, attempt); |
| | | 157 | | } |
| | | 158 | | catch (InvalidDataException ex) |
| | | 159 | | { |
| | | 160 | | // A foreign/malformed entry (or a trimmed tombstone) can never be handled; dead-letter and |
| | | 161 | | // ACK it so it drains instead of poisoning the pending-claim loop forever. |
| | | 162 | | await dispatcher.DiscardUnprocessableAsync(Stream, ConsumerGroup, entry, ex, cancellationToken).ConfigureAwa |
| | | 163 | | return RedisDispatchOutcome.Processed; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | return await dispatcher.HandleAsync(delivery, cancellationToken).ConfigureAwait(false); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private async Task EnsureConsumerGroupAsync(CancellationToken cancellationToken) |
| | | 170 | | { |
| | | 171 | | try |
| | | 172 | | { |
| | | 173 | | await _database.StreamCreateConsumerGroupAsync( |
| | | 174 | | Stream, |
| | | 175 | | ConsumerGroup, |
| | | 176 | | StreamPosition.Beginning, |
| | | 177 | | createStream: true, |
| | | 178 | | cancellationToken).ConfigureAwait(false); |
| | | 179 | | } |
| | | 180 | | catch (RedisServerException ex) when (ex.Message.Contains("BUSYGROUP", StringComparison.OrdinalIgnoreCase)) |
| | | 181 | | { |
| | | 182 | | // The group already exists; this is the expected path after the first app instance. |
| | | 183 | | } |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private async Task<int> ClaimPendingAsync( |
| | | 187 | | RedisMessageDispatcher dispatcher, |
| | | 188 | | RedisValue consumerName, |
| | | 189 | | CancellationToken cancellationToken) |
| | | 190 | | { |
| | | 191 | | var minIdleMs = ToPositiveMilliseconds(SubscriberOptions.PendingMessageMinIdleTime); |
| | | 192 | | var pending = await _database.StreamPendingMessagesAsync( |
| | | 193 | | Stream, |
| | | 194 | | ConsumerGroup, |
| | | 195 | | SubscriberOptions.PendingClaimBatchSize, |
| | | 196 | | RedisValue.Null, |
| | | 197 | | minId: null, |
| | | 198 | | maxId: null, |
| | | 199 | | minIdleMs, |
| | | 200 | | cancellationToken).ConfigureAwait(false); |
| | | 201 | | |
| | | 202 | | if (pending.Length == 0) |
| | | 203 | | return 0; |
| | | 204 | | |
| | | 205 | | var pendingById = pending.ToDictionary( |
| | | 206 | | item => item.MessageId.ToString(), |
| | | 207 | | StringComparer.Ordinal); |
| | | 208 | | var claimed = await _database.StreamClaimAsync( |
| | | 209 | | Stream, |
| | | 210 | | ConsumerGroup, |
| | | 211 | | consumerName, |
| | | 212 | | minIdleMs, |
| | | 213 | | pending.Select(item => item.MessageId).ToArray(), |
| | | 214 | | cancellationToken).ConfigureAwait(false); |
| | | 215 | | |
| | | 216 | | var processed = 0; |
| | | 217 | | foreach (var entry in claimed) |
| | | 218 | | { |
| | | 219 | | var priorDeliveries = pendingById.TryGetValue(entry.Id.ToString(), out var info) |
| | | 220 | | ? info.DeliveryCount |
| | | 221 | | : 1; |
| | | 222 | | if (await DispatchEntryAsync(dispatcher, entry, Math.Max(1, priorDeliveries + 1), cancellationToken).Configu |
| | | 223 | | == RedisDispatchOutcome.Processed) |
| | | 224 | | { |
| | | 225 | | processed++; |
| | | 226 | | } |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | return processed; |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | private RedisStreamDelivery CreateDelivery(StreamEntry entry, int attempt) |
| | | 233 | | { |
| | | 234 | | var payload = RedisCorrelationIdExtractor.TryReadField(entry, Options.PayloadField); |
| | | 235 | | if (string.IsNullOrWhiteSpace(payload)) |
| | | 236 | | { |
| | | 237 | | throw new InvalidDataException( |
| | | 238 | | $"Redis stream entry {entry.Id} on {Stream.ToString()} does not contain payload field '{Options.PayloadF |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | var correlationId = SubscriberRole is RedisSubscriberRole.ResponseIngress |
| | | 242 | | ? RedisCorrelationIdExtractor.Extract(entry, payload, Options) |
| | | 243 | | : RedisCorrelationIdExtractor.TryReadField(entry, Options.CorrelationIdField); |
| | | 244 | | |
| | | 245 | | return new RedisStreamDelivery( |
| | | 246 | | Stream, |
| | | 247 | | ConsumerGroup, |
| | | 248 | | entry.Id, |
| | | 249 | | payload, |
| | | 250 | | correlationId, |
| | | 251 | | attempt, |
| | | 252 | | entry); |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | private static long ToPositiveMilliseconds(TimeSpan value) |
| | | 256 | | => Math.Max(1, (long)Math.Ceiling(value.TotalMilliseconds)); |
| | | 257 | | |
| | | 258 | | private static RedisValue ResolveConsumerName( |
| | | 259 | | RedisAsyncResponseTransportOptions options, |
| | | 260 | | RedisSubscriberRole role) |
| | | 261 | | { |
| | | 262 | | // Append the role even to an explicitly configured name so the worker and response subscribers |
| | | 263 | | // never share a consumer identity (and therefore a pending-entry list) within their groups. |
| | | 264 | | var baseName = !string.IsNullOrWhiteSpace(options.ConsumerName) |
| | | 265 | | ? options.ConsumerName |
| | | 266 | | : GeneratedConsumerName; |
| | | 267 | | |
| | | 268 | | return $"{baseName}-{role.ToString().ToLowerInvariant()}"; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | private static string CreateGeneratedConsumerName() |
| | | 272 | | { |
| | | 273 | | var name = $"{Environment.MachineName}-{Environment.ProcessId}-{Guid.NewGuid():N}"; |
| | | 274 | | return TrimConsumerName(name); |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | internal static string TrimConsumerName(string name) |
| | | 278 | | => name.Length <= 64 ? name : name[..64]; |
| | | 279 | | } |
| | | 280 | | |
| | | 281 | | internal sealed class RedisWorkerSubscriber : RedisSubscriberService |
| | | 282 | | { |
| | | 283 | | private readonly IAsyncResponseIngress _ingress; |
| | | 284 | | private readonly RedisTransportKeySchema _keys; |
| | | 285 | | |
| | | 286 | | /// <summary>Runs the RedisWorkerSubscriber operation.</summary> |
| | | 287 | | public RedisWorkerSubscriber( |
| | | 288 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 289 | | IConnectionMultiplexer multiplexer, |
| | | 290 | | IAsyncResponseIngress ingress, |
| | | 291 | | ILogger<RedisWorkerSubscriber> logger) |
| | | 292 | | : base(options, multiplexer, logger) |
| | | 293 | | { |
| | | 294 | | _ingress = ingress; |
| | | 295 | | _keys = new RedisTransportKeySchema(options.Value); |
| | | 296 | | } |
| | | 297 | | |
| | | 298 | | internal RedisWorkerSubscriber( |
| | | 299 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 300 | | IRedisStreamDatabase database, |
| | | 301 | | IAsyncResponseIngress ingress, |
| | | 302 | | ILogger<RedisWorkerSubscriber> logger) |
| | | 303 | | : base(options, database, logger) |
| | | 304 | | { |
| | | 305 | | _ingress = ingress; |
| | | 306 | | _keys = new RedisTransportKeySchema(options.Value); |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | protected override RedisKey Stream => _keys.WorkerStream; |
| | | 310 | | protected override RedisValue ConsumerGroup => Options.WorkerConsumerGroup; |
| | | 311 | | protected override RedisSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 312 | | protected override RedisSubscriberRole SubscriberRole => RedisSubscriberRole.Worker; |
| | | 313 | | |
| | | 314 | | /// <summary>Handles the delivered message.</summary> |
| | | 315 | | protected override Task HandleMessageAsync(RedisStreamDelivery delivery, CancellationToken cancellationToken) |
| | | 316 | | => _ingress.HandleWorkerMessageAsync(delivery.Payload); |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | internal sealed class RedisResponseIngressSubscriber : RedisSubscriberService |
| | | 320 | | { |
| | | 321 | | private readonly IAsyncResponseIngress _ingress; |
| | | 322 | | private readonly RedisTransportKeySchema _keys; |
| | | 323 | | |
| | | 324 | | /// <summary>Runs the RedisResponseIngressSubscriber operation.</summary> |
| | | 325 | | public RedisResponseIngressSubscriber( |
| | | 326 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 327 | | IConnectionMultiplexer multiplexer, |
| | | 328 | | IAsyncResponseIngress ingress, |
| | | 329 | | ILogger<RedisResponseIngressSubscriber> logger) |
| | 3 | 330 | | : base(options, multiplexer, logger) |
| | | 331 | | { |
| | 3 | 332 | | _ingress = ingress; |
| | 3 | 333 | | _keys = new RedisTransportKeySchema(options.Value); |
| | 3 | 334 | | } |
| | | 335 | | |
| | | 336 | | internal RedisResponseIngressSubscriber( |
| | | 337 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 338 | | IRedisStreamDatabase database, |
| | | 339 | | IAsyncResponseIngress ingress, |
| | | 340 | | ILogger<RedisResponseIngressSubscriber> logger) |
| | 2 | 341 | | : base(options, database, logger) |
| | | 342 | | { |
| | 2 | 343 | | _ingress = ingress; |
| | 2 | 344 | | _keys = new RedisTransportKeySchema(options.Value); |
| | 3 | 345 | | } |
| | | 346 | | |
| | 3 | 347 | | protected override RedisKey Stream => _keys.ResponseStream; |
| | 3 | 348 | | protected override RedisValue ConsumerGroup => Options.ResponseConsumerGroup; |
| | 3 | 349 | | protected override RedisSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | 3 | 350 | | protected override RedisSubscriberRole SubscriberRole => RedisSubscriberRole.ResponseIngress; |
| | | 351 | | |
| | | 352 | | /// <summary>Handles the delivered message.</summary> |
| | | 353 | | protected override Task HandleMessageAsync(RedisStreamDelivery delivery, CancellationToken cancellationToken) |
| | 3 | 354 | | => _ingress.HandleResponseMessageAsync(delivery.Payload, delivery.CorrelationId); |
| | | 355 | | } |