Skip to content

Commit

Permalink
Bind OnConnectionLost on RPC Disconnected event + Add EraEnd
Browse files Browse the repository at this point in the history
  • Loading branch information
Apolixit committed Jul 16, 2024
1 parent 3658516 commit 66150d4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 24 deletions.
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
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
33 changes: 12 additions & 21 deletions Substrate.NetApi/SubstrateClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,9 @@ public async Task ConnectAsync(bool useMetaData, bool standardSubstrate, Cancell
OnConnectionSet();

linkedTokenSource.Dispose();
//_connectTokenSource.Dispose();
//_connectTokenSource = null;
_connectTokenSource.Dispose();
_connectTokenSource = null;

Logger.Debug("Connected to Websocket.");

var formatter = new JsonMessageFormatter();
Expand All @@ -252,6 +253,13 @@ public async Task ConnectAsync(bool useMetaData, bool standardSubstrate, Cancell
_jsonRpc = new JsonRpc(new WebSocketMessageHandler(_socket, formatter));
_jsonRpc.TraceSource.Listeners.Add(new SerilogTraceListener.SerilogTraceListener());
_jsonRpc.TraceSource.Switch.Level = SourceLevels.Warning;

_jsonRpc.Disconnected += (sender, args) =>
{
Logger.Debug("Disconnected from websocket.");
OnConnectionLost();
};

_jsonRpc.AddLocalRpcTarget(Listener, new JsonRpcTargetOptions { AllowNonPublicInvocation = false });
_jsonRpc.StartListening();
Logger.Debug("Listening to websocket.");
Expand Down Expand Up @@ -288,24 +296,6 @@ public async Task ConnectAsync(bool useMetaData, bool standardSubstrate, Cancell
Logger.Warning(ex, "Could not deserialize properties on connect.");
}
}

// Start a background task to monitor the WebSocket connection
_ = Task.Run(async () =>
{
while (IsConnected)
{
await Task.Delay(_connectionCheckDelay);

if (!IsConnected)
{
// Raise the ConnectionLost event on a separate thread
ThreadPool.QueueUserWorkItem(state =>
{
OnConnectionLost();
});
}
}
});
}

/// <summary>
Expand Down Expand Up @@ -496,6 +486,8 @@ public async Task CloseAsync()
/// <returns> An asynchronous result. </returns>
public async Task CloseAsync(CancellationToken token)
{
_connectTokenSource?.Cancel();

await Task.Run(async () =>
{
// cancel remaining request tokens
Expand All @@ -505,7 +497,6 @@ await Task.Run(async () =>
if (_socket != null && _socket.State == WebSocketState.Open)
{
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
_connectTokenSource?.Cancel();
_jsonRpc?.Dispose();
Logger.Debug("Client closed.");
}
Expand Down

0 comments on commit 66150d4

Please sign in to comment.