Path: redb-route/redb.Route/Core/EndpointBase.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/EndpointBase.cs
----
using System.Collections.Concurrent;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
namespace redb.Route.Core;
///
/// Base class for endpoints with built-in lightweight statistics tracking.
/// All counters use for thread safety with zero lock contention.
/// Consumers call //
/// to update counters; external code reads via .
///
/// Typed options for this endpoint.
public abstract class EndpointBase : IEndpoint, IEndpointStatistics, ISupervisingEndpoint where TOptions : EndpointOptions
{
///
public EndpointUri Uri { get; }
///
public IComponent Component { get; }
/// Typed options bound from URI parameters.
protected TOptions Options { get; }
/// Scope factory for per-exchange DI scope creation. Set by RouteContext.
public IServiceScopeFactory? ScopeFactory { get; set; }
// ── Statistics fields (Interlocked-based, zero lock contention) ──
private long _messagesIn;
private long _messagesOut;
private long _errors;
private long _bytesIn;
private long _bytesOut;
private long _rejected;
private long _cancelled;
private long _refused;
private long _lastRefusalTicks;
private volatile string _lastRefusalMessage = "";
private long _lastActivityTicks;
private readonly DateTime _startTime = DateTime.UtcNow;
// ── Error tracking ──
private long _lastErrorTicks;
private volatile string _lastErrorMessage = "";
// ── Warning tracking ──
private long _warnings;
private long _lastWarningTicks;
private volatile string _lastWarningMessage = "";
// The values this endpoint knows to be secret, longest first; read on the first recorded text.
private string[]? _secretValues;
// A secret this short would mask ordinary words and numbers of the text; it is left to the key=value masking.
private const int MinSecretLength = 4;
// ── Processing time (sliding window of last 100 durations in ticks) ──
private readonly ConcurrentQueue _processingTimes = new();
private const int MaxProcessingTimesHistory = 100;
// ── Throughput (sliding window of message timestamps in ticks, 60s) ──
private readonly ConcurrentQueue _messageTimestamps = new();
private const int ThroughputWindowSeconds = 60;
/// Creates an endpoint with parsed URI, owning component, and bound options.
/// Parsed endpoint URI.
/// The component that created this endpoint.
/// Options already bound via BindFromUri and validated.
protected EndpointBase(EndpointUri uri, IComponent component, TOptions options)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
Component = component ?? throw new ArgumentNullException(nameof(component));
Options = options ?? throw new ArgumentNullException(nameof(options));
}
///
public abstract IProducer CreateProducer();
///
public abstract IConsumer CreateConsumer(IProcessor processor);
///
public virtual Task Start(CancellationToken ct = default) => Task.CompletedTask;
///
public virtual Task Stop(CancellationToken ct = default) => Task.CompletedTask;
///
public override string ToString() => Uri.NormalizedKey;
// ── IEndpointStatistics — read properties ──
///
public long MessagesIn => Interlocked.Read(ref _messagesIn);
///
public long MessagesOut => Interlocked.Read(ref _messagesOut);
///
public long Errors => Interlocked.Read(ref _errors);
///
public long Warnings => Interlocked.Read(ref _warnings);
///
public long BytesIn => Interlocked.Read(ref _bytesIn);
///
public long BytesOut => Interlocked.Read(ref _bytesOut);
///
public long Rejected => Interlocked.Read(ref _rejected);
///
public long Cancelled => Interlocked.Read(ref _cancelled);
///
public long Refused => Interlocked.Read(ref _refused);
///
public long Reconnects => Interlocked.Read(ref _reconnects);
// ── Connection supervision ──
// The supervisors whose condition this endpoint's health takes into account; replaced as a whole (copy on write).
private ConnectionSupervisor[] _supervisors = [];
private readonly object _supervisorsLock = new();
private long _reconnects;
///
/// Creates a for one connection or link of this endpoint, with the context's
/// (RedbRoute:Reconnect; their defaults when the endpoint has no
/// context), and registers it (). A consumer creates one per connection
/// or worker when it starts and removes it with when it stops.
///
/// What is supervised, for logs and the health reason, such as wmq:ORDERS consumer worker 2.
/// Logger for the loss and recovery lines.
public ConnectionSupervisor Supervise(string name, Microsoft.Extensions.Logging.ILogger? logger)
{
var options = ((Component as ComponentBase)?.Context as RouteContext)?.ReconnectOptions
?? new Configuration.ReconnectOptions();
var supervisor = new ConnectionSupervisor(name, options, logger);
Supervise(supervisor);
return supervisor;
}
///
/// Registers a supervisor: its becomes part of this endpoint's health (the
/// worst of all registered supervisors and ) and its recoveries count in
/// . Its losses are not counted in : the supervisor's condition shows a loss
/// while it lasts, so health is Healthy again when the connection is back, and the error rate stays the rate of failed
/// messages.
///
public void Supervise(ConnectionSupervisor supervisor)
{
ArgumentNullException.ThrowIfNull(supervisor);
supervisor.AttachTo(Masked, () => Interlocked.Increment(ref _reconnects));
if ((Component as ComponentBase)?.Context is RouteContext context)
supervisor.EventSink ??= new EndpointConnectionEventSink(context, this, EndpointUri.Sanitize(Uri.BaseKey));
lock (_supervisorsLock)
{
if (Array.IndexOf(_supervisors, supervisor) < 0)
_supervisors = [.. _supervisors, supervisor];
}
}
/// Removes a supervisor registered with ; its condition no longer counts.
public void Unsupervise(ConnectionSupervisor supervisor)
{
ArgumentNullException.ThrowIfNull(supervisor);
lock (_supervisorsLock)
_supervisors = _supervisors.Where(s => !ReferenceEquals(s, supervisor)).ToArray();
}
/// The worst condition of the registered supervisors and , or null when none has one.
private (EndpointHealthStatus Status, string Reason)? WorstCondition()
{
(EndpointHealthStatus Status, string Reason)? worst = null;
foreach (var supervisor in Volatile.Read(ref _supervisors))
{
if (supervisor.Condition is { } condition && (worst is null || condition.Status > worst.Value.Status))
worst = condition;
}
if (TransportCondition is { } transport && (worst is null || transport.Status > worst.Value.Status))
worst = transport;
return worst;
}
///
public DateTime? LastRefusalTime
{
get
{
var ticks = Interlocked.Read(ref _lastRefusalTicks);
return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc);
}
}
///
public string LastRefusalMessage => _lastRefusalMessage;
///
public DateTime? LastActivity
{
get
{
var ticks = Interlocked.Read(ref _lastActivityTicks);
return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc);
}
}
///
public DateTime StartTime => _startTime;
///
public TimeSpan Uptime => DateTime.UtcNow - _startTime;
///
public TimeSpan AverageProcessingTime
{
get
{
// Snapshot the queue — ConcurrentQueue enumerator is safe
var items = _processingTimes.ToArray();
if (items.Length == 0) return TimeSpan.Zero;
var avgTicks = items.Sum() / items.Length;
return new TimeSpan(avgTicks);
}
}
///
public double ThroughputPerSecond
{
get
{
var nowTicks = DateTime.UtcNow.Ticks;
var cutoff = nowTicks - TimeSpan.TicksPerSecond * ThroughputWindowSeconds;
// Drain stale entries
while (_messageTimestamps.TryPeek(out var oldest) && oldest < cutoff)
_messageTimestamps.TryDequeue(out _);
var count = _messageTimestamps.Count;
if (count == 0) return 0.0;
// Time span from oldest remaining to now
if (!_messageTimestamps.TryPeek(out var oldestRemaining))
return 0.0;
var windowSeconds = (double)(nowTicks - oldestRemaining) / TimeSpan.TicksPerSecond;
return windowSeconds > 0 ? count / windowSeconds : 0.0;
}
}
///
public DateTime? LastErrorTime
{
get
{
var ticks = Interlocked.Read(ref _lastErrorTicks);
return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc);
}
}
///
public string LastErrorMessage => _lastErrorMessage;
///
public DateTime? LastWarningTime
{
get
{
var ticks = Interlocked.Read(ref _lastWarningTicks);
return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc);
}
}
///
public string LastWarningMessage => _lastWarningMessage;
///
public EndpointHealthStatus HealthStatus => GetHealthStatus().Status;
///
public string HealthReason => GetHealthStatus().Reason;
///
/// A state the endpoint knows from its transport and the counters cannot show, such as a broker that blocks the
/// connection the endpoint sends over. While it is not null it is the endpoint's health status and reason,
/// unless a registered reports a worse one; when both are null the status is
/// computed from the counters again.
///
/// Health checks read it on every probe: an override returns a state the endpoint already holds, and never opens a
/// connection, takes a lock a send holds or does I/O.
///
///
protected virtual (EndpointHealthStatus Status, string Reason)? TransportCondition => null;
private (EndpointHealthStatus Status, string Reason) GetHealthStatus()
{
if (WorstCondition() is { } condition)
return condition;
var lastErr = LastErrorTime;
var msgs = MessagesIn;
var errs = Errors;
// Recent errors (last 5 min)
if (lastErr.HasValue && (DateTime.UtcNow - lastErr.Value).TotalMinutes < 5)
{
var rate = msgs > 0 ? errs * 100.0 / msgs : 0;
if (rate > 10)
return (EndpointHealthStatus.Critical, $"High error rate: {rate:F1}% ({errs}/{msgs})");
return (EndpointHealthStatus.Warning, $"Recent errors (last 5 min): {errs} error(s)");
}
// No activity for > 10 min (only if there was any activity at all)
var last = LastActivity;
if (last.HasValue && (DateTime.UtcNow - last.Value).TotalMinutes > 10)
{
var idle = DateTime.UtcNow - last.Value;
return (EndpointHealthStatus.Warning, $"No activity for {idle.TotalMinutes:F0} min");
}
return (EndpointHealthStatus.Healthy, "OK");
}
///
public void ResetStatistics()
{
Interlocked.Exchange(ref _messagesIn, 0);
Interlocked.Exchange(ref _messagesOut, 0);
Interlocked.Exchange(ref _errors, 0);
Interlocked.Exchange(ref _bytesIn, 0);
Interlocked.Exchange(ref _bytesOut, 0);
Interlocked.Exchange(ref _rejected, 0);
Interlocked.Exchange(ref _cancelled, 0);
Interlocked.Exchange(ref _refused, 0);
Interlocked.Exchange(ref _reconnects, 0);
Interlocked.Exchange(ref _lastRefusalTicks, 0);
_lastRefusalMessage = "";
Interlocked.Exchange(ref _lastActivityTicks, 0);
Interlocked.Exchange(ref _lastErrorTicks, 0);
_lastErrorMessage = "";
Interlocked.Exchange(ref _warnings, 0);
Interlocked.Exchange(ref _lastWarningTicks, 0);
_lastWarningMessage = "";
while (_processingTimes.TryDequeue(out _)) { }
while (_messageTimestamps.TryDequeue(out _)) { }
}
// ── Recording helpers (thread-safe) ──
/// Record an incoming message (consumed). Thread-safe.
public void RecordMessageIn()
{
Interlocked.Increment(ref _messagesIn);
var nowTicks = DateTime.UtcNow.Ticks;
Interlocked.Exchange(ref _lastActivityTicks, nowTicks);
// Throughput sliding window
_messageTimestamps.Enqueue(nowTicks);
var cutoff = nowTicks - TimeSpan.TicksPerSecond * ThroughputWindowSeconds;
while (_messageTimestamps.TryPeek(out var oldest) && oldest < cutoff)
_messageTimestamps.TryDequeue(out _);
}
/// Record an outgoing message (produced). Thread-safe.
public void RecordMessageOut()
{
Interlocked.Increment(ref _messagesOut);
Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks);
}
/// Record a processing error. Thread-safe.
public void RecordError()
{
Interlocked.Increment(ref _errors);
var nowTicks = DateTime.UtcNow.Ticks;
Interlocked.Exchange(ref _lastActivityTicks, nowTicks);
Interlocked.Exchange(ref _lastErrorTicks, nowTicks);
}
/// Record a processing error with exception details. Thread-safe.
public void RecordError(Exception exception)
{
_lastErrorMessage = Masked(exception.Message);
RecordError();
}
/// Record a processing warning. Thread-safe.
public void RecordWarning()
{
Interlocked.Increment(ref _warnings);
Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks);
Interlocked.Exchange(ref _lastWarningTicks, DateTime.UtcNow.Ticks);
}
/// Record a processing warning with message. Thread-safe.
public void RecordWarning(string message)
{
_lastWarningMessage = Masked(message);
RecordWarning();
}
/// Record processing time of a single message. Thread-safe.
public void RecordProcessingTime(TimeSpan duration)
{
_processingTimes.Enqueue(duration.Ticks);
// Trim beyond history limit — approximate, no lock needed
while (_processingTimes.Count > MaxProcessingTimesHistory)
_processingTimes.TryDequeue(out _);
}
/// Record incoming bytes (message body size). Thread-safe.
public void RecordBytesIn(long bytes)
{
Interlocked.Add(ref _bytesIn, bytes);
}
/// Record outgoing bytes (message body size). Thread-safe.
public void RecordBytesOut(long bytes)
{
Interlocked.Add(ref _bytesOut, bytes);
}
///
public void RecordRejected()
{
Interlocked.Increment(ref _rejected);
}
///
///
/// Bumps activity but neither the error counter nor the last-error stamp: cancellation must
/// not feed the health calculation, whose "recent errors" window would otherwise mark an
/// endpoint degraded for five minutes per closed dashboard tab.
///
public void RecordCancelled()
{
Interlocked.Increment(ref _cancelled);
Interlocked.Exchange(ref _lastActivityTicks, DateTime.UtcNow.Ticks);
}
///
///
/// Bumps activity and its own stamp, never the error counter or the last-error stamp: a caller's bad request is not
/// a failure of the endpoint, and must not mark it degraded in the health calculation.
///
public void RecordRefused(string reason)
{
_lastRefusalMessage = Masked(reason);
Interlocked.Increment(ref _refused);
var nowTicks = DateTime.UtcNow.Ticks;
Interlocked.Exchange(ref _lastActivityTicks, nowTicks);
Interlocked.Exchange(ref _lastRefusalTicks, nowTicks);
}
///
/// as the endpoint statistics keep it: secret key=value pairs and URI passwords masked
/// (), and every value this endpoint knows to be secret masked wherever it
/// stands, plain or URL-escaped, such as a bot token in the path of a request URL. The secrets are the
/// options of the endpoint and the URI parameters whose names are sensitive.
///
internal string Masked(string? text)
{
var masked = EndpointUri.RedactSecrets(text);
if (masked.Length == 0)
return masked;
foreach (var secret in _secretValues ??= SecretValues())
masked = masked.Replace(secret, EndpointUri.Redacted, StringComparison.Ordinal);
return masked;
}
private string[] SecretValues()
{
var values = Options.SensitiveValues()
.Concat(Uri.RawParameters.Where(p => EndpointUri.IsSensitiveKey(p.Key)).Select(p => p.Value))
.Where(v => v.Length >= MinSecretLength);
return values
.SelectMany(v => new[] { v, System.Uri.EscapeDataString(v) })
.Distinct(StringComparer.Ordinal)
.OrderByDescending(v => v.Length)
.ToArray();
}
// ── Utility ──
/// Estimate size of exchange body in bytes (for byte-volume tracking).
internal static int EstimateBodySize(object? body)
{
if (body is null) return 0;
if (body is string str) return Encoding.UTF8.GetByteCount(str);
if (body is byte[] bytes) return bytes.Length;
if (body is ReadOnlyMemory rom) return rom.Length;
if (body is ArraySegment seg) return seg.Count;
// A stream is measured by its length when it has one; a forward-only stream cannot be measured without reading
// it, and serializing the stream object would count its properties, not its content.
if (body is Stream stream) return stream.CanSeek ? (int)Math.Min(stream.Length, int.MaxValue) : 0;
// Any other object counts as 0, as Camel counts no bytes at all: serializing it on every exchange only to count
// the bytes of the result doubled the serialization cost of an object route.
return 0;
}
}