Path: redb-route/redb.Route.Redis/RedisConsumer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/RedisConsumer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using StackExchange.Redis; namespace redb.Route.Redis; /// /// Redis consumer. Supports three modes based on the operation type: /// /// / — /// Pub/Sub with event-driven callback. /// / — /// Redis Streams polling loop: with a consumer group, acknowledged after the route (or NOACK) and pending entries /// claimed again after an idle time; without one, a position of its own that moves past every entry read. /// / — /// list pop via polling (a blocking pop would hold the shared connection); at-least-once with a processing list. /// /// public sealed partial class RedisConsumer : DrainableConsumer { private readonly RedisEndpoint _endpoint; private readonly RedisEndpointOptions _options; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"redis:{_endpoint.OperationType}:{_endpoint.Resource}"; /// Number of messages successfully processed. public long ProcessedCount { get; private set; } /// Creates a Redis consumer. public RedisConsumer(RedisEndpoint endpoint, IProcessor processor, RedisEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } // Set up by OnStarting, read by the loop RunAsync starts. private ISubscriber? _subscriber; private ChannelMessageQueue? _queue; private RedisChannel _channel; private IDatabase? _db; private RedisValue _streamPosition; /// /// Everything a message depends on is in place before returns: the pub/sub /// subscription, the consumer group, the XREAD position. Done in the loop, after Start, it lost whatever was /// published or added in between. A Redis that does not answer fails Start, naming this consumer; it used to leave a /// started consumer that never received anything. /// protected override async Task OnStarting(CancellationToken ct) { try { switch (_endpoint.OperationType) { case RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE: await SubscribeAsync(ct).ConfigureAwait(false); break; case RedisOperationType.XREAD or RedisOperationType.XGROUP: await PrepareStreamAsync(ct).ConfigureAwait(false); break; case RedisOperationType.BLPOP or RedisOperationType.BRPOP: // A list keeps its items, nothing to set up; the round trip only proves Redis answers. _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false); await _db.PingAsync().ConfigureAwait(false); break; default: throw new NotSupportedException( $"Consumer not supported for operation {_endpoint.OperationType}. " + "Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported."); } } catch (Exception ex) when (ex is RedisException or TimeoutException) { throw new InvalidOperationException( $"Redis consumer {ConsumerName} cannot start, Redis did not answer: {ex.Message}", ex); } } /// protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { return _endpoint.OperationType switch { RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE => RunPubSubConsumerAsync(pollCt, processingCt), RedisOperationType.XREAD or RedisOperationType.XGROUP when _options.Batch is { } batch => RunStreamBatchAsync(batch, pollCt, processingCt), RedisOperationType.XREAD or RedisOperationType.XGROUP => RunStreamConsumerAsync(pollCt, processingCt), RedisOperationType.BLPOP or RedisOperationType.BRPOP => RunListConsumerAsync(pollCt, processingCt), _ => throw new NotSupportedException( $"Consumer not supported for operation {_endpoint.OperationType}. " + "Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported.") }; } // ═══════════════════════════════════════════════════════════ // Pub/Sub // ═══════════════════════════════════════════════════════════ private async Task SubscribeAsync(CancellationToken ct) { _subscriber = await _endpoint.GetSubscriberAsync(ct).ConfigureAwait(false); var channel = _options.Channel ?? _endpoint.Resource; // PSUBSCRIBE is a pattern subscription by itself; usePattern makes SUBSCRIBE one too. var pattern = _endpoint.OperationType == RedisOperationType.PSUBSCRIBE || _options.UsePattern; _channel = pattern ? new RedisChannel(channel, RedisChannel.PatternMode.Pattern) : new RedisChannel(channel, RedisChannel.PatternMode.Literal); _queue = await _subscriber.SubscribeAsync(_channel).ConfigureAwait(false); Logger?.LogInformation("Redis subscribed to channel: {Channel} (pattern={Pattern})", channel, pattern); } private async Task RunPubSubConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var subscriber = _subscriber!; var queue = _queue!; var redisChannel = _channel; try { while (!pollCt.IsCancellationRequested) { var msg = await queue.ReadAsync(pollCt).ConfigureAwait(false); await ProcessPubSubMessageAsync(msg.Channel!, msg.Message, processingCt).ConfigureAwait(false); } } catch (OperationCanceledException) { /* normal shutdown */ } catch (Exception ex) { Logger?.LogError(ex, "Error in Redis Pub/Sub consumer for channel {Channel}", redisChannel.ToString()); } finally { try { await subscriber.UnsubscribeAsync(redisChannel).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error unsubscribing from Redis channel"); } _queue = null; } } private async Task ProcessPubSubMessageAsync(RedisChannel channel, RedisValue message, CancellationToken ct) { var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; using var span = StartReceiveSpan(); IncrementInflight(); try { exchange.In.Headers[RedisHeaders.Channel] = channel.ToString(); exchange.In.Headers[RedisHeaders.MessageType] = "PubSub"; exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow; await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); ProcessedCount++; } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing Pub/Sub message from channel {Channel}", channel); } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } // ═══════════════════════════════════════════════════════════ // Streams (XREAD / XGROUP) // ═══════════════════════════════════════════════════════════ private async Task PrepareStreamAsync(CancellationToken ct) { var db = _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false); var streamName = _options.StreamName ?? _endpoint.Resource; var consumerGroup = _options.ConsumerGroup; // Create consumer group if needed if (!string.IsNullOrEmpty(consumerGroup)) { try { // Unset position: the group starts at the stream's end ($), as StackExchange.Redis does by default. await db.StreamCreateConsumerGroupAsync( streamName, consumerGroup, // RedisValue? explicitly: a null string converts to RedisValue.Null, which XGROUP CREATE refuses // ("A null value is not valid"), and a group consumer without streamStartPosition never started. _options.StreamStartPosition is { } start ? (RedisValue?)start : null, createStream: true).ConfigureAwait(false); Logger?.LogInformation("Redis stream consumer group created: {Group} for {Stream}", consumerGroup, streamName); } catch (RedisServerException ex) when (ex.Message.Contains("BUSYGROUP")) { Logger?.LogDebug("Redis stream consumer group {Group} already exists", consumerGroup); } } // Without a group the position is this consumer's to keep, and it moves past every entry read. _streamPosition = string.IsNullOrEmpty(consumerGroup) ? await StartPositionAsync(db, streamName).ConfigureAwait(false) : default; } private async Task RunStreamConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var db = _db!; var streamName = _options.StreamName ?? _endpoint.Resource; var consumerGroup = _options.ConsumerGroup; var consumerName = _options.ConsumerName ?? Environment.MachineName; var position = _streamPosition; RedisValue claimCursor = "0-0"; Logger?.LogInformation("Redis stream consumer started: stream={Stream}, group={Group}, consumer={Consumer}", streamName, consumerGroup, consumerName); while (!pollCt.IsCancellationRequested) { try { StreamEntry[] entries; var claimedAny = false; if (!string.IsNullOrEmpty(consumerGroup)) { if (_options.StreamClaimMinIdleMs is { } minIdle) { // Entries of the group pending for longer than minIdle — a failed entry of this consumer, or one // a dead consumer left behind — are taken over and processed again. The cursor walks the // pending list and comes back to the start once it has seen all of it. var claimed = await db.StreamAutoClaimAsync( streamName, consumerGroup, consumerName, minIdle, claimCursor, _options.StreamReadCount) .ConfigureAwait(false); claimCursor = claimed.NextStartId; foreach (var entry in claimed.ClaimedEntries.Where(e => !e.IsNull)) { claimedAny = true; await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt) .ConfigureAwait(false); } } entries = await db.StreamReadGroupAsync( streamName, consumerGroup, consumerName, StreamPosition.NewMessages, _options.StreamReadCount, noAck: _options.AckMode == AckMode.Auto).ConfigureAwait(false); } else { entries = await db.StreamReadAsync( streamName, position, _options.StreamReadCount).ConfigureAwait(false); } if (entries is { Length: > 0 }) { foreach (var entry in entries) { await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt) .ConfigureAwait(false); // Past a failed entry too: without a group nothing keeps it pending, as a Kafka consumer // without breakOnFirstError moves on. if (string.IsNullOrEmpty(consumerGroup)) position = entry.Id; } } else if (!claimedAny) { await Task.Delay(_options.StreamBlockTimeMs, pollCt).ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { Logger?.LogError(ex, "Error reading from Redis stream {Stream}", streamName); try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } /// /// Where an XREAD consumer without a group starts. Unset or $: the entries added from now on. XREAD takes /// $ as "after the last entry at the time of this call", which a polling loop would evaluate again on every /// call and so skip whatever arrived in between: it is pinned once, to the id of the stream's last entry, or to the /// start of an empty stream. Anything else (0, an entry id) is taken as given. /// private async Task StartPositionAsync(IDatabase db, string streamName) { if (_options.StreamStartPosition is not (null or "$")) return _options.StreamStartPosition; var last = await db.StreamRangeAsync(streamName, "-", "+", count: 1, messageOrder: Order.Descending) .ConfigureAwait(false); return last.Length > 0 ? last[0].Id : "0-0"; } private async Task ProcessStreamEntryAsync( StreamEntry entry, IDatabase db, string streamName, string? consumerGroup, CancellationToken ct) { using var span = StartReceiveSpan(); try { var exchange = Exchange.Create(StreamMessage(entry, streamName), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; IncrementInflight(); try { // The entry is acknowledged by this consumer after the unit of work ended well (below), not by // the route transaction: the transaction owns the database and the outgoing sends. await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); // Acknowledge the entry now that the whole unit of work, the route transaction included, is done. A // failed entry is not acknowledged: it stays pending, for streamClaimMinIdleMs to claim again. if (!string.IsNullOrEmpty(consumerGroup) && _options.AckMode == AckMode.Manual) { await db.StreamAcknowledgeAsync(streamName, consumerGroup, entry.Id).ConfigureAwait(false); } ProcessedCount++; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing stream entry {MessageId} from {Stream}", entry.Id, streamName); } } // ═══════════════════════════════════════════════════════════ // List (BLPOP / BRPOP) // ═══════════════════════════════════════════════════════════ private async Task RunListConsumerAsync(CancellationToken pollCt, CancellationToken processingCt) { var db = _db!; var key = _options.Key ?? _endpoint.Resource; // BLPOP takes from the head, BRPOP from the tail. Both poll: a blocking pop would hold the multiplexed // connection every other command of this process shares. var side = _endpoint.OperationType == RedisOperationType.BLPOP ? ListSide.Left : ListSide.Right; var processing = _options.ProcessingList; Logger?.LogInformation("Redis list consumer started: key={Key}, operation={Op}, processing list={Processing}", key, _endpoint.OperationType, processing); if (processing is not null) await ReturnLeftoversAsync(db, processing, key, side).ConfigureAwait(false); while (!pollCt.IsCancellationRequested) { try { // With a processing list the item is moved there (LMOVE) and leaves it only once processed; without one // it is popped, and a failed item is gone. var result = processing is null ? side == ListSide.Left ? await db.ListLeftPopAsync(key).ConfigureAwait(false) : await db.ListRightPopAsync(key).ConfigureAwait(false) : await db.ListMoveAsync(key, processing, side, ListSide.Left).ConfigureAwait(false); if (!result.HasValue) { await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false); continue; } var processed = await ProcessListMessageAsync(result, key, processingCt).ConfigureAwait(false); if (processing is null) continue; if (processed) { await db.ListRemoveAsync(processing, result, count: 1).ConfigureAwait(false); } else { // Back to the side it was taken from, so it is the next one taken; atomically, so a crash in // between cannot leave it in both lists or in neither. var back = db.CreateTransaction(); _ = back.ListRemoveAsync(processing, result, count: 1); _ = side == ListSide.Left ? back.ListLeftPushAsync(key, result) : back.ListRightPushAsync(key, result); await back.ExecuteAsync().ConfigureAwait(false); await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { Logger?.LogError(ex, "Error reading from Redis list {Key}", key); try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } /// /// Returns what a previous run left in the processing list — items it took and never finished — to the side of the /// queue this consumer takes from, oldest first. /// private async Task ReturnLeftoversAsync(IDatabase db, string processing, string key, ListSide side) { var returned = 0; // The newest item sits at the head of the processing list; moving from the head to the taking side, one by one, // leaves the oldest nearest to it. while ((await db.ListMoveAsync(processing, key, ListSide.Left, side).ConfigureAwait(false)).HasValue) returned++; if (returned > 0) Logger?.LogWarning("Redis list consumer returned {Count} unfinished item(s) from {Processing} to {Key}", returned, processing, key); } /// Whether the route succeeded with the item. private async Task ProcessListMessageAsync(RedisValue message, string key, CancellationToken ct) { var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; using var span = StartReceiveSpan(); IncrementInflight(); try { exchange.In.Headers[RedisHeaders.Key] = key; exchange.In.Headers[RedisHeaders.MessageType] = "List"; exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow; await Processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); ProcessedCount++; return true; } catch (Exception ex) { RecordFailure(span, ex, ct); Logger?.LogError(ex, "Error processing list message from {Key}", key); return false; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } /// /// The span of one message, entry or item: it carries no trace context (a Redis value has no headers; a stream entry's /// fields are its body), so the span is a root, never a child of the activity the consumer loop holds. /// private TransportSpan StartReceiveSpan() => RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"redis {_endpoint.OperationType} receive", ActivityKind.Consumer, "messaging.system", "redis", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.Resource, operation: "receive"); /// Marks the span failed; our own stop is not a failure, any other cancellation is. private static void RecordFailure(TransportSpan span, Exception exception, CancellationToken ct) { if (exception is not OperationCanceledException || !ct.IsCancellationRequested) span.Activity.RecordFailure(exception); } }