Path: redb-route/redb.Route.SignalR/SignalRProducer.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/SignalRProducer.cs
----
using System.Diagnostics;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.SignalR;
///
/// SignalR producer. Two modes:
///
/// Client: Uses to connect to a remote SignalR hub and invoke methods.
/// Server: Uses to broadcast messages to clients of the local hub.
///
///
public class SignalRProducer : ConnectableProducer
{
private readonly SignalREndpoint _endpoint;
private readonly SignalREndpointOptions _options;
private HubConnection? _hubConnection;
private IHubContext? _hubContext;
/// Creates a SignalR producer.
public SignalRProducer(SignalREndpoint endpoint, SignalREndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
// The name reaches the log as "producer started", so a URI carrying userinfo must not print
// its password there.
protected override string ProducerName =>
$"signalr:{_options.Mode}:{EndpointUri.Sanitize(_endpoint.BuildClientUrl())}";
/// The logged producer name, so a test can pin the masking.
internal string DiagnosticName => ProducerName;
///
protected override async Task ConnectAsync(CancellationToken ct)
{
if (_options.Mode == SignalRMode.Client)
await StartClientMode(ct).ConfigureAwait(false);
else
StartServerMode();
}
///
protected override async Task DisconnectAsync(CancellationToken ct)
{
if (_hubConnection is not null)
{
try
{
await _hubConnection.StopAsync(ct).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "SignalR: error stopping hub connection");
}
await _hubConnection.DisposeAsync().ConfigureAwait(false);
_hubConnection = null;
}
_hubContext = null;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"signalr {_options.Mode} {_options.Method}", ActivityKind.Producer,
"messaging.system", "signalr",
_endpoint.Uri.NormalizedKey,
destination: _endpoint.HubPath,
operation: _options.Mode.ToString());
try
{
if (_options.Mode == SignalRMode.Client)
await ProcessClientMode(exchange, ct).ConfigureAwait(false);
else
await ProcessServerMode(exchange, ct).ConfigureAwait(false);
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the send is a stop; any other failure marks the span.
activity.RecordFailure(ex);
Logger?.LogError(ex, "SignalR send failed: hub={HubPath}, method={Method}, mode={Mode}",
_endpoint.HubPath, _options.Method, _options.Mode);
throw; // the core records the error against this endpoint
}
}
// ── Client mode ─────────────────────────────────────────────────
private async Task StartClientMode(CancellationToken ct)
{
var url = _endpoint.BuildClientUrl();
var builder = new HubConnectionBuilder()
.WithUrl(url, connectionOptions =>
{
// Configure transport
connectionOptions.Transports = _options.Transport switch
{
SignalRTransport.ServerSentEvents => HttpTransportType.ServerSentEvents,
SignalRTransport.LongPolling => HttpTransportType.LongPolling,
_ => HttpTransportType.WebSockets
};
// Configure access token
if (_options.AccessToken is not null)
{
var token = _options.AccessToken;
connectionOptions.AccessTokenProvider = () => Task.FromResult(token);
}
// Explicit and opt-in. This used to fire when ssl=false, on the theory that "TLS
// was not asked for, so there is nothing to check" — but the handler covers the
// whole SignalR transport, negotiate and redirects included, so an http:// hub
// that redirected to https:// was accepted with any certificate at all.
if (_options.TrustAllCertificates)
{
connectionOptions.HttpMessageHandlerFactory = handler =>
{
if (handler is HttpClientHandler clientHandler)
clientHandler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
return handler;
};
// The handler above covers negotiate and the long-polling / SSE transports;
// the WebSocket upgrade runs on its own ClientWebSocket and needs its own
// callback, or the connection dies at the upgrade with UntrustedRoot.
connectionOptions.WebSocketConfiguration = ws =>
ws.RemoteCertificateValidationCallback = (_, _, _, _) => true;
}
});
if (_options.Reconnect)
builder.WithAutomaticReconnect(BuildRetryPolicy());
_hubConnection = builder.Build();
await _hubConnection.StartAsync(ct).ConfigureAwait(false);
}
private async Task ProcessClientMode(IExchange exchange, CancellationToken ct)
{
if (_hubConnection is null or { State: not HubConnectionState.Connected })
{
if (_options.Reconnect && _hubConnection is not null)
{
await _hubConnection.StartAsync(ct).ConfigureAwait(false);
}
else
{
throw new InvalidOperationException("Hub connection lost and reconnect is disabled.");
}
}
var method = ResolveMethod(exchange);
var body = exchange.In.Body;
if (_options.Bridge)
{
// Bridge mode: route through RedbBridgeHub's single "Invoke(string method, object?[]? args)" entry point.
// Used when connecting to our own hub (redb.Route route-to-route).
var hubArgs = body switch
{
object?[] argsArray => argsArray,
not null => new object?[] { body },
_ => null
};
if (_options.InOut)
{
var result = await _hubConnection!.InvokeCoreAsync