Path: redb-route/redb.Route/Core/DrainableConsumer.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/DrainableConsumer.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.Core;
///
/// Base class for consumers with Two-CTS graceful shutdown.
/// Handles: CTS lifecycle, inflight tracking, drain-on-stop, force-cancel.
/// Subclasses only implement and optionally override hooks.
///
public abstract class DrainableConsumer : IConsumer
{
private CancellationTokenSource? _pollCts;
private readonly InflightDrainGuard _drain = new();
private Task? _runTask;
private ILogger? _logger;
/// The endpoint this consumer is attached to.
protected abstract IEndpoint ConsumerEndpoint { get; }
/// The processor to execute on each exchange.
protected IProcessor Processor { get; }
///
public IEndpoint Endpoint => ConsumerEndpoint;
/// Logger resolved from the component.
protected ILogger? Logger => _logger ??= (ConsumerEndpoint.Component as ComponentBase)?.Logger;
/// Drain timeout for graceful stop.
internal TimeSpan DrainTimeout { get => _drain.DrainTimeout; set => _drain.DrainTimeout = value; }
/// Display name for logging (e.g. "kafka:orders", "file:/tmp/in").
protected abstract string ConsumerName { get; }
/// Creates a drainable consumer.
protected DrainableConsumer(IProcessor processor)
{
Processor = processor ?? throw new ArgumentNullException(nameof(processor));
}
// ── IConsumer lifecycle ──
///
public async Task Start(CancellationToken ct = default)
{
_pollCts?.Dispose();
_pollCts = new CancellationTokenSource();
_drain.Start(ct);
try
{
await OnStarting(ct).ConfigureAwait(false);
}
catch
{
_pollCts.Dispose();
_pollCts = null;
_drain.Dispose();
throw;
}
_runTask = RunAsync(_pollCts.Token, _drain.ProcessingToken);
Logger?.LogInformation("{Consumer} started.", EndpointUri.ForLog(ConsumerName, Logger));
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_pollCts != null)
{
try
{
// Step 1: stop accepting new work
await OnStopAccepting().ConfigureAwait(false);
await _pollCts.CancelAsync().ConfigureAwait(false);
// Step 2: drain in-flight
await _drain.DrainAsync(ct, Logger, ConsumerName).ConfigureAwait(false);
// Step 3: await run task(s)
await AwaitRunTask().ConfigureAwait(false);
}
finally
{
// Step 4: cleanup — guaranteed even if drain/await throws
_pollCts.Dispose();
_pollCts = null;
_drain.Dispose();
}
await OnStopped().ConfigureAwait(false);
}
Logger?.LogInformation("{Consumer} stopped.", EndpointUri.ForLog(ConsumerName, Logger));
}
// ── Abstract / virtual hooks ──
///
/// Main consumer loop. Receives (stop accepting new work)
/// and (cancel in-flight processing).
/// Use for automatic inflight tracking.
///
protected abstract Task RunAsync(CancellationToken pollCt, CancellationToken processingCt);
/// Called during Start() before RunAsync. Override for async setup (topology, subscriptions).
protected virtual Task OnStarting(CancellationToken ct) => Task.CompletedTask;
/// Called at the beginning of Stop() before poll cancel. Override for protocol-level unsubscribe.
protected virtual Task OnStopAccepting() => Task.CompletedTask;
/// Called at the end of Stop() after CTS disposal. Override for resource cleanup.
protected virtual Task OnStopped() => Task.CompletedTask;
///
/// Awaits the run task. Override for consumers with multiple workers (e.g. Task.WhenAll).
///
protected virtual async Task AwaitRunTask()
{
if (_runTask != null)
{
try { await _runTask.ConfigureAwait(false); }
catch (OperationCanceledException) { }
}
}
// ── Inflight tracking helper ──
///
/// Processes an exchange with automatic inflight count tracking.
/// Increments before, decrements in finally. Disposes the exchange after processing.
///
protected Task ProcessWithTracking(IExchange exchange, CancellationToken processingCt)
=> ProcessWithTracking(exchange, default, processingCt);
///
/// inside the receive span of the exchange, opened by
/// the consumer (). A failed route marks
/// the span, whether its failure stayed on the exchange or escaped the pipeline; the consumer's own stop does not,
/// any other cancellation (an HttpClient timeout inside the route) does. The span stays the consumer's to dispose.
///
protected async Task ProcessWithTracking(IExchange exchange, Telemetry.TransportSpan span, CancellationToken processingCt)
{
_drain.Increment();
try
{
// What escapes the pipeline goes on the exchange (a consumer that decides on the outcome, delete after read
// or move on failure, sees a failed route); it is logged and dropped: a single failure must NOT terminate the
// worker and silently stop the consumer draining the queue. The consumer's stop is rethrown.
if (await ExchangeProcessing.RunAsync(Processor, exchange, processingCt).ConfigureAwait(false) is { } escaped)
Logger?.LogError(escaped, "{Consumer} dropped an exchange after an unhandled failure; continuing.", ConsumerName);
ExchangeProcessing.RecordFailure(exchange, span, processingCt);
}
finally
{
_drain.Decrement();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
///
/// Increments the inflight counter. Must be paired with .
/// Use when you need custom logic between increment and process (e.g. ack/nack).
///
protected void IncrementInflight() => _drain.Increment();
/// Decrements the inflight counter.
protected void DecrementInflight() => _drain.Decrement();
}