Updated
This commit is contained in:
1 parent
2c5b69bf2c
commit
22dee59f47
132 files changed
+19653
-7192
No files matched your search
@@ -0,0 +1,554 @@
|
||||
using EonaCat.Connections.EventArguments;
|
||||
using EonaCat.Connections.Models;
|
||||
using EonaCat.Connections.ConnectionDiagnostics;
|
||||
using EonaCat.Connections.Helpers;
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
|
||||
|
||||
namespace EonaCat.Connections.Quic
|
||||
{
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
[RequiresPreviewFeatures]
|
||||
public class QuicNetworkClient : IAsyncDisposable, IDisposable
|
||||
{
|
||||
public static event EventHandler<LogMessage> OnLog;
|
||||
private readonly Configuration _config;
|
||||
private QuicConnection? _connection;
|
||||
private QuicStream? _stream;
|
||||
private Task? _receiveTask;
|
||||
private Task? _autoReconnectTask;
|
||||
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 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 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 int DEFAULT_STREAM_ERROR_CODE { get; set; } = 0;
|
||||
public int DEFAULT_CLOSE_ERROR_CODE { get; set; } = 0;
|
||||
public int MAX_INBOUND_BIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public int MAX_INBOUND_UNIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public string PROTOCOL_CONNECTION_NAME { get; set; } = "EonaCat-connector";
|
||||
|
||||
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 QuicNetworkClient(Configuration config)
|
||||
{
|
||||
_config = config ?? throw new ArgumentNullException(nameof(config));
|
||||
_clientCts = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
public async Task<bool> ConnectAsync()
|
||||
{
|
||||
if (!QuicConnection.IsSupported)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Message = "QUIC is not supported on this platform."
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
|
||||
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 clientOptions = new QuicClientConnectionOptions
|
||||
{
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
||||
DefaultStreamErrorCode = DEFAULT_STREAM_ERROR_CODE,
|
||||
DefaultCloseErrorCode = DEFAULT_CLOSE_ERROR_CODE,
|
||||
MaxInboundBidirectionalStreams = MAX_INBOUND_BIDIRECTIONAL_STREAMS,
|
||||
MaxInboundUnidirectionalStreams = MAX_INBOUND_UNIDIRECTIONAL_STREAMS,
|
||||
ClientAuthenticationOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = new List<SslApplicationProtocol>
|
||||
{
|
||||
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
|
||||
},
|
||||
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
|
||||
{
|
||||
if (_config.IsSelfSignedEnabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return errors == SslPolicyErrors.None;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_connection = await QuicConnection.ConnectAsync(clientOptions, _connectionCts.Token).ConfigureAwait(false);
|
||||
_stream = await _connection.OpenOutboundStreamAsync(QuicStreamType.Bidirectional, _connectionCts.Token).ConfigureAwait(false);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
_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 = "QUIC connection error"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
_connectLock.Release();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveLoopAsync(CancellationToken token)
|
||||
{
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
|
||||
try
|
||||
{
|
||||
while (!token.IsCancellationRequested && _stream != null)
|
||||
{
|
||||
int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataReceived = DateTime.UtcNow;
|
||||
BytesReceived += bytesRead;
|
||||
MessagesReceived++;
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDataReceived,
|
||||
this,
|
||||
new DataReceivedEventArgs
|
||||
{
|
||||
ClientId = Nickname ?? "self",
|
||||
Data = data,
|
||||
RemoteEndPoint = _connection?.RemoteEndPoint as IPEndPoint,
|
||||
Nickname = Nickname
|
||||
},
|
||||
nameof(OnDataReceived));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "Error receiving QUIC data"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendAsync(byte[] data)
|
||||
{
|
||||
if (!IsConnected || _stream == null || data == null || data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
await _stream.WriteAsync(data, _connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false);
|
||||
await _stream.FlushAsync(_connectionCts?.Token ?? CancellationToken.None).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)
|
||||
{
|
||||
await SendAsync($"NICK:{nickname}").ConfigureAwait(false);
|
||||
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
|
||||
{
|
||||
ClientId = nickname,
|
||||
Nickname = nickname
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
|
||||
{
|
||||
if (!IsConnected && _connection == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
DisconnectionTime = DateTime.UtcNow;
|
||||
_reason = reason;
|
||||
|
||||
_connectionCts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
if (_stream != null)
|
||||
{
|
||||
_stream.Abort(QuicAbortDirection.Both, 0);
|
||||
await _stream.DisposeAsync().ConfigureAwait(false);
|
||||
_stream = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_connection != null)
|
||||
{
|
||||
await _connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await _connection.DisposeAsync().ConfigureAwait(false);
|
||||
_connection = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
var determinedReason = ConnectionEventArgs.Determine(reason, exception);
|
||||
var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception);
|
||||
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception);
|
||||
|
||||
var diagnosticContext = new Dictionary<string, string>();
|
||||
if (exception is System.Net.Sockets.SocketException socketEx)
|
||||
{
|
||||
var socketContext = DisconnectionDiagnostics.AnalyzeSocketException(socketEx);
|
||||
foreach (var kvp in socketContext)
|
||||
{
|
||||
diagnosticContext[$"Socket_{kvp.Key}"] = kvp.Value;
|
||||
}
|
||||
}
|
||||
|
||||
diagnosticContext["IsLocalInitiated"] = initiator == "Local" ? "true" : "false";
|
||||
|
||||
var remoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port);
|
||||
var connectionEventArgs = new ConnectionEventArgs
|
||||
{
|
||||
ClientId = Nickname ?? "self",
|
||||
Reason = determinedReason,
|
||||
Exception = exception,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
Initiator = initiator,
|
||||
ReasonDetails = reasonDetails,
|
||||
DiagnosticContext = diagnosticContext
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var clientLogger = ConnectionLogManager.GetClientLogger();
|
||||
var localEndPoint = _connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
|
||||
clientLogger.LogDisconnection(
|
||||
Nickname ?? "self",
|
||||
"[QUIC Client]",
|
||||
remoteEndPoint.ToString(),
|
||||
localEndPoint,
|
||||
determinedReason.ToString(),
|
||||
initiator,
|
||||
exception,
|
||||
diagnosticContext
|
||||
);
|
||||
}
|
||||
catch (Exception logEx)
|
||||
{
|
||||
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDisconnected,
|
||||
this,
|
||||
connectionEventArgs,
|
||||
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 = "QUIC auto-reconnect: attempting reconnection..." });
|
||||
await ConnectAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"QUIC auto-reconnect error: {ex.Message}" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void StopAutoReconnect()
|
||||
{
|
||||
_stopAutoReconnecting = true;
|
||||
_autoReconnectSource?.Cancel();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
try
|
||||
{
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_connectionCts?.Cancel();
|
||||
_connectionCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_stream?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_connectLock.Dispose();
|
||||
_streamWriteLock.Dispose();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
try
|
||||
{
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_connectionCts?.Cancel();
|
||||
_connectionCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_stream?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_connection is not null)
|
||||
{
|
||||
await _connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_connectLock.Dispose();
|
||||
_streamWriteLock.Dispose();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user