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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::collections::VecDeque;
use std::sync::RwLock;

use async_trait::async_trait;

use crate::cardano_block_scanner::{BlockScanner, BlockStreamer, ScannedBlock};
use crate::cardano_block_scanner::{ChainScannedBlocks, RawCardanoPoint};
use crate::entities::{BlockNumber, ChainPoint};
use crate::StdResult;

/// Dumb block scanner
pub struct DumbBlockScanner {
    streamer: RwLock<DumbBlockStreamer>,
}

impl DumbBlockScanner {
    /// Factory
    pub fn new() -> Self {
        Self {
            streamer: RwLock::new(DumbBlockStreamer::new()),
        }
    }

    /// Add to the inner streamer several [ChainScannedBlocks::RollForwards] responses at the end of
    /// its queue.
    pub fn forwards(self, blocks: Vec<Vec<ScannedBlock>>) -> Self {
        self.add_forwards(blocks);
        self
    }

    /// Add to the inner streamer a [ChainScannedBlocks::RollBackward] response at the end of its queue.
    pub fn backward(self, chain_point: ChainPoint) -> Self {
        self.add_backward(chain_point);
        self
    }

    /// Set the last polled point to return when [Self::last_polled_point] is called.
    pub fn last_polled_point(self, raw_point: Option<RawCardanoPoint>) -> Self {
        self.set_last_polled_point(raw_point);
        self
    }

    /// Add to the inner streamer several [ChainScannedBlocks::RollForwards] responses at the end of
    /// its queue.
    pub fn add_forwards(&self, blocks: Vec<Vec<ScannedBlock>>) {
        let mut streamer = self.streamer.write().unwrap();
        *streamer = streamer.clone().forwards(blocks);
    }

    /// Add to the inner streamer a [ChainScannedBlocks::RollBackward] response at the end of its queue.
    pub fn add_backward(&self, chain_point: ChainPoint) {
        let mut streamer = self.streamer.write().unwrap();
        *streamer = streamer.clone().rollback(chain_point);
    }

    /// Set the last polled point to return when [Self::last_polled_point] is called.
    pub fn set_last_polled_point(&self, raw_point: Option<RawCardanoPoint>) {
        let mut streamer = self.streamer.write().unwrap();
        *streamer = streamer.clone().set_last_polled_point(raw_point);
    }
}

impl Default for DumbBlockScanner {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BlockScanner for DumbBlockScanner {
    async fn scan(
        &self,
        _from: Option<RawCardanoPoint>,
        _until: BlockNumber,
    ) -> StdResult<Box<dyn BlockStreamer>> {
        let streamer = self.streamer.read().unwrap();
        Ok(Box::new(streamer.clone()))
    }
}

/// Dumb block streamer
#[derive(Clone)]
pub struct DumbBlockStreamer {
    streamer_responses: VecDeque<ChainScannedBlocks>,
    last_polled_point: Option<RawCardanoPoint>,
}

impl DumbBlockStreamer {
    /// Factory - the resulting streamer can be polled one time for each list of blocks given
    pub fn new() -> Self {
        Self {
            streamer_responses: VecDeque::new(),
            last_polled_point: None,
        }
    }

    /// Set the last polled point to return when [Self::last_polled_point] is called
    pub fn set_last_polled_point(mut self, raw_point: Option<RawCardanoPoint>) -> Self {
        self.last_polled_point = raw_point;
        self
    }

    /// Add to the streamer several [ChainScannedBlocks::RollForwards] responses at the end of
    /// its queue.
    pub fn forwards(mut self, blocks: Vec<Vec<ScannedBlock>>) -> Self {
        let mut source: VecDeque<_> = blocks
            .into_iter()
            .map(ChainScannedBlocks::RollForwards)
            .collect();
        self.streamer_responses.append(&mut source);

        self
    }

    /// Add to the streamer a [ChainScannedBlocks::RollBackward] response at the end of its queue.
    pub fn rollback(mut self, chain_point: ChainPoint) -> Self {
        self.streamer_responses
            .push_back(ChainScannedBlocks::RollBackward(chain_point.slot_number));
        self
    }
}

impl Default for DumbBlockStreamer {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BlockStreamer for DumbBlockStreamer {
    async fn poll_next(&mut self) -> StdResult<Option<ChainScannedBlocks>> {
        Ok(self.streamer_responses.pop_front())
    }

    fn last_polled_point(&self) -> Option<RawCardanoPoint> {
        self.last_polled_point.clone()
    }
}

#[cfg(test)]
mod tests {
    use crate::cardano_block_scanner::BlockStreamerTestExtensions;

