You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Framework/Connected.Net/Hubs/Clients.cs

51 lines
1.2 KiB

using System.Collections.Concurrent;
using System.Collections.Immutable;
namespace Connected.Net.Hubs;
public sealed class Clients<TArgs>
{
public Clients()
{
Items = new(StringComparer.OrdinalIgnoreCase);
}
private ConcurrentDictionary<string, Client<TArgs>> Items { get; set; }
public void AddOrUpdate(Client<TArgs> client)
{
if (!Items.TryGetValue(client.Connection, out Client<TArgs>? existing))
{
Items.TryAdd(client.Connection, client);
return;
}
existing.RetentionDeadline = DateTime.MinValue;
}
public void Clean()
{
var dead = Items.Where(f => f.Value.RetentionDeadline != DateTime.MinValue && f.Value.RetentionDeadline <= DateTime.UtcNow).ToImmutableList();
if (dead.IsEmpty)
return;
foreach (var client in dead)
Items.TryRemove(client.Key, out _);
}
public void Remove(string connectionId)
{
if (!Items.TryGetValue(connectionId, out Client<TArgs>? client))
return;
if (client.Behavior == MessageClientBehavior.FireForget)
Items.TryRemove(connectionId, out _);
else
client.RetentionDeadline = DateTime.UtcNow.AddMinutes(5);
}
public ImmutableList<Client<TArgs>> Query()
{
return Items.Values.ToImmutableList();
}
}