Path: redb-route/redb.Route.SignalR/SignalRConsumer.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.SignalR/SignalRConsumer.cs ---- using System.Diagnostics; using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Route.Telemetry; namespace redb.Route.SignalR; /// /// SignalR consumer. Embedded Kestrel-based SignalR Hub server that accepts connections, /// receives method invocations, and dispatches them into the route processor pipeline. /// Supports JSON and MessagePack protocols, group management, InOut exchange pattern, /// and lifecycle events (Connected/Disconnected). /// public class SignalRConsumer : IConsumer { private readonly SignalREndpoint _endpoint; /// public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private readonly SignalREndpointOptions _options; private SharedHttpServerManager? _serverManager; private readonly InflightDrainGuard _drain = new(); private long _processedCount; private ILogger? _logger; /// Creates a SignalR consumer. public SignalRConsumer(SignalREndpoint endpoint, IProcessor processor, SignalREndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// Number of invocations successfully processed. public long ProcessedCount => Interlocked.Read(ref _processedCount); // ── Connection admission ─────────────────────────────────────────── private int _connections; /// /// Claims a connection slot against maxConnections. A refusal is counted in the /// endpoint's Rejected; the hub aborts the connection before the Connected lifecycle event /// can reach the pipeline. Always 'true' when the limit is off (0). /// internal bool TryAcquireConnection() { if (_options.MaxConnections <= 0) return true; var now = Interlocked.Increment(ref _connections); if (now <= _options.MaxConnections) return true; Interlocked.Decrement(ref _connections); _endpoint.RecordRejected(); _logger?.LogWarning( "SignalR hub {HubPath}: connection refused - maxConnections={Max} reached", HubPath, _options.MaxConnections); return false; } /// Releases a slot claimed by . internal void ReleaseConnection() { if (_options.MaxConnections > 0) Interlocked.Decrement(ref _connections); } /// The base URL the server is listening on. Available after Start(). public string? BaseUrl { get; private set; } /// The hub path for this consumer. public string HubPath => _endpoint.HubPath; /// The endpoint options, exposed for the bridge hub. internal SignalREndpointOptions EndpointOptions => _options; /// The service scope factory from the endpoint, for creating scoped exchanges. internal IServiceScopeFactory? ScopeFactory => _endpoint.ScopeFactory; /// /// The hub's own container (see ). The server-mode producer resolves /// IHubContext from here, so it reaches the clients of this hub and of no other. /// internal IServiceProvider? HubServices => _endpoint.HubServices; /// /// Processes an exchange through the pipeline. Called by . /// /// The invocation or lifecycle event. /// The connection's abort token. /// /// The trace context the client sent with its connection request, or default. A hub message carries no /// headers of its own, so the span of each one is a root that links this context; the connection may live for /// hours and is never the parent. /// internal async Task ProcessExchange(IExchange exchange, CancellationToken ct, ActivityContext handshake = default) { using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"signalr {_endpoint.HubPath} receive", ActivityKind.Consumer, "messaging.system", "signalr", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.HubPath, operation: "receive", links: handshake == default ? null : [new ActivityLink(handshake)]); // Pipeline statistics belong to the core: StatisticsProcessor wraps a routed consumer // and counts MessagesIn/Errors - self-recording here double-counted them (ownership audit). _drain.Increment(); try { await _processor.Process(exchange, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "SignalR message processing failed: hub={HubPath}", _endpoint.HubPath); exchange.Exception ??= ex; } finally { _drain.Decrement(); } // The connection's own abort cancelling the route is not a failure; any other cancellation, a timeout inside // the route, is. if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); Interlocked.Increment(ref _processedCount); } /// public async Task Start(CancellationToken ct = default) { // ssl=true without a certificate anywhere refuses to bind — enforced once, by the shared // host, which is the only place that sees the endpoint, the connection factory and the // host default together. _drain.Start(ct); // The hub itself was put on the listener during the endpoint's Start. Here we only make sure // the listener is running: it may already be serving HTTP, gRPC, SOAP or another hub. _serverManager = _endpoint.ServerManager; // Idempotent: the endpoint already did this during its own Start when the route context // owns the lifecycle. Repeating it keeps a hand-built consumer working. await _endpoint.EnsureHubRegisteredAsync(ct).ConfigureAwait(false); // Registered before the listener starts: a client can connect the moment it is up. if (_endpoint.Component is SignalRComponent comp) comp.RegisterConsumer(this); try { await _serverManager.EnsureStarted(_options.Host, _options.Port, ct).ConfigureAwait(false); } catch { if (_endpoint.Component is SignalRComponent failed) failed.UnregisterConsumer(this); await _endpoint.ReleaseHubRegistrationAsync().ConfigureAwait(false); _drain.Dispose(); throw; } BaseUrl = _serverManager.GetBaseUrl(_options.Host, _options.Port) ?? BuildBaseUrl(); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("SignalR consumer started: {Url}{Path}", BaseUrl, _endpoint.HubPath); } /// public async Task Stop(CancellationToken ct = default) { // Stop accepting new invocations: the hub can no longer find this consumer. if (_endpoint.Component is SignalRComponent comp) comp.UnregisterConsumer(this); // Drain invocations already inside the pipeline before the listener can go away, // so a deploy does not cut them mid-flight. await _drain.DrainAsync(ct, _logger, $"signalr://{_endpoint.HubPath}").ConfigureAwait(false); // Take the hub off the listener before asking it to stop: until then the listener has an // occupant, and a later Start must put the hub back. Its connections close; the other hubs // and routes on the listener keep theirs. await _endpoint.ReleaseHubRegistrationAsync().ConfigureAwait(false); // The listener stops only when the last route AND the last hub on it are gone: HTTP or // another hub may still be serving this port. if (_serverManager is not null) { await _serverManager.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false); _serverManager = null; } _drain.Dispose(); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("SignalR consumer stopped"); } private string BuildBaseUrl() { var scheme = _options.Ssl ? "https" : "http"; var host = _options.Host == "0.0.0.0" ? "127.0.0.1" : _options.Host; return $"{scheme}://{host}:{_options.Port}"; } }