Path: redb-route/tests/redb.Route.Tests.SignalR/SignalRBackplaneTests.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/tests/redb.Route.Tests.SignalR/SignalRBackplaneTests.cs
----
using System.Collections.Concurrent;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.SignalR.StackExchangeRedis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.SignalR;
using StackExchange.Redis;
namespace redb.Route.Tests.SignalR;
///
/// End to end against the live Redis container: a hub keeps its connections in the memory of one
/// process, so with more than one replica a broadcast reaches only the clients of the replica that sent it. The
/// backplane (UseRedisBackplane, redb.Route.SignalR.StackExchangeRedis) fixes that, and keys the Redis channels
/// on the hub path so the hubs of one listener stay apart on one Redis.
/// Requires redis on localhost:6379 (docker: docker start redis).
///
[Trait("Category", "Integration")]
public sealed class SignalRBackplaneTests : IAsyncLifetime
{
private const string RedisConnection = "localhost:6379";
private readonly List _managers = [];
private readonly List _consumers = [];
private readonly List _producers = [];
private readonly List _connections = [];
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
foreach (var c in _connections) await c.DisposeAsync();
foreach (var p in _producers) await p.Stop();
foreach (var c in _consumers) await c.Stop();
foreach (var m in _managers) await m.DisposeAsync();
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static Action Backplane(string? applicationPrefix = null)
=> new SignalRRegistrationOptions().UseRedisBackplane(RedisConnection, redis =>
{
if (applicationPrefix is not null)
redis.Configuration.ChannelPrefix = RedisChannel.Literal(applicationPrefix);
}).HubServices!;
// The client sends the token in the Authorization header on negotiate and in access_token on the upgrade.
private static Func> UserFromToken => ctx =>
{
var header = ctx.Request.Headers.Authorization.ToString();
var token = header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? header["Bearer ".Length..]
: ctx.Request.Query["access_token"].ToString();
return Task.FromResult(string.IsNullOrEmpty(token)
? null
: new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, token)], "test")));
};
///
/// One "replica": its own listener and its own component, wired to one Redis. A replica is a process of its own,
/// so it holds its backplane channels apart from the other replicas of this test unless
/// puts them in one.
///
private SignalRComponent Replica(Action? backplane,
RedisBackplaneClaims? process = null)
{
var manager = new SharedHttpServerManager();
_managers.Add(manager);
var claims = process ?? new RedisBackplaneClaims();
return new SignalRComponent
{
ServerManager = manager,
HubServicesConfigurator = backplane is null ? null : (services, hub) =>
{
backplane(services, hub);
services.AddSingleton(claims);
},
Authenticate = UserFromToken,
};
}
/// Joins the group "g" on the method "Join".
private sealed class GroupProcessor : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default)
{
if (exchange.In.GetHeader(SignalRHeaders.Method) == "Join")
exchange.In.Headers[SignalRHeaders.AddToGroup] = "g";
return Task.CompletedTask;
}
}
private async Task StartHubAsync(SignalRComponent component, int port, string hubPath)
{
var endpoint = (SignalREndpoint)component.CreateEndpoint(EndpointUriParser.Parse($"signalr://127.0.0.1:{port}{hubPath}"));
await endpoint.Start();
var consumer = endpoint.CreateConsumer(new GroupProcessor());
_consumers.Add(consumer);
await consumer.Start();
}
private async Task ConnectAsync(int port, string hubPath, string user = "u1")
{
var connection = new HubConnectionBuilder().WithUrl($"http://127.0.0.1:{port}{hubPath}",
o => o.AccessTokenProvider = () => Task.FromResult(user)).Build();
_connections.Add(connection);
await connection.StartAsync();
return connection;
}
private async Task PushAsync(SignalRComponent component, int port, string hubPath, string body,
Action? target = null)
{
var endpoint = (SignalREndpoint)component.CreateEndpoint(
EndpointUriParser.Parse($"signalr://127.0.0.1:{port}{hubPath}?mode=Server&method=Quote"));
var producer = endpoint.CreateProducer();
_producers.Add(producer);
await producer.Start();
var message = new Message(body);
target?.Invoke(message);
await producer.Process(new Exchange(message));
}
[Fact]
public async Task BroadcastFromOneReplica_ReachesClientsOfTheOther()
{
// A prefix of the application per run keeps parallel runs of this suite from hearing each other.
var backplane = Backplane($"redb-route-test-{Guid.NewGuid():N}");
var alpha = Replica(backplane);
var beta = Replica(backplane);
var alphaPort = GetFreePort();
var betaPort = GetFreePort();
await StartHubAsync(alpha, alphaPort, "/feed");
await StartHubAsync(beta, betaPort, "/feed");
// The client is attached to alpha only; the push comes from beta, which has no clients of its own.
var connection = await ConnectAsync(alphaPort, "/feed");
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
connection.On("Quote", q => received.TrySetResult(q));
await PushAsync(beta, betaPort, "/feed", "42");
(await received.Task.WaitAsync(TimeSpan.FromSeconds(15))).Should().Be("42",
"with several replicas a broadcast without a backplane reaches only the clients of its own replica");
}
[Fact]
public async Task HubsOfOneListener_StayApartOnOneRedis_WithoutAnExplicitPrefix()
{
// No prefix of the application: the hub path alone keys the channels. Paths unique to the run keep parallel
// runs apart.
var run = Guid.NewGuid().ToString("N");
var left = $"/left-{run}";
var right = $"/right-{run}";
var alpha = Replica(Backplane());
var beta = Replica(Backplane());
var alphaPort = GetFreePort();
var betaPort = GetFreePort();
foreach (var (component, port) in new[] { (alpha, alphaPort), (beta, betaPort) })
{
await StartHubAsync(component, port, left);
await StartHubAsync(component, port, right);
}
// The same user in the same group on both hubs of alpha.
var toLeft = await ConnectAsync(alphaPort, left);
var toRight = await ConnectAsync(alphaPort, right);
var leftGot = new ConcurrentQueue();
var rightGot = new ConcurrentQueue();
toLeft.On("Quote", leftGot.Enqueue);
toRight.On("Quote", rightGot.Enqueue);
await toLeft.InvokeAsync