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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use std::sync::Arc;

use async_trait::async_trait;
use slog::{debug, Logger};

use mithril_common::entities::BlockNumber;
use mithril_common::logging::LoggerExtensions;
use mithril_common::signable_builder::TransactionsImporter;
use mithril_common::StdResult;

/// Trait to get the highest transaction block number
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait HighestTransactionBlockNumberGetter: Send + Sync {
    /// Get the highest known transaction block number
    async fn get(&self) -> StdResult<Option<BlockNumber>>;
}

/// A decorator of [TransactionsImporter] that does the import by chunks
pub struct TransactionsImporterByChunk {
    highest_transaction_block_number_getter: Arc<dyn HighestTransactionBlockNumberGetter>,
    wrapped_importer: Arc<dyn TransactionsImporter>,
    chunk_size: BlockNumber,
    logger: Logger,
}

impl TransactionsImporterByChunk {
    /// Create a new instance of `TransactionsImporterByChunk`.
    pub fn new(
        highest_transaction_block_number_getter: Arc<dyn HighestTransactionBlockNumberGetter>,
        wrapped_importer: Arc<dyn TransactionsImporter>,
        chunk_size: BlockNumber,
        logger: Logger,
    ) -> Self {
        Self {
            highest_transaction_block_number_getter,
            wrapped_importer,
            chunk_size,
            logger: logger.new_with_component_name::<Self>(),
        }
    }
}

#[async_trait]
impl TransactionsImporter for TransactionsImporterByChunk {
    async fn import(&self, up_to_beacon: BlockNumber) -> StdResult<()> {
        let mut intermediate_up_to = self
            .highest_transaction_block_number_getter
            .get()
            .await?
            .unwrap_or(BlockNumber(0));

        while intermediate_up_to < up_to_beacon {
            let next_up_to = (intermediate_up_to + self.chunk_size).min(up_to_beacon);
            debug!(
                self.logger,
                "Running Transactions import between block '{intermediate_up_to}' and '{next_up_to}'";
            );
            self.wrapped_importer.import(next_up_to).await?;
            intermediate_up_to = next_up_to;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use mockall::predicate::eq;
    use mockall::{mock, Sequence};

    use crate::test_tools::TestLogger;

    use super::*;

    mock! {
        pub TransactionImporterImpl {}

        #[async_trait]
        impl TransactionsImporter for TransactionImporterImpl {
            async fn import(&self, up_to_beacon: BlockNumber) -> StdResult<()>;
        }
    }

    fn create_highest_transaction_block_number_getter_mock(
        highest_block_number: BlockNumber,
    ) -> Arc<dyn HighestTransactionBlockNumberGetter> {
        Arc::new({
            let mut mock = MockHighestTransactionBlockNumberGetter::new();
            mock.expect_get()
                .returning(move || Ok(Some(highest_block_number)));
            mock
        })
    }

    fn create_transaction_importer_mock(
        expected_values: Vec<BlockNumber>,
    ) -> MockTransactionImporterImpl {
        let mut seq = Sequence::new();
        let mut wrapped_importer = MockTransactionImporterImpl::new();
        for expected_value in expected_values {
            wrapped_importer
                .expect_import()
                .once()
                .in_sequence(&mut seq)
                .with(eq(expected_value))
                .returning(|_| Ok(()));
        }
        wrapped_importer
    }

    #[tokio::test]
    async fn test_import_nothing_to_do_when_highest_block_number_lower_or_equal_up_to_beacon() {
        let highest_block_number = BlockNumber(10);
        let chunk_size = BlockNumber(5);

        let highest_transaction_block_number_getter =
            create_highest_transaction_block_number_getter_mock(highest_block_number);
        let mut wrapped_importer = MockTransactionImporterImpl::new();
        wrapped_importer.expect_import().never();

        let importer = TransactionsImporterByChunk::new(
            highest_transaction_block_number_getter,
            Arc::new(wrapped_importer),
            chunk_size,
            TestLogger::stdout(),
        );

        let up_to_beacon = highest_block_number;
        importer.import(up_to_beacon).await.unwrap();

        let up_to_beacon = highest_block_number - 1;
        importer.import(up_to_beacon).await.unwrap();
    }

    #[tokio::test]
    async fn test_import_even_when_highest_block_number_is_none() {
        let highest_block_number = None;
        let chunk_size = BlockNumber(5);
        let up_to_beacon = chunk_size - 1;

        let highest_transaction_block_number_getter = Arc::new({
            let mut mock = MockHighestTransactionBlockNumberGetter::new();
            mock.expect_get()
                .returning(move || Ok(highest_block_number));
            mock
        });
        let wrapped_importer = create_transaction_importer_mock(vec![up_to_beacon]);

        let importer = TransactionsImporterByChunk::new(
            highest_transaction_block_number_getter,
            Arc::new(wrapped_importer),
            chunk_size,
            TestLogger::stdout(),
        );

        importer.import(up_to_beacon).await.unwrap();
    }

    #[tokio::test]
    async fn test_import_only_once_when_block_delta_less_than_chunk_size() {
        let highest_block_number = BlockNumber(10);
        let chunk_size = BlockNumber(5);
        let up_to_beacon = highest_block_number + chunk_size - 1;

        let highest_transaction_block_number_getter =
            create_highest_transaction_block_number_getter_mock(highest_block_number);
        let wrapped_importer = create_transaction_importer_mock(vec![up_to_beacon]);

        let importer = TransactionsImporterByChunk::new(
            highest_transaction_block_number_getter,
            Arc::new(wrapped_importer),
            chunk_size,
            TestLogger::stdout(),
        );

        importer.import(up_to_beacon).await.unwrap();
    }

    #[tokio::test]
    async fn test_import_multiple_times_when_block_delta_is_not_a_multiple_of_chunk_size() {
        let highest_block_number = BlockNumber(10);
        let chunk_size = BlockNumber(5);
        let up_to_beacon = highest_block_number + chunk_size * 2 + 1;

        let highest_transaction_block_number_getter =
            create_highest_transaction_block_number_getter_mock(highest_block_number);
        let wrapped_importer = create_transaction_importer_mock(vec![
            highest_block_number + chunk_size,
            highest_block_number + chunk_size * 2,
            up_to_beacon,
        ]);

        let importer = TransactionsImporterByChunk::new(
            highest_transaction_block_number_getter,
            Arc::new(wrapped_importer),
            chunk_size,
            TestLogger::stdout(),
        );

        importer.import(up_to_beacon).await.unwrap();
    }

    #[tokio::test]
    async fn test_import_multiple_times_when_block_delta_is_a_multiple_of_chunk_size() {
        let highest_block_number = BlockNumber(10);
        let chunk_size = BlockNumber(5);
        let up_to_beacon = highest_block_number + chunk_size * 2;

        let highest_transaction_block_number_getter =
            create_highest_transaction_block_number_getter_mock(highest_block_number);
        let wrapped_importer = create_transaction_importer_mock(vec![
            highest_block_number + chunk_size,
            highest_block_number + chunk_size * 2,
        ]);

        let importer = TransactionsImporterByChunk::new(
            highest_transaction_block_number_getter,
            Arc::new(wrapped_importer),
            chunk_size,
            TestLogger::stdout(),
        );

        importer.import(up_to_beacon).await.unwrap();
    }
}