Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Websocket - Add events (OnConnect / OnDisconnect) #86

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions Substrate.NetApi.Test/Extrinsic/EraTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,21 @@ public void EraEncodeDecodeTest()
}

[Test]
public void EraBeginTest()
[TestCase(64u, 49u, 1587u, 1585u)]
[TestCase(64u, 45u, 21604404u, 21604397u)]
public void EraBeginTest(ulong period, ulong phase, ulong currentBlock, ulong expectedBlock)
{
var era = new Era(64, 49, false);
Assert.AreEqual(1585, era.EraStart(1587));
var era = new Era(period, phase, false);
Assert.AreEqual(expectedBlock, era.EraStart(currentBlock));
}

[Test]
[TestCase(64u, 49u, 1587u, 1649u)]
[TestCase(64u, 45u, 21604404u, 21604461u)]
public void EraEndTest(ulong period, ulong phase, ulong currentBlock, ulong expectedBlock)
{
var era = new Era(period, phase, false);
Assert.AreEqual(expectedBlock, era.EraEnd(currentBlock));
}

[Test]
Expand Down
1 change: 1 addition & 0 deletions Substrate.NetApi.Test/Substrate.NetApi.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="nunit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
Expand Down
96 changes: 96 additions & 0 deletions Substrate.NetApi.TestNode/ClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using NUnit.Framework;
using Substrate.NetApi.Model.Extrinsics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Substrate.NetApi.TestNode
{
public class ClientTests
{
private SubstrateClient _client;

[SetUp]
public void Setup()
{
_client = new SubstrateClient(new Uri("ws://rpc-parachain.bajun.network"), ChargeTransactionPayment.Default());
}

[TearDown]
public async Task TeardownAsync()
{
await _client.CloseAsync();
}

[Test]
public async Task Connect_ShouldConnectSuccessfullyAsync()
{
Assert.That(_client.IsConnected, Is.False);

await _client.ConnectAsync();
Assert.That(_client.IsConnected, Is.True);
}

[Test]
public async Task Connect_ShouldDisconnectSuccessfullyAsync()
{
await _client.ConnectAsync();
Assert.That(_client.IsConnected, Is.True);

await _client.CloseAsync();
Assert.That(_client.IsConnected, Is.False);
}

[Test]
public async Task Connect_ShouldTriggerEventAsync()
{
var onConnectionSetTriggered = new TaskCompletionSource<bool>();
_client.ConnectionSet += (sender, e) => onConnectionSetTriggered.SetResult(true);

await _client.ConnectAsync();

await Task.WhenAny(onConnectionSetTriggered.Task, Task.Delay(TimeSpan.FromMinutes(1)));
Assert.That(onConnectionSetTriggered.Task.IsCompleted, Is.True);
}

[Test]
public async Task OnConnectionLost_ShouldThrowDisconnectedEventAsync()
{
var onConnectionLostTriggered = new TaskCompletionSource<bool>();
_client.ConnectionLost += (sender, e) => onConnectionLostTriggered.SetResult(true);

await _client.ConnectAsync();
await _client.CloseAsync();

await Task.WhenAny(onConnectionLostTriggered.Task, Task.Delay(TimeSpan.FromMinutes(1)));
Assert.That(onConnectionLostTriggered.Task.IsCompleted, Is.True);
}

[Test]
public async Task ManuallyDisconnect_ShouldNotTryToReconnectAsync()
{
await _client.ConnectAsync();
await _client.CloseAsync();

Assert.That(_client.IsConnected, Is.False);
}

[Test]
public async Task Disconnect_ShouldTryToReconnectAsync()
{
var onReconnectedTriggered = new TaskCompletionSource<(bool, int)>();
_client.OnReconnected += (sender, e) => onReconnectedTriggered.SetResult((true, e));

await _client.ConnectAsync();
await _client._socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

await Task.WhenAny(onReconnectedTriggered.Task, Task.Delay(TimeSpan.FromMinutes(1)));
Assert.That(_client.IsConnected, Is.True);
}
}
}
7 changes: 7 additions & 0 deletions Substrate.NetApi/Model/Extrinsics/Era.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ public class Era : IEncodable
/// <returns></returns>
public ulong EraStart(ulong currentBlockNumber) => IsImmortal ? 0 : (Math.Max(currentBlockNumber, Phase) - Phase) / Period * Period + Phase;

