Path: redb-route/redb.Route/Processors/DebounceProcessor.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/Processors/DebounceProcessor.cs
----
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Telemetry;
namespace redb.Route.Processors;
///
/// Per-key debounce: suppresses rapid-fire messages and forwards only the last
/// exchange for each key after a configurable quiet period.
/// When a new message arrives for a key that already has a pending timer,
/// the previous exchange is discarded and the timer is reset.
/// Thread-safe for concurrent pipeline usage.
///
internal sealed class DebounceProcessor : IProcessor, IAsyncDisposable, IDisposable
{
private readonly IProcessor _next;
private readonly Func _keyExtractor;
private readonly TimeSpan _quietPeriod;
private readonly ILogger? _logger;
private readonly TimeProvider _time;
private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal);
private int _disposed;
/// Creates a debounce processor.
/// Next processor in the pipeline.
/// Function extracting the debounce key from the exchange.
/// Duration of silence required before forwarding the last exchange.
/// Optional logger for diagnostics.
/// The clock of the quiet period; when omitted.
public DebounceProcessor(
IProcessor next,
Func keyExtractor,
TimeSpan quietPeriod,
ILogger? logger = null,
TimeProvider? timeProvider = null)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor));
if (quietPeriod <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(quietPeriod), "Must be positive.");
_quietPeriod = quietPeriod;
_logger = logger;
_time = timeProvider ?? TimeProvider.System;
}
///
public Task Process(IExchange exchange, CancellationToken ct = default)
{
ObjectDisposedException.ThrowIf(_disposed != 0, this);
var key = _keyExtractor(exchange) ?? string.Empty;
// Create or update the entry for this key
_entries.AddOrUpdate(
key,
_ => CreateEntry(key, exchange, ct),
(k, existing) =>
{
ProcessorMetrics.DebounceDiscarded.Add(1);
existing.Reset(exchange, ct);
ScheduleFlush(k, existing);
return existing;
});
// Return immediately — the downstream call happens asynchronously after quiet period
return Task.CompletedTask;
}
private DebounceEntry CreateEntry(string key, IExchange exchange, CancellationToken ct)
{
var entry = new DebounceEntry(exchange, ct);
ScheduleFlush(key, entry);
return entry;
}
private void ScheduleFlush(string key, DebounceEntry entry)
{
var cts = entry.Cts;
// Capture ambient trace + transaction state on the scheduling (originating) thread. The
// flush below runs detached after the quiet period — by then the originating route call,
// and any ambient TransactionScope it ran in, has unwound. See DetachedDispatch.
var origin = DetachedDispatch.Capture();
_ = Task.Delay(_quietPeriod, _time, cts.Token).ContinueWith(async _ =>
{
if (_entries.TryRemove(key, out var removed))
{
// Suppress the leaked ambient transaction and re-root telemetry as a span linked
// to the originating trace, so the flushed forward does not enlist in an
// already-completed TransactionScope nor parent under an already-stopped span.
using var frame = DetachedDispatch.Enter(origin, "redb.route.debounce.flush");
try
{
await _next.Process(removed.Exchange, removed.UpstreamCt).ConfigureAwait(false);
ProcessorMetrics.DebounceFlushed.Add(1);
}
catch (Exception ex)
{
removed.Exchange.Exception = ex;
_logger?.LogError(ex, "Debounce flush failed for key '{Key}'", key);
}
finally
{
removed.Dispose();
}
}
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
}
/// Flush all pending entries immediately (used during graceful shutdown).
public async Task FlushAsync()
{
var keys = _entries.Keys.ToArray();
foreach (var key in keys)
{
if (_entries.TryRemove(key, out var entry))
{
try
{
await _next.Process(entry.Exchange, entry.UpstreamCt).ConfigureAwait(false);
}
catch (Exception ex)
{
entry.Exchange.Exception = ex;
_logger?.LogError(ex, "Debounce flush failed for key '{Key}'", key);
}
finally
{
entry.Dispose();
}
}
}
}
/// Cancels pending timers and disposes all entries.
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
foreach (var kvp in _entries)
{
kvp.Value.Dispose();
}
_entries.Clear();
}
/// Flushes pending entries and disposes.
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
await FlushAsync().ConfigureAwait(false);
_entries.Clear();
}
private sealed class DebounceEntry : IDisposable
{
private CancellationTokenSource _cts;
private IExchange _exchange;
private CancellationToken _upstreamCt;
public DebounceEntry(IExchange exchange, CancellationToken upstreamCt)
{
_cts = new CancellationTokenSource();
_exchange = exchange;
_upstreamCt = upstreamCt;
}
public CancellationTokenSource Cts => Volatile.Read(ref _cts);
public IExchange Exchange => Volatile.Read(ref _exchange);
public CancellationToken UpstreamCt => _upstreamCt;
/// Replaces the stored exchange and resets the timer.
public void Reset(IExchange newExchange, CancellationToken ct)
{
var oldCts = Interlocked.Exchange(ref _cts, new CancellationTokenSource());
try { oldCts.Cancel(); } catch (ObjectDisposedException) { }
oldCts.Dispose();
Volatile.Write(ref _exchange, newExchange);
_upstreamCt = ct;
}
public void Dispose()
{
try { _cts.Cancel(); } catch (ObjectDisposedException) { }
_cts.Dispose();
}
}
}