Bundle: redb-route / redb.Route.SignalR (redb.Route.SignalR.txt), 14 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.SignalR/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
using redb.Route.Http;
namespace redb.Route.SignalR;
///
/// Extension methods for registering the SignalR component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the SignalR component with the route context. The hub is served by the shared
/// Kestrel host, so it can share a port with HTTP, gRPC, SOAP and AS2 routes.
///
public static IServiceCollection AddRedbRouteSignalR(this IServiceCollection services)
=> AddRedbRouteSignalR(services, null);
///
/// Registers the SignalR component and lets the host configure its hubs.
///
/// This is the seam for everything the connector deliberately does not depend on: a backplane
/// for scale-out, and authentication. A hub keeps its connections and groups in the memory of
/// one process, so with more than one replica a backplane is required: without it a
/// broadcast only reaches the clients attached to the replica that sent it.
///
///
/// services.AddRedbRouteSignalR(o =>
/// {
/// o.UseRedisBackplane("redis:6379"); // redb.Route.SignalR.StackExchangeRedis
/// o.Authenticate = async ctx => await myJwtValidator.ValidateAsync(
/// ctx.Request.Query["access_token"]);
/// });
///
///
public static IServiceCollection AddRedbRouteSignalR(
this IServiceCollection services,
Action? configure)
{
var registration = new SignalRRegistrationOptions();
configure?.Invoke(registration);
// The hub multiplexes onto the same Kestrel as HTTP/gRPC/SOAP/AS2 (idempotent call).
services.AddRedbRouteHttpHosting();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var component = sp.GetRequiredService();
component.ServerManager = sp.GetRequiredService();
component.HubServicesConfigurator = registration.HubServices;
component.Authenticate = registration.Authenticate;
context.AddComponent(component);
});
return services;
}
}
///
/// Host-supplied configuration for the SignalR hubs. Everything here is a delegate on
/// purpose: the connector stays free of Redis, Azure and authentication dependencies, and the
/// host, which knows its own infrastructure, supplies them.
///
public sealed class SignalRRegistrationOptions
{
internal Action? HubServices { get; private set; }
///
/// Authenticates a hub connection. Returns the principal to attach to the request (its
/// NameIdentifier claim becomes SignalR's UserIdentifier, which is what makes
/// Clients.User(...) and the redbSignalR.UserId header work), or null to reject
/// the handshake with 401 before the connection is upgraded.
///
/// Browsers cannot set headers on a WebSocket handshake, so a token normally arrives in the
/// access_token query parameter: read it from there and from the Authorization header.
///
///
/// The principal is also put on every exchange the hub produces (ExchangePrincipal). Build its
/// identity with an authentication type (new ClaimsIdentity(claims, "Bearer")): code that reads
/// the principal treats an identity that is not authenticated as anonymous.
///
///
public Func>? Authenticate { get; set; }
///
/// Adds services to the container of each hub: a SignalR backplane, extra protocols, an
/// IUserIdProvider, hosted services, and so on. Every consumer endpoint has a container of
/// its own, so runs once per hub, with the hub it is for. The container
/// does NOT see the services of the application hosting the route context: anything the hub needs
/// must be registered here.
///
/// For a Redis backplane prefer UseRedisBackplane from the
/// redb.Route.SignalR.StackExchangeRedis package: it keys the channels on the hub path. A
/// backplane added here by hand shares its channels between every hub of the same hub class, so
/// the hubs of one listener would see each other's broadcasts; keying its channels on
/// is then the host's job.
///
///
public SignalRRegistrationOptions ConfigureHubServices(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
var previous = HubServices;
HubServices = previous is null
? configure
: (s, hub) => { previous(s, hub); configure(s, hub); };
return this;
}
}
Path: redb-route/redb.Route.SignalR/Fluent/SignalR.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/Fluent/SignalR.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.SignalR;
///
/// Fluent entry point for SignalR endpoints.
///
/// // Consumer — listen for SignalR connections (hub server):
/// .From(SignalR.Hub("0.0.0.0:5000/chatHub").InOut().MessagePack())
///
/// // Producer (client) — connect to a remote SignalR hub:
/// .To(SignalR.Connect("api.example.com:5000/chatHub").Method("Send").Ssl())
///
/// // Producer (server) — broadcast to connected clients via local hub:
/// .To(SignalR.Broadcast("0.0.0.0:5000/chatHub").Method("Notify").Group("room1"))
///
///
public static class SignalR
{
/// Listen for SignalR connections — start a hub server (consumer).
/// Bind address, e.g. 0.0.0.0:5000/chatHub.
public static SignalRBuilder Hub(string hostPortPath) => new(hostPortPath);
/// Connect to a remote SignalR hub (producer, client mode).
/// Target address, e.g. api.example.com:5000/chatHub.
public static SignalRBuilder Connect(string hostPortPath) => new(hostPortPath, SignalRMode.Client);
/// Broadcast to clients of a local hub (producer, server mode).
/// Hub address matching the consumer, e.g. 0.0.0.0:5000/chatHub.
public static SignalRBuilder Broadcast(string hostPortPath) => new(hostPortPath, SignalRMode.Server);
}
/// Fluent builder for SignalR endpoint URIs. Scheme: signalr.
public sealed class SignalRBuilder
{
private readonly string _hostPortPath;
private SignalRMode? _mode;
// Common
private string? _method;
private bool? _inOut;
// Transport
private SignalRTransport? _transport;
private bool? _messagePack;
private int? _maxConnections;
private int? _maxParallelInvocationsPerClient;
// Groups / targeting
private string? _defaultGroup;
private string? _targetType;
private string? _targetGroup;
// TLS
private bool _ssl;
private string? _sslCertPath;
private string? _sslCertPassword;
private bool _trustAllCertificates;
// Client: reconnect
private bool _reconnect;
private int? _reconnectInterval;
private int? _maxReconnectAttempts;
// Client: auth
private string? _accessToken;
// Client: bridge mode (default true = route through RedbBridgeHub)
private bool _bridge = true;
internal SignalRBuilder(string hostPortPath, SignalRMode? mode = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(hostPortPath);
_hostPortPath = hostPortPath;
_mode = mode;
}
// ── Common ──────────────────────────────────────────────────────
/// Hub method name to invoke/listen on.
public SignalRBuilder Method(string method) { _method = method; return this; }
/// Hub method name from an expression.
public SignalRBuilder Method(IExpression expr) { _method = expr.ToTemplateString(); return this; }
/// Enable request-response (InOut) exchange pattern.
public SignalRBuilder InOut(bool value = true) { _inOut = value; return this; }
// ── Transport ───────────────────────────────────────────────────
/// Force specific transport type.
public SignalRBuilder Transport(SignalRTransport transport) { _transport = transport; return this; }
/// Enable MessagePack protocol.
public SignalRBuilder MessagePack(bool value = true) { _messagePack = value; return this; }
/// Maximum hub connections (server mode); a connection over the limit is aborted at OnConnected. 0 = unlimited.
public SignalRBuilder MaxConnections(int max) { _maxConnections = max; return this; }
/// SignalR MaximumParallelInvocationsPerClient; 0 = SignalR default (per-client serial).
public SignalRBuilder MaxParallelInvocationsPerClient(int max) { _maxParallelInvocationsPerClient = max; return this; }
// ── Groups / targeting ──────────────────────────────────────────
/// Default group for auto-join on connect (consumer).
public SignalRBuilder DefaultGroup(string group) { _defaultGroup = group; return this; }
/// Target type for server-mode broadcast: all, group, user, connection.
public SignalRBuilder Target(string targetType) { _targetType = targetType; return this; }
/// Target type from an expression.
public SignalRBuilder Target(IExpression expr) { _targetType = expr.ToTemplateString(); return this; }
/// Target group name for server-mode broadcast.
public SignalRBuilder Group(string group) { _targetType = "group"; _targetGroup = group; return this; }
/// Target group name from an expression.
public SignalRBuilder Group(IExpression expr) { _targetType = "group"; _targetGroup = expr.ToTemplateString(); return this; }
// ── TLS ─────────────────────────────────────────────────────────
/// Enable SSL/TLS.
public SignalRBuilder Ssl() { _ssl = true; return this; }
/// Path to SSL certificate.
public SignalRBuilder SslCertPath(string path) { _sslCertPath = path; return this; }
/// SSL certificate password.
public SignalRBuilder SslCertPassword(string password) { _sslCertPassword = password; return this; }
///
/// Producer: accept any server certificate, including a self-signed one. Explicit on purpose --
/// this used to switch itself on whenever ssl was NOT set.
///
public SignalRBuilder TrustAllCertificates() { _trustAllCertificates = true; return this; }
// ── Client reconnect ────────────────────────────────────────────
/// Enable auto-reconnect (client mode).
public SignalRBuilder Reconnect(int intervalMs = 5000, int maxAttempts = 0)
{
_reconnect = true;
_reconnectInterval = intervalMs;
_maxReconnectAttempts = maxAttempts;
return this;
}
/// Access token for authentication (client mode).
public SignalRBuilder AccessToken(string token) { _accessToken = token; return this; }
///
/// Direct mode — call external hub methods by name instead of routing through the bridge.
/// Equivalent to bridge=false. Use when connecting to third-party SignalR hubs.
///
public SignalRBuilder Direct() { _bridge = false; return this; }
// ── Build ───────────────────────────────────────────────────────
/// Builds the endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("signalr:");
sb.Append(_hostPortPath);
var sep = '?';
void Append(string key, string v)
{
sb.Append(sep);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(v));
sep = '&';
}
void AppendStr(string key, string? v) { if (v is not null) Append(key, v); }
void AppendInt(string key, int? v) { if (v.HasValue) Append(key, v.Value.ToString()); }
void AppendBool(string key, bool v) { if (v) Append(key, "true"); }
void AppendBoolN(string key, bool? v) { if (v.HasValue) Append(key, v.Value.ToString().ToLowerInvariant()); }
if (_mode is not null) Append("mode", _mode.Value.ToString().ToLowerInvariant());
AppendStr("method", _method);
AppendBoolN("inOut", _inOut);
if (_transport is not null) Append("transport", _transport.Value.ToString());
AppendBoolN("messagePack", _messagePack);
AppendStr("defaultGroup", _defaultGroup);
AppendStr("targetType", _targetType);
AppendStr("targetGroup", _targetGroup);
AppendBool("ssl", _ssl);
AppendStr("sslCertPath", _sslCertPath);
AppendStr("sslCertPassword", _sslCertPassword);
AppendBool("trustAllCertificates", _trustAllCertificates);
AppendBool("reconnect", _reconnect);
AppendInt("reconnectInterval", _reconnectInterval);
AppendInt("maxReconnectAttempts", _maxReconnectAttempts);
AppendStr("accessToken", _accessToken);
AppendInt("maxConnections", _maxConnections);
AppendInt("maxParallelInvocationsPerClient", _maxParallelInvocationsPerClient);
if (!_bridge) Append("bridge", "false");
return sb.ToString();
}
/// Implicit conversion to string URI.
public static implicit operator string(SignalRBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.SignalR/README.md
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/README.md
----
# redb.Route.SignalR
> Documentation and articles:
SignalR transport for the **redb.Route** ESB framework.
Provides an embedded Kestrel-based SignalR Hub **consumer** (server) and two **producer** modes:
client (`HubConnection` to remote hub) and server (`IHubContext` broadcast to connected clients).
Supports JSON and MessagePack protocols, WebSocket / SSE / LongPolling transports, group management,
InOut exchange pattern, lifecycle events, auto-reconnect, and TLS.
[](https://www.nuget.org/packages/redb.Route.SignalR)
[](../../LICENSE)
| | |
|---|---|
| **Scheme** | `signalr` |
| **NuGet** | `redb.Route.SignalR` |
| **Dependencies** | Microsoft.AspNetCore.App, Microsoft.AspNetCore.SignalR.Client and .Protocols.MessagePack (the ASP.NET Core line of the target framework) |
| **Backplane** | [redb.Route.SignalR.StackExchangeRedis](../redb.Route.SignalR.StackExchangeRedis/README.md) |
| **Namespace** | `redb.Route.SignalR` |
---
## Quick Start
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteSignalR();
// Hub server — accept connections, process method invocations
route.AddRoutes(r => r
.From(SignalR.Hub("0.0.0.0:5000/chatHub").InOut())
.RouteId("signalr-server")
.Process(e =>
{
var method = e.In.Headers["redbSignalR.Method"];
e.Out = new Message($"Echo: {e.In.Body}");
}));
// Client — connect to a remote hub and send messages
route.AddRoutes(r => r
.From("direct:send")
.RouteId("signalr-client")
.To(SignalR.Connect("api.example.com:5000/chatHub")
.Method("Send").Reconnect()));
// Server broadcast — push to all connected clients of the local hub
route.AddRoutes(r => r
.From("direct:notify")
.RouteId("signalr-broadcast")
.To(SignalR.Broadcast("0.0.0.0:5000/chatHub")
.Method("Notify")));
});
```
---
## Architecture
### Consumer (Hub Server)
The consumer serves a `RedbBridgeHub` — an internal bridge hub that converts all SignalR
invocations into redb.Route exchanges — on the **shared Kestrel host**
(`redb.Route.Http.Hosting`), the same listener HTTP, gRPC, SOAP and AS2 routes use. So the hub
and the REST API it pushes for sit on one port, behind one proxy and one TLS termination:
```csharp
From("http://0.0.0.0:8080/api/orders") // REST
From("signalr://0.0.0.0:8080/hub") // push, same port
From("signalr://0.0.0.0:8080/admin") // another hub, same port again
```
Clients call `Invoke("MethodName", arg1, arg2, ...)` on the hub. The hub creates an exchange
with the method name and arguments, processes it through the route pipeline, and optionally returns
the `Out` body as the method result (when `InOut` is enabled).
Lifecycle events (`OnConnectedAsync`, `OnDisconnectedAsync`) are also dispatched as exchanges
with the `redbSignalR.Event` header set to `"Connected"` or `"Disconnected"`.
### Hubs on a shared listener
Only a consumer endpoint (`SignalR.Hub(...)`, `From("signalr:...")`) puts a hub on the listener. A broadcast endpoint
(`SignalR.Broadcast(...)`, `mode=server`) sends through the hub of the consumer on the same address and maps nothing
of its own.
Every hub is served from a **service container of its own**, built when its consumer starts and disposed when it
stops. That container holds what SignalR keeps per hub: the connection manager, the lifetime manager behind
`Clients.All`, `Group` and `User`, the protocols, the hub options and the backplane. As a result:
- **A hub joins a listener that is already serving**, whoever started it. On a Tsak worker several route contexts take
one `SharedHttpServerManager` from the worker's container, and the order they start in does not matter: the hub of
one context goes onto the port the HTTP routes of another context already serve, and the other way round.
- **A hub leaves without touching anything else.** When its context stops or reloads, its endpoints come off the
listener, its own connections are closed, and the other hubs and routes on the port keep their connections. The
hub of the restarted context is a new one; nothing answers from the mapping of the previous instance.
- **Hubs are isolated from each other.** A broadcast of `/orders` (All, Group or User) reaches the clients of `/orders`
only, even when `/alerts` on the same port has the same users in groups of the same name.
- **Protocols and transports belong to one hub.** `messagePack=true` and `transport=LongPolling` apply to that hub;
another hub on the same port keeps its own.
- **The hub path wins over the route table.** A hub on `/hub/ui` is served by the hub even when an HTTP route of the
same port matches `/hub/ui/negotiate`; when the hub leaves, the route table serves the path again.
What a hub does not change is the listener itself. Its pipeline (trusted proxies, CORS, the caller's principal,
WebSocket upgrades) is built when the listener starts, and so is its TLS: the first route or hub registered on a port
decides whether it is HTTPS. Every listener accepts WebSocket upgrades.
The hub's container does **not** see the services of the application hosting the route context. A hub request runs in
a scope of the hub's container, so `Context.GetHttpContext().RequestServices` resolves from there, not from the
application; what the pipeline needs from the application it takes from the exchange (`Exchange.Create` with the
consumer's scope factory), and what the hub itself needs is registered with `ConfigureHubServices`.
### Producer — Client Mode (default)
Uses `HubConnection` to connect to a remote SignalR hub and invoke methods.
Two sub-modes:
- **Bridge** (default, `bridge=true`) — calls `Invoke(method, args)` on the bridge hub entry point.
Used when connecting to another redb.Route hub.
- **Direct** (`bridge=false`) — calls the hub method directly by name. Used when connecting to
external (third-party) SignalR hubs with real named methods.
### Producer — Server Mode
Uses `IHubContext` to broadcast messages to clients connected to the local hub.
Requires a consumer running on the same endpoint. Target audience configurable: All, Group, User, Connection.
---
## URI Format
```
signalr:host:port/hubPath?option=value&...
```
**Consumer** (hub server):
```
signalr:0.0.0.0:5000/chatHub?inOut=true&messagePack=true&defaultGroup=lobby
```
**Producer — Client** (connect to remote):
```
signalr:api.example.com:5000/chatHub?mode=client&method=Send&reconnect=true
```
**Producer — Server** (broadcast to local clients):
```
signalr:0.0.0.0:5000/chatHub?mode=server&method=Notify&targetType=group&targetGroup=room1
```
---
## DSL
```csharp
using redb.Route.SignalR;
// Consumer — start hub server
SignalR.Hub("0.0.0.0:5000/chatHub")
.InOut()
.MessagePack()
.DefaultGroup("lobby")
// Producer — connect to remote hub (client mode)
SignalR.Connect("api.example.com:5000/chatHub")
.Method("Send")
.Reconnect(intervalMs: 3000, maxAttempts: 10)
.AccessToken("jwt-token")
.Ssl()
// Producer — connect to external (non-redb) hub
SignalR.Connect("external.host:5000/hub")
.Method("SendMessage")
.Direct()
// Producer — broadcast to local hub clients (server mode)
SignalR.Broadcast("0.0.0.0:5000/chatHub")
.Method("Notify")
.Group("room1")
```
The builder implements `implicit operator string` — pass directly to `.From()` / `.To()`.
---
## Exchange Pattern
### InOnly (default)
Client invocations are fire-and-forget. The hub returns `null`.
### InOut
When `inOut=true`, the consumer returns the `exchange.Out.Body` as the hub method result:
```csharp
route.AddRoutes(r => r
.From(SignalR.Hub("0.0.0.0:5000/rpcHub").InOut())
.RouteId("rpc")
.Process(e =>
{
var input = (long)e.In.Body!;
e.Out = new Message(input * 2);
}));
```
Client calls `Invoke("Multiply", 21)` → receives `42`.
---
## Group Management
### Default Group
Auto-join all connections to a group on connect:
```csharp
SignalR.Hub("0.0.0.0:5000/chatHub").DefaultGroup("lobby")
```
### Dynamic Group Management
Set headers on the exchange `Out` (or `In`) to add/remove the current connection from groups:
| Header | Action |
|---|---|
| `redbSignalR.AddToGroup` | Add connection to the named group |
| `redbSignalR.RemoveFromGroup` | Remove connection from the named group |
```csharp
.Process(e =>
{
e.Out = new Message("Joined room");
e.Out.Headers["redbSignalR.AddToGroup"] = "premium-users";
})
```
### Groups do not survive a reconnect
A group membership belongs to a connection, and a reconnect is a new connection with a new id, so
whatever the client joined is gone. SignalR does not restore it and neither can a backplane —
nobody remembers who was in what. Two ways to put it back, both from the connector:
```csharp
// Everyone lands in the same group: declare it, and every connection joins on connect.
SignalR.Hub("0.0.0.0:5000/chatHub").DefaultGroup("lobby")
// Membership depends on who is connecting: rejoin on the Connected event, which the hub
// dispatches as an exchange like any other.
route.AddRoutes(r => r
.From(SignalR.Hub("0.0.0.0:5000/chatHub"))
.RouteId("rejoin")
.Filter(Header(SignalRHeaders.Event).isEqualTo("Connected"))
.Process(async (e, ct) =>
{
var user = e.In.GetHeader(SignalRHeaders.UserId);
e.Out = new Message(null);
e.Out.Headers["redbSignalR.AddToGroup"] = await groups.ResolveFor(user);
}));
```
---
## Server-Mode Broadcasting
Target audiences for server-mode producer:
| TargetType | Header Override | Description |
|---|---|---|
| `All` (default) | `redbSignalR.Target = "All"` | Send to all connected clients |
| `Group` | `redbSignalR.Group = "name"` | Send to a specific group |
| `User` | `redbSignalR.TargetUser = "userId"` | Send to a specific user |
| `Connection` | `redbSignalR.TargetConnection = "connId"` | Send to a specific connection |
```csharp
// Broadcast to a specific group
route.AddRoutes(r => r
.From("direct:alert")
.RouteId("group-notify")
.SetHeader("redbSignalR.Group", "admins")
.To(SignalR.Broadcast("0.0.0.0:5000/chatHub")
.Method("Alert")));
```
Server mode pushes through the hub of the consumer serving the same address, so **the consumer
has to be running**: a producer that finds none refuses to start rather than pushing into
nothing. In a route context that happens by itself — consumers start with the context, producers
resolve lazily on the first message.
---
## Reconnect (Client Mode)
```csharp
SignalR.Connect("host:5000/hub")
.Method("Send")
.Reconnect(intervalMs: 5000, maxAttempts: 0) // 0 = unlimited
```
Uses a fixed-interval retry policy. When connection drops and `Reconnect` is enabled,
the producer automatically re-establishes the connection before sending.
---
## TLS
### Consumer (Server)
```csharp
SignalR.Hub("0.0.0.0:5443/hub")
.Ssl()
.SslCertPath("/certs/server.pfx")
.SslCertPassword("password")
```
Configures Kestrel to listen with HTTPS using the PFX certificate.
### Producer (Client)
```csharp
SignalR.Connect("host:5443/hub")
.Ssl()
```
Switches the connection URL scheme to `https://`.
`ssl=true` on a consumer **requires** `sslCertPath`: without it the listener would be plain HTTP
while the log said `https://`, so the consumer refuses to start instead.
To reach a hub with a self-signed certificate (staging), say so out loud:
```csharp
SignalR.Connect("staging:5443/hub").Ssl().TrustAllCertificates()
```
It is never implied by anything else, and it disables certificate validation for the whole
transport — negotiate, redirects and the WebSocket upgrade alike.
---
## Authentication
### Producer (client) — sending a token
```csharp
SignalR.Connect("host:5000/hub")
.Method("Send")
.AccessToken("eyJhbGciOiJIUzI1...")
```
Passed via `AccessTokenProvider` on the `HubConnection`.
### Consumer (hub) — validating one
The process hosting a route context is a generic host, not an ASP.NET application, so there is no
`AddAuthentication`/`AddJwtBearer` to hang the hub off. The host supplies a delegate instead:
```csharp
services.AddRedbRouteSignalR(o =>
{
o.Authenticate = async ctx =>
{
// A browser cannot set headers on a WebSocket handshake, so the token normally arrives
// in the query string; a service client will use the header. Read both.
var header = ctx.Request.Headers.Authorization.ToString();
var token = header.StartsWith("Bearer ")
? header["Bearer ".Length..]
: ctx.Request.Query["access_token"].ToString();
return await myJwtValidator.ValidateAsync(token); // null → 401
};
});
```
Returning null rejects the handshake with 401 **before** the connection is upgraded. The
principal's `NameIdentifier` claim becomes SignalR's `UserIdentifier`, which is what makes
`Clients.User(...)` (`targetType=User`) and the `redbSignalR.UserId` header work. The principal itself
is on every exchange the hub produces (`ExchangePrincipal.Get(exchange)`); an anonymous connection
carries none. Build the identity with an authentication type (`new ClaimsIdentity(claims, "Bearer")`):
code that reads the principal treats an identity that is not authenticated as anonymous.
Without this delegate, a caller identified by the shared host
(`AddRedbRouteHttpHosting(o => o.ResolvePrincipal = ...)`) is handed to SignalR the same way, but an
anonymous handshake is not rejected. When the delegate is set, it takes precedence.
---
## Scale-out: a backplane is mandatory with more than one replica
A hub keeps its connections and groups in the memory of one process. With two replicas behind a
load balancer, a broadcast from one reaches only the clients attached to that one — the other
replica's clients hear nothing.
For Redis, add [redb.Route.SignalR.StackExchangeRedis](../redb.Route.SignalR.StackExchangeRedis/README.md):
```csharp
services.AddRedbRouteSignalR(o => o.UseRedisBackplane("redis:6379"));
```
It keys the Redis channels of every hub on its path, so the hubs of one listener stay apart on one Redis, and it
refuses to start a second hub of the process that would share the channels of another.
The connector itself does not depend on Redis or Azure SignalR. `ConfigureHubServices` is the seam for any other
backplane, protocol or service a hub needs; it runs once per hub, with that hub's description:
```csharp
services.AddRedbRouteSignalR(o => o.ConfigureHubServices((services, hub) =>
services.AddSignalR().AddStackExchangeRedis("redis:6379", redis =>
redis.Configuration.ChannelPrefix = RedisChannel.Literal("myapp" + hub.Path))));
```
A backplane added by hand is the host's responsibility: SignalR names its channels after the hub class, every hub of
this connector is the same class, so without a prefix that includes `hub.Path` the hubs of one listener would see each
other's broadcasts through Redis.
The container `ConfigureHubServices` fills belongs to the hub and does **not** see the services of the application
hosting the route context, so anything the hub needs must be registered here.
---
## Configuration Reference
| Parameter | Type | Default | Description |
|---|---|---|---|
| `host` | string | `"0.0.0.0"` | Bind/connect host (parsed from URI path) |
| `port` | int | `5000` | Bind/connect port (parsed from URI path) |
| `mode` | enum | `Client` | Producer mode: `Client` or `Server` |
| `method` | string | `null` | Hub method to invoke/filter |
| `inOut` | bool | `false` | Request-response exchange pattern |
| `bridge` | bool | `true` | Route through bridge hub (client mode). `false` = direct method calls |
| `transport` | enum | `WebSockets` | `WebSockets`, `ServerSentEvents`, `LongPolling` |
| `messagePack` | bool | `false` | Register the MessagePack protocol beside JSON (JSON stays the base, so existing clients keep working) |
| `defaultGroup` | string | `null` | Auto-join group on connect (consumer) |
| `targetType` | string | `"All"` | Broadcast target: `All`, `Group`, `User`, `Connection` (server mode) |
| `targetGroup` | string | `null` | Default target group (server mode) |
| `ssl` | bool | `false` | Enable TLS. On a consumer, requires `sslCertPath` |
| `sslCertPath` | string | `null` | PFX certificate path (consumer) |
| `sslCertPassword` | string | `null` | PFX certificate password |
| `trustAllCertificates` | bool | `false` | Producer: accept any server certificate (self-signed staging). Explicit, never implied |
| `reconnect` | bool | `false` | Auto-reconnect on disconnect (client mode) |
| `reconnectInterval` | int | `5000` | Reconnect interval in ms |
| `maxReconnectAttempts` | int | `0` | Max reconnect attempts (0 = unlimited: `WithAutomaticReconnect` keeps retrying in the background, which is its normal mode) |
| `accessToken` | string | `null` | JWT token for client auth |
---
## Headers Reference
### Common (set by consumer)
| Header | Description |
|---|---|
| `redbSignalR.Method` | Hub method name |
| `redbSignalR.ConnectionId` | SignalR connection ID |
| `redbSignalR.UserId` | Authenticated user ID |
| `redbSignalR.Event` | Lifecycle event: `"Connected"` / `"Disconnected"` |
| `redbSignalR.HubPath` | Hub path (e.g. `/chatHub`) |
| `redbSignalR.Protocol` | `"json"` or `"messagepack"` |
| `redbSignalR.Ssl` | `"True"` / `"False"` |
| `redbSignalR.DisconnectError` | Error message from disconnection |
### Producer Targeting
| Header | Description |
|---|---|
| `redbSignalR.Target` | Broadcast audience: `"All"`, `"Group"`, `"User"`, `"Connection"` |
| `redbSignalR.Group` | Target group name |
| `redbSignalR.TargetConnection` | Target connection ID |
| `redbSignalR.TargetUser` | Target user ID |
### Group Management (post-processing commands)
| Header | Description |
|---|---|
| `redbSignalR.AddToGroup` | Add current connection to specified group |
| `redbSignalR.RemoveFromGroup` | Remove current connection from specified group |
---
## DI Registration
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteSignalR();
// ...
});
```
Registers the `SignalRComponent` (scheme `signalr`).
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new SignalRConnectionFactory
{
AccessToken = secrets.HubToken,
});
// signalr://https://hub.internal/notify?connectionFactory=prod
```
## Concurrency limits
SignalR concurrency is connections × invocations, so the levers differ from plain HTTP:
| Parameter | Default | Description |
|---|---|---|
| `maxConnections` | `0` (unlimited) | Max hub connections; an over-limit connection is aborted at OnConnected — before the `Connected` lifecycle event reaches the pipeline — and counted in the endpoint's `Rejected` |
| `maxParallelInvocationsPerClient` | `0` (SignalR default = 1) | SignalR's own per-client invocation parallelism |
With the defaults one client's invocations are serial (SignalR's own default) and the number of
clients is unbounded; `maxConnections` is the coarse lever, the per-client setting the fine one.
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `signalr` and
`redb.route.endpoint`:
- **Consumer.** One `Consumer` span, `signalr {hubPath} receive`, per exchange that reaches the route: each invocation
and the `Connected` / `Disconnected` events. A hub message carries no headers, so the span is a root; when the client
sent `traceparent` with its connection request, every span of that connection links that context. The connection
itself, which may live for hours, is never the parent. A failed route marks the span an error; the connection's own
abort cancelling the route does not.
- **Producer.** One `Producer` span per send, `signalr {mode} {method}`; an error when the send fails, unless our own
token cancelled it. No trace context is written to the hub message.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.SignalR/RedbBridgeHub.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/RedbBridgeHub.cs
----
using System.Diagnostics;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.SignalR;
///
/// Internal bridge hub that converts SignalR invocations into redb.Route exchanges.
/// Not subclassed by users — acts as a generic bridge (like gRPC RedbServiceImpl).
///
/// Clients call Invoke("MethodName", arg1, arg2, ...) — the hub creates an exchange
/// with the method name and arguments, processes it through the pipeline, and returns
/// the Out body as the method result (when InOut is enabled).
///
///
internal sealed class RedbBridgeHub(SignalREndpoint endpoint) : Hub
{
private const string HandshakeTraceItem = "__redb_handshake_trace";
///
/// Called by SignalR clients. All client method invocations are routed here.
///
/// Hub method name the client wants to invoke.
/// Arguments passed by the client.
/// Result from the pipeline (when InOut), otherwise null.
public async Task