forked from NethermindEth/nethermind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockTreeSuggestPacer.cs
More file actions
63 lines (54 loc) · 2.05 KB
/
BlockTreeSuggestPacer.cs
File metadata and controls
63 lines (54 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Core;
namespace Nethermind.Blockchain;
/// <summary>
/// Utility class during bulk loading to prevent processing queue from becoming too large
/// </summary>
public class BlockTreeSuggestPacer : IDisposable
{
private TaskCompletionSource? _dbBatchProcessed;
private long _blockNumberReachedToUnlock = 0;
private readonly long _stopBatchSize;
private readonly long _resumeBatchSize;
private readonly IBlockTree _blockTree;
public BlockTreeSuggestPacer(IBlockTree blockTree, long stopBatchSize = 4096, long resumeBatchSize = 2048)
{
blockTree.NewHeadBlock += BlockTreeOnNewHeadBlock;
_blockTree = blockTree;
_stopBatchSize = stopBatchSize;
_resumeBatchSize = resumeBatchSize;
}
private void BlockTreeOnNewHeadBlock(object sender, BlockEventArgs e)
{
TaskCompletionSource? completionSource = _dbBatchProcessed;
if (completionSource is null) return;
if (e.Block.Number < _blockNumberReachedToUnlock) return;
_dbBatchProcessed = null;
completionSource.SetResult();
}
public async Task WaitForQueue(long currentBlockNumber, CancellationToken token)
{
long currentHeadNumber = _blockTree.Head?.Number ?? 0;
if (currentBlockNumber - currentHeadNumber > _stopBatchSize && _dbBatchProcessed is null)
{
_blockNumberReachedToUnlock = currentBlockNumber - _stopBatchSize + _resumeBatchSize;
TaskCompletionSource completionSource = new TaskCompletionSource();
_dbBatchProcessed = completionSource;
}
if (_dbBatchProcessed is not null)
{
await using (token.Register(() => _dbBatchProcessed.TrySetCanceled()))
{
await _dbBatchProcessed.Task;
}
}
}
public void Dispose()
{
_blockTree.NewHeadBlock -= BlockTreeOnNewHeadBlock;
}
}