Path: redb-route/redb.Route/Core/PushConsumer.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/Core/PushConsumer.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Telemetry;
namespace redb.Route.Core;
/// What became of one message a push consumer handed to .
public enum PushOutcome
{
/// The route ended well (and the work after it, if any): settle the message as consumed.
Accepted,
///
/// The route failed every attempt: settle the message by the connector's failure rule (reject to a dead letter
/// queue, or requeue). holds the failure.
///
Rejected,
/// The message arrived after the consumer began to stop: it was not run; give it back to the broker.
Refused,
///
/// The message was given up without a verdict on the route: the consumer's stop ended it (the drain window ran out,
/// or the pause before its next attempt was cut short), or the work after the route failed. Give it back.
///
Returned,
}
/// The outcome of one dispatch, with the failure behind or a failed follow-up.
/// What became of the message.
/// The route's failure (Rejected) or the follow-up's (Returned); null otherwise.
public readonly record struct PushDispatch(PushOutcome Outcome, Exception? Failure)
{
/// Converts to the outcome alone.
public static implicit operator PushOutcome(PushDispatch dispatch) => dispatch.Outcome;
}
/// How often a push consumer tries a failed message before it is .
/// Attempts in all, at least 1; each attempt runs on a fresh exchange.
/// Pause between attempts; a stop of the consumer cuts it short (the message is Returned).
public readonly record struct PushRetry(int Attempts, TimeSpan Delay)
{
/// One attempt, no retry.
public static PushRetry None => new(1, TimeSpan.Zero);
}
///
/// Base class for consumers whose client library calls a handler for every message (RabbitMQ
/// AsyncEventingBasicConsumer, MQTT, a service bus processor): the counterpart of ,
/// which runs its own receive loop. The base keeps the order of a graceful stop, so a connector does not repeat it:
/// new messages are refused once a stop begins, the messages in work drain within , then their
/// processing is cancelled, and only then is the subscription released.
///
/// The connector gives three steps: (open and subscribe),
/// (cancel the subscription so nothing new arrives) and (release what Subscribe opened).
/// Its message handler calls and settles the message by the : the
/// base never acknowledges, the rules of that differ per broker.
///
///
/// A subscription the broker ends while the route runs (a closed channel, a dropped link) is reported to a
/// (), and brings it
/// back on the supervisor's schedule while the endpoint's health says so.
///
///
public abstract class PushConsumer : IConsumer
{
private readonly InflightDrainGuard _drain = new();
private readonly SemaphoreSlim? _slots;
private readonly object _resubscribeGate = new();
private readonly List _supervisors = [];
private CancellationTokenSource _stopRequested = new();
private Task? _resubscribe;
private volatile bool _stopping;
private ILogger? _logger;
/// Creates a push consumer.
/// The route the messages run through.
///
/// How many messages run through the route at once; a message over the limit waits for a slot, counted as in work.
/// null: no limit beyond what the client hands over.
///
protected PushConsumer(IProcessor processor, int? maxConcurrency = null)
{
Processor = processor ?? throw new ArgumentNullException(nameof(processor));
if (maxConcurrency is { } max)
{
ArgumentOutOfRangeException.ThrowIfLessThan(max, 1, nameof(maxConcurrency));
_slots = new SemaphoreSlim(max, max);
}
}
/// The endpoint this consumer is attached to.
protected abstract IEndpoint ConsumerEndpoint { get; }
/// Display name for logging (rabbitmq:orders).
protected abstract string ConsumerName { get; }
///
public IEndpoint Endpoint => ConsumerEndpoint;
/// The route the messages run through.
protected IProcessor Processor { get; }
/// Logger resolved from the component.
protected ILogger? Logger => _logger ??= (ConsumerEndpoint.Component as ComponentBase)?.Logger;
/// How long a stop waits for the messages in work before it cancels their processing (default 30 s).
protected TimeSpan DrainTimeout { get => _drain.DrainTimeout; set => _drain.DrainTimeout = value; }
/// Set once a stop begins: from then on a cancelled subscription or a closed channel is the stop's, not news.
protected bool IsStopping => _stopping;
/// Cancelled when a stop begins, before the drain; a pause or a wait of the connector's own ends with it.
protected CancellationToken StopToken => _stopRequested.Token;
/// The processing token of the messages in work; cancelled when the drain window of a stop runs out.
protected CancellationToken ProcessingToken => _drain.ProcessingToken;
/// Messages in work now.
protected int InflightCount => _drain.InflightCount;
// ── IConsumer lifecycle ──
///
public async Task Start(CancellationToken ct = default)
{
_stopping = false;
_stopRequested.Dispose();
_stopRequested = new CancellationTokenSource();
_drain.Start(ct);
try
{
await SubscribeAsync(ct).ConfigureAwait(false);
}
catch
{
ReleaseSupervisors();
_drain.Dispose();
throw;
}
Logger?.LogInformation("{Consumer} started.", EndpointUri.ForLog(ConsumerName, Logger));
}
///
public async Task Stop(CancellationToken ct = default)
{
_stopping = true;
await _stopRequested.CancelAsync().ConfigureAwait(false);
try
{
// Step 1: a resubscribe in flight ends (the stop token ends its loop), then nothing new arrives on the
// subscription that is current now.
await AwaitResubscribeAsync().ConfigureAwait(false);
try
{
await StopAcceptingAsync(ct).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "{Consumer}: error cancelling the subscription", ConsumerName);
}
// Step 2: drain the messages in work, then cancel what is left.
await _drain.DrainAsync(ct, Logger, ConsumerName).ConfigureAwait(false);
// Step 3: release what Subscribe opened.
await UnsubscribeAsync(ct).ConfigureAwait(false);
}
finally
{
ReleaseSupervisors();
_drain.Dispose();
}
Logger?.LogInformation("{Consumer} stopped.", EndpointUri.ForLog(ConsumerName, Logger));
}
// ── The connector's steps ──
/// Opens what the subscription needs and subscribes; a failure fails the start.
protected abstract Task SubscribeAsync(CancellationToken ct);
/// Cancels the subscription so that no new message arrives (a broker-side cancel); errors are logged.
protected abstract Task StopAcceptingAsync(CancellationToken ct);
/// Releases what opened; runs after the drain.
protected abstract Task UnsubscribeAsync(CancellationToken ct);
// ── Messages ──
///
/// Runs one message through the route and says what became of it; the connector settles it by the outcome. Refused
/// when a stop has begun (also when the stop began while the message waited for a slot); counted as in work until it
/// returns, so a stop's drain waits for it. Each attempt runs on a fresh exchange from
/// and is disposed after it. A route that failed is tried again by ; after the last attempt the
/// failure marks and the outcome is .
///
/// Creates the exchange of one attempt from the message.
/// The receive span the consumer opened (and disposes); a failure marks it.
/// Attempts and the pause between them; when null.
///
/// Work after a route that ended well and before the message is settled (an RPC reply). If it fails, the message is
/// , the failure marks the span and is returned in .
///
protected async Task DispatchAsync(Func createExchange, TransportSpan span,
PushRetry? retry = null, Func? afterRoute = null)
{
ArgumentNullException.ThrowIfNull(createExchange);
var plan = retry ?? PushRetry.None;
if (_stopping)
return new PushDispatch(PushOutcome.Refused, null);
// Counted before the wait for a slot, so a stop's drain waits for a message still waiting: it must not start
// after the drain gave up and disposed the processing token.
_drain.Increment();
var slot = false;
IExchange? exchange = null;
try
{
if (_slots is not null)
{
await _slots.WaitAsync().ConfigureAwait(false);
slot = true;
}
if (_stopping)
return new PushDispatch(PushOutcome.Refused, null);
// This message's processing token, taken now: the drain disposes its source when a stop gives up waiting.
var token = _drain.ProcessingToken;
for (var attempt = 1; ; attempt++)
{
exchange = createExchange();
await ExchangeProcessing.RunAsync(Processor, exchange, token).ConfigureAwait(false);
if (ExchangeFailureExtensions.FailureOf(exchange) is not { } failure)
break;
if (IsOwnStop(failure, token))
return new PushDispatch(PushOutcome.Returned, null);
if (attempt >= Math.Max(1, plan.Attempts))
{
RouteTelemetryExtensions.RecordFailure(span.Activity, failure);
return new PushDispatch(PushOutcome.Rejected, failure);
}
Logger?.LogWarning(failure, "{Consumer}: attempt {Attempt} of {Max} failed; the next in {Delay} ms",
ConsumerName, attempt, plan.Attempts, (long)plan.Delay.TotalMilliseconds);
if (plan.Delay > TimeSpan.Zero)
{
using var pause = CancellationTokenSource.CreateLinkedTokenSource(token, StopToken);
await Task.Delay(plan.Delay, pause.Token).ConfigureAwait(false);
}
await exchange.DisposeAsync().ConfigureAwait(false);
exchange = null;
}
if (afterRoute is not null)
{
try
{
await afterRoute(exchange, token).ConfigureAwait(false);
}
catch (Exception ex) when (!IsOwnStop(ex, token))
{
RouteTelemetryExtensions.RecordFailure(span.Activity, ex);
return new PushDispatch(PushOutcome.Returned, ex);
}
}
return new PushDispatch(PushOutcome.Accepted, null);
}
catch (OperationCanceledException ex) when (IsOwnStop(ex, _drain.ProcessingToken))
{
return new PushDispatch(PushOutcome.Returned, null);
}
finally
{
if (exchange is not null)
await exchange.DisposeAsync().ConfigureAwait(false);
if (slot)
_slots!.Release();
_drain.Decrement();
}
}
///
/// Counts one unit of work the connector runs itself (a batch) as in work, so a stop's drain waits for it; dispose
/// the result when the unit is done.
///
protected InflightScope TrackInflight()
{
_drain.Increment();
return new InflightScope(_drain);
}
/// A cancellation the consumer's own stop caused; any other one, a timeout inside the route included, is a failure.
protected bool IsOwnStop(Exception exception, CancellationToken processingToken)
=> exception is OperationCanceledException
&& (processingToken.IsCancellationRequested || _stopRequested.IsCancellationRequested);
// ── Losing the subscription ──
///
/// Creates a supervisor for one subscription of this consumer and registers it with the endpoint, whose health then
/// follows it; it is removed when the consumer stops. The endpoint must derive from .
///
/// What is supervised, for the log and the health reason: rabbitmq:orders consumer channel.
protected ConnectionSupervisor SuperviseConnection(string name)
{
if (ConsumerEndpoint is not ISupervisingEndpoint endpoint)
throw new InvalidOperationException(
$"{ConsumerName}: the endpoint {ConsumerEndpoint.GetType().Name} does not take connection supervisors.");
var supervisor = endpoint.Supervise(name, Logger);
lock (_supervisors) _supervisors.Add(supervisor);
return supervisor;
}
///
/// Brings a lost subscription back: runs on the supervisor's schedule
/// () until it succeeds or the consumer stops. Call it once, for the
/// report of that returned true; while one runs, a second call returns
/// the running one. A stop waits for it before the subscription is released, and its token ends it.
///
/// The supervisor the loss was reported to.
/// Opens a new subscription in place of the lost one; a failure counts as a failed attempt.
/// The loop; true once resubscribed, false when the stop ended it.
protected Task ResubscribeAsync(ConnectionSupervisor supervisor, Func resubscribe)
{
ArgumentNullException.ThrowIfNull(supervisor);
ArgumentNullException.ThrowIfNull(resubscribe);
lock (_resubscribeGate)
{
if (_resubscribe is Task { IsCompleted: false } running)
return running;
if (_stopping)
return Task.FromResult(false);
var stop = StopToken;
var loop = Task.Run(() => supervisor.ReconnectAsync(resubscribe, stop), CancellationToken.None);
_resubscribe = loop;
return loop;
}
}
private async Task AwaitResubscribeAsync()
{
Task? loop;
lock (_resubscribeGate) loop = _resubscribe;
if (loop is null)
return;
try { await loop.ConfigureAwait(false); }
catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: the resubscribe ended with an error", ConsumerName); }
}
private void ReleaseSupervisors()
{
ConnectionSupervisor[] supervisors;
lock (_supervisors)
{
supervisors = [.. _supervisors];
_supervisors.Clear();
}
if (ConsumerEndpoint is ISupervisingEndpoint endpoint)
foreach (var supervisor in supervisors)
endpoint.Unsupervise(supervisor);
}
/// One unit of work counted by ; disposing it ends the count.
protected readonly struct InflightScope : IDisposable
{
private readonly InflightDrainGuard? _drain;
internal InflightScope(InflightDrainGuard drain) => _drain = drain;
///
public void Dispose() => _drain?.Decrement();
}
}