Skip to content

Commit

Permalink
Cancel setup outgoing peer connection if throttled
Browse files Browse the repository at this point in the history
  • Loading branch information
asdacap committed Jun 21, 2023
1 parent e9375c4 commit a0a17fe
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/Nethermind/Nethermind.Core.Test/RateLimiterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,12 @@ public async Task RateLimiter_should_throw_when_cancelled()
Func<Task> act = async () => await waitTask;
await act.Should().ThrowAsync<OperationCanceledException>();
}

[Test]
public async Task RateLimiter_should_return_true_on_is_throttled_if_throttled()
{
RateLimiter rateLimiter = new(1);
await rateLimiter.WaitAsync(CancellationToken.None);
rateLimiter.IsThrottled().Should().BeTrue();
}
}
5 changes: 5 additions & 0 deletions src/Nethermind/Nethermind.Core/RateLimiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ private RateLimiter(double intervalSec)
_nextSlot = DateTimeOffset.Now;
}

public bool IsThrottled()
{
return DateTimeOffset.Now < _nextSlot;
}

public async Task WaitAsync(CancellationToken ctx)
{
while (true)
Expand Down
8 changes: 6 additions & 2 deletions src/Nethermind/Nethermind.Network/PeerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private void PeerPoolOnPeerAdded(object sender, PeerEventArgs nodeEventArgs)
// fire and forget - all the surrounding logic will be executed
// exceptions can be lost here without issues
// this for rapid connections to newly discovered peers without having to go through the UpdatePeerLoop
SetupOutgoingPeerConnection(peer);
SetupOutgoingPeerConnection(peer, true);
}
#pragma warning restore 4014
}
Expand Down Expand Up @@ -606,8 +606,12 @@ public int Compare(PeerStats x, PeerStats y)
#region Outgoing connection handling

[Todo(Improve.MissingFunctionality, "Add cancellation support for the peer connection (so it does not wait for the 10sec timeout")]
private async Task SetupOutgoingPeerConnection(Peer peer)
private async Task SetupOutgoingPeerConnection(Peer peer, bool cancelIfThrottled = false)
{
if (cancelIfThrottled)
{
if (_outgoingConnectionRateLimiter.IsThrottled()) return;
}
await _outgoingConnectionRateLimiter.WaitAsync(_cancellationTokenSource.Token);

// Can happen when In connection is received from the same peer and is initialized before we get here
Expand Down

0 comments on commit a0a17fe

Please sign in to comment.