    use super::*;

    use crate::entities::SlotNumber;

    #[tokio::test]
    async fn polling_without_set_of_block_return_none() {
        let mut streamer = DumbBlockStreamer::new().forwards(vec![]);
        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(blocks, None);
    }

    #[tokio::test]
    async fn polling_with_one_set_of_block_returns_some_once() {
        let expected_blocks = vec![ScannedBlock::new(
            "hash-1",
            BlockNumber(1),
            SlotNumber(10),
            Vec::<&str>::new(),
        )];
        let mut streamer = DumbBlockStreamer::new().forwards(vec![expected_blocks.clone()]);

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(blocks, None);
    }

    #[tokio::test]
    async fn polling_with_multiple_sets_of_blocks_returns_some_once() {
        let expected_blocks = vec![
            vec![ScannedBlock::new(
                "hash-1",
                BlockNumber(1),
                SlotNumber(10),
                Vec::<&str>::new(),
            )],
            vec![
                ScannedBlock::new("hash-2", BlockNumber(2), SlotNumber(11), Vec::<&str>::new()),
                ScannedBlock::new("hash-3", BlockNumber(3), SlotNumber(12), Vec::<&str>::new()),
            ],
            vec![ScannedBlock::new(
                "hash-4",
                BlockNumber(4),
                SlotNumber(13),
                Vec::<&str>::new(),
            )],
        ];
        let mut streamer = DumbBlockStreamer::new().forwards(expected_blocks.clone());

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks[0].clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks[1].clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks[2].clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(blocks, None);
    }

    #[tokio::test]
    async fn dumb_scanned_construct_a_streamer_based_on_its_stored_blocks() {
        let expected_blocks = vec![ScannedBlock::new(
            "hash-1",
            BlockNumber(1),
            SlotNumber(10),
            Vec::<&str>::new(),
        )];

        let scanner = DumbBlockScanner::new().forwards(vec![expected_blocks.clone()]);
        let mut streamer = scanner.scan(None, BlockNumber(5)).await.unwrap();

        let blocks = streamer.poll_all().await.unwrap();
        assert_eq!(blocks, expected_blocks);
    }

    #[tokio::test]
    async fn dumb_scanned_construct_a_streamer_based_on_its_stored_chain_scanned_blocks() {
        let expected_blocks = vec![ScannedBlock::new(
            "hash-1",
            BlockNumber(1),
            SlotNumber(10),
            Vec::<&str>::new(),
        )];
        let expected_chain_point = ChainPoint::new(SlotNumber(10), BlockNumber(2), "block-hash");

        let scanner = DumbBlockScanner::new()
            .forwards(vec![expected_blocks.clone()])
            .backward(expected_chain_point.clone());
        let mut streamer = scanner.scan(None, BlockNumber(5)).await.unwrap();

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks.clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollBackward(
                expected_chain_point.slot_number
            ))
        );
    }

    #[tokio::test]
    async fn polling_with_can_return_roll_backward() {
        let expected_blocks = vec![
            vec![ScannedBlock::new(
                "hash-1",
                BlockNumber(1),
                SlotNumber(10),
                Vec::<&str>::new(),
            )],
            vec![ScannedBlock::new(
                "hash-4",
                BlockNumber(4),
                SlotNumber(13),
                Vec::<&str>::new(),
            )],
        ];

        let expected_chain_point = ChainPoint::new(SlotNumber(10), BlockNumber(2), "block-hash");

        let mut streamer = DumbBlockStreamer::new()
            .forwards(expected_blocks.clone())
            .rollback(expected_chain_point.clone());

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks[0].clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollForwards(expected_blocks[1].clone()))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(
            blocks,
            Some(ChainScannedBlocks::RollBackward(
                expected_chain_point.slot_number
            ))
        );

        let blocks = streamer.poll_next().await.unwrap();
        assert_eq!(blocks, None);
    }

    #[tokio::test]
    async fn setting_last_polled_block() {
        let mut streamer = DumbBlockStreamer::new().forwards(vec![]);
        assert_eq!(streamer.last_polled_point(), None);

        let raw_point = RawCardanoPoint::new(SlotNumber(10), "block-hash".as_bytes());
        streamer = streamer.set_last_polled_point(Some(raw_point.clone()));
        assert_eq!(streamer.last_polled_point(), Some(raw_point));

        streamer = streamer.set_last_polled_point(None);
        assert_eq!(streamer.last_polled_point(), None);
    }
}