Skip to content

Commit

Permalink
Favoring incoming connection over existing one
Browse files Browse the repository at this point in the history
  • Loading branch information
tpeczek committed Oct 13, 2023
1 parent c23ffa7 commit f33d876
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
2 changes: 2 additions & 0 deletions Lib.AspNetCore.ServerSentEvents/ServerSentEventsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public sealed class ServerSentEventsClient : IServerSentEventsClient
public bool IsConnected { get; internal set; }

internal bool PreventReconnect { get; set; } = false;

internal bool IsRemoved { get; set; } = false;
#endregion

#region Constructor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ public async Task Invoke(HttpContext context, IPolicyEvaluator policyEvaluator)
Guid clientId = _serverSentEventsClientIdProvider.AcquireClientId(context);
if (_serverSentEventsService.IsClientConnected(clientId))
{
_logger.LogWarning("The IServerSentEventsClient with identifier {ClientId} is already connected. The request can't have been accepted.", clientId);
return;
_serverSentEventsService.RemoveClient(clientId);
}

if (await PreventReconnectAsync(clientId, context))
Expand Down
22 changes: 18 additions & 4 deletions Lib.AspNetCore.ServerSentEvents/ServerSentEventsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -383,15 +383,29 @@ internal void AddClient(ServerSentEventsClient client)
_clients.TryAdd(client.Id, client);
}

internal void RemoveClient(Guid clientId)
{
IServerSentEventsClient client;

_clients.TryGetValue(clientId, out client);

RemoveClient((ServerSentEventsClient)client);
}

internal void RemoveClient(ServerSentEventsClient client)
{
client.IsConnected = false;

_clients.TryRemove(client.Id, out _);

foreach(KeyValuePair<string, ConcurrentDictionary<Guid, IServerSentEventsClient>> group in _groups)
if (!client.IsRemoved)
{
group.Value.TryRemove(client.Id, out _);
_clients.TryRemove(client.Id, out _);

client.IsRemoved = true;

foreach (KeyValuePair<string, ConcurrentDictionary<Guid, IServerSentEventsClient>> group in _groups)
{
group.Value.TryRemove(client.Id, out _);
}
}
}

Expand Down

0 comments on commit f33d876

Please sign in to comment.