This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 07:53:40 +01:00
1 parent 2c5b69bf2c
commit 22dee59f47
132 files changed
+19653 -7192

No files matched your search

@@ -0,0 +1,163 @@
using Grpc.Core;
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
internal class ConnectorServiceImplementation : ConnectorService.ConnectorServiceBase
{
private readonly GrpcNetworkServer _server;
public ConnectorServiceImplementation(GrpcNetworkServer server)
{
_server = server;
}
public override async Task Connect(
IAsyncStreamReader<ConnectorMessage> requestStream,
IServerStreamWriter<ConnectorMessage> responseStream,
ServerCallContext context)
{
if (!_server.CanAcceptConnection())
{
_server.IncrementDroppedConnection();
throw new RpcException(new Status(StatusCode.ResourceExhausted, "Max connections reached"));
}
var clientId = Guid.NewGuid().ToString("N");
IPEndPoint? remoteEndPoint = null;
var httpContext = context.GetHttpContext();
if (httpContext?.Connection.RemoteIpAddress != null)
{
remoteEndPoint = new IPEndPoint(
httpContext.Connection.RemoteIpAddress,
httpContext.Connection.RemotePort);
}
var clientCts = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
var clientConnection = new GrpcClientConnection
{
Id = clientId,
ResponseStream = responseStream,
RemoteEndPoint = remoteEndPoint,
ConnectedAt = DateTime.UtcNow,
CancellationSource = clientCts
};
if (!_server.AddClient(clientId, clientConnection))
{
clientCts.Dispose();
throw new RpcException(new Status(StatusCode.Aborted, "Failed to register client connection"));
}
_server.RaiseOnConnected(new ConnectionEventArgs
{
ClientId = clientId,
RemoteEndPoint = remoteEndPoint
});
try
{
while (await requestStream.MoveNext(clientCts.Token).ConfigureAwait(false))
{
if (clientCts.Token.IsCancellationRequested)
{
break;
}
var message = requestStream.Current;
clientConnection.LastActive = DateTime.UtcNow;
switch (message.Type)
{
case MessageType.Nickname:
clientConnection.Nickname = message.Text;
continue;
case MessageType.Pong:
_server.HandlePongReceived(clientId);
continue;
case MessageType.Ping:
await clientConnection.WriteLock.WaitAsync(clientCts.Token).ConfigureAwait(false);
try
{
var pongMsg = new ConnectorMessage { Type = MessageType.Pong };
await responseStream.WriteAsync(pongMsg).ConfigureAwait(false);
}
finally
{
clientConnection.WriteLock.Release();
}
continue;
case MessageType.Disconnect:
break;
case MessageType.Data:
default:
break;
}
if (message.Type == MessageType.Disconnect)
{
break;
}
clientConnection.LastDataReceived = DateTime.UtcNow;
var data = message.Data.ToByteArray();
clientConnection.BytesReceived += data.Length;
clientConnection.MessagesReceived++;
_server.TrackBytesReceived(data.Length);
_server.RaiseOnDataReceived(new DataReceivedEventArgs
{
ClientId = clientId,
Data = data,
RemoteEndPoint = remoteEndPoint,
Nickname = clientConnection.Nickname
});
}
}
catch (OperationCanceledException)
{
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
}
catch (Exception exception)
{
_server.RaiseOnGeneralError(new ErrorEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
Exception = exception,
Message = "Error handling gRPC client"
});
}
finally
{
if (_server.RemoveClient(clientId, out _))
{
_server.RaiseOnDisconnected(new ConnectionEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
RemoteEndPoint = remoteEndPoint,
Reason = DisconnectReason.RemoteClosed
});
}
clientCts.Dispose();
}
}
}
}
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>EonaCat.Connections.gRPC</Title>
<Company>EonaCat</Company>
<Copyright>Jeroen Saey</Copyright>
<PackageId>EonaCat.Connections.gRPC</PackageId>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<Description>EonaCat.Connections.gRPC for gRPC client/servers with optional TLS 1.2</Description>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\connector.proto" GrpcServices="Both" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.85.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.85.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
using Grpc.Net.Client;
using EonaCat.Connections.Models;
using System.Net.Security;
using System.Security.Authentication;
namespace EonaCat.Connections.gRPC
{
public static class GrpcChannelFactory
{
public static GrpcChannel Create(Configuration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var scheme = config.UseSsl ? "https" : "http";
var address = $"{scheme}://{config.Host}:{config.Port}";
return Create(address, config);
}
public static GrpcChannel Create(string address, Configuration config)
{
if (string.IsNullOrWhiteSpace(address))
{
throw new ArgumentNullException(nameof(address));
}
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
return GrpcChannel.ForAddress(address, BuildChannelOptions(config));
}
public static GrpcChannelOptions BuildChannelOptions(Configuration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var options = new GrpcChannelOptions();
if (config.UseSsl)
{
options.HttpHandler = new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
{
if (config.IsSelfSignedEnabled)
{
return true;
}
return errors == SslPolicyErrors.None;
}
}
};
}
else
{
options.HttpHandler = new SocketsHttpHandler
{
EnableMultipleHttp2Connections = true
};
}
return options;
}
}
}
@@ -0,0 +1,40 @@
using Grpc.Core;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
namespace EonaCat.Connections.gRPC
{
public class GrpcClientConnection
{
public string Id { get; set; } = string.Empty;
public IServerStreamWriter<ConnectorMessage>? ResponseStream { get; set; }
public IPEndPoint? RemoteEndPoint { get; set; }
public SemaphoreSlim WriteLock { get; } = new(1, 1);
public CancellationTokenSource? CancellationSource { get; set; }
public DateTime ConnectedAt { get; set; }
public DateTime LastActive { get; set; }
public DateTime LastDataSent { get; set; }
public DateTime LastDataReceived { get; set; }
public DateTime LastPingSent { get; set; }
public DateTime LastPongReceived { get; set; }
public long BytesSent { get; set; }
public long BytesReceived { get; set; }
public long MessagesSent { get; set; }
public long MessagesReceived { get; set; }
public bool IsConnected => CancellationSource != null && !CancellationSource.IsCancellationRequested;
public TimeSpan ConnectedTime() => DateTime.UtcNow - ConnectedAt;
public TimeSpan IdleTime() => DateTime.UtcNow - (LastActive == default ? ConnectedAt : LastActive);
private string? _nickname;
public string Nickname
{
get => string.IsNullOrWhiteSpace(_nickname) ? Id : _nickname;
set => _nickname = string.IsNullOrWhiteSpace(value) ? Id : value;
}
public bool HasNickname => !string.IsNullOrWhiteSpace(_nickname) && _nickname != Id;
}
}
@@ -0,0 +1,599 @@
using Google.Protobuf;
using Grpc.Core;
using Grpc.Net.Client;
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
public class GrpcNetworkClient : IAsyncDisposable, IDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _config;
private GrpcChannel? _channel;
private AsyncDuplexStreamingCall<ConnectorMessage, ConnectorMessage>? _call;
private Task? _receiveTask;
private Task? _autoReconnectTask;
private Task? _pingTask;
private CancellationTokenSource? _clientCts;
private CancellationTokenSource? _connectionCts;
private CancellationTokenSource? _autoReconnectSource;
private bool _disposed;
private bool _stopAutoReconnecting;
private bool _wasConnected;
private DisconnectReason _reason;
private readonly SemaphoreSlim _connectLock = new(1, 1);
private readonly SemaphoreSlim _streamWriteLock = new(1, 1);
public GrpcChannel? Channel => _channel;
public bool IsConnected { get; private set; }
public string? Nickname { get; private set; }
public DateTime ConnectionTime { get; private set; }
public TimeSpan Uptime => DateTime.UtcNow - ConnectionTime;
public DateTime LastActive { get; internal set; }
public DateTime LastDataSent { get; private set; }
public DateTime LastDataReceived { get; private set; }
public DateTime DisconnectionTime { get; private set; }
public DateTime LastPingSent { get; private set; }
public DateTime LastPongReceived { get; private set; }
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
public long BytesSent { get; private set; }
public long BytesReceived { get; private set; }
public long MessagesSent { get; private set; }
public long MessagesReceived { get; private set; }
public HealthApiServer HealthApi { get; }
public event EventHandler<ConnectionEventArgs>? OnConnected;
public event EventHandler<ConnectionEventArgs>? OnNicknameSend;
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
public event EventHandler<ErrorEventArgs>? OnGeneralError;
public event EventHandler<PingEventArgs>? OnPingReceived;
public event EventHandler<PingEventArgs>? OnPongReceived;
public GrpcNetworkClient(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_clientCts = new CancellationTokenSource();
HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson);
}
public async Task<bool> ConnectAsync()
{
await _connectLock.WaitAsync().ConfigureAwait(false);
try
{
if (_clientCts == null || _clientCts.IsCancellationRequested)
{
_clientCts?.Dispose();
_clientCts = new CancellationTokenSource();
}
if (IsConnected)
{
return true;
}
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_connectionCts = new CancellationTokenSource();
var scheme = _config.UseSsl ? "https" : "http";
var address = $"{scheme}://{_config.Host}:{_config.Port}";
_channel = GrpcChannelFactory.Create(address, _config);
var client = new ConnectorService.ConnectorServiceClient(_channel);
_call = client.Connect(cancellationToken: _connectionCts.Token);
IsConnected = true;
ConnectionTime = DateTime.UtcNow;
LastActive = DateTime.UtcNow;
_receiveTask = Task.Run(() => ReceiveLoopAsync(_connectionCts.Token), _connectionCts.Token);
if (!string.IsNullOrEmpty(Nickname))
{
await SendNicknameAsync(Nickname).ConfigureAwait(false);
}
if (_config.EnableAutoReconnect &&
(_autoReconnectTask == null || _autoReconnectTask.IsCompleted))
{
if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested)
{
_autoReconnectSource?.Dispose();
_autoReconnectSource = new CancellationTokenSource();
}
_autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token);
}
if (_config.EnableHeartbeat)
{
_pingTask = Task.Run(() => PingLoopAsync(_connectionCts.Token), _connectionCts.Token);
}
if (_config.EnableHealthApi)
{
HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress);
}
_wasConnected = true;
HandlingHelpers.SafeInvokeEventHandler(
OnConnected,
this,
new ConnectionEventArgs
{
ClientId = Nickname ?? "self",
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
},
nameof(OnConnected));
return true;
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = exception,
Message = "gRPC connection error"
},
nameof(OnGeneralError));
return false;
}
finally
{
try
{
_connectLock.Release();
}
catch
{
}
}
}
private async Task ReceiveLoopAsync(CancellationToken token)
{
try
{
if (_call == null)
{
return;
}
while (await _call.ResponseStream.MoveNext(token).ConfigureAwait(false))
{
if (token.IsCancellationRequested)
{
break;
}
var message = _call.ResponseStream.Current;
LastActive = DateTime.UtcNow;
switch (message.Type)
{
case MessageType.Ping:
OnPingReceived?.Invoke(this, new PingEventArgs
{
Id = Nickname ?? "self",
ReceivedTime = DateTime.UtcNow
});
await SendPongAsync().ConfigureAwait(false);
continue;
case MessageType.Pong:
LastPongReceived = DateTime.UtcNow;
OnPongReceived?.Invoke(this, new PingEventArgs
{
Id = Nickname ?? "self",
ReceivedTime = DateTime.UtcNow
});
continue;
case MessageType.Disconnect:
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
return;
case MessageType.Data:
default:
break;
}
LastDataReceived = DateTime.UtcNow;
var data = message.Data.ToByteArray();
BytesReceived += data.Length;
MessagesReceived++;
HandlingHelpers.SafeInvokeEventHandler(
OnDataReceived,
this,
new DataReceivedEventArgs
{
ClientId = Nickname ?? "self",
Data = data,
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
Nickname = Nickname
},
nameof(OnDataReceived));
}
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = exception,
Message = "Error receiving gRPC data"
},
nameof(OnGeneralError));
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
}
}
private async Task PingLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false);
if (IsConnected && _call != null)
{
await _streamWriteLock.WaitAsync(token).ConfigureAwait(false);
try
{
var pingMsg = new ConnectorMessage { Type = MessageType.Ping };
await _call.RequestStream.WriteAsync(pingMsg).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
LastPingSent = DateTime.UtcNow;
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC ping loop error: {ex.Message}" });
}
}
}
private async Task SendPongAsync()
{
if (!IsConnected || _call == null)
{
return;
}
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var pongMsg = new ConnectorMessage { Type = MessageType.Pong };
await _call.RequestStream.WriteAsync(pongMsg).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
}
public async Task<bool> SendAsync(byte[] data)
{
if (!IsConnected || _call == null || data == null || data.Length == 0)
{
return false;
}
try
{
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Data,
Data = ByteString.CopyFrom(data)
};
await _call.RequestStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
LastActive = DateTime.UtcNow;
LastDataSent = DateTime.UtcNow;
BytesSent += data.Length;
MessagesSent++;
return true;
}
catch (Exception ex)
{
await DisconnectAsync(DisconnectReason.Error, ex).ConfigureAwait(false);
return false;
}
}
public async Task<bool> SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public async Task SendNicknameAsync(string nickname)
{
Nickname = nickname;
if (IsConnected && _call != null)
{
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Nickname,
Text = nickname
};
await _call.RequestStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
{
ClientId = nickname,
Nickname = nickname
});
}
}
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
{
if (!IsConnected && _channel == null)
{
return;
}
IsConnected = false;
DisconnectionTime = DateTime.UtcNow;
_reason = reason;
_connectionCts?.Cancel();
try
{
if (_call != null)
{
await _call.RequestStream.CompleteAsync().ConfigureAwait(false);
_call.Dispose();
_call = null;
}
}
catch
{
}
try
{
if (_channel != null)
{
_channel.Dispose();
_channel = null;
}
}
catch
{
}
HealthApi.Stop();
HandlingHelpers.SafeInvokeEventHandler(
OnDisconnected,
this,
new ConnectionEventArgs
{
ClientId = Nickname ?? "self",
Reason = reason,
Exception = exception,
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
},
nameof(OnDisconnected));
}
private async Task AutoReconnectAsync(CancellationToken token)
{
while (!token.IsCancellationRequested && !_stopAutoReconnecting)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_config.ReconnectDelayInSeconds), token).ConfigureAwait(false);
if (!IsConnected && _wasConnected)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "gRPC auto-reconnect: attempting reconnection..." });
await ConnectAsync().ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC auto-reconnect error: {ex.Message}" });
}
}
}
public void StopAutoReconnect()
{
_stopAutoReconnecting = true;
_autoReconnectSource?.Cancel();
}
public TClient CreateClient<TClient>(Func<GrpcChannel, TClient> factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
if (_channel == null)
{
throw new InvalidOperationException("Not connected. Call ConnectAsync first.");
}
return factory(_channel);
}
private string BuildHealthJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-client\"," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" +
"}";
}
private string BuildStatusJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-client\"," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"nickname\":{E(Nickname ?? "self")}," +
$"\"bytesSent\":{BytesSent}," +
$"\"bytesReceived\":{BytesReceived}," +
$"\"messagesSent\":{MessagesSent}," +
$"\"messagesReceived\":{MessagesReceived}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," +
$"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," +
$"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}" +
"}";
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_clientCts?.Cancel();
_clientCts?.Dispose();
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
HealthApi.Stop();
try
{
_call?.Dispose();
}
catch
{
}
try
{
_channel?.Dispose();
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
_clientCts?.Cancel();
_clientCts?.Dispose();
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
HealthApi.Stop();
try
{
_call?.Dispose();
}
catch
{
}
try
{
_channel?.Dispose();
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
}
}
}
@@ -0,0 +1,698 @@
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using EonaCat.Connections.gRPC.Proto;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Authentication;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
public class GrpcNetworkServer : IDisposable, IAsyncDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _config;
private readonly Stats _stats;
private readonly ConcurrentDictionary<string, GrpcClientConnection> _clients = new();
private readonly ConcurrentDictionary<string, DateTime> _lastPingTimes = new();
private WebApplication? _app;
private CancellationTokenSource? _serverCts;
private Task? _serverTask;
private Task? _pingTask;
private Task? _pongTask;
private Task? _idleTask;
private bool _disposed;
public bool IsStarted => _serverCts != null && !_serverCts.IsCancellationRequested;
public int ActiveConnections => GetActiveConnectionCount();
public int MaxConnections => _config.MaxConnections;
public string IpAddress => _config.Host;
public int Port => _config.Port;
public long BytesSent => _stats.BytesSent;
public long BytesReceived => _stats.BytesReceived;
public long MessagesSent => _stats.MessagesSent;
public long MessagesReceived => _stats.MessagesReceived;
public double MessagesPerSecond => _stats.MessagesPerSecond;
public long TotalConnections => _stats.TotalConnections;
public long DroppedConnections => _stats.DroppedConnections;
public TimeSpan Uptime => _stats.Uptime;
public DateTime StartTime => _stats.StartTime;
public HealthApiServer HealthApi { get; }
public event EventHandler<ConnectionEventArgs>? OnConnected;
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
public event EventHandler<ErrorEventArgs>? OnGeneralError;
public event EventHandler<PingEventArgs>? OnClientPingResponse;
public event EventHandler<PingEventArgs>? OnPongMissed;
public GrpcNetworkServer(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_stats = new Stats { StartTime = DateTime.UtcNow };
HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson);
}
public Stats GetStats()
{
_stats.ActiveConnections = GetActiveConnectionCount();
return _stats;
}
private int GetActiveConnectionCount()
{
if (_clients.IsEmpty)
{
return 0;
}
int activeCount = 0;
foreach (var client in _clients.Values)
{
if (client?.IsConnected == true)
{
activeCount++;
}
}
return activeCount;
}
internal void TrackDisconnect(DisconnectReason reason)
{
if (reason == DisconnectReason.Error
|| reason == DisconnectReason.Timeout
|| reason == DisconnectReason.SSLError
|| reason == DisconnectReason.NoPongReceived
|| reason == DisconnectReason.ProtocolError)
{
_stats.IncrementDroppedConnections();
}
}
public async Task StartAsync()
{
_serverCts?.Dispose();
_serverCts = new CancellationTokenSource();
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = Array.Empty<string>()
});
builder.Services.AddSingleton(this);
builder.Services.AddGrpc(options =>
{
options.MaxReceiveMessageSize = _config.MAX_MESSAGE_SIZE;
options.MaxSendMessageSize = _config.MAX_MESSAGE_SIZE;
});
builder.WebHost.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Parse(_config.Host), _config.Port, listenOptions =>
{
if (_config.Certificate != null && _config.UseSsl)
{
listenOptions.UseHttps(httpsOptions =>
{
httpsOptions.ServerCertificate = _config.Certificate;
httpsOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13;
});
}
listenOptions.Protocols = HttpProtocols.Http2;
});
});
_app = builder.Build();
_app.MapGrpcService<ConnectorServiceImplementation>();
_serverTask = _app.RunAsync(_serverCts.Token);
if (_config.EnableHeartbeat)
{
_pingTask = Task.Run(() => PingLoopAsync(_serverCts.Token), _serverCts.Token);
_pongTask = Task.Run(() => PongMonitorLoopAsync(_serverCts.Token), _serverCts.Token);
}
if (_config.EnableHealthApi)
{
HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress);
}
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"EonaCat gRPC server started on {_config.Host}:{_config.Port}" });
}
internal bool CanAcceptConnection()
{
return _config.MaxConnections <= 0 || GetActiveConnectionCount() < _config.MaxConnections;
}
internal void IncrementDroppedConnection() => _stats.IncrementDroppedConnections();
internal bool AddClient(string clientId, GrpcClientConnection connection)
{
if (_clients.TryAdd(clientId, connection))
{
_stats.IncrementTotalConnections();
return true;
}
_stats.IncrementDroppedConnections();
return false;
}
internal bool RemoveClient(string clientId, out GrpcClientConnection? client)
{
var removed = _clients.TryRemove(clientId, out client);
_lastPingTimes.TryRemove(clientId, out _);
return removed;
}
internal void RaiseOnConnected(ConnectionEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnConnected, this, args, nameof(OnConnected));
internal void RaiseOnDataReceived(DataReceivedEventArgs args)
{
_stats.IncrementMessagesReceived();
HandlingHelpers.SafeInvokeEventHandler(OnDataReceived, this, args, nameof(OnDataReceived));
}
internal void RaiseOnDisconnected(ConnectionEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnDisconnected, this, args, nameof(OnDisconnected));
internal void RaiseOnGeneralError(ErrorEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnGeneralError, this, args, nameof(OnGeneralError));
internal void TrackBytesReceived(long bytes) => _stats.AddBytesReceived(bytes);
internal void TrackBytesSent(long bytes) => _stats.AddBytesSent(bytes);
public async Task<bool> SendToClientAsync(string clientId, byte[] data)
{
if (data == null || data.Length == 0)
{
return false;
}
if (!_clients.TryGetValue(clientId, out var client) || client.ResponseStream == null)
{
return false;
}
try
{
await client.WriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Data,
Data = Google.Protobuf.ByteString.CopyFrom(data)
};
await client.ResponseStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
client.WriteLock.Release();
}
var sentAt = DateTime.UtcNow;
client.LastDataSent = sentAt;
client.LastActive = sentAt;
client.BytesSent += data.Length;
client.MessagesSent++;
_stats.IncrementMessagesSent();
_stats.AddBytesSent(data.Length);
return true;
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
ClientId = clientId,
Nickname = client.Nickname,
Exception = exception,
Message = "Error sending data to gRPC client"
},
nameof(OnGeneralError));
return false;
}
}
public async Task<bool> SendToClientAsync(string clientId, string message)
=> await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public async Task<bool> BroadcastAsync(byte[] data)
{
if (data == null || data.Length == 0)
{
return false;
}
bool any = false;
foreach (var client in _clients)
{
if (await SendToClientAsync(client.Key, data).ConfigureAwait(false))
{
any = true;
}
}
return any;
}
public async Task<bool> BroadcastAsync(string message)
=> await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public async Task<bool> BroadcastExceptAsync(byte[] data, string excludeClientId)
{
if (data == null || data.Length == 0)
{
return false;
}
bool any = false;
foreach (var client in _clients)
{
if (client.Key == excludeClientId)
{
continue;
}
if (await SendToClientAsync(client.Key, data).ConfigureAwait(false))
{
any = true;
}
}
return any;
}
public async Task<bool> BroadcastExceptAsync(string message, string excludeClientId)
=> await BroadcastExceptAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false);
public ConcurrentDictionary<string, GrpcClientConnection> GetClients() => _clients;
public GrpcClientConnection? GetClient(string clientId)
{
_clients.TryGetValue(clientId, out var client);
return client;
}
public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown)
{
if (!RemoveClient(clientId, out var client))
{
return;
}
try
{
if (client?.ResponseStream != null)
{
await client.WriteLock.WaitAsync().ConfigureAwait(false);
try
{
var msg = new ConnectorMessage { Type = MessageType.Disconnect };
await client.ResponseStream.WriteAsync(msg).ConfigureAwait(false);
}
catch
{
}
finally
{
client.WriteLock.Release();
}
}
client?.CancellationSource?.Cancel();
}
catch
{
}
TrackDisconnect(reason);
HandlingHelpers.SafeInvokeEventHandler(
OnDisconnected,
this,
new ConnectionEventArgs
{
ClientId = clientId,
Nickname = client?.Nickname,
RemoteEndPoint = client?.RemoteEndPoint,
Reason = reason
},
nameof(OnDisconnected));
}
private async Task PingLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false);
foreach (var kvp in _clients)
{
var clientId = kvp.Key;
var client = kvp.Value;
if (client.ResponseStream == null || !client.IsConnected)
{
continue;
}
try
{
await client.WriteLock.WaitAsync(token).ConfigureAwait(false);
try
{
var pingMsg = new ConnectorMessage { Type = MessageType.Ping };
await client.ResponseStream.WriteAsync(pingMsg).ConfigureAwait(false);
}
finally
{
client.WriteLock.Release();
}
client.LastPingSent = DateTime.UtcNow;
_lastPingTimes[clientId] = DateTime.UtcNow;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Error sending ping to {client.Nickname}: {ex.Message}" });
}
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = ex,
Message = "Ping loop error"
},
nameof(OnGeneralError));
}
}
}
private async Task PongMonitorLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(1), token).ConfigureAwait(false);
var now = DateTime.UtcNow;
var timeout = _config.HeartbeatIntervalSeconds * 2;
foreach (var kvp in _lastPingTimes)
{
var clientId = kvp.Key;
var lastPing = kvp.Value;
if (!_clients.TryGetValue(clientId, out var client))
{
_lastPingTimes.TryRemove(clientId, out _);
continue;
}
var elapsed = (now - client.LastPongReceived).TotalSeconds;
if (client.LastPongReceived == default)
{
elapsed = (now - lastPing).TotalSeconds;
}
if (elapsed > timeout)
{
OnPongMissed?.Invoke(this, new PingEventArgs
{
Id = client.Id,
Nickname = client.Nickname,
ReceivedTime = now,
RemoteEndPoint = client.RemoteEndPoint
});
if (_config.DisconectOnMissedPong)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"gRPC client '{client.Nickname}' no PONG for {elapsed:F1}s, disconnecting." });
_ = DisconnectClientAsync(clientId, DisconnectReason.NoPongReceived);
}
}
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = ex,
Message = "Pong monitor loop error"
},
nameof(OnGeneralError));
}
}
}
internal void HandlePongReceived(string clientId)
{
if (_clients.TryGetValue(clientId, out var client))
{
client.LastPongReceived = DateTime.UtcNow;
client.LastActive = DateTime.UtcNow;
OnClientPingResponse?.Invoke(this, new PingEventArgs
{
Id = clientId,
Nickname = client.Nickname,
ReceivedTime = DateTime.UtcNow,
RemoteEndPoint = client.RemoteEndPoint
});
}
}
private string BuildHealthJson()
{
var E = HealthApiServer.JsonEscape;
var stats = GetStats();
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-server\"," +
$"\"listenAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isStarted\":{(IsStarted ? "true" : "false")}," +
$"\"activeConnections\":{stats.ActiveConnections}," +
$"\"maxConnections\":{_config.MaxConnections}," +
$"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1}," +
$"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))}" +
"}";
}
private string BuildStatusJson()
{
var E = HealthApiServer.JsonEscape;
var stats = GetStats();
var sb = new StringBuilder();
sb.Append("{");
sb.Append("\"status\":\"ok\",");
sb.Append("\"type\":\"grpc-server\",");
sb.Append($"\"listenAddress\":{E(_config.Host + ":" + _config.Port)},");
sb.Append($"\"isStarted\":{(IsStarted ? "true" : "false")},");
sb.Append($"\"activeConnections\":{stats.ActiveConnections},");
sb.Append($"\"maxConnections\":{_config.MaxConnections},");
sb.Append($"\"totalConnections\":{stats.TotalConnections},");
sb.Append($"\"droppedConnections\":{stats.DroppedConnections},");
sb.Append($"\"bytesSent\":{stats.BytesSent},");
sb.Append($"\"bytesReceived\":{stats.BytesReceived},");
sb.Append($"\"messagesSent\":{stats.MessagesSent},");
sb.Append($"\"messagesReceived\":{stats.MessagesReceived},");
sb.Append($"\"messagesPerSecond\":{stats.MessagesPerSecond:F2},");
sb.Append($"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1},");
sb.Append($"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))},");
sb.Append("\"clients\":[");
var clientList = _clients.Values.ToArray();
for (int i = 0; i < clientList.Length; i++)
{
var c = clientList[i];
if (i > 0)
{
sb.Append(",");
}
sb.Append("{");
sb.Append($"\"id\":{E(c.Id)},");
sb.Append($"\"nickname\":{E(c.Nickname)},");
sb.Append($"\"remoteEndPoint\":{E(c.RemoteEndPoint?.ToString())},");
sb.Append($"\"connectedAtUtc\":{E(c.ConnectedAt.ToString("O"))},");
sb.Append($"\"connectedTimeSeconds\":{c.ConnectedTime().TotalSeconds:F1},");
sb.Append($"\"idleTimeSeconds\":{c.IdleTime().TotalSeconds:F1},");
sb.Append($"\"bytesSent\":{c.BytesSent},");
sb.Append($"\"bytesReceived\":{c.BytesReceived},");
sb.Append($"\"messagesSent\":{c.MessagesSent},");
sb.Append($"\"messagesReceived\":{c.MessagesReceived}");
sb.Append("}");
}
sb.Append("]");
sb.Append("}");
return sb.ToString();
}
public void Stop()
{
_serverCts?.Cancel();
foreach (var client in _clients.Keys.ToList())
{
DisconnectClientAsync(client, DisconnectReason.ServerShutdown).GetAwaiter().GetResult();
}
_clients.Clear();
HealthApi.Stop();
try
{
_app?.StopAsync().GetAwaiter().GetResult();
}
catch
{
}
try
{
_app?.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
catch
{
}
_app = null;
}
public async Task StopAsync()
{
_serverCts?.Cancel();
foreach (var client in _clients.Keys.ToList())
{
await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false);
}
_clients.Clear();
HealthApi.Stop();
try
{
if (_app != null)
{
await _app.StopAsync().ConfigureAwait(false);
}
}
catch
{
}
try
{
if (_app != null)
{
await _app.DisposeAsync().ConfigureAwait(false);
}
}
catch
{
}
_app = null;
if (_serverTask != null)
{
try
{
await _serverTask.ConfigureAwait(false);
}
catch
{
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
Stop();
_serverCts?.Dispose();
_stats.Dispose();
OnConnected = null;
OnDisconnected = null;
OnDataReceived = null;
OnGeneralError = null;
OnClientPingResponse = null;
OnPongMissed = null;
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
await StopAsync().ConfigureAwait(false);
_serverCts?.Dispose();
_stats.Dispose();
OnConnected = null;
OnDisconnected = null;
OnDataReceived = null;
OnGeneralError = null;
OnClientPingResponse = null;
OnPongMissed = null;
}
}
}
@@ -0,0 +1,23 @@
syntax = "proto3";
option csharp_namespace = "EonaCat.Connections.gRPC.Proto";
package connector;
service ConnectorService {
rpc Connect (stream ConnectorMessage) returns (stream ConnectorMessage);
}
message ConnectorMessage {
MessageType type = 1;
bytes data = 2;
string text = 3;
}
enum MessageType {
DATA = 0;
NICKNAME = 1;
PING = 2;
PONG = 3;
DISCONNECT = 4;
}