Path: redb-route/redb.Route/Core/ConnectionEventDispatcher.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/ConnectionEventDispatcher.cs
----
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.Core;
///
/// The route context's queue of connection events: supervisors post into it and return at once, one background reader
/// hands the events, in order, to the lifecycle listeners. The queue is bounded: when listeners fall so far behind that
/// it is full, the oldest event is dropped, counted, and one warning line says so; a reconnect loop never waits for it.
///
internal sealed class ConnectionEventDispatcher
{
/// How many events wait at most for slow listeners.
internal const int Capacity = 1024;
private readonly Channel _queue;
private readonly Func _deliver;
private readonly ILogger? _logger;
private readonly object _readerLock = new();
private Task? _reader;
private long _dropped;
private int _dropWarned;
/// Hands one event to the listeners; its errors are logged, the reader goes on.
/// Logger for dropped events and delivery errors.
public ConnectionEventDispatcher(Func deliver, ILogger? logger)
{
_deliver = deliver;
_logger = logger;
_queue = Channel.CreateBounded(
new BoundedChannelOptions(Capacity) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true },
_ => OnDropped());
}
/// The background reader, once the first event started it; it completes after .
internal Task? Reader => Volatile.Read(ref _reader);
/// Events dropped because the queue was full.
public long Dropped => Interlocked.Read(ref _dropped);
/// Queues one event and returns at once; the reader starts with the first event.
public void Post(ConnectionEvent change)
{
if (!_queue.Writer.TryWrite(change))
return; // completed: the context is disposed
if (Volatile.Read(ref _reader) is null)
{
lock (_readerLock)
_reader ??= Task.Run(ReadAsync);
}
}
/// Ends the queue: the reader delivers what is queued and stops.
public void Complete() => _queue.Writer.TryComplete();
private async Task ReadAsync()
{
await foreach (var change in _queue.Reader.ReadAllAsync().ConfigureAwait(false))
{
try
{
await _deliver(change).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Delivering the connection event {Kind} of {Connection} failed",
change.Kind, change.Connection);
}
}
}
private void OnDropped()
{
Interlocked.Increment(ref _dropped);
if (Interlocked.Exchange(ref _dropWarned, 1) == 0)
_logger?.LogWarning(
"Connection events are dropped: lifecycle listeners fall behind and {Capacity} events wait already. " +
"The oldest are dropped; reconnects go on.", Capacity);
}
}
///
/// The event sink an endpoint gives its supervisors: stamps the endpoint on each event and passes it to the context.
///
internal sealed class EndpointConnectionEventSink(RouteContext context, IEndpoint endpoint, string endpointName)
: IConnectionEventSink
{
public void Post(ConnectionEvent change) => context.PostConnectionEvent(change with { Endpoint = endpointName }, endpoint);
}