Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(client): connection cleanup on max attempts #97

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/SignalR.Orleans/Clients/ClientGrain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ internal class ClientGrain : Grain<ClientState>, IClientGrain
private IAsyncStream<ClientMessage> _serverStream;
private IAsyncStream<string> _clientDisconnectStream;
private ConnectionGrainKey _keyData;
private const int _maxFailAttempts = 3;
private int _failAttempts;

public ClientGrain(ILogger<ClientGrain> logger)
{
Expand All @@ -45,16 +47,25 @@ public override Task OnActivateAsync()
return Task.CompletedTask;
}

public Task Send(InvocationMessage message)
public async Task Send(InvocationMessage message)
{
if (State.ServerId != Guid.Empty)
{
_logger.LogDebug("Sending message on {hubName}.{targetMethod} to connection {connectionId}", _keyData.HubName, message.Target, _keyData.Id);
return _serverStream.OnNextAsync(new ClientMessage { ConnectionId = _keyData.Id, Payload = message, HubName = _keyData.HubName });
_failAttempts = 0;
await _serverStream.OnNextAsync(new ClientMessage { ConnectionId = _keyData.Id, Payload = message, HubName = _keyData.HubName });
return;
}

_logger.LogError("Client not connected for connectionId '{connectionId}' and hub '{hubName}'", _keyData.Id, _keyData.HubName);
return Task.CompletedTask;
_logger.LogInformation("Client not connected for connectionId {connectionId} and hub {hubName} ({targetMethod})", _keyData.Id, _keyData.HubName, message.Target);

_failAttempts++;
if (_failAttempts >= _maxFailAttempts)
{
await OnDisconnect();
_logger.LogWarning("Force disconnect client for connectionId {connectionId} and hub {hubName} ({targetMethod}) after exceeding attempts limit",
_keyData.Id, _keyData.HubName, message.Target);
}
}

public Task OnConnect(Guid serverId)
Expand Down
21 changes: 10 additions & 11 deletions src/SignalR.Orleans/OrleansHubLifetimeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,14 @@ public override async Task OnConnectedAsync(HubConnectionContext connection)
{
_connections.Add(connection);

var client = _clusterClientProvider.GetClient().GetClientGrain(_hubName, connection.ConnectionId);
await client.OnConnect(_serverId);

if (connection.User.Identity.IsAuthenticated)
{
var user = _clusterClientProvider.GetClient().GetUserGrain(_hubName, connection.UserIdentifier);
await user.Add(connection.ConnectionId);
}

var client = _clusterClientProvider.GetClient().GetClientGrain(_hubName, connection.ConnectionId);
await client.OnConnect(_serverId);
}
catch (Exception ex)
{
Expand All @@ -129,16 +129,15 @@ public override async Task OnConnectedAsync(HubConnectionContext connection)

public override async Task OnDisconnectedAsync(HubConnectionContext connection)
{
var client = _clusterClientProvider.GetClient().GetClientGrain(_hubName, connection.ConnectionId);
await client.OnDisconnect();

if (connection.User.Identity.IsAuthenticated)
try
{
var user = _clusterClientProvider.GetClient().GetUserGrain(_hubName, connection.UserIdentifier);
await user.Remove(connection.ConnectionId);
var client = _clusterClientProvider.GetClient().GetClientGrain(_hubName, connection.ConnectionId);
await client.OnDisconnect();
}
finally
{
_connections.Remove(connection);
}

_connections.Remove(connection);
}

public override Task SendAllAsync(string methodName, object[] args, CancellationToken cancellationToken = new CancellationToken())
Expand Down
32 changes: 32 additions & 0 deletions test/SignalR.Orleans.Tests/OrleansHubLifetimeManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,38 @@ public async Task InvokeGroupAsync_WhenOneDisconnected_ShouldDeliverOthers()
}
}

[Fact]
public async Task InvokeAsync_WhenNotConnectedAfterFailedAttemptsExceeds_ShouldForceDisconnect()
{
using (var client1 = new TestClient())
using (var client2 = new TestClient())
{
var manager = new OrleansHubLifetimeManager<MyHub>(new LoggerFactory().CreateLogger<OrleansHubLifetimeManager<MyHub>>(), _fixture.ClientProvider);
var connection1 = HubConnectionContextUtils.Create(client1.Connection);
var connection2 = HubConnectionContextUtils.Create(client2.Connection);

await manager.OnConnectedAsync(connection1);

var groupName = "flex";
await manager.AddToGroupAsync(connection1.ConnectionId, groupName);
await manager.AddToGroupAsync(connection2.ConnectionId, groupName);

await manager.SendGroupAsync(groupName, "Hello", new object[] { "World" });

var grain = _fixture.ClientProvider.GetClient().GetGroupGrain("MyHub", groupName);
var connectionsCount = await grain.Count();

await AssertMessageAsync(client1);
Assert.Equal(2, connectionsCount);

await manager.SendGroupAsync(groupName, "Hello", new object[] { "World" });
await manager.SendGroupAsync(groupName, "Hello", new object[] { "World" });

connectionsCount = await grain.Count();
Assert.Equal(1, connectionsCount);
}
}

[Fact]
public async Task InvokeConnectionAsync_WritesToConnection_Output()
{
Expand Down