Path: redb-route/redb.Route/Core/InflightDrainGuard.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/InflightDrainGuard.cs
----
using Microsoft.Extensions.Logging;
namespace redb.Route.Core;
///
/// Encapsulates inflight tracking and drain-on-stop logic.
/// Used by both poll-based () and callback-based consumers
/// (RabbitMQ, MQTT, AMQP, TCP) to avoid duplicating CTS lifecycle + drain + force-cancel boilerplate.
///
public sealed class InflightDrainGuard : IDisposable
{
private CancellationTokenSource? _processingCts;
private int _inflightCount;
/// Drain timeout for graceful stop (default 30s).
public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30);
/// Current number of in-flight exchanges.
public int InflightCount => Volatile.Read(ref _inflightCount);
/// The processing cancellation token. Valid after .
public CancellationToken ProcessingToken =>
_processingCts?.Token ?? CancellationToken.None;
///
/// Initializes the processing CTS linked to the application shutdown token.
/// Safe to call multiple times — disposes the previous CTS if any.
///
public void Start(CancellationToken ct = default)
{
_processingCts?.Dispose();
_processingCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
}
/// Increments the inflight counter. Must be paired with .
public void Increment() => Interlocked.Increment(ref _inflightCount);
/// Decrements the inflight counter.
public void Decrement() => Interlocked.Decrement(ref _inflightCount);
///
/// Drains in-flight exchanges and force-cancels if drain times out.
/// Call in consumer Stop() after stopping acceptance of new work.
///
public async Task DrainAsync(CancellationToken ct, ILogger? logger = null, string? consumerName = null)
{
if (Volatile.Read(ref _inflightCount) > 0)
{
var drained = await DrainAwaiter.WaitAsync(
() => Volatile.Read(ref _inflightCount),
DrainTimeout, ct, logger,
consumerName).ConfigureAwait(false);
if (!drained && _processingCts != null)
{
logger?.LogWarning("[{Consumer}] Force-cancelling in-flight processing.", consumerName);
await _processingCts.CancelAsync().ConfigureAwait(false);
}
}
}
///
public void Dispose()
{
_processingCts?.Dispose();
_processingCts = null;
}
}