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. [![NuGet](https://img.shields.io/nuget/v/redb.Route.SignalR?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.SignalR) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../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 Invoke(string method, object?[]? args) { var consumer = ResolveConsumer() ?? throw new HubException("SignalRConsumer not available for this hub path."); var options = consumer.EndpointOptions; // If a method filter is set, reject non-matching invocations if (options.Method is not null && !options.Method.Equals(method, StringComparison.OrdinalIgnoreCase)) { throw new HubException($"Method '{method}' is not supported on this hub."); } // Normalize args: deserialize any JsonElement values to basic .NET types var normalizedArgs = NormalizeArgs(args); var body = normalizedArgs switch { null or { Length: 0 } => (object?)null, { Length: 1 } => normalizedArgs[0], _ => normalizedArgs }; var message = new Message(body); message.Headers[SignalRHeaders.Method] = method; message.Headers[SignalRHeaders.ConnectionId] = Context.ConnectionId; message.Headers[SignalRHeaders.HubPath] = consumer.HubPath; message.Headers[SignalRHeaders.Ssl] = options.Ssl.ToString(); message.Headers[SignalRHeaders.Protocol] = options.MessagePack ? "messagepack" : "json"; if (Context.UserIdentifier is not null) message.Headers[SignalRHeaders.UserId] = Context.UserIdentifier; var exchange = Exchange.Create(message, consumer.ScopeFactory); ExchangePrincipal.Set(exchange, CallerPrincipal()); exchange.Pattern = options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly; try { await consumer.ProcessExchange(exchange, Context.ConnectionAborted, HandshakeTrace()).ConfigureAwait(false); // Post-process: group management commands await HandleGroupCommands(exchange).ConfigureAwait(false); if (exchange.Exception is not null && !exchange.ExceptionHandled) throw new HubException(exchange.Exception.Message); // InOut: return Out body if (options.InOut && exchange.HasOut && exchange.Out!.Body is not null) return exchange.Out.Body; return null; } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// public override async Task OnConnectedAsync() { var consumer = ResolveConsumer(); if (consumer is null) { await base.OnConnectedAsync(); return; } // Admission: a connection over maxConnections is aborted here — // no group membership, no Connected event, nothing reaches the pipeline. The marker keeps // OnDisconnected from releasing a slot this connection never held. if (!consumer.TryAcquireConnection()) { Context.Abort(); return; } Context.Items["__redb_conn_slot"] = true; // The connection request is the only place a client can put trace headers; every message span links it. if (Context.GetHttpContext() is { } http) { var handshake = RouteTelemetryExtensions.ExtractTraceContext(http.Request.Headers, ReadHeader); if (handshake != default) Context.Items[HandshakeTraceItem] = handshake; } // Auto-add to default group if (consumer.EndpointOptions.DefaultGroup is not null) { await Groups.AddToGroupAsync(Context.ConnectionId, consumer.EndpointOptions.DefaultGroup) .ConfigureAwait(false); } // Fire Connected event through pipeline var message = new Message(null); message.Headers[SignalRHeaders.Event] = "Connected"; message.Headers[SignalRHeaders.ConnectionId] = Context.ConnectionId; message.Headers[SignalRHeaders.HubPath] = consumer.HubPath; if (Context.UserIdentifier is not null) message.Headers[SignalRHeaders.UserId] = Context.UserIdentifier; var exchange = Exchange.Create(message, consumer.ScopeFactory); ExchangePrincipal.Set(exchange, CallerPrincipal()); try { await consumer.ProcessExchange(exchange, Context.ConnectionAborted, HandshakeTrace()).ConfigureAwait(false); await HandleGroupCommands(exchange).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } await base.OnConnectedAsync(); } /// public override async Task OnDisconnectedAsync(Exception? exception) { var consumer = ResolveConsumer(); if (consumer is null) { await base.OnDisconnectedAsync(exception); return; } // Release the admission slot only if OnConnected actually claimed one (see the marker). // A refused connection (no marker under an active limit) also gets NO Disconnected event: // the pipeline never saw it connect, so it must not see it disconnect. if (Context.Items.ContainsKey("__redb_conn_slot")) consumer.ReleaseConnection(); else if (consumer.EndpointOptions.MaxConnections > 0) { await base.OnDisconnectedAsync(exception).ConfigureAwait(false); return; } var message = new Message(null); message.Headers[SignalRHeaders.Event] = "Disconnected"; message.Headers[SignalRHeaders.ConnectionId] = Context.ConnectionId; message.Headers[SignalRHeaders.HubPath] = consumer.HubPath; if (exception is not null) message.Headers[SignalRHeaders.DisconnectError] = exception.Message; if (Context.UserIdentifier is not null) message.Headers[SignalRHeaders.UserId] = Context.UserIdentifier; var exchange = Exchange.Create(message, consumer.ScopeFactory); ExchangePrincipal.Set(exchange, CallerPrincipal()); try { await consumer.ProcessExchange(exchange, default, HandshakeTrace()).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } await base.OnDisconnectedAsync(exception); } /// The trace context of the connection request, or default when the client sent none. private ActivityContext HandshakeTrace() => Context.Items.TryGetValue(HandshakeTraceItem, out var value) && value is ActivityContext handshake ? handshake : default; private static string? ReadHeader(IHeaderDictionary headers, string name) => headers.TryGetValue(name, out var values) ? values.ToString() : null; /// /// The caller's principal as the hub's identity gate handed it to SignalR, or null for an anonymous /// connection. SignalR always has a User; for an anonymous connection it is an empty principal /// (no claims, no authenticated identity), which identifies nobody and is not put on the exchange. /// private System.Security.Claims.ClaimsPrincipal? CallerPrincipal() { var user = Context.User; return user is not null && user.Identities.Any(i => i.IsAuthenticated || i.Claims.Any()) ? user : null; } /// /// The consumer behind this hub. Each hub has a container of its own () /// holding its endpoint, so the hub knows its consumer without looking at the request path. /// private SignalRConsumer? ResolveConsumer() => endpoint.ServingConsumer; private async Task HandleGroupCommands(IExchange exchange) { var outMsg = exchange.HasOut ? exchange.Out! : exchange.In; if (outMsg.Headers.TryGetValue(SignalRHeaders.AddToGroup, out var addGroup) && addGroup is string groupToAdd && !string.IsNullOrEmpty(groupToAdd)) { await Groups.AddToGroupAsync(Context.ConnectionId, groupToAdd).ConfigureAwait(false); } if (outMsg.Headers.TryGetValue(SignalRHeaders.RemoveFromGroup, out var removeGroup) && removeGroup is string groupToRemove && !string.IsNullOrEmpty(groupToRemove)) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupToRemove).ConfigureAwait(false); } } private static object?[]? NormalizeArgs(object?[]? args) { if (args is null) return null; for (var i = 0; i < args.Length; i++) { if (args[i] is JsonElement je) args[i] = DeserializeJsonElement(je); } return args; } private static object? DeserializeJsonElement(JsonElement element) { return element.ValueKind switch { JsonValueKind.String => element.GetString(), JsonValueKind.Number when element.TryGetInt64(out var l) => l, JsonValueKind.Number => element.GetDouble(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null or JsonValueKind.Undefined => null, // For arrays and objects, keep as JsonElement — pipeline can deserialize as needed _ => element }; } } Path: redb-route/redb.Route.SignalR/SignalRComponent.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/SignalRComponent.cs ---- using System.Collections.Concurrent; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; using redb.Route.Http; namespace redb.Route.SignalR; /// /// SignalR component. Scheme: "signalr". /// Consumer: Kestrel-based SignalR Hub server — accepts connections and receives method invocations. /// Producer (client): HubConnection — connects to a remote SignalR hub and invokes methods. /// Producer (server): IHubContext — broadcasts to clients of the local hub. /// URI format: signalr:host:port/hubPath?method=Send&inOut=true&messagePack=true /// public class SignalRComponent : ComponentBase { private readonly ConcurrentDictionary _consumers = new(StringComparer.OrdinalIgnoreCase); private SharedHttpServerManager? _ownedServerManager; /// public override string Scheme => "signalr"; /// /// Shared Kestrel host. Set by AddRedbRouteSignalR() so a hub multiplexes onto the same /// listener as HTTP, gRPC, SOAP and AS2 — that is what lets /hub/ and the REST API live /// on one port behind one reverse proxy. A hand-built component owns a private manager instead /// of failing, so new SignalRComponent() stays usable on its own. /// public SharedHttpServerManager? ServerManager { get; set; } /// /// The manager actually used. Resolution order: explicitly assigned → the context's DI singleton /// → a private instance. The DI step matters for module hosts that add the component by scanning /// rather than through the extension method, so nothing ever assigns /// while the one shared manager sits in the container (gRPC and AS2 resolve the same way). /// internal SharedHttpServerManager EffectiveServerManager => ServerManager ?? Context.Resolve() ?? (_ownedServerManager ??= new SharedHttpServerManager()); /// /// Extra service registrations for the container of each hub, supplied by the host: a SignalR /// backplane for scale-out, extra protocols, anything else the hub needs. Runs once per hub, with /// the hub it is for. Kept as a delegate on purpose: the connector stays free of those /// dependencies and the host picks its own. /// public Action? HubServicesConfigurator { get; set; } /// /// Authenticates hub connections. Without it the hub accepts anonymous connections and /// UserIdentifier stays empty, which makes Clients.User(...) useless. Supplied by /// the host (see AddRedbRouteSignalR(o => o.Authenticate = ...)) rather than built in, /// because token validation belongs to whoever issues the tokens. The principal is put on every /// exchange the hub produces (ExchangePrincipal); build its identity with an authentication /// type, because code that reads it treats an identity that is not authenticated as anonymous. /// public Func>? Authenticate { get; set; } /// public override async ValueTask DisposeAsync() { if (_ownedServerManager is not null) { await _ownedServerManager.DisposeAsync().ConfigureAwait(false); _ownedServerManager = null; } await base.DisposeAsync().ConfigureAwait(false); } /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new SignalREndpointOptions(); ParseHostPort(uri.Path, options); options.BindFromUri(uri.RawParameters); // Named ConnectionFactory keeps the access token / cert password out of the route URI. if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud -- never a silent fallback to URI params. var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory); factory.ApplyTo(options, uri); } options.Validate(); return new SignalREndpoint(uri, this, options); } /// /// Registers a running consumer for the bridge hub and for server-mode producer lookup. /// /// The lookup key is the listener address plus the hub path, NOT the endpoint's normalized /// key: that one carries the sorted query parameters, and a server-mode producer always /// carries at least mode=server, so it never matched the consumer it was meant to push /// through. /// /// internal void RegisterConsumer(SignalRConsumer consumer) => _consumers[ConsumerKey(consumer.EndpointOptions.Host, consumer.EndpointOptions.Port, consumer.HubPath)] = consumer; /// Unregisters a consumer. internal void UnregisterConsumer(SignalRConsumer consumer) => _consumers.TryRemove(ConsumerKey(consumer.EndpointOptions.Host, consumer.EndpointOptions.Port, consumer.HubPath), out _); internal static string ConsumerKey(string host, int port, string hubPath) => $"{host}:{port}{hubPath}"; /// Gets the running consumer serving a hub, by listener address and hub path. internal SignalRConsumer? GetConsumer(string host, int port, string hubPath) => _consumers.TryGetValue(ConsumerKey(host, port, hubPath), out var c) ? c : null; /// /// Parses "host:port/hubPath" from the URI path segment. /// Sets Host and Port on options. HubPath is extracted separately via . /// internal static void ParseHostPort(string path, SignalREndpointOptions options) { var clean = path.TrimStart('/'); var slashIdx = clean.IndexOf('/'); var hostPort = slashIdx >= 0 ? clean[..slashIdx] : clean; var colonIdx = hostPort.LastIndexOf(':'); if (colonIdx > 0 && int.TryParse(hostPort[(colonIdx + 1)..], out var port)) { options.Host = hostPort[..colonIdx]; options.Port = port; } else { options.Host = hostPort; } } /// /// Extracts the hub path after host:port. /// "0.0.0.0:5000/chatHub" → "/chatHub" /// "0.0.0.0:5000" → "/" /// internal static string ExtractHubPath(string uriPath) { var clean = uriPath.TrimStart('/'); var slashIdx = clean.IndexOf('/'); return slashIdx >= 0 ? clean[slashIdx..] : "/"; } } /// /// SignalR endpoint. Creates either a producer or consumer for the SignalR hub. /// public class SignalREndpoint : EndpointBase { /// Creates a SignalR endpoint. public SignalREndpoint(EndpointUri uri, SignalRComponent component, SignalREndpointOptions options) : base(uri, component, options) { } /// The hub path (after host:port in the URI). public string HubPath => SignalRComponent.ExtractHubPath(Uri.Path); /// The shared host this endpoint serves on. internal SharedHttpServerManager ServerManager => ((SignalRComponent)Component).EffectiveServerManager; /// /// Registers the hub with the shared listener, when this endpoint serves one: a consumer was created on it (the /// route context creates every consumer while it compiles the routes, before it starts any endpoint). A producer /// endpoint (mode=server broadcast, mode=client connection) maps nothing: the server-mode producer /// sends through the hub its consumer registered, and a second registration of one hub path would map it twice. /// public override async Task Start(CancellationToken ct = default) { if (Volatile.Read(ref _servesHub)) await EnsureHubRegisteredAsync(ct).ConfigureAwait(false); } // Set by CreateConsumer: this endpoint is a hub, not a producer that talks to one. private bool _servesHub; // Serializes putting the hub on the listener and taking it off; _hub itself is read without it. private readonly SemaphoreSlim _hubGate = new(1, 1); private SignalRHubHost? _hub; /// /// The hub's own container while the hub is on the listener: the server-mode producer resolves /// IHubContext from here. /// internal IServiceProvider? HubServices { get { return Volatile.Read(ref _hub)?.Services; } } /// The consumer this hub dispatches to, while it runs. internal SignalRConsumer? ServingConsumer => ((SignalRComponent)Component).GetConsumer(Options.Host, Options.Port, HubPath); /// /// Puts the hub on the listener exactly once per run, with a container of its own (see /// ), whether the listener is already serving or not. Called from /// when the route context owns the lifecycle, and again from the consumer so a /// hand-built consumer (tests, embedded use) works without anyone having started the endpoint first. /// internal async Task EnsureHubRegisteredAsync(CancellationToken ct) { await _hubGate.WaitAsync(ct).ConfigureAwait(false); try { if (_hub is null) Volatile.Write(ref _hub, await SignalRHubHost.StartAsync(this, ct).ConfigureAwait(false)); } finally { _hubGate.Release(); } } /// /// Takes the hub off the listener when the consumer stops: its endpoints go, its connections are /// closed and its container is disposed, while the other hubs and routes on the listener keep /// serving. The listener can then shut down once nothing occupies it, and a later Start puts the /// hub back instead of finding a listener that no longer exists. /// internal async Task ReleaseHubRegistrationAsync() { await _hubGate.WaitAsync().ConfigureAwait(false); try { var hub = Interlocked.Exchange(ref _hub, null); if (hub is not null) await hub.DisposeAsync().ConfigureAwait(false); } finally { _hubGate.Release(); } } /// The endpoint options for external access. internal SignalREndpointOptions EndpointOptions => Options; /// /// Builds the full URL for producer client connections. /// "signalr:api.example.com:5000/chatHub" → "http://api.example.com:5000/chatHub" /// public string BuildClientUrl() { var scheme = Options.Ssl ? "https" : "http"; var host = Options.Host; var hubPath = HubPath; return $"{scheme}://{host}:{Options.Port}{hubPath}"; } /// public override IProducer CreateProducer() { return new SignalRProducer(this, Options); } /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); Volatile.Write(ref _servesHub, true); return new SignalRConsumer(this, processor, Options); } } Path: redb-route/redb.Route.SignalR/SignalRConnectionFactory.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/SignalRConnectionFactory.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.SignalR; /// /// Named connection factory for SignalR. Register it in the route registry and reference it by /// name from the endpoint URI (connectionFactory=my-hub) so the access token and TLS /// certificate password never have to appear in the URI, and therefore can never reach logs, /// telemetry, or the dashboard. /// /// The hub address stays in the endpoint path — a factory carries credentials and TLS material /// only and can never silently redirect a route. /// /// public sealed class SignalRConnectionFactory { /// Bearer access token for hub authentication. [Sensitive] public string? AccessToken { get; set; } /// Transport to use (WebSockets, ServerSentEvents, LongPolling). public SignalRTransport Transport { get; set; } = SignalRTransport.WebSockets; /// Serve/connect over TLS. public bool Ssl { get; set; } /// Path to the PFX certificate. public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// /// Copies this factory's credential and TLS settings onto the endpoint options, but only for /// parameters the endpoint URI did not set explicitly — an inline URI value always wins. /// internal void ApplyTo(SignalREndpointOptions options, EndpointUri uri) { var supplied = uri.RawParameters; if (!supplied.ContainsKey(nameof(options.AccessToken))) options.AccessToken = AccessToken; if (!supplied.ContainsKey(nameof(options.Transport))) options.Transport = Transport; if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl; if (!supplied.ContainsKey(nameof(options.SslCertPath))) options.SslCertPath = SslCertPath; if (!supplied.ContainsKey(nameof(options.SslCertPassword))) options.SslCertPassword = SslCertPassword; } } 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}"; } } Path: redb-route/redb.Route.SignalR/SignalREndpointOptions.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/SignalREndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.SignalR; /// /// Options for the SignalR endpoint. Bound from URI parameters via reflection. /// URI format: signalr:host:port/hubPath?mode=Client&inOut=true&messagePack=true /// public class SignalREndpointOptions : EndpointOptions { // ── Connection ────────────────────────────────────── /// Bind/connect host. Parsed from URI path. Default: 0.0.0.0. public string Host { get; set; } = "0.0.0.0"; /// Bind/connect port. Parsed from URI path. Default: 5000. public int Port { get; set; } = 5000; // ── Dispatch ──────────────────────────────────────── /// /// Producer mode: Client (HubConnection to remote) or Server (IHubContext broadcast). /// Ignored for consumer. Default: Client. /// public SignalRMode Mode { get; set; } = SignalRMode.Client; /// /// Hub method name. For consumer: filter invocations to this method only. /// For producer: target method to invoke/send. If null, taken from exchange header. /// public string? Method { get; set; } // ── Groups ────────────────────────────────────────── /// /// Default group name. If set, OnConnectedAsync automatically adds the connection to this group. /// public string? DefaultGroup { get; set; } // ── Exchange ──────────────────────────────────────── /// /// If true, the consumer returns exchange Out body as the hub method return value (InOut pattern). /// Default: false. /// public bool InOut { get; set; } // ── Bridge ────────────────────────────────────────── /// /// When true (default), client-mode producer calls the bridge hub entry point /// Invoke(method, args) — for connecting to our . /// When false, producer calls the hub method directly by name — for connecting to /// external (third-party) SignalR hubs that expose real named methods. /// public bool Bridge { get; set; } = true; // ── Transport ─────────────────────────────────────── /// Preferred transport for client connections. Default: WebSockets. public SignalRTransport Transport { get; set; } = SignalRTransport.WebSockets; /// Use MessagePack protocol instead of JSON. Default: false. public bool MessagePack { get; set; } // ── Producer (client mode) ────────────────────────── /// Auto-reconnect on disconnect (client mode). Default: false. public bool Reconnect { get; set; } /// Interval between reconnect attempts in milliseconds (client mode). Default: 5000. public int ReconnectInterval { get; set; } = 5_000; /// Maximum reconnect attempts. 0 = unlimited. Default: 0. public int MaxReconnectAttempts { get; set; } // ── Producer (server mode) ────────────────────────── /// /// Default target for server-mode producer: All, Group, User, Connection. /// Can be overridden per-exchange via signalR.Target header. Default: "All". /// public string TargetType { get; set; } = "All"; /// Default group for server-mode producer. Overridden by signalR.Group header. public string? TargetGroup { get; set; } // ── TLS ───────────────────────────────────────────── /// Enable TLS. Default: false. public bool Ssl { get; set; } /// Path to PFX certificate file for TLS (consumer/server). public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// /// Client-mode producer only: accept any server certificate, including a self-signed one. /// Off by default and never implied by another option — earlier this fired whenever /// ssl=false, which silently disabled validation for the whole transport. /// public bool TrustAllCertificates { get; set; } /// /// Named from the route registry. Lets the access token /// and TLS certificate password live in the registry instead of the endpoint URI, so they /// never reach logs or dashboards. /// [RegistryReference(typeof(SignalRConnectionFactory))] public string? ConnectionFactory { get; set; } // ── Auth ──────────────────────────────────────────── /// Access token for client authentication (JWT). Used by producer in client mode. [Sensitive] public string? AccessToken { get; set; } // ── Admission limits ─────────────────────────────────────────── /// /// Maximum hub connections this endpoint accepts (server mode). 0 (default) = unlimited. /// A connection over the limit is aborted at OnConnected — before the Connected lifecycle /// event reaches the pipeline — and counted in the endpoint's Rejected. SignalR concurrency /// is connections × invocations, so this is the coarse lever; /// is the fine one. /// public int MaxConnections { get; set; } /// /// SignalR's own MaximumParallelInvocationsPerClient: how many hub method calls ONE /// client may run in parallel. 0 (default) = SignalR's default (1, i.e. per-client serial). /// public int MaxParallelInvocationsPerClient { get; set; } /// public override void Validate() { if (Port is < 0 or > 65535) throw new ArgumentException("Port must be between 0 and 65535."); if (ReconnectInterval <= 0) throw new ArgumentException("ReconnectInterval must be > 0."); if (MaxReconnectAttempts < 0) throw new ArgumentException("MaxReconnectAttempts must be >= 0."); if (MaxConnections < 0) throw new ArgumentException("maxConnections must be >= 0 (0 = unlimited)."); if (MaxParallelInvocationsPerClient < 0) throw new ArgumentException("maxParallelInvocationsPerClient must be >= 0 (0 = SignalR default)."); } } Path: redb-route/redb.Route.SignalR/SignalREnums.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/SignalREnums.cs ---- namespace redb.Route.SignalR; /// /// SignalR producer mode. Determines how the producer sends messages. /// public enum SignalRMode { /// HubConnection — connects to an external SignalR hub as a client. Client, /// IHubContext — broadcasts to clients of the local hub (requires consumer on the same endpoint). Server } /// /// SignalR transport type for client connections. /// public enum SignalRTransport { /// WebSocket transport (default, best performance). WebSockets, /// Server-Sent Events fallback. ServerSentEvents, /// Long polling fallback. LongPolling } Path: redb-route/redb.Route.SignalR/SignalRHeaders.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/SignalRHeaders.cs ---- namespace redb.Route.SignalR; /// /// Well-known header constants used by the SignalR component. /// public static class SignalRHeaders { /// Common prefix for all SignalR component headers. public const string Prefix = "redbSignalR."; /// Hub method name invoked by the client or targeted by the producer. public const string Method = "redbSignalR.Method"; /// SignalR connection identifier. public const string ConnectionId = "redbSignalR.ConnectionId"; /// Authenticated user identifier. public const string UserId = "redbSignalR.UserId"; /// Hub lifecycle event: "Connected" or "Disconnected". public const string Event = "redbSignalR.Event"; /// Hub path the message was received on. public const string HubPath = "redbSignalR.HubPath"; /// Protocol in use: "json" or "messagepack". public const string Protocol = "redbSignalR.Protocol"; /// Whether TLS is used: "True"/"False". public const string Ssl = "redbSignalR.Ssl"; // ── Producer targeting headers ── /// Target audience for producer broadcast: "All", "Group", "User", "Connection". public const string Target = "redbSignalR.Target"; /// Target group name for producer broadcast. public const string Group = "redbSignalR.Group"; /// Target connection ID for producer send. public const string TargetConnection = "redbSignalR.TargetConnection"; /// Target user ID for producer send. public const string TargetUser = "redbSignalR.TargetUser"; // ── Group management headers (post-process commands) ── /// Add the current connection to the specified group after processing. public const string AddToGroup = "redbSignalR.AddToGroup"; /// Remove the current connection from the specified group after processing. public const string RemoveFromGroup = "redbSignalR.RemoveFromGroup"; /// Exception message from disconnection (set on Disconnected event). public const string DisconnectError = "redbSignalR.DisconnectError"; /// Returns true if the header key starts with the SignalR prefix. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.Ordinal); } Path: redb-route/redb.Route.SignalR/SignalRHubDescriptor.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/SignalRHubDescriptor.cs ---- namespace redb.Route.SignalR; /// /// The hub whose container is filling: every consumer /// endpoint gets a container of its own, and this says which one. A backplane keys its channels on , /// so the hubs of one listener stay apart on a shared Redis or service. /// /// Bind host of the hub's listener, as the route URI names it. /// Port of the hub's listener. /// The hub path, with its leading slash (/chatHub). public sealed record SignalRHubDescriptor(string Host, int Port, string Path); Path: redb-route/redb.Route.SignalR/SignalRHubHost.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/SignalRHubHost.cs ---- using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Route.Extensions; using redb.Route.Http; namespace redb.Route.SignalR; /// /// The hub of one consumer endpoint on the shared listener. It has a service container of its own, so whatever SignalR /// keeps per container stays with this hub: the connection manager, the lifetime manager behind Clients.All, /// Group and User, the protocols, the hub options and a backplane. Two hubs on one listener, from one /// route context or from two, never see each other's connections, and one of them can come and go while the other /// serves. /// internal sealed class SignalRHubHost : IAsyncDisposable { private readonly ServiceProvider _services; private readonly HubLifetime _lifetime; private readonly IHostedService[] _hosted; private readonly EndpointRegistration _registration; private SignalRHubHost(ServiceProvider services, HubLifetime lifetime, IHostedService[] hosted, EndpointRegistration registration) { _services = services; _lifetime = lifetime; _hosted = hosted; _registration = registration; } /// /// The hub's container. The server-mode producer resolves IHubContext from here, and a hub request runs in /// a scope of it (Context.GetHttpContext().RequestServices). /// public IServiceProvider Services => _services; /// /// Builds the hub's container, starts the hosted services registered in it, the way a host would, and maps the /// hub onto the endpoint's listener, running or not. A hosted service that refuses to start (a backplane whose /// channels another hub of this process already holds) keeps the hub off the listener. /// public static async Task StartAsync(SignalREndpoint endpoint, CancellationToken ct) { var component = (SignalRComponent)endpoint.Component; var options = endpoint.EndpointOptions; var lifetime = new HubLifetime(); var services = BuildServices(endpoint, component, options, lifetime); var started = new List(); try { foreach (var hosted in services.GetServices()) { await hosted.StartAsync(ct).ConfigureAwait(false); started.Add(hosted); } var registration = endpoint.ServerManager.RegisterEndpoints(options.Host, options.Port, services, routes => routes.MapHub(endpoint.HubPath, dispatcher => ConfigureDispatcher(dispatcher, options)) .Add(hub => Gate(hub, component)), // A hub maps itself instead of calling RegisterRoute, so this is where the listener learns it has to // terminate TLS. options.Ssl, options.SslCertPath, options.SslCertPassword); return new SignalRHubHost(services, lifetime, [.. started], registration); } catch { lifetime.StopApplication(); await StopAsync(started, CancellationToken.None).ConfigureAwait(false); await services.DisposeAsync().ConfigureAwait(false); lifetime.Dispose(); throw; } } private static async Task StopAsync(IReadOnlyList hosted, CancellationToken ct) { for (var i = hosted.Count - 1; i >= 0; i--) await hosted[i].StopAsync(ct).ConfigureAwait(false); } private static ServiceProvider BuildServices(SignalREndpoint endpoint, SignalRComponent component, SignalREndpointOptions options, HubLifetime lifetime) { var services = new ServiceCollection(); // SignalR logs through the route context, like the rest of the connector. Registered before AddLogging, which // only fills in what is missing; the container does not dispose an instance it was handed. if (component.Context.Resolve() is { } loggerFactory) services.AddSingleton(loggerFactory); services.AddLogging(); // The hub's own lifetime: the connection manager closes the hub's connections when it stops, and the listener's // lifetime is not the hub's to stop. services.AddSingleton(lifetime); var signalR = services.AddSignalR(hub => { // SignalR's own per-client invocation parallelism. // 0 keeps SignalR's default (1 = per-client serial). if (options.MaxParallelInvocationsPerClient > 0) hub.MaximumParallelInvocationsPerClient = options.MaxParallelInvocationsPerClient; }); if (options.MessagePack) signalR.AddMessagePackProtocol(); // The bridge hub is activated from this container and takes its endpoint from it. services.AddSingleton(endpoint); // Host-supplied extras: backplane for scale-out, custom protocols, a user id provider, and so on. component.HubServicesConfigurator?.Invoke(services, new SignalRHubDescriptor(options.Host, options.Port, endpoint.HubPath)); return services.BuildServiceProvider(); } private static void ConfigureDispatcher(HttpConnectionDispatcherOptions dispatcher, SignalREndpointOptions options) { dispatcher.Transports = options.Transport switch { SignalRTransport.ServerSentEvents => HttpTransportType.ServerSentEvents, SignalRTransport.LongPolling => HttpTransportType.LongPolling, _ => HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling }; } /// /// Authentication gate on the hub's endpoints (negotiate and the connection itself): the host's own validator /// decides, and a rejected handshake gets 401 before the connection is upgraded. Not ASP.NET authentication, /// because the process hosting the route context is a generic host, not an ASP.NET application. Without the /// component's own delegate, the caller is whoever the shared host's resolver identified (it runs earlier in the /// pipeline), and that principal is handed to SignalR the same way. /// private static void Gate(EndpointBuilder hub, SignalRComponent component) { var authenticate = component.Authenticate; if ((authenticate is null && component.EffectiveServerManager.Options.ResolvePrincipal is null) || hub.RequestDelegate is not { } next) return; hub.RequestDelegate = async context => { if (authenticate is not null) { var principal = await authenticate(context).ConfigureAwait(false); if (principal is null) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return; } // SignalR reads UserIdentifier from HttpContext.User. context.User = principal; } else if (SharedHttpServerManager.GetResolvedPrincipal(context) is { } resolved) { context.User = resolved; } await next(context).ConfigureAwait(false); }; } /// /// Takes the hub off the listener: the endpoints first, so no new connection reaches a hub that is going away, then /// the hub's lifetime, which closes its connections, then its hosted services in reverse order, then its container. /// public async ValueTask DisposeAsync() { _registration.Dispose(); _lifetime.StopApplication(); try { await StopAsync(_hosted, CancellationToken.None).ConfigureAwait(false); } finally { await _services.DisposeAsync().ConfigureAwait(false); _lifetime.Dispose(); } } /// /// The lifetime of one hub. Started when it is created; stopping it is what makes the hub's connection manager /// close the hub's connections, and only those. /// private sealed class HubLifetime : IHostApplicationLifetime, IDisposable { private readonly CancellationTokenSource _started = new(); private readonly CancellationTokenSource _stopping = new(); private readonly CancellationTokenSource _stopped = new(); private int _stop; public HubLifetime() => _started.Cancel(); public CancellationToken ApplicationStarted => _started.Token; public CancellationToken ApplicationStopping => _stopping.Token; public CancellationToken ApplicationStopped => _stopped.Token; public void StopApplication() { if (Interlocked.Exchange(ref _stop, 1) != 0) return; _stopping.Cancel(); _stopped.Cancel(); } public void Dispose() { StopApplication(); _started.Dispose(); _stopping.Dispose(); _stopped.Dispose(); } } } 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("Invoke", [method, hubArgs], ct).ConfigureAwait(false); var outMsg = new Message(result); outMsg.Headers[SignalRHeaders.Method] = method; exchange.Out = outMsg; } else { await _hubConnection!.SendCoreAsync("Invoke", [method, hubArgs], ct).ConfigureAwait(false); } } else { // Direct mode: call the hub method by its actual name. // Used when connecting to an external (third-party) SignalR hub. var directArgs = body switch { object?[] argsArray => argsArray, not null => [body], _ => Array.Empty() }; if (_options.InOut) { var result = await _hubConnection!.InvokeCoreAsync(method, directArgs, ct).ConfigureAwait(false); var outMsg = new Message(result); outMsg.Headers[SignalRHeaders.Method] = method; exchange.Out = outMsg; } else { await _hubConnection!.SendCoreAsync(method, directArgs, ct).ConfigureAwait(false); } } } // ── Server mode ───────────────────────────────────────────────── private void StartServerMode() { // Find the consumer's WebApplication to get IHubContext // Server-mode producer needs the consumer running on the same endpoint var consumer = FindConsumer(); if (consumer?.HubServices is null) throw new InvalidOperationException( "Server-mode producer requires a running SignalR consumer on the same endpoint. " + "Ensure From(\"signalr:...\") is started before To(\"signalr:...?mode=server\")."); _hubContext = consumer.HubServices.GetRequiredService>(); } private async Task ProcessServerMode(IExchange exchange, CancellationToken ct) { if (_hubContext is null) throw new InvalidOperationException("IHubContext not available. Is the consumer running?"); var method = ResolveMethod(exchange); var body = exchange.In.Body; var args = body is object?[] argsArray ? argsArray : body is not null ? [body] : Array.Empty(); var clients = ResolveTargetClients(exchange); await clients.SendCoreAsync(method, args, ct).ConfigureAwait(false); } private IClientProxy ResolveTargetClients(IExchange exchange) { var targetType = ResolveHeaderString(exchange, SignalRHeaders.Target) ?? _options.ResolveOption(_options.TargetType, exchange) ?? _options.TargetType; var group = ResolveHeaderString(exchange, SignalRHeaders.Group) ?? _options.ResolveOption(_options.TargetGroup, exchange); var connectionId = ResolveHeaderString(exchange, SignalRHeaders.TargetConnection); var userId = ResolveHeaderString(exchange, SignalRHeaders.TargetUser); return targetType.ToUpperInvariant() switch { "GROUP" when group is not null => _hubContext!.Clients.Group(group), "USER" when userId is not null => _hubContext!.Clients.User(userId), "CONNECTION" when connectionId is not null => _hubContext!.Clients.Client(connectionId), _ => _hubContext!.Clients.All }; } // ── Helpers ────────────────────────────────────────────────────── private string ResolveMethod(IExchange exchange) { if (exchange.In.Headers.TryGetValue(SignalRHeaders.Method, out var m) && m is string method && !string.IsNullOrEmpty(method)) return method; if (_options.Method is not null) return _options.ResolveOption(_options.Method, exchange) ?? _options.Method; throw new InvalidOperationException( "No method specified. Set 'method' in URI or signalR.Method header on exchange."); } private static string? ResolveHeaderString(IExchange exchange, string header) { if (exchange.In.Headers.TryGetValue(header, out var val) && val is string s && !string.IsNullOrEmpty(s)) return s; return null; } private SignalRConsumer? FindConsumer() { // The endpoint caches consumers/producers. Walk the route context to find the consumer // sharing our endpoint URI. For now, store on the endpoint itself. return _endpoint.Component is SignalRComponent comp ? comp.GetConsumer(_options.Host, _options.Port, _endpoint.HubPath) : null; } private IRetryPolicy BuildRetryPolicy() { return new RedbRetryPolicy(_options.ReconnectInterval, _options.MaxReconnectAttempts); } /// Simple retry policy with configurable interval and max attempts. private sealed class RedbRetryPolicy : IRetryPolicy { private readonly int _intervalMs; private readonly int _maxAttempts; public RedbRetryPolicy(int intervalMs, int maxAttempts) { _intervalMs = intervalMs; _maxAttempts = maxAttempts; } public TimeSpan? NextRetryDelay(RetryContext retryContext) { if (_maxAttempts > 0 && retryContext.PreviousRetryCount >= _maxAttempts) return null; return TimeSpan.FromMilliseconds(_intervalMs); } } } Path: redb-route/redb.Route.SignalR/redb.Route.SignalR.csproj 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/redb.Route.SignalR.csproj ---- redb.Route.SignalR SignalR transport for redb.Route ESB framework. Provides Kestrel-based SignalR Hub consumer (server) and HubConnection-based producer (client) with dynamic method dispatch, group management, and JSON/MessagePack support. esb;messaging;signalr;realtime;hub;websocket;rpc;redb README.md