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
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;

/// Cardano transactions pruner
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait TransactionPruner: Send + Sync {
    /// Prune the transactions older than the given number of blocks.
    async fn prune(&self, number_of_blocks_to_keep: BlockNumber) -> StdResult<()>;
}

/// A decorator of [TransactionsImporter] that prunes the transactions older than a given number of
/// blocks after running the import.
///
/// If the number of blocks to keep is not provided, no pruning is performed.
pub struct TransactionsImporterWithPruner {
    number_of_blocks_to_keep: Option<BlockNumber>,
    transaction_pruner: Arc<dyn TransactionPruner>,
    wrapped_importer: Arc<dyn TransactionsImporter>,
    logger: Logger,
}

impl TransactionsImporterWithPruner {
    /// Create a new instance of [TransactionsImporterWithPruner].
    pub fn new(
        number_of_blocks_to_keep: Option<BlockNumber>,
        transaction_pruner: Arc<dyn TransactionPruner>,
        wrapped_importer: Arc<dyn TransactionsImporter>,
        logger: Logger,
    ) -> Self {
        Self {
            number_of_blocks_to_keep,
            transaction_pruner,
            wrapped_importer,
            logger: logger.new_with_component_name::<Self>(),
        }
    }
}

#[async_trait]
impl TransactionsImporter for TransactionsImporterWithPruner {
    async fn import(&self, up_to_beacon: BlockNumber) -> StdResult<()> {
        self.wrapped_importer.import(up_to_beacon).await?;

        if let Some(number_of_blocks_to_keep) = self.number_of_blocks_to_keep {
            debug!(
                self.logger,
                "Transaction Import finished - Pruning transactions included in block range roots";
                "number_of_blocks_to_keep" => *number_of_blocks_to_keep,
            );
            self.transaction_pruner
                .prune(number_of_blocks_to_keep)
                .await?;
        }

        Ok(())
    }
}

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

    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<()>;
        }
    }

    impl TransactionsImporterWithPruner {
        pub fn new_with_mock<P, I>(
            number_of_blocks_to_keep: Option<BlockNumber>,
            transaction_pruner_mock_config: P,
            importer_mock_config: I,
        ) -> Self
        where
            P: FnOnce(&mut MockTransactionPruner),
            I: FnOnce(&mut MockTransactionImporterImpl),
        {
            let mut transaction_pruner = MockTransactionPruner::new();
            transaction_pruner_mock_config(&mut transaction_pruner);
            let mut transaction_importer = MockTransactionImporterImpl::new();
            importer_mock_config(&mut transaction_importer);

            Self::new(
                number_of_blocks_to_keep,
                Arc::new(transaction_pruner),
                Arc::new(transaction_importer),
                TestLogger::stdout(),
            )
        }
    }

    #[tokio::test]
    async fn test_does_not_prune_if_none_is_configured() {
        let importer = TransactionsImporterWithPruner::new_with_mock(
            None,
            |mock| {
                mock.expect_prune().never();
            },
            |mock| {
                mock.expect_import().once().returning(|_| Ok(()));
            },
        );

        importer
            .import(BlockNumber(100))
            .await
            .expect("Import should not fail");
    }

    #[tokio::test]
    async fn test_does_prune_if_a_block_number_is_configured() {
        let expected_block_number = BlockNumber(5);
        let importer = TransactionsImporterWithPruner::new_with_mock(
            Some(expected_block_number),
            |mock| {
                mock.expect_prune()
                    .with(eq(expected_block_number))
                    .once()
                    .returning(|_| Ok(()));
            },
            |mock| {
                mock.expect_import().once().returning(|_| Ok(()));
            },
        );

        importer
            .import(BlockNumber(100))
            .await
            .expect("Import should not fail");
    }
}