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

Fix Swarm<T>.Preload() #839

Merged
merged 4 commits into from
Apr 3, 2020
Merged
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
6 changes: 6 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ To be released.
if `cancellationToken` was requested. [[#798]]
- Fixed a bug where `Swarm<T>` had crashed if it received invalid
`Transaction<T>` from the nodes. [[#820]]
- Fixed a bug where `Swarm<T>` hadn't reported `IProgress<PreloadState>`s
correctly.[[#839]]
- Fixed a `Swarm<T>.PreloadAsync()` method's bug that it had hung forever
when a block failed to be fetched due to an unexpected inner exception.
[[#839]]

### CLI tools

Expand All @@ -136,6 +141,7 @@ To be released.
[#831]: https://github.com/planetarium/libplanet/pull/831
[#837]: https://github.com/planetarium/libplanet/pull/837
[#838]: https://github.com/planetarium/libplanet/pull/838
[#839]: https://github.com/planetarium/libplanet/pull/839


Version 0.8.0
Expand Down
38 changes: 38 additions & 0 deletions Libplanet.Tests/Net/BlockCompletionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,44 @@ public async Task CompleteWithNonRespondingPeers()
}
});

Tuple<Block<DumbAction>, char>[] result =
await AsyncEnumerable.ToArrayAsync(
bc.Complete(
new[] { 'A', 'B' }, blockFetcher, millisecondsSingleSessionTimeout: 3000
)
);
Assert.Equal(
fixture.Select(b => Tuple.Create(b, 'B')).ToHashSet(),
result.ToHashSet()
);
}

[Fact(Timeout = Timeout)]
public async Task CompleteWithCrashingPeers()
{
ImmutableArray<Block<DumbAction>> fixture =
GenerateBlocks<DumbAction>(15).ToImmutableArray();
var bc = new BlockCompletion<char, DumbAction>(_ => false, 5);
bc.Demand(fixture.Select(b => b.Hash));

BlockCompletion<char, DumbAction>.BlockFetcher blockFetcher =
(peer, blockHashes, token) => new AsyncEnumerable<Block<DumbAction>>(async yield =>
{
// Peer A does crash and Peer B does respond.
if (peer == 'A')
{
throw new Exception("Peer A can't respond.");
}

foreach (Block<DumbAction> b in fixture)
{
if (blockHashes.Contains(b.Hash))
{
await yield.ReturnAsync(b);
}
}
});

Tuple<Block<DumbAction>, char>[] result =
await AsyncEnumerable.ToArrayAsync(bc.Complete(new[] { 'A', 'B' }, blockFetcher));
Assert.Equal(
Expand Down
226 changes: 125 additions & 101 deletions Libplanet/Net/BlockCompletion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ public async IAsyncEnumerable<IEnumerable<HashDigest<SHA256>>> EnumerateChunks(
)
{
var chunk = new List<HashDigest<SHA256>>(capacity: _window);
bool QueuedDemandCompleted() =>
_started && _demands.IsEmpty && _satisfiedBlocks.All(kv => kv.Value);
while (!(cancellationToken.IsCancellationRequested ||
QueuedDemandCompleted()))
{
Expand Down Expand Up @@ -206,110 +204,39 @@ public async IAsyncEnumerable<Tuple<Block<TAction>, TPeer>> Complete(

var pool = new PeerPool(peers);
var queue = new AsyncProducerConsumerQueue<Tuple<Block<TAction>, TPeer>>();
var completion =
new ConcurrentDictionary<HashDigest<SHA256>, bool>(_satisfiedBlocks);

await foreach (var hashes in EnumerateChunks(cancellationToken))
Task producer = Task.Run(async () =>
{
cancellationToken.ThrowIfCancellationRequested();
IList<HashDigest<SHA256>> hashDigests =
hashes is IList<HashDigest<SHA256>> l ? l : hashes.ToList();

foreach (HashDigest<SHA256> hash in hashDigests)
try
{
completion.TryAdd(hash, false);
}

cancellationToken.ThrowIfCancellationRequested();
await pool.SpawnAsync(
async (peer, ct) =>
await foreach (var hashes in EnumerateChunks(cancellationToken))
{
ct.ThrowIfCancellationRequested();
var demands = new HashSet<HashDigest<SHA256>>(hashDigests);
try
{
_logger.Debug(
"Request blocks {BlockHashes} to {Peer}...",
cancellationToken.ThrowIfCancellationRequested();
IList<HashDigest<SHA256>> hashDigests =
hashes is IList<HashDigest<SHA256>> l ? l : hashes.ToList();

cancellationToken.ThrowIfCancellationRequested();
await pool.SpawnAsync(
CreateEnqueuing(
hashDigests,
peer
);
var timeout = new CancellationTokenSource(singleSessionTimeout);
CancellationToken timeoutToken = timeout.Token;
timeoutToken.Register(() =>
_logger.Debug("Timed out to wait a response from {Peer}.", peer)
);
ct.Register(() => timeout.Cancel());
blockFetcher,
singleSessionTimeout,
cancellationToken,
queue
),
cancellationToken: cancellationToken
);
}

try
{
ConfiguredCancelableAsyncEnumerable<Block<TAction>> blocks =
blockFetcher(peer, hashDigests, timeoutToken)
.WithCancellation(timeoutToken);
await foreach (Block<TAction> block in blocks)
{
_logger.Debug(
"Downloaded a block #{BlockIndex} {BlockHash} " +
"from {Peer}.",
block.Index,
block.Hash,
peer
);

if (Satisfy(block))
{
await queue.EnqueueAsync(
Tuple.Create(block, peer),
cancellationToken
);
}

demands.Remove(block.Hash);
}
}
catch (OperationCanceledException e)
{
if (ct.IsCancellationRequested)
{
_logger.Error(
e,
"A blockFetcher job (peer: {Peer}) is cancelled.",
peer
);
throw;
}

_logger.Debug(
e,
"Timed out to wait a response from {Peer}.",
peer
);
}
}
finally
{
if (demands.Any())
{
_logger.Verbose(
"Fetched blocks from {Peer}, but there are still " +
"unsatisfied demands ({UnsatisfiedDemandsNumber}) so " +
"enqueue them again: {UnsatisfiedDemands}.",
peer,
demands.Count,
demands
);
Demand(demands, retry: true);
}
else
{
_logger.Verbose("Fetched blocks from {Peer}.", peer);
}
}
},
cancellationToken: cancellationToken
);
}
await pool.WaitAll(cancellationToken);
}
finally
{
queue.CompleteAdding();
}
});

while (!completion.All(kv => kv.Value))
while (await queue.OutputAvailableAsync(cancellationToken))
{
Tuple<Block<TAction>, TPeer> pair;
try
Expand All @@ -328,10 +255,9 @@ await queue.EnqueueAsync(
pair.Item1.Hash,
pair.Item2
);
completion[pair.Item1.Hash] = true;
}

_logger.Verbose("Completed all blocks ({Number}).", completion.Count);
await producer;
}

/// <summary>
Expand Down Expand Up @@ -395,6 +321,104 @@ private int Demand(IEnumerable<HashDigest<SHA256>> blockHashes, bool retry)
return sum;
}

private bool QueuedDemandCompleted() =>
_started && _demands.IsEmpty && _satisfiedBlocks.All(kv => kv.Value);

private Func<TPeer, CancellationToken, Task> CreateEnqueuing(
IList<HashDigest<SHA256>> hashDigests,
BlockFetcher blockFetcher,
TimeSpan singleSessionTimeout,
CancellationToken cancellationToken,
AsyncProducerConsumerQueue<Tuple<Block<TAction>, TPeer>> queue
) =>
async (peer, ct) =>
{
ct.ThrowIfCancellationRequested();
var demands = new HashSet<HashDigest<SHA256>>(hashDigests);
try
{
_logger.Debug(
"Request blocks {BlockHashes} to {Peer}...",
hashDigests,
peer
);
var timeout = new CancellationTokenSource(singleSessionTimeout);
CancellationToken timeoutToken = timeout.Token;
timeoutToken.Register(() =>
_logger.Debug("Timed out to wait a response from {Peer}.", peer)
);
ct.Register(() => timeout.Cancel());

try
{
ConfiguredCancelableAsyncEnumerable<Block<TAction>> blocks =
blockFetcher(peer, hashDigests, timeoutToken)
.WithCancellation(timeoutToken);
await foreach (Block<TAction> block in blocks)
{
_logger.Debug(
"Downloaded a block #{BlockIndex} {BlockHash} " +
"from {Peer}.",
block.Index,
block.Hash,
peer
);

if (Satisfy(block))
{
await queue.EnqueueAsync(
Tuple.Create(block, peer),
cancellationToken
);
}

demands.Remove(block.Hash);
}
}
catch (OperationCanceledException e)
{
if (ct.IsCancellationRequested)
{
_logger.Error(
e,
"A blockFetcher job (peer: {Peer}) is cancelled.",
peer
);
throw;
}

_logger.Debug(
e,
"Timed out to wait a response from {Peer}.",
peer
);
}
catch (Exception e)
{
_logger.Error(e, "A blockFetcher job (peer: {Peer}) is failed.", peer);
}
}
finally
{
if (demands.Any())
{
_logger.Verbose(
"Fetched blocks from {Peer}, but there are still " +
"unsatisfied demands ({UnsatisfiedDemandsNumber}) so " +
"enqueue them again: {UnsatisfiedDemands}.",
peer,
demands.Count,
demands
);
Demand(demands, retry: true);
}
else
{
_logger.Verbose("Fetched blocks from {Peer}.", peer);
}
}
};

internal class PeerPool
{
private readonly ConcurrentQueue<TPeer> _completions;
Expand Down