1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-15 02:13:01 +00:00

Squashed commit of the following:

commit 90f285d7f6bcd926ce9ca3d5832b1d70a5eae6ab
Author: JKorf <jankorf91@gmail.com>
Date:   Sun Jun 25 19:51:12 2023 +0200

    Docs

commit 72187035c703d1402b37bd2f4c3e066706f28d67
Author: JKorf <jankorf91@gmail.com>
Date:   Sat Jun 24 16:02:53 2023 +0200

    docs

commit 8411977292f1fb0b6e0705b1ad675b79a5311d90
Author: JKorf <jankorf91@gmail.com>
Date:   Fri Jun 23 18:25:15 2023 +0200

    wip

commit cb7d33aad5d2751104c8b8a6c6eadbf0d36b672c
Author: JKorf <jankorf91@gmail.com>
Date:   Fri Jun 2 19:26:26 2023 +0200

    wip

commit 4359a2d05ea1141cff516dab18f364a6ca854e18
Author: JKorf <jankorf91@gmail.com>
Date:   Wed May 31 20:51:36 2023 +0200

    wip

commit c6adb1b2f728d143f6bd667139c619581122a3c9
Author: JKorf <jankorf91@gmail.com>
Date:   Mon May 1 21:13:47 2023 +0200

    wip

commit 7fee733f82fa6ff574030452f0955c9e817647dd
Author: JKorf <jankorf91@gmail.com>
Date:   Thu Apr 27 13:02:56 2023 +0200

    wip

commit f8057313ffc9b0c31effcda71d35d105ea390971
Author: JKorf <jankorf91@gmail.com>
Date:   Mon Apr 17 21:37:51 2023 +0200

    wip
