600 lines
20 KiB
C#
600 lines
20 KiB
C#
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();
|
|
}
|
|
}
|
|
}
|