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
use std::path::Path;

use crate::{
    digesters::{ImmutableDigester, ImmutableDigesterError},
    entities::CardanoDbBeacon,
};
use async_trait::async_trait;
use tokio::sync::RwLock;

/// A [ImmutableDigester] returning configurable result for testing purpose.
pub struct DumbImmutableDigester {
    digest: RwLock<String>,
    is_success: bool,
}

impl DumbImmutableDigester {
    /// DumbDigester factory
    pub fn new(digest: &str, is_success: bool) -> Self {
        let digest = RwLock::new(String::from(digest));

        Self { digest, is_success }
    }

    /// Update digest returned by [compute_digest][DumbImmutableDigester::compute_digest]
    pub async fn update_digest(&self, new_digest: String) {
        let mut digest = self.digest.write().await;
        *digest = new_digest;
    }
}

impl Default for DumbImmutableDigester {
    fn default() -> Self {
        Self::new("1234", true)
    }
}

#[async_trait]
impl ImmutableDigester for DumbImmutableDigester {
    async fn compute_digest(
        &self,
        dirpath: &Path,
        beacon: &CardanoDbBeacon,
    ) -> Result<String, ImmutableDigesterError> {
        if self.is_success {
            Ok(self.digest.read().await.clone())
        } else {
            Err(ImmutableDigesterError::NotEnoughImmutable {
                expected_number: beacon.immutable_file_number,
                found_number: None,
                db_dir: dirpath.to_owned(),
            })
        }
    }
}