/// <summary>
/// Era End
/// </summary>
/// <param name="currentBlockNumber"></param>
/// <returns></returns>
public ulong EraEnd(ulong currentBlockNumber) => EraStart(currentBlockNumber) + Period;

/// <summary>
/// Initializes a new instance of the <see cref="Era"/> class.
/// </summary>
Expand Down
64 changes: 59 additions & 5 deletions Substrate.NetApi/SubstrateClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using Substrate.NetApi.Model.Types.Metadata.V14;

[assembly: InternalsVisibleTo("Substrate.NetApi.Test")]
[assembly: InternalsVisibleTo("Substrate.NetApi.TestNode")]

namespace Substrate.NetApi
{
Expand Down Expand Up @@ -62,10 +63,29 @@ public class SubstrateClient : IDisposable
/// </summary>
private JsonRpc _jsonRpc;

/// <summary> The socket. </summary>
internal ClientWebSocket _socket;

/// <summary>
/// The "ping" to check the connection status
/// </summary>
private int _connectionCheckDelay = 500;

/// <summary>
/// The socket
/// The connexion lost event trigger when the websocket change state to disconnected
/// </summary>
private ClientWebSocket _socket;
public event EventHandler ConnectionLost;

/// <summary>
/// Event triggered when the connection is set
/// </summary>
public event EventHandler ConnectionSet;

/// <summary>
/// Event triggered when the connection is reconnected
/// </summary>

public event EventHandler<int> OnReconnected;

/// <summary>
/// Bypass Remote Certificate Validation. Useful when testing with self-signed SSL certificates.
Expand Down Expand Up @@ -185,6 +205,30 @@ public bool SetJsonRPCTraceLevel(SourceLevels sourceLevels)
return true;
}

/// <summary>
/// Raises the event when the connection to the server is lost.
/// </summary>
protected virtual void OnConnectionLost()
{
ConnectionLost?.Invoke(this, EventArgs.Empty);
}

/// <summary>
/// Raises the event when the connection to the server is set.
/// </summary>
protected virtual void OnConnectionSet()
{
ConnectionSet?.Invoke(this, EventArgs.Empty);
}

/// <summary>
/// Raises the event when reconnected
/// </summary>
protected virtual void OnReconnectedSet(int nbTry)
{
OnReconnected?.Invoke(this, nbTry);
}

/// <summary>
/// Asynchronously connects to the node.
/// </summary>
Expand Down Expand Up @@ -259,14 +303,18 @@ public async Task ConnectAsync(bool useMetaData, bool standardSubstrate, int max
#if NETSTANDARD2_0
throw new NotSupportedException("Bypass remote certification validation not supported in NETStandard2.0");
#elif NETSTANDARD2_1_OR_GREATER
_socket.Options.RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => true;
_socket.Options.RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => true;
#endif
}
}

_connectTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, _connectTokenSource.Token);
await _socket.ConnectAsync(_uri, linkedTokenSource.Token);

// Triger the event
OnConnectionSet();

linkedTokenSource.Dispose();
_connectTokenSource.Dispose();
_connectTokenSource = null;
Expand Down Expand Up @@ -333,6 +381,9 @@ public async Task ConnectAsync(bool useMetaData, bool standardSubstrate, int max
private void OnJsonRpcDisconnected(object sender, JsonRpcDisconnectedEventArgs e)
{
Logger.Error(e.Exception, $"JsonRpc disconnected: {e.Reason}");
OnConnectionLost();

if (_jsonRpc == null || _jsonRpc.IsDisposed) return;

// Attempt to reconnect asynchronously
_ = Task.Run(async () =>
Apolixit marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -368,6 +419,8 @@ await ConnectAsync(
);

Logger.Information("Reconnected successfully.");

OnReconnectedSet(retry);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -563,14 +616,15 @@ public async Task CloseAsync(CancellationToken token)
{
_connectTokenSource?.Cancel();

await Task.Run(() =>
await Task.Run(async () =>
{
// cancel remaining request tokens
foreach (var key in _requestTokenSourceDict.Keys) key?.Cancel();
_requestTokenSourceDict.Clear();

if (_socket != null && _socket.State == WebSocketState.Open)
{
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
_jsonRpc?.Dispose();
Logger.Debug("Client closed.");
}
Expand Down Expand Up @@ -629,4 +683,4 @@ public void Dispose()

#endregion IDisposable Support
}
}
}
Loading