1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-12 00:43:03 +00:00

Compare commits

..

1 Commits

Author SHA1 Message Date
JKorf decef7b137 Update CryptoExchange.Net.csproj 2024-07-03 21:53:36 +02:00
26 changed files with 194 additions and 372 deletions
@@ -58,7 +58,9 @@ namespace CryptoExchange.Net.UnitTests
options.ReconnectInterval = TimeSpan.Zero;
});
var socket = client.CreateSocket();
socket.ShouldReconnect = true;
socket.CanConnect = true;
socket.DisconnectTime = DateTime.UtcNow;
var sub = new SocketConnection(new TraceLogger(), client.SubClient, socket, null);
var rstEvent = new ManualResetEvent(false);
Dictionary<string, string> result = null;
@@ -73,7 +75,7 @@ namespace CryptoExchange.Net.UnitTests
sub.AddSubscription(subObj);
// act
socket.InvokeMessage("{\"property\": \"123\", \"action\": \"update\", \"topic\": \"topic\"}");
socket.InvokeMessage("{\"property\": \"123\", \"topic\": \"topic\"}");
rstEvent.WaitOne(1000);
// assert
@@ -91,7 +93,9 @@ namespace CryptoExchange.Net.UnitTests
options.SubOptions.OutputOriginalData = enabled;
});
var socket = client.CreateSocket();
socket.ShouldReconnect = true;
socket.CanConnect = true;
socket.DisconnectTime = DateTime.UtcNow;
var sub = new SocketConnection(new TraceLogger(), client.SubClient, socket, null);
var rstEvent = new ManualResetEvent(false);
string original = null;
@@ -103,7 +107,7 @@ namespace CryptoExchange.Net.UnitTests
rstEvent.Set();
});
sub.AddSubscription(subObj);
var msgToSend = JsonConvert.SerializeObject(new { topic = "topic", action = "update", property = 123 });
var msgToSend = JsonConvert.SerializeObject(new { topic = "topic", property = 123 });
// act
socket.InvokeMessage(msgToSend);
@@ -198,7 +202,7 @@ namespace CryptoExchange.Net.UnitTests
// act
var sub = client.SubClient.SubscribeToSomethingAsync(channel, onUpdate => {}, ct: default);
socket.InvokeMessage(JsonConvert.SerializeObject(new { channel, action = "subscribe", status = "error" }));
socket.InvokeMessage(JsonConvert.SerializeObject(new { channel, status = "error" }));
await sub;
// assert
@@ -221,7 +225,7 @@ namespace CryptoExchange.Net.UnitTests
// act
var sub = client.SubClient.SubscribeToSomethingAsync(channel, onUpdate => {}, ct: default);
socket.InvokeMessage(JsonConvert.SerializeObject(new { channel, action = "subscribe", status = "confirmed" }));
socket.InvokeMessage(JsonConvert.SerializeObject(new { channel, status = "confirmed" }));
await sub;
// assert
@@ -10,10 +10,6 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations.Sockets
{
internal class SubResponse
{
[JsonProperty("action")]
public string Action { get; set; } = null!;
[JsonProperty("channel")]
public string Channel { get; set; } = null!;
@@ -23,9 +19,6 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations.Sockets
internal class UnsubResponse
{
[JsonProperty("action")]
public string Action { get; set; } = null!;
[JsonProperty("status")]
public string Status { get; set; } = null!;
}
@@ -36,7 +29,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations.Sockets
public TestChannelQuery(string channel, string request, bool authenticated, int weight = 1) : base(request, authenticated, weight)
{
ListenerIdentifiers = new HashSet<string> { request + "-" + channel };
ListenerIdentifiers = new HashSet<string> { channel };
}
public override CallResult<SubResponse> HandleMessage(SocketConnection connection, DataEvent<SubResponse> message)
@@ -15,7 +15,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations.Sockets
{
private readonly Action<DataEvent<T>> _handler;
public override HashSet<string> ListenerIdentifiers { get; set; } = new HashSet<string> { "update-topic" };
public override HashSet<string> ListenerIdentifiers { get; set; } = new HashSet<string> { "topic" };
public TestSubscription(ILogger logger, Action<DataEvent<T>> handler) : base(logger, false)
{
@@ -1,132 +1,131 @@
//using System;
//using System.IO;
//using System.Net.WebSockets;
//using System.Security.Authentication;
//using System.Text;
//using System.Threading.Tasks;
//using CryptoExchange.Net.Interfaces;
//using CryptoExchange.Net.Objects;
using System;
using System.IO;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
//namespace CryptoExchange.Net.UnitTests.TestImplementations
//{
// public class TestSocket: IWebsocket
// {
// public bool CanConnect { get; set; }
// public bool Connected { get; set; }
namespace CryptoExchange.Net.UnitTests.TestImplementations
{
public class TestSocket: IWebsocket
{
public bool CanConnect { get; set; }
public bool Connected { get; set; }
// public event Func<Task> OnClose;
//#pragma warning disable 0067
// public event Func<Task> OnReconnected;
// public event Func<Task> OnReconnecting;
// public event Func<int, Task> OnRequestRateLimited;
//#pragma warning restore 0067
// public event Func<int, Task> OnRequestSent;
// public event Func<WebSocketMessageType, ReadOnlyMemory<byte>, Task> OnStreamMessage;
// public event Func<Exception, Task> OnError;
// public event Func<Task> OnOpen;
// public Func<Task<Uri>> GetReconnectionUrl { get; set; }
public event Func<Task> OnClose;
#pragma warning disable 0067
public event Func<Task> OnReconnected;
public event Func<Task> OnReconnecting;
public event Func<int, Task> OnRequestRateLimited;
#pragma warning restore 0067
public event Func<int, Task> OnRequestSent;
public event Action<WebSocketMessageType, ReadOnlyMemory<byte>> OnStreamMessage;
public event Func<Exception, Task> OnError;
public event Func<Task> OnOpen;
public Func<Task<Uri>> GetReconnectionUrl { get; set; }
// public int Id { get; }
// public bool ShouldReconnect { get; set; }
// public TimeSpan Timeout { get; set; }
// public Func<string, string> DataInterpreterString { get; set; }
// public Func<byte[], string> DataInterpreterBytes { get; set; }
// public DateTime? DisconnectTime { get; set; }
// public string Url { get; }
// public bool IsClosed => !Connected;
// public bool IsOpen => Connected;
// public bool PingConnection { get; set; }
// public TimeSpan PingInterval { get; set; }
// public SslProtocols SSLProtocols { get; set; }
// public Encoding Encoding { get; set; }
public int Id { get; }
public bool ShouldReconnect { get; set; }
public TimeSpan Timeout { get; set; }
public Func<string, string> DataInterpreterString { get; set; }
public Func<byte[], string> DataInterpreterBytes { get; set; }
public DateTime? DisconnectTime { get; set; }
public string Url { get; }
public bool IsClosed => !Connected;
public bool IsOpen => Connected;
public bool PingConnection { get; set; }
public TimeSpan PingInterval { get; set; }
public SslProtocols SSLProtocols { get; set; }
public Encoding Encoding { get; set; }
// public int ConnectCalls { get; private set; }
// public bool Reconnecting { get; set; }
// public string Origin { get; set; }
// public int? RatelimitPerSecond { get; set; }
public int ConnectCalls { get; private set; }
public bool Reconnecting { get; set; }
public string Origin { get; set; }
public int? RatelimitPerSecond { get; set; }
// public double IncomingKbps => throw new NotImplementedException();
public double IncomingKbps => throw new NotImplementedException();
// public Uri Uri => new Uri("");
public Uri Uri => new Uri("");
// public TimeSpan KeepAliveInterval { get; set; }
public TimeSpan KeepAliveInterval { get; set; }
// public static int lastId = 0;
// public static object lastIdLock = new object();
public static int lastId = 0;
public static object lastIdLock = new object();
// public TestSocket()
// {
// lock (lastIdLock)
// {
// Id = lastId + 1;
// lastId++;
// }
// }
public TestSocket()
{
lock (lastIdLock)
{
Id = lastId + 1;
lastId++;
}
}
// public Task<CallResult> ConnectAsync()
// {
// Connected = CanConnect;
// ConnectCalls++;
// if (CanConnect)
// InvokeOpen();
// return Task.FromResult(CanConnect ? new CallResult(null) : new CallResult(new CantConnectError()));
// }
public Task<CallResult> ConnectAsync()
{
Connected = CanConnect;
ConnectCalls++;
if (CanConnect)
InvokeOpen();
return Task.FromResult(CanConnect ? new CallResult(null) : new CallResult(new CantConnectError()));
}
// public bool Send(int requestId, string data, int weight)
// {
// if(!Connected)
// throw new Exception("Socket not connected");
// OnRequestSent?.Invoke(requestId);
// return true;
// }
public void Send(int requestId, string data, int weight)
{
if(!Connected)
throw new Exception("Socket not connected");
OnRequestSent?.Invoke(requestId);
}
// public void Reset()
// {
// }
public void Reset()
{
}
// public Task CloseAsync()
// {
// Connected = false;
// DisconnectTime = DateTime.UtcNow;
// OnClose?.Invoke();
// return Task.FromResult(0);
// }
public Task CloseAsync()
{
Connected = false;
DisconnectTime = DateTime.UtcNow;
OnClose?.Invoke();
return Task.FromResult(0);
}
// public void SetProxy(string host, int port)
// {
// throw new NotImplementedException();
// }
// public void Dispose()
// {
// }
public void SetProxy(string host, int port)
{
throw new NotImplementedException();
}
public void Dispose()
{
}
// public void InvokeClose()
// {
// Connected = false;
// DisconnectTime = DateTime.UtcNow;
// Reconnecting = true;
// OnClose?.Invoke();
// }
public void InvokeClose()
{
Connected = false;
DisconnectTime = DateTime.UtcNow;
Reconnecting = true;
OnClose?.Invoke();
}
// public void InvokeOpen()
// {
// OnOpen?.Invoke();
// }
public void InvokeOpen()
{
OnOpen?.Invoke();
}
// public void InvokeMessage(string data)
// {
// OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(data))).Wait();
// }
public void InvokeMessage(string data)
{
OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(data)));
}
// public void SetProxy(ApiProxy proxy)
// {
// throw new NotImplementedException();
// }
public void SetProxy(ApiProxy proxy)
{
throw new NotImplementedException();
}
// public void InvokeError(Exception error)
// {
// OnError?.Invoke(error);
// }
// public Task ReconnectAsync() => Task.CompletedTask;
// }
//}
public void InvokeError(Exception error)
{
OnError?.Invoke(error);
}
public Task ReconnectAsync() => Task.CompletedTask;
}
}
@@ -13,11 +13,11 @@ using CryptoExchange.Net.Sockets;
using CryptoExchange.Net.UnitTests.TestImplementations.Sockets;
using Microsoft.Extensions.Logging;
using Moq;
using CryptoExchange.Net.Testing.Implementations;
using Newtonsoft.Json.Linq;
namespace CryptoExchange.Net.UnitTests.TestImplementations
{
internal class TestSocketClient: BaseSocketClient
public class TestSocketClient: BaseSocketClient
{
public TestSubSocketClient SubClient { get; }
@@ -41,12 +41,12 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
SubClient = AddApiClient(new TestSubSocketClient(options, options.SubOptions));
SubClient.SocketFactory = new Mock<IWebsocketFactory>().Object;
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket("https://test.com"));
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket());
}
public TestSocket CreateSocket()
{
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket("https://test.com"));
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket());
return (TestSocket)SubClient.CreateSocketInternal("https://localhost:123/");
}
@@ -75,7 +75,6 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
public class TestSubSocketClient : SocketApiClient
{
private MessagePath _channelPath = MessagePath.Get().Property("channel");
private MessagePath _actionPath = MessagePath.Get().Property("action");
private MessagePath _topicPath = MessagePath.Get().Property("topic");
public Subscription TestSubscription { get; private set; } = null;
@@ -111,7 +110,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
var id = message.GetValue<string>(_channelPath);
id ??= message.GetValue<string>(_topicPath);
return message.GetValue<string>(_actionPath) + "-" + id;
return id;
}
public Task<CallResult<UpdateSubscription>> SubscribeToSomethingAsync(string channel, Action<DataEvent<string>> onUpdate, CancellationToken ct)
@@ -251,7 +251,7 @@ namespace CryptoExchange.Net.Clients
return new CallResult<UpdateSubscription>(new ServerError("Socket is paused"));
}
var waitEvent = new AsyncResetEvent(false);
var waitEvent = new ManualResetEvent(false);
var subQuery = subscription.GetSubQuery(socketConnection);
if (subQuery != null)
{
@@ -269,7 +269,7 @@ namespace CryptoExchange.Net.Clients
{
_logger.FailedToSubscribe(socketConnection.SocketId, subResult.Error?.ToString());
// If this was a timeout we still need to send an unsubscribe to prevent messages coming in later
await socketConnection.CloseAsync(subscription).ConfigureAwait(false);
await socketConnection.CloseAsync(subscription, isTimeout).ConfigureAwait(false);
return new CallResult<UpdateSubscription>(subResult.Error!);
}
}
@@ -32,7 +32,6 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public ArrayPropertyAttribute ArrayProperty { get; set; } = null!;
public Type? JsonConverterType { get; set; }
public bool DefaultDeserialization { get; set; }
public Type TargetType { get; set; } = null!;
}
private class ArrayConverterInner<T> : JsonConverter<T>
@@ -71,8 +70,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
ArrayProperty = att,
PropertyInfo = property,
DefaultDeserialization = property.GetCustomAttribute<JsonConversionAttribute>() != null,
JsonConverterType = property.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType,
TargetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType
JsonConverterType = property.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType
});
}
@@ -98,7 +96,8 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
if (attribute == null)
continue;
var targetType = attribute.TargetType;
var targetType = attribute.PropertyInfo.PropertyType;
object? value = null;
if (attribute.JsonConverterType != null)
{
@@ -125,7 +124,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
};
}
attribute.PropertyInfo.SetValue(result, value == null ? null : Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture));
attribute.PropertyInfo.SetValue(result, value == null ? null : Convert.ChangeType(value, attribute.PropertyInfo.PropertyType, CultureInfo.InvariantCulture));
index++;
}
@@ -242,7 +242,6 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
{
_stream?.Dispose();
_stream = null;
_document?.Dispose();
_document = null;
}
@@ -262,14 +261,6 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
try
{
var firstByte = data.Span[0];
if (firstByte != 0x7b && firstByte != 0x5b)
{
// Value doesn't start with `{` or `[`, prevent deserialization attempt as it's slow
IsJson = false;
return new CallResult(new ServerError("Not a json value"));
}
_document = JsonDocument.Parse(data);
IsJson = true;
return new CallResult(null);
@@ -298,7 +289,6 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public override void Clear()
{
_bytes = null;
_document?.Dispose();
_document = null;
}
}
+5 -4
View File
@@ -6,9 +6,9 @@
<PackageId>CryptoExchange.Net</PackageId>
<Authors>JKorf</Authors>
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
<PackageVersion>7.9.0</PackageVersion>
<AssemblyVersion>7.9.0</AssemblyVersion>
<FileVersion>7.9.0</FileVersion>
<PackageVersion>7.8.0</PackageVersion>
<AssemblyVersion>7.8.0</AssemblyVersion>
<FileVersion>7.8.0</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange</PackageTags>
<RepositoryType>git</RepositoryType>
@@ -53,11 +53,12 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.4" />
<PackageReference Include="System.Text.Json" Version="8.0.3" />
</ItemGroup>
</Project>
@@ -3,7 +3,6 @@ using CryptoExchange.Net.Objects.Sockets;
using CryptoExchange.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
{
@@ -26,7 +25,7 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="connection"></param>
/// <param name="message"></param>
/// <returns></returns>
Task<CallResult> Handle(SocketConnection connection, DataEvent<object> message);
CallResult Handle(SocketConnection connection, DataEvent<object> message);
/// <summary>
/// Get the type the message should be deserialized to
/// </summary>
+2 -2
View File
@@ -17,7 +17,7 @@ namespace CryptoExchange.Net.Interfaces
/// <summary>
/// Websocket message received event
/// </summary>
event Func<WebSocketMessageType, ReadOnlyMemory<byte>, Task> OnStreamMessage;
event Action<WebSocketMessageType, ReadOnlyMemory<byte>> OnStreamMessage;
/// <summary>
/// Websocket sent event, RequestId as parameter
/// </summary>
@@ -78,7 +78,7 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="id"></param>
/// <param name="data"></param>
/// <param name="weight"></param>
bool Send(int id, string data, int weight);
void Send(int id, string data, int weight);
/// <summary>
/// Reconnect the socket
/// </summary>
@@ -3,8 +3,7 @@ using System;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class CryptoExchangeWebSocketClientLoggingExtension
internal static class CryptoExchangeWebSocketClientLoggingExtension
{
private static readonly Action<ILogger, int, Exception?> _connecting;
private static readonly Action<ILogger, int, string, Exception?> _connectionFailed;
@@ -152,7 +151,7 @@ namespace CryptoExchange.Net.Logging.Extensions
"[Sckt {SocketId}] discarding incomplete message of {NumBytes} bytes");
_receiveLoopStoppedWithException = LoggerMessage.Define<int>(
LogLevel.Error,
LogLevel.Warning,
new EventId(1024, "ReceiveLoopStoppedWithException"),
"[Sckt {SocketId}] receive loop stopped with exception");
@@ -3,8 +3,7 @@ using System;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class RateLimitGateLoggingExtensions
internal static class RateLimitGateLoggingExtensions
{
private static readonly Action<ILogger, int, string, string, string, Exception?> _rateLimitRequestFailed;
private static readonly Action<ILogger, int, string, string, Exception?> _rateLimitConnectionFailed;
@@ -6,8 +6,7 @@ using System.Net.Http;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class RestApiClientLoggingExtensions
internal static class RestApiClientLoggingExtensions
{
private static readonly Action<ILogger, int?, int?, long, string?, Exception?> _restApiErrorReceived;
private static readonly Action<ILogger, int?, int?, long, string?, Exception?> _restApiResponseReceived;
@@ -3,8 +3,7 @@ using System;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SocketApiClientLoggingExtension
internal static class SocketApiClientLoggingExtension
{
private static readonly Action<ILogger, int, Exception?> _failedToAddSubscriptionRetryOnDifferentConnection;
private static readonly Action<ILogger, int, Exception?> _hasBeenPausedCantSubscribeAtThisMoment;
@@ -4,8 +4,7 @@ using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SocketConnectionLoggingExtension
internal static class SocketConnectionLoggingExtension
{
private static readonly Action<ILogger, int, bool, Exception?> _activityPaused;
private static readonly Action<ILogger, int, Sockets.SocketConnection.SocketStatus, Sockets.SocketConnection.SocketStatus, Exception?> _socketStatusChanged;
@@ -4,9 +4,7 @@ using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Logging.Extensions
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SymbolOrderBookLoggingExtensions
internal static class SymbolOrderBookLoggingExtensions
{
private static readonly Action<ILogger, string, string, OrderBookStatus, OrderBookStatus, Exception?> _orderBookStatusChanged;
private static readonly Action<ILogger, string, string, Exception?> _orderBookStarting;
-22
View File
@@ -273,28 +273,6 @@ namespace CryptoExchange.Net.Objects
return new WebCallResult(ResponseStatusCode, ResponseHeaders, ResponseTime, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, error);
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <param name="data">The data of the new type</param>
/// <returns></returns>
public WebCallResult<K> As<K>([AllowNull] K data)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, data, Error);
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <param name="error">The error returned</param>
/// <returns></returns>
public WebCallResult<K> AsError<K>(Error error)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, default, error);
}
/// <inheritdoc />
public override string ToString()
{
@@ -144,11 +144,5 @@ namespace CryptoExchange.Net.Objects.Sockets
{
return new CallResult<K>(default, OriginalData, error);
}
/// <inheritdoc />
public override string ToString()
{
return $"{StreamId} - {(Symbol == null ? "" : (Symbol + " - "))}{(UpdateType == null ? "" : (UpdateType + " - "))}{Data}";
}
}
}
@@ -108,7 +108,7 @@ namespace CryptoExchange.Net.Sockets
public event Func<Task>? OnClose;
/// <inheritdoc />
public event Func<WebSocketMessageType, ReadOnlyMemory<byte>, Task>? OnStreamMessage;
public event Action<WebSocketMessageType, ReadOnlyMemory<byte>>? OnStreamMessage;
/// <inheritdoc />
public event Func<int, Task>? OnRequestSent;
@@ -245,8 +245,7 @@ namespace CryptoExchange.Net.Sockets
await Task.Delay(50).ConfigureAwait(false);
await _closeTask.ConfigureAwait(false);
if (!_stopRequested)
_closeTask = null;
_closeTask = null;
if (Parameters.ReconnectPolicy == ReconnectPolicy.Disabled)
{
@@ -323,16 +322,15 @@ namespace CryptoExchange.Net.Sockets
}
/// <inheritdoc />
public virtual bool Send(int id, string data, int weight)
public virtual void Send(int id, string data, int weight)
{
if (_ctsSource.IsCancellationRequested || _processState != ProcessState.Processing)
return false;
if (_ctsSource.IsCancellationRequested)
return;
var bytes = Parameters.Encoding.GetBytes(data);
_logger.SocketAddingBytesToSendBuffer(Id, id, bytes);
_sendBuffer.Enqueue(new SendItem { Id = id, Weight = weight, Bytes = bytes });
_sendEvent.Set();
return true;
}
/// <inheritdoc />
@@ -391,7 +389,9 @@ namespace CryptoExchange.Net.Sockets
if (_disposed)
return;
//_closeState = CloseState.Closing;
_ctsSource.Cancel();
_sendEvent.Set();
if (_socket.State == WebSocketState.Open)
{
@@ -436,7 +436,6 @@ namespace CryptoExchange.Net.Sockets
_disposed = true;
_socket.Dispose();
_ctsSource?.Dispose();
_sendEvent.Dispose();
_logger.SocketDisposed(Id);
}
@@ -451,15 +450,10 @@ namespace CryptoExchange.Net.Sockets
{
while (true)
{
try
{
if (!_sendBuffer.Any())
await _sendEvent.WaitAsync(ct: _ctsSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
if (_ctsSource.IsCancellationRequested)
break;
}
await _sendEvent.WaitAsync().ConfigureAwait(false);
if (_ctsSource.IsCancellationRequested)
break;
@@ -513,8 +507,7 @@ namespace CryptoExchange.Net.Sockets
// Make sure we at least let the owner know there was an error
_logger.SocketSendLoopStoppedWithException(Id, e.Message, e);
await (OnError?.Invoke(e) ?? Task.CompletedTask).ConfigureAwait(false);
if (_closeTask?.IsCompleted != false)
_closeTask = CloseInternalAsync();
throw;
}
finally
{
@@ -589,7 +582,7 @@ namespace CryptoExchange.Net.Sockets
{
// Received a complete message and it's not multi part
_logger.SocketReceivedSingleMessage(Id, receiveResult.Count);
await ProcessData(receiveResult.MessageType, new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, receiveResult.Count)).ConfigureAwait(false);
ProcessData(receiveResult.MessageType, new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, receiveResult.Count));
}
else
{
@@ -624,7 +617,7 @@ namespace CryptoExchange.Net.Sockets
{
_logger.SocketReassembledMessage(Id, multipartStream!.Length);
// Get the underlying buffer of the memorystream holding the written data and delimit it (GetBuffer return the full array, not only the written part)
await ProcessData(receiveResult.MessageType, new ReadOnlyMemory<byte>(multipartStream.GetBuffer(), 0, (int)multipartStream.Length)).ConfigureAwait(false);
ProcessData(receiveResult.MessageType, new ReadOnlyMemory<byte>(multipartStream.GetBuffer(), 0, (int)multipartStream.Length));
}
else
{
@@ -640,8 +633,7 @@ namespace CryptoExchange.Net.Sockets
// Make sure we at least let the owner know there was an error
_logger.SocketReceiveLoopStoppedWithException(Id, e);
await (OnError?.Invoke(e) ?? Task.CompletedTask).ConfigureAwait(false);
if (_closeTask?.IsCompleted != false)
_closeTask = CloseInternalAsync();
throw;
}
finally
{
@@ -655,10 +647,10 @@ namespace CryptoExchange.Net.Sockets
/// <param name="type"></param>
/// <param name="data"></param>
/// <returns></returns>
protected async Task ProcessData(WebSocketMessageType type, ReadOnlyMemory<byte> data)
protected void ProcessData(WebSocketMessageType type, ReadOnlyMemory<byte> data)
{
LastActionTime = DateTime.UtcNow;
await (OnStreamMessage?.Invoke(type, data) ?? Task.CompletedTask).ConfigureAwait(false);
OnStreamMessage?.Invoke(type, data);
}
/// <summary>
@@ -699,6 +691,7 @@ namespace CryptoExchange.Net.Sockets
// any exception here will stop the timeout checking, but do so silently unless the socket get's stopped.
// Make sure we at least let the owner know there was an error
await (OnError?.Invoke(e) ?? Task.CompletedTask).ConfigureAwait(false);
throw;
}
}
@@ -723,14 +716,10 @@ namespace CryptoExchange.Net.Sockets
var checkTime = DateTime.UtcNow;
if (checkTime - _lastReceivedMessagesUpdate > TimeSpan.FromSeconds(1))
{
for (var i = 0; i < _receivedMessages.Count; i++)
foreach (var msg in _receivedMessages.ToList()) // To list here because we're removing from the list
{
var msg = _receivedMessages[i];
if (checkTime - msg.Timestamp > TimeSpan.FromSeconds(3))
{
_receivedMessages.Remove(msg);
i--;
}
}
_lastReceivedMessagesUpdate = checkTime;
+9 -33
View File
@@ -24,17 +24,6 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public bool Completed { get; set; }
/// <summary>
/// The number of required responses. Can be more than 1 when for example subscribing multiple symbols streams in a single request,
/// and each symbol receives it's own confirmation response
/// </summary>
public int RequiredResponses { get; set; } = 1;
/// <summary>
/// The current number of responses received on this query
/// </summary>
public int CurrentResponses { get; set; }
/// <summary>
/// Timestamp of when the request was send
/// </summary>
@@ -53,7 +42,7 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// Wait event for the calling message processing thread
/// </summary>
public AsyncResetEvent? ContinueAwaiter { get; set; }
public ManualResetEvent? ContinueAwaiter { get; set; }
/// <summary>
/// Strings to match this query to a received message
@@ -119,7 +108,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Wait until timeout or the request is completed
/// Wait untill timeout or the request is competed
/// </summary>
/// <param name="timeout"></param>
/// <param name="ct">Cancellation token</param>
@@ -146,7 +135,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="message"></param>
/// <param name="connection"></param>
/// <returns></returns>
public abstract Task<CallResult> Handle(SocketConnection connection, DataEvent<object> message);
public abstract CallResult Handle(SocketConnection connection, DataEvent<object> message);
}
@@ -176,26 +165,13 @@ namespace CryptoExchange.Net.Sockets
}
/// <inheritdoc />
public override async Task<CallResult> Handle(SocketConnection connection, DataEvent<object> message)
public override CallResult Handle(SocketConnection connection, DataEvent<object> message)
{
CurrentResponses++;
if (CurrentResponses == RequiredResponses)
{
Completed = true;
Response = message.Data;
}
if (Result?.Success != false)
// If an error result is already set don't override that
Result = HandleMessage(connection, message.As((TServerResponse)message.Data));
if (CurrentResponses == RequiredResponses)
{
_event.Set();
if (ContinueAwaiter != null)
await ContinueAwaiter.WaitAsync().ConfigureAwait(false);
}
Completed = true;
Response = message.Data;
Result = HandleMessage(connection, message.As((TServerResponse)message.Data));
_event.Set();
ContinueAwaiter?.WaitOne();
return Result;
}
+11 -18
View File
@@ -413,7 +413,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="data"></param>
/// <param name="type"></param>
/// <returns></returns>
protected virtual async Task HandleStreamMessage(WebSocketMessageType type, ReadOnlyMemory<byte> data)
protected virtual void HandleStreamMessage(WebSocketMessageType type, ReadOnlyMemory<byte> data)
{
var sw = Stopwatch.StartNew();
var receiveTime = DateTime.UtcNow;
@@ -507,9 +507,7 @@ namespace CryptoExchange.Net.Sockets
try
{
var innerSw = Stopwatch.StartNew();
await processor.Handle(this, new DataEvent<object>(deserialized, null, null, originalData, receiveTime, null)).ConfigureAwait(false);
if (processor is Query query && query.RequiredResponses != 1)
_logger.LogDebug($"[Sckt {SocketId}] [Req {query.Id}] responses: {query.CurrentResponses}/{query.RequiredResponses}");
processor.Handle(this, new DataEvent<object>(deserialized, null, null, originalData, receiveTime, null));
totalUserTime += (int)innerSw.ElapsedMilliseconds;
}
catch (Exception ex)
@@ -575,8 +573,9 @@ namespace CryptoExchange.Net.Sockets
/// Close a subscription on this connection. If all subscriptions on this connection are closed the connection gets closed as well
/// </summary>
/// <param name="subscription">Subscription to close</param>
/// <param name="unsubEvenIfNotConfirmed">Whether to send an unsub request even if the subscription wasn't confirmed</param>
/// <returns></returns>
public async Task CloseAsync(Subscription subscription)
public async Task CloseAsync(Subscription subscription, bool unsubEvenIfNotConfirmed = false)
{
subscription.Closed = true;
@@ -597,7 +596,7 @@ namespace CryptoExchange.Net.Sockets
lock (_listenersLock)
needUnsub = _listeners.Contains(subscription);
if (needUnsub && _socket.IsOpen)
if (needUnsub && (unsubEvenIfNotConfirmed || subscription.Confirmed) && _socket.IsOpen)
await UnsubscribeAsync(subscription).ConfigureAwait(false);
}
else
@@ -698,7 +697,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="continueEvent">Wait event for when the socket message handler can continue</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
public virtual async Task<CallResult> SendAndWaitQueryAsync(Query query, AsyncResetEvent? continueEvent = null, CancellationToken ct = default)
public virtual async Task<CallResult> SendAndWaitQueryAsync(Query query, ManualResetEvent? continueEvent = null, CancellationToken ct = default)
{
await SendAndWaitIntAsync(query, continueEvent, ct).ConfigureAwait(false);
return query.Result ?? new CallResult(new ServerError("Timeout"));
@@ -713,13 +712,13 @@ namespace CryptoExchange.Net.Sockets
/// <param name="continueEvent">Wait event for when the socket message handler can continue</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
public virtual async Task<CallResult<THandlerResponse>> SendAndWaitQueryAsync<TServerResponse, THandlerResponse>(Query<TServerResponse, THandlerResponse> query, AsyncResetEvent? continueEvent = null, CancellationToken ct = default)
public virtual async Task<CallResult<THandlerResponse>> SendAndWaitQueryAsync<TServerResponse, THandlerResponse>(Query<TServerResponse, THandlerResponse> query, ManualResetEvent? continueEvent = null, CancellationToken ct = default)
{
await SendAndWaitIntAsync(query, continueEvent, ct).ConfigureAwait(false);
return query.TypedResult ?? new CallResult<THandlerResponse>(new ServerError("Timeout"));
}
private async Task SendAndWaitIntAsync(Query query, AsyncResetEvent? continueEvent, CancellationToken ct = default)
private async Task SendAndWaitIntAsync(Query query, ManualResetEvent? continueEvent, CancellationToken ct = default)
{
lock(_listenersLock)
_listeners.Add(query);
@@ -803,9 +802,7 @@ namespace CryptoExchange.Net.Sockets
_logger.SendingData(SocketId, requestId, data);
try
{
if (!_socket.Send(requestId, data, weight))
return new CallResult(new WebError("Failed to send message, connection not open"));
_socket.Send(requestId, data, weight);
return new CallResult(null);
}
catch(Exception ex)
@@ -835,11 +832,7 @@ namespace CryptoExchange.Net.Sockets
bool anyAuthenticated;
lock (_listenersLock)
{
anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated)
|| (DedicatedRequestConnection && ApiClient.AuthenticationProvider != null);
}
anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated) || DedicatedRequestConnection;
if (anyAuthenticated)
{
// If we reconnected a authenticated connection we need to re-authenticate
@@ -883,7 +876,7 @@ namespace CryptoExchange.Net.Sockets
if (subQuery == null)
continue;
var waitEvent = new AsyncResetEvent(false);
var waitEvent = new ManualResetEvent(false);
taskList.Add(SendAndWaitQueryAsync(subQuery, waitEvent).ContinueWith((r) =>
{
subscription.HandleSubQueryResponse(subQuery.Response!);
+2 -3
View File
@@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Sockets
{
@@ -123,11 +122,11 @@ namespace CryptoExchange.Net.Sockets
/// <param name="connection"></param>
/// <param name="message"></param>
/// <returns></returns>
public Task<CallResult> Handle(SocketConnection connection, DataEvent<object> message)
public CallResult Handle(SocketConnection connection, DataEvent<object> message)
{
ConnectionInvocations++;
TotalInvocations++;
return Task.FromResult(DoHandleMessage(connection, message));
return DoHandleMessage(connection, message);
}
/// <summary>
@@ -75,10 +75,7 @@ namespace CryptoExchange.Net.Testing.Comparers
var enumerator = list.GetEnumerator();
foreach (var jObj in jObjs)
{
if (!enumerator.MoveNext())
{
}
enumerator.MoveNext();
if (jObj.Type == JTokenType.Object)
{
foreach (var subProp in ((JObject)jObj).Properties())
@@ -275,67 +272,6 @@ namespace CryptoExchange.Net.Testing.Comparers
}
}
}
else if (propValue.Type == JTokenType.Array)
{
var jObjs = (JArray)propValue;
if (propertyValue is IEnumerable list)
{
var enumerator = list.GetEnumerator();
foreach (var jObj in jObjs)
{
if (!enumerator.MoveNext())
{
}
if (jObj.Type == JTokenType.Object)
{
foreach (var subProp in ((JObject)jObj).Properties())
{
if (ignoreProperties?.Contains(subProp.Name) == true)
continue;
CheckObject(method, subProp, enumerator.Current, ignoreProperties!);
}
}
else if (jObj.Type == JTokenType.Array)
{
var resultObj = enumerator.Current;
var resultProps = resultObj.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast<ArrayPropertyAttribute>().SingleOrDefault()));
var arrayConverterProperty = resultObj.GetType().GetCustomAttributes(typeof(JsonConverterAttribute), true).FirstOrDefault();
var jsonConverter = ((JsonConverterAttribute)arrayConverterProperty!).ConverterType;
if (jsonConverter != typeof(ArrayConverter))
// Not array converter?
continue;
int i = 0;
foreach (var item in jObj.Values())
{
var arrayProp = resultProps.SingleOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
CheckPropertyValue(method, item, arrayProp.GetValue(resultObj), arrayProp.PropertyType, arrayProp.Name, "Array index " + i, ignoreProperties!);
i++;
}
}
else
{
var value = enumerator.Current;
if (value == default && ((JValue)jObj).Type != JTokenType.Null)
throw new Exception($"{method}: Array has no value while input json array has value {jObj}");
}
}
}
else
{
var resultProps = propertyValue.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast<ArrayPropertyAttribute>().SingleOrDefault()));
int i = 0;
foreach (var item in jObjs.Children())
{
var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
CheckPropertyValue(method, item, arrayProp.GetValue(propertyValue), arrayProp.PropertyType, arrayProp.Name, "Array index " + i, ignoreProperties!);
i++;
}
}
}
else
{
CheckValues(method, propertyName!, propertyType, (JValue)propValue, propertyValue);
@@ -371,7 +307,7 @@ namespace CryptoExchange.Net.Testing.Comparers
if (objectValue is DateTime time)
{
if (time != DateTimeConverter.ParseFromDouble(jsonValue.Value<long>()!))
throw new Exception($"{method}: {property} not equal: {DateTimeConverter.ParseFromDouble(jsonValue.Value<long>()!)} vs {time}");
throw new Exception($"{method}: {property} not equal: {jsonValue.Value<decimal>()} vs {time}");
}
else if (propertyType.IsEnum || Nullable.GetUnderlyingType(propertyType)?.IsEnum == true)
{
@@ -23,7 +23,7 @@ namespace CryptoExchange.Net.Testing.Implementations
public event Func<Exception, Task>? OnError;
#pragma warning restore 0067
public event Func<int, Task>? OnRequestSent;
public event Func<WebSocketMessageType, ReadOnlyMemory<byte>, Task>? OnStreamMessage;
public event Action<WebSocketMessageType, ReadOnlyMemory<byte>>? OnStreamMessage;
public event Func<Task>? OnOpen;
public int Id { get; }
@@ -33,17 +33,9 @@ namespace CryptoExchange.Net.Testing.Implementations
public Uri Uri { get; set; }
public Func<Task<Uri?>>? GetReconnectionUrl { get; set; }
public static int lastId = 0;
public static object lastIdLock = new object();
public TestSocket(string address)
{
Uri = new Uri(address);
lock (lastIdLock)
{
Id = lastId + 1;
lastId++;
}
}
public Task<CallResult> ConnectAsync()
@@ -52,14 +44,13 @@ namespace CryptoExchange.Net.Testing.Implementations
return Task.FromResult(CanConnect ? new CallResult(null) : new CallResult(new CantConnectError()));
}
public bool Send(int requestId, string data, int weight)
public void Send(int requestId, string data, int weight)
{
if (!Connected)
throw new Exception("Socket not connected");
OnRequestSent?.Invoke(requestId);
OnMessageSend?.Invoke(data);
return true;
}
public Task CloseAsync()
@@ -81,12 +72,12 @@ namespace CryptoExchange.Net.Testing.Implementations
public void InvokeMessage(string data)
{
OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(data))).Wait();
OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(data)));
}
public void InvokeMessage<T>(T data)
{
OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)))).Wait();
OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data))));
}
public Task ReconnectAsync() => throw new NotImplementedException();
-11
View File
@@ -46,17 +46,6 @@ Make a one time donation in a crypto currency of your choice. If you prefer to d
Alternatively, sponsor me on Github using [Github Sponsors](https://github.com/sponsors/JKorf).
## Release notes
* Version 7.9.0 - 16 Jul 2024
* Added some checks in websocket connection handling
* Added As<T> and AsError<T> methods on untyped WebCallResult
* Updated System.Text.Json package to version 8.0.4 to fix vulnerability
* Updated websocket subscription response handling to remove the thread blocking ManualResetEvent usage
* Updated static logging classes access modifier from internal to public so they can be called in overriden methods
* Updated some testing object implementations
* Fixed authentication error when reconnecting an unauthenticated connection which was marked as dedicated query connection
* Small improvements in SystemTextJsonMessageAccessor
* Fixed System.Text.Json ArrayConverter implementation nullable value types handling
* Version 7.8.0 - 02 Jul 2024
* Updated single endpoint limit configuration
* Added LongConverter for nullable longs