This commit is contained in:
JKorf
2023-06-25 19:58:46 +02:00
parent 19cc020852
commit 690f2a63e5
74 changed files with 1946 additions and 1826 deletions
@@ -1,5 +1,4 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging;
using CryptoExchange.Net.Objects;
using Microsoft.Extensions.Logging;
using System;
@@ -9,7 +8,6 @@ using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -28,8 +26,8 @@ namespace CryptoExchange.Net.Sockets
Reconnecting
}
internal static int lastStreamId;
private static readonly object streamIdLock = new();
internal static int _lastStreamId;
private static readonly object _streamIdLock = new();
private readonly AsyncResetEvent _sendEvent;
private readonly ConcurrentQueue<byte[]> _sendBuffer;
@@ -60,7 +58,7 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// Log
/// </summary>
protected Log _log;
protected ILogger _logger;
/// <inheritdoc />
public int Id { get; }
@@ -101,14 +99,19 @@ namespace CryptoExchange.Net.Sockets
/// <inheritdoc />
public event Action? OnClose;
/// <inheritdoc />
public event Action<string>? OnMessage;
/// <inheritdoc />
public event Action<Exception>? OnError;
/// <inheritdoc />
public event Action? OnOpen;
/// <inheritdoc />
public event Action? OnReconnecting;
/// <inheritdoc />
public event Action? OnReconnected;
/// <inheritdoc />
@@ -117,12 +120,12 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// ctor
/// </summary>
/// <param name="log">The log object to use</param>
/// <param name="logger">The log object to use</param>
/// <param name="websocketParameters">The parameters for this socket</param>
public CryptoExchangeWebSocketClient(Log log, WebSocketParameters websocketParameters)
public CryptoExchangeWebSocketClient(ILogger logger, WebSocketParameters websocketParameters)
{
Id = NextStreamId();
_log = log;
_logger = logger;
Parameters = websocketParameters;
_outgoingMessages = new List<DateTime>();
@@ -178,7 +181,7 @@ namespace CryptoExchange.Net.Sockets
private async Task<bool> ConnectInternalAsync()
{
_log.Write(LogLevel.Debug, $"Socket {Id} connecting");
_logger.Log(LogLevel.Debug, $"Socket {Id} connecting");
try
{
using CancellationTokenSource tcs = new(TimeSpan.FromSeconds(10));
@@ -186,11 +189,11 @@ namespace CryptoExchange.Net.Sockets
}
catch (Exception e)
{
_log.Write(LogLevel.Debug, $"Socket {Id} connection failed: " + e.ToLogString());
_logger.Log(LogLevel.Debug, $"Socket {Id} connection failed: " + e.ToLogString());
return false;
}
_log.Write(LogLevel.Debug, $"Socket {Id} connected to {Uri}");
_logger.Log(LogLevel.Debug, $"Socket {Id} connected to {Uri}");
return true;
}
@@ -199,13 +202,13 @@ namespace CryptoExchange.Net.Sockets
{
while (!_stopRequested)
{
_log.Write(LogLevel.Debug, $"Socket {Id} starting processing tasks");
_logger.Log(LogLevel.Debug, $"Socket {Id} starting processing tasks");
_processState = ProcessState.Processing;
var sendTask = SendLoopAsync();
var receiveTask = ReceiveLoopAsync();
var timeoutTask = Parameters.Timeout != null && Parameters.Timeout > TimeSpan.FromSeconds(0) ? CheckTimeoutAsync() : Task.CompletedTask;
await Task.WhenAll(sendTask, receiveTask, timeoutTask).ConfigureAwait(false);
_log.Write(LogLevel.Debug, $"Socket {Id} processing tasks finished");
_logger.Log(LogLevel.Debug, $"Socket {Id} processing tasks finished");
_processState = ProcessState.WaitingForClose;
while (_closeTask == null)
@@ -233,14 +236,14 @@ namespace CryptoExchange.Net.Sockets
while (!_stopRequested)
{
_log.Write(LogLevel.Debug, $"Socket {Id} attempting to reconnect");
_logger.Log(LogLevel.Debug, $"Socket {Id} attempting to reconnect");
var task = GetReconnectionUrl?.Invoke();
if (task != null)
{
var reconnectUri = await task.ConfigureAwait(false);
if (reconnectUri != null && Parameters.Uri != reconnectUri)
{
_log.Write(LogLevel.Debug, $"Socket {Id} reconnect URI set to {reconnectUri}");
_logger.Log(LogLevel.Debug, $"Socket {Id} reconnect URI set to {reconnectUri}");
Parameters.Uri = reconnectUri;
}
}
@@ -273,7 +276,7 @@ namespace CryptoExchange.Net.Sockets
return;
var bytes = Parameters.Encoding.GetBytes(data);
_log.Write(LogLevel.Trace, $"Socket {Id} Adding {bytes.Length} to sent buffer");
_logger.Log(LogLevel.Trace, $"Socket {Id} Adding {bytes.Length} to sent buffer");
_sendBuffer.Enqueue(bytes);
_sendEvent.Set();
}
@@ -284,7 +287,7 @@ namespace CryptoExchange.Net.Sockets
if (_processState != ProcessState.Processing && IsOpen)
return;
_log.Write(LogLevel.Debug, $"Socket {Id} reconnect requested");
_logger.Log(LogLevel.Debug, $"Socket {Id} reconnect requested");
_closeTask = CloseInternalAsync();
await _closeTask.ConfigureAwait(false);
}
@@ -299,18 +302,18 @@ namespace CryptoExchange.Net.Sockets
{
if (_closeTask?.IsCompleted == false)
{
_log.Write(LogLevel.Debug, $"Socket {Id} CloseAsync() waiting for existing close task");
_logger.Log(LogLevel.Debug, $"Socket {Id} CloseAsync() waiting for existing close task");
await _closeTask.ConfigureAwait(false);
return;
}
if (!IsOpen)
{
_log.Write(LogLevel.Debug, $"Socket {Id} CloseAsync() socket not open");
_logger.Log(LogLevel.Debug, $"Socket {Id} CloseAsync() socket not open");
return;
}
_log.Write(LogLevel.Debug, $"Socket {Id} closing");
_logger.Log(LogLevel.Debug, $"Socket {Id} closing");
_closeTask = CloseInternalAsync();
}
finally
@@ -322,7 +325,7 @@ namespace CryptoExchange.Net.Sockets
if(_processTask != null)
await _processTask.ConfigureAwait(false);
OnClose?.Invoke();
_log.Write(LogLevel.Debug, $"Socket {Id} closed");
_logger.Log(LogLevel.Debug, $"Socket {Id} closed");
}
/// <summary>
@@ -374,11 +377,11 @@ namespace CryptoExchange.Net.Sockets
if (_disposed)
return;
_log.Write(LogLevel.Debug, $"Socket {Id} disposing");
_logger.Log(LogLevel.Debug, $"Socket {Id} disposing");
_disposed = true;
_socket.Dispose();
_ctsSource.Dispose();
_log.Write(LogLevel.Trace, $"Socket {Id} disposed");
_logger.Log(LogLevel.Trace, $"Socket {Id} disposed");
}
/// <summary>
@@ -412,14 +415,14 @@ namespace CryptoExchange.Net.Sockets
}
if (start != null)
_log.Write(LogLevel.Debug, $"Socket {Id} sent delayed {Math.Round((DateTime.UtcNow - start.Value).TotalMilliseconds)}ms because of rate limit");
_logger.Log(LogLevel.Debug, $"Socket {Id} sent delayed {Math.Round((DateTime.UtcNow - start.Value).TotalMilliseconds)}ms because of rate limit");
}
try
{
await _socket.SendAsync(new ArraySegment<byte>(data, 0, data.Length), WebSocketMessageType.Text, true, _ctsSource.Token).ConfigureAwait(false);
_outgoingMessages.Add(DateTime.UtcNow);
_log.Write(LogLevel.Trace, $"Socket {Id} sent {data.Length} bytes");
_logger.Log(LogLevel.Trace, $"Socket {Id} sent {data.Length} bytes");
}
catch (OperationCanceledException)
{
@@ -442,13 +445,13 @@ namespace CryptoExchange.Net.Sockets
// Because this is running in a separate task and not awaited until the socket gets closed
// any exception here will crash the send processing, but do so silently unless the socket get's stopped.
// Make sure we at least let the owner know there was an error
_log.Write(LogLevel.Warning, $"Socket {Id} Send loop stopped with exception");
_logger.Log(LogLevel.Warning, $"Socket {Id} Send loop stopped with exception");
OnError?.Invoke(e);
throw;
}
finally
{
_log.Write(LogLevel.Debug, $"Socket {Id} Send loop finished");
_logger.Log(LogLevel.Debug, $"Socket {Id} Send loop finished");
}
}
@@ -496,7 +499,7 @@ namespace CryptoExchange.Net.Sockets
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
// Connection closed unexpectedly
_log.Write(LogLevel.Debug, $"Socket {Id} received `Close` message");
_logger.Log(LogLevel.Debug, $"Socket {Id} received `Close` message");
if (_closeTask?.IsCompleted != false)
_closeTask = CloseInternalAsync();
break;
@@ -507,7 +510,7 @@ namespace CryptoExchange.Net.Sockets
// We received data, but it is not complete, write it to a memory stream for reassembling
multiPartMessage = true;
memoryStream ??= new MemoryStream();
_log.Write(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in partial message");
_logger.Log(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in partial message");
await memoryStream.WriteAsync(buffer.Array, buffer.Offset, receiveResult.Count).ConfigureAwait(false);
}
else
@@ -515,13 +518,13 @@ namespace CryptoExchange.Net.Sockets
if (!multiPartMessage)
{
// Received a complete message and it's not multi part
_log.Write(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in single message");
_logger.Log(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in single message");
HandleMessage(buffer.Array!, buffer.Offset, receiveResult.Count, receiveResult.MessageType);
}
else
{
// Received the end of a multipart message, write to memory stream for reassembling
_log.Write(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in partial message");
_logger.Log(LogLevel.Trace, $"Socket {Id} received {receiveResult.Count} bytes in partial message");
await memoryStream!.WriteAsync(buffer.Array, buffer.Offset, receiveResult.Count).ConfigureAwait(false);
}
break;
@@ -549,12 +552,12 @@ namespace CryptoExchange.Net.Sockets
if (receiveResult?.EndOfMessage == true)
{
// Reassemble complete message from memory stream
_log.Write(LogLevel.Trace, $"Socket {Id} reassembled message of {memoryStream!.Length} bytes");
_logger.Log(LogLevel.Trace, $"Socket {Id} reassembled message of {memoryStream!.Length} bytes");
HandleMessage(memoryStream!.ToArray(), 0, (int)memoryStream.Length, receiveResult.MessageType);
memoryStream.Dispose();
}
else
_log.Write(LogLevel.Trace, $"Socket {Id} discarding incomplete message of {memoryStream!.Length} bytes");
_logger.Log(LogLevel.Trace, $"Socket {Id} discarding incomplete message of {memoryStream!.Length} bytes");
}
}
}
@@ -563,13 +566,13 @@ namespace CryptoExchange.Net.Sockets
// Because this is running in a separate task and not awaited until the socket gets closed
// any exception here will crash the receive processing, but do so silently unless the socket gets stopped.
// Make sure we at least let the owner know there was an error
_log.Write(LogLevel.Warning, $"Socket {Id} Receive loop stopped with exception");
_logger.Log(LogLevel.Warning, $"Socket {Id} Receive loop stopped with exception");
OnError?.Invoke(e);
throw;
}
finally
{
_log.Write(LogLevel.Debug, $"Socket {Id} Receive loop finished");
_logger.Log(LogLevel.Debug, $"Socket {Id} Receive loop finished");
}
}
@@ -596,7 +599,7 @@ namespace CryptoExchange.Net.Sockets
}
catch(Exception e)
{
_log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during byte data interpretation: " + e.ToLogString());
_logger.Log(LogLevel.Error, $"Socket {Id} unhandled exception during byte data interpretation: " + e.ToLogString());
return;
}
}
@@ -611,7 +614,7 @@ namespace CryptoExchange.Net.Sockets
}
catch(Exception e)
{
_log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during string data interpretation: " + e.ToLogString());
_logger.Log(LogLevel.Error, $"Socket {Id} unhandled exception during string data interpretation: " + e.ToLogString());
return;
}
}
@@ -623,7 +626,7 @@ namespace CryptoExchange.Net.Sockets
}
catch(Exception e)
{
_log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during message processing: " + e.ToLogString());
_logger.Log(LogLevel.Error, $"Socket {Id} unhandled exception during message processing: " + e.ToLogString());
}
}
@@ -669,7 +672,7 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
protected async Task CheckTimeoutAsync()
{
_log.Write(LogLevel.Debug, $"Socket {Id} Starting task checking for no data received for {Parameters.Timeout}");
_logger.Log(LogLevel.Debug, $"Socket {Id} Starting task checking for no data received for {Parameters.Timeout}");
LastActionTime = DateTime.UtcNow;
try
{
@@ -680,7 +683,7 @@ namespace CryptoExchange.Net.Sockets
if (DateTime.UtcNow - LastActionTime > Parameters.Timeout)
{
_log.Write(LogLevel.Warning, $"Socket {Id} No data received for {Parameters.Timeout}, reconnecting socket");
_logger.Log(LogLevel.Warning, $"Socket {Id} No data received for {Parameters.Timeout}, reconnecting socket");
_ = ReconnectAsync().ConfigureAwait(false);
return;
}
@@ -711,10 +714,10 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
private static int NextStreamId()
{
lock (streamIdLock)
lock (_streamIdLock)
{
lastStreamId++;
return lastStreamId;
_lastStreamId++;
return _lastStreamId;
}
}
@@ -734,8 +737,10 @@ namespace CryptoExchange.Net.Sockets
if (checkTime - _lastReceivedMessagesUpdate > TimeSpan.FromSeconds(1))
{
foreach (var msg in _receivedMessages.ToList()) // To list here because we're removing from the list
{
if (checkTime - msg.Timestamp > TimeSpan.FromSeconds(3))
_receivedMessages.Remove(msg);
}
_lastReceivedMessagesUpdate = checkTime;
}
+3
View File
@@ -12,14 +12,17 @@ namespace CryptoExchange.Net.Sockets
/// The timestamp the data was received
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// The topic of the update, what symbol/asset etc..
/// </summary>
public string? Topic { get; set; }
/// <summary>
/// The original data that was received, only available when OutputOriginalData is set to true in the client options
/// </summary>
public string? OriginalData { get; set; }
/// <summary>
/// The received data deserialized into an object
/// </summary>
@@ -12,14 +12,17 @@ namespace CryptoExchange.Net.Sockets
/// The connection the message was received on
/// </summary>
public SocketConnection Connection { get; set; }
/// <summary>
/// The json object of the data
/// </summary>
public JToken JsonData { get; set; }
/// <summary>
/// The originally received string data
/// </summary>
public string? OriginalData { get; set; }
/// <summary>
/// The timestamp of when the data was received
/// </summary>
+3 -3
View File
@@ -15,7 +15,7 @@ namespace CryptoExchange.Net.Sockets
public TimeSpan Timeout { get; }
public SocketSubscription? Subscription { get; }
private CancellationTokenSource cts;
private CancellationTokenSource _cts;
public PendingRequest(Func<JToken, bool> handler, TimeSpan timeout, SocketSubscription? subscription)
{
@@ -25,8 +25,8 @@ namespace CryptoExchange.Net.Sockets
RequestTimestamp = DateTime.UtcNow;
Subscription = subscription;
cts = new CancellationTokenSource(timeout);
cts.Token.Register(Fail, false);
_cts = new CancellationTokenSource(timeout);
_cts.Token.Register(Fail, false);
}
public bool CheckData(JToken data)
+30 -31
View File
@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using CryptoExchange.Net.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
@@ -120,7 +119,7 @@ namespace CryptoExchange.Net.Sockets
if (_pausedActivity != value)
{
_pausedActivity = value;
_log.Write(LogLevel.Information, $"Socket {SocketId} Paused activity: " + value);
_logger.Log(LogLevel.Information, $"Socket {SocketId} Paused activity: " + value);
if(_pausedActivity) _ = Task.Run(() => ActivityPaused?.Invoke());
else _ = Task.Run(() => ActivityUnpaused?.Invoke());
}
@@ -140,7 +139,7 @@ namespace CryptoExchange.Net.Sockets
var oldStatus = _status;
_status = value;
_log.Write(LogLevel.Debug, $"Socket {SocketId} status changed from {oldStatus} to {_status}");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} status changed from {oldStatus} to {_status}");
}
}
@@ -148,7 +147,7 @@ namespace CryptoExchange.Net.Sockets
private readonly List<SocketSubscription> _subscriptions;
private readonly object _subscriptionLock = new();
private readonly Log _log;
private readonly ILogger _logger;
private readonly List<PendingRequest> _pendingRequests;
@@ -162,13 +161,13 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// New socket connection
/// </summary>
/// <param name="log">The logger</param>
/// <param name="logger">The logger</param>
/// <param name="apiClient">The api client</param>
/// <param name="socket">The socket</param>
/// <param name="tag"></param>
public SocketConnection(Log log, SocketApiClient apiClient, IWebsocket socket, string tag)
public SocketConnection(ILogger logger, SocketApiClient apiClient, IWebsocket socket, string tag)
{
this._log = log;
_logger = logger;
ApiClient = apiClient;
Tag = tag;
@@ -253,7 +252,7 @@ namespace CryptoExchange.Net.Sockets
var reconnectSuccessful = await ProcessReconnectAsync().ConfigureAwait(false);
if (!reconnectSuccessful)
{
_log.Write(LogLevel.Warning, $"Failed reconnect processing: {reconnectSuccessful.Error}, reconnecting again");
_logger.Log(LogLevel.Warning, $"Failed reconnect processing: {reconnectSuccessful.Error}, reconnecting again");
await _socket.ReconnectAsync().ConfigureAwait(false);
}
else
@@ -274,9 +273,9 @@ namespace CryptoExchange.Net.Sockets
protected virtual void HandleError(Exception e)
{
if (e is WebSocketException wse)
_log.Write(LogLevel.Warning, $"Socket {SocketId} error: Websocket error code {wse.WebSocketErrorCode}, details: " + e.ToLogString());
_logger.Log(LogLevel.Warning, $"Socket {SocketId} error: Websocket error code {wse.WebSocketErrorCode}, details: " + e.ToLogString());
else
_log.Write(LogLevel.Warning, $"Socket {SocketId} error: " + e.ToLogString());
_logger.Log(LogLevel.Warning, $"Socket {SocketId} error: " + e.ToLogString());
}
/// <summary>
@@ -286,14 +285,14 @@ namespace CryptoExchange.Net.Sockets
protected virtual void HandleMessage(string data)
{
var timestamp = DateTime.UtcNow;
_log.Write(LogLevel.Trace, $"Socket {SocketId} received data: " + data);
_logger.Log(LogLevel.Trace, $"Socket {SocketId} received data: " + data);
if (string.IsNullOrEmpty(data)) return;
var tokenData = data.ToJToken(_log);
var tokenData = data.ToJToken(_logger);
if (tokenData == null)
{
data = $"\"{data}\"";
tokenData = data.ToJToken(_log);
tokenData = data.ToJToken(_logger);
if (tokenData == null)
return;
}
@@ -324,7 +323,7 @@ namespace CryptoExchange.Net.Sockets
// Answer to a timed out request, unsub if it is a subscription request
if (pendingRequest.Subscription != null)
{
_log.Write(LogLevel.Warning, "Received subscription info after request timed out; unsubscribing. Consider increasing the SocketResponseTimout");
_logger.Log(LogLevel.Warning, "Received subscription info after request timed out; unsubscribing. Consider increasing the SocketResponseTimout");
_ = ApiClient.UnsubscribeAsync(this, pendingRequest.Subscription).ConfigureAwait(false);
}
}
@@ -342,23 +341,23 @@ namespace CryptoExchange.Net.Sockets
}
// Message was not a request response, check data handlers
var messageEvent = new MessageEvent(this, tokenData, ApiClient.Options.OutputOriginalData ? data : null, timestamp);
var messageEvent = new MessageEvent(this, tokenData, ApiClient.OutputOriginalData ? data : null, timestamp);
var (handled, userProcessTime, subscription) = HandleData(messageEvent);
if (!handled && !handledResponse)
{
if (!ApiClient.UnhandledMessageExpected)
_log.Write(LogLevel.Warning, $"Socket {SocketId} Message not handled: " + tokenData);
_logger.Log(LogLevel.Warning, $"Socket {SocketId} Message not handled: " + tokenData);
UnhandledMessage?.Invoke(tokenData);
}
var total = DateTime.UtcNow - timestamp;
if (userProcessTime.TotalMilliseconds > 500)
{
_log.Write(LogLevel.Debug, $"Socket {SocketId}{(subscription == null ? "" : " subscription " + subscription!.Id)} message processing slow ({(int)total.TotalMilliseconds}ms, {(int)userProcessTime.TotalMilliseconds}ms user code), consider offloading data handling to another thread. " +
_logger.Log(LogLevel.Debug, $"Socket {SocketId}{(subscription == null ? "" : " subscription " + subscription!.Id)} message processing slow ({(int)total.TotalMilliseconds}ms, {(int)userProcessTime.TotalMilliseconds}ms user code), consider offloading data handling to another thread. " +
"Data from this socket may arrive late or not at all if message processing is continuously slow.");
}
_log.Write(LogLevel.Trace, $"Socket {SocketId}{(subscription == null ? "" : " subscription " + subscription!.Id)} message processed in {(int)total.TotalMilliseconds}ms, ({(int)userProcessTime.TotalMilliseconds}ms user code)");
_logger.Log(LogLevel.Trace, $"Socket {SocketId}{(subscription == null ? "" : " subscription " + subscription!.Id)} message processed in {(int)total.TotalMilliseconds}ms, ({(int)userProcessTime.TotalMilliseconds}ms user code)");
}
/// <summary>
@@ -422,7 +421,7 @@ namespace CryptoExchange.Net.Sockets
if (Status == SocketStatus.Closing || Status == SocketStatus.Closed || Status == SocketStatus.Disposed)
return;
_log.Write(LogLevel.Debug, $"Socket {SocketId} closing subscription {subscription.Id}");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} closing subscription {subscription.Id}");
if (subscription.CancellationTokenRegistration.HasValue)
subscription.CancellationTokenRegistration.Value.Dispose();
@@ -434,7 +433,7 @@ namespace CryptoExchange.Net.Sockets
{
if (Status == SocketStatus.Closing)
{
_log.Write(LogLevel.Debug, $"Socket {SocketId} already closing");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} already closing");
return;
}
@@ -445,7 +444,7 @@ namespace CryptoExchange.Net.Sockets
if (shouldCloseConnection)
{
_log.Write(LogLevel.Debug, $"Socket {SocketId} closing as there are no more subscriptions");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} closing as there are no more subscriptions");
await CloseAsync().ConfigureAwait(false);
}
@@ -475,7 +474,7 @@ namespace CryptoExchange.Net.Sockets
_subscriptions.Add(subscription);
if(subscription.UserSubscription)
_log.Write(LogLevel.Debug, $"Socket {SocketId} adding new subscription with id {subscription.Id}, total subscriptions on connection: {_subscriptions.Count(s => s.UserSubscription)}");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} adding new subscription with id {subscription.Id}, total subscriptions on connection: {_subscriptions.Count(s => s.UserSubscription)}");
return true;
}
}
@@ -551,7 +550,7 @@ namespace CryptoExchange.Net.Sockets
}
catch (Exception ex)
{
_log.Write(LogLevel.Error, $"Socket {SocketId} Exception during message processing\r\nException: {ex.ToLogString()}\r\nData: {messageEvent.JsonData}");
_logger.Log(LogLevel.Error, $"Socket {SocketId} Exception during message processing\r\nException: {ex.ToLogString()}\r\nData: {messageEvent.JsonData}");
currentSubscription?.InvokeExceptionHandler(ex);
return (false, TimeSpan.Zero, null);
}
@@ -600,7 +599,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="data">The data to send</param>
public virtual bool Send(string data)
{
_log.Write(LogLevel.Trace, $"Socket {SocketId} sending data: {data}");
_logger.Log(LogLevel.Trace, $"Socket {SocketId} sending data: {data}");
try
{
_socket.Send(data);
@@ -624,7 +623,7 @@ namespace CryptoExchange.Net.Sockets
if (!anySubscriptions)
{
// No need to resubscribe anything
_log.Write(LogLevel.Debug, $"Socket {SocketId} Nothing to resubscribe, closing connection");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} Nothing to resubscribe, closing connection");
_ = _socket.CloseAsync();
return new CallResult<bool>(true);
}
@@ -639,12 +638,12 @@ namespace CryptoExchange.Net.Sockets
var authResult = await ApiClient.AuthenticateSocketAsync(this).ConfigureAwait(false);
if (!authResult)
{
_log.Write(LogLevel.Warning, $"Socket {SocketId} authentication failed on reconnected socket. Disconnecting and reconnecting.");
_logger.Log(LogLevel.Warning, $"Socket {SocketId} authentication failed on reconnected socket. Disconnecting and reconnecting.");
return authResult;
}
Authenticated = true;
_log.Write(LogLevel.Debug, $"Socket {SocketId} authentication succeeded on reconnected socket.");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} authentication succeeded on reconnected socket.");
}
// Get a list of all subscriptions on the socket
@@ -665,19 +664,19 @@ namespace CryptoExchange.Net.Sockets
var result = await ApiClient.RevitalizeRequestAsync(subscription.Request!).ConfigureAwait(false);
if (!result)
{
_log.Write(LogLevel.Warning, "Failed request revitalization: " + result.Error);
_logger.Log(LogLevel.Warning, "Failed request revitalization: " + result.Error);
return result.As<bool>(false);
}
}
// Foreach subscription which is subscribed by a subscription request we will need to resend that request to resubscribe
for (var i = 0; i < subscriptionList.Count; i += ApiClient.Options.MaxConcurrentResubscriptionsPerSocket)
for (var i = 0; i < subscriptionList.Count; i += ApiClient.ClientOptions.MaxConcurrentResubscriptionsPerSocket)
{
if (!_socket.IsOpen)
return new CallResult<bool>(new WebError("Socket not connected"));
var taskList = new List<Task<CallResult<bool>>>();
foreach (var subscription in subscriptionList.Skip(i).Take(ApiClient.Options.MaxConcurrentResubscriptionsPerSocket))
foreach (var subscription in subscriptionList.Skip(i).Take(ApiClient.ClientOptions.MaxConcurrentResubscriptionsPerSocket))
taskList.Add(ApiClient.SubscribeAndWaitAsync(this, subscription.Request!, subscription));
await Task.WhenAll(taskList).ConfigureAwait(false);
@@ -691,7 +690,7 @@ namespace CryptoExchange.Net.Sockets
if (!_socket.IsOpen)
return new CallResult<bool>(new WebError("Socket not connected"));
_log.Write(LogLevel.Debug, $"Socket {SocketId} all subscription successfully resubscribed on reconnected socket.");
_logger.Log(LogLevel.Debug, $"Socket {SocketId} all subscription successfully resubscribed on reconnected socket.");
return new CallResult<bool>(true);
}
@@ -9,16 +9,16 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public class UpdateSubscription
{
private readonly SocketConnection connection;
private readonly SocketSubscription subscription;
private readonly SocketConnection _connection;
private readonly SocketSubscription _subscription;
/// <summary>
/// Event when the connection is lost. The socket will automatically reconnect when possible.
/// </summary>
public event Action ConnectionLost
{
add => connection.ConnectionLost += value;
remove => connection.ConnectionLost -= value;
add => _connection.ConnectionLost += value;
remove => _connection.ConnectionLost -= value;
}
/// <summary>
@@ -26,8 +26,8 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public event Action ConnectionClosed
{
add => connection.ConnectionClosed += value;
remove => connection.ConnectionClosed -= value;
add => _connection.ConnectionClosed += value;
remove => _connection.ConnectionClosed -= value;
}
/// <summary>
@@ -37,8 +37,8 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public event Action<TimeSpan> ConnectionRestored
{
add => connection.ConnectionRestored += value;
remove => connection.ConnectionRestored -= value;
add => _connection.ConnectionRestored += value;
remove => _connection.ConnectionRestored -= value;
}
/// <summary>
@@ -46,8 +46,8 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public event Action ActivityPaused
{
add => connection.ActivityPaused += value;
remove => connection.ActivityPaused -= value;
add => _connection.ActivityPaused += value;
remove => _connection.ActivityPaused -= value;
}
/// <summary>
@@ -55,8 +55,8 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public event Action ActivityUnpaused
{
add => connection.ActivityUnpaused += value;
remove => connection.ActivityUnpaused -= value;
add => _connection.ActivityUnpaused += value;
remove => _connection.ActivityUnpaused -= value;
}
/// <summary>
@@ -64,19 +64,19 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public event Action<Exception> Exception
{
add => subscription.Exception += value;
remove => subscription.Exception -= value;
add => _subscription.Exception += value;
remove => _subscription.Exception -= value;
}
/// <summary>
/// The id of the socket
/// </summary>
public int SocketId => connection.SocketId;
public int SocketId => _connection.SocketId;
/// <summary>
/// The id of the subscription
/// </summary>
public int Id => subscription.Id;
public int Id => _subscription.Id;
/// <summary>
/// ctor
@@ -85,8 +85,8 @@ namespace CryptoExchange.Net.Sockets
/// <param name="subscription">The subscription</param>
public UpdateSubscription(SocketConnection connection, SocketSubscription subscription)
{
this.connection = connection;
this.subscription = subscription;
this._connection = connection;
this._subscription = subscription;
}
/// <summary>
@@ -95,7 +95,7 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
public Task CloseAsync()
{
return connection.CloseAsync(subscription);
return _connection.CloseAsync(_subscription);
}
/// <summary>
@@ -104,7 +104,7 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
public Task ReconnectAsync()
{
return connection.TriggerReconnectAsync();
return _connection.TriggerReconnectAsync();
}
/// <summary>
@@ -113,7 +113,7 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
internal async Task UnsubscribeAsync()
{
await connection.UnsubscribeAsync(subscription).ConfigureAwait(false);
await _connection.UnsubscribeAsync(_subscription).ConfigureAwait(false);
}
/// <summary>
@@ -122,7 +122,7 @@ namespace CryptoExchange.Net.Sockets
/// <returns></returns>
internal async Task<CallResult<bool>> ResubscribeAsync()
{
return await connection.ResubscribeAsync(subscription).ConfigureAwait(false);
return await _connection.ResubscribeAsync(_subscription).ConfigureAwait(false);
}
}
}
@@ -15,42 +15,52 @@ namespace CryptoExchange.Net.Sockets
/// The uri to connect to
/// </summary>
public Uri Uri { get; set; }
/// <summary>
/// Headers to send in the connection handshake
/// </summary>
public IDictionary<string, string> Headers { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Cookies to send in the connection handshake
/// </summary>
public IDictionary<string, string> Cookies { get; set; } = new Dictionary<string, string>();
/// <summary>
/// The time to wait between reconnect attempts
/// </summary>
public TimeSpan ReconnectInterval { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Proxy for the connection
/// </summary>
public ApiProxy? Proxy { get; set; }
/// <summary>
/// Whether the socket should automatically reconnect when connection is lost
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// The maximum time of no data received before considering the connection lost and closting/reconnecting the socket
/// </summary>
public TimeSpan? Timeout { get; set; }
/// <summary>
/// Interval at which to send ping frames
/// </summary>
public TimeSpan? KeepAliveInterval { get; set; }
/// <summary>
/// The max amount of messages to send per second
/// </summary>
public int? RatelimitPerSecond { get; set; }
/// <summary>
/// Origin header value to send in the connection handshake
/// </summary>
public string? Origin { get; set; }
/// <summary>
/// Delegate used for processing byte data received from socket connections before it is processed by handlers
/// </summary>
@@ -1,5 +1,5 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Sockets
{
@@ -9,9 +9,9 @@ namespace CryptoExchange.Net.Sockets
public class WebsocketFactory : IWebsocketFactory
{
/// <inheritdoc />
public IWebsocket CreateWebsocket(Log log, WebSocketParameters parameters)
public IWebsocket CreateWebsocket(ILogger logger, WebSocketParameters parameters)
{
return new CryptoExchangeWebSocketClient(log, parameters);
return new CryptoExchangeWebSocketClient(logger, parameters);
}
}
}