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
use anyhow::anyhow;
use anyhow::Context;
use async_trait::async_trait;
use std::sync::Arc;
use thiserror::Error;

use crate::StdResult;
use crate::{
    chain_observer::ChainObserver, digesters::ImmutableFileObserver, entities::Beacon,
    CardanoNetwork,
};

/// Provide the current [Beacon] of a cardano node.
#[async_trait]
pub trait BeaconProvider
where
    Self: Sync + Send,
{
    /// Get the current [Beacon] of the cardano node.
    async fn get_current_beacon(&self) -> StdResult<Beacon>;
}

/// [BeaconProvider] related errors.
#[derive(Error, Debug)]
pub enum BeaconProviderError {
    /// Raised reading the current epoch succeeded but yield no result.
    #[error("No epoch yield by the chain observer, is your cardano node ready ?")]
    NoEpoch(),
}

/// A [BeaconProvider] using a [ChainObserver] and a [ImmutableFileObserver].
pub struct BeaconProviderImpl {
    chain_observer: Arc<dyn ChainObserver>,
    immutable_observer: Arc<dyn ImmutableFileObserver>,
    network: CardanoNetwork,
}

impl BeaconProviderImpl {
    /// [BeaconProviderImpl] factory.
    pub fn new(
        chain_observer: Arc<dyn ChainObserver>,
        immutable_observer: Arc<dyn ImmutableFileObserver>,
        network: CardanoNetwork,
    ) -> Self {
        Self {
            chain_observer,
            immutable_observer,
            network,
        }
    }
}

#[async_trait]
impl BeaconProvider for BeaconProviderImpl {
    async fn get_current_beacon(&self) -> StdResult<Beacon> {
        let epoch = self
            .chain_observer
            .get_current_epoch()
            .await
            .map_err(|e| anyhow!(e))
            .with_context(|| "Beacon Provider can not get current epoch")?
            .ok_or(BeaconProviderError::NoEpoch())?;

        let immutable_file_number = self
            .immutable_observer
            .get_last_immutable_number()
            .await
            .with_context(|| {
                format!(
                    "Beacon Provider can not get last immutable file number for epoch: '{epoch}'"
                )
            })?;

        let beacon = Beacon {
            network: self.network.to_string(),
            epoch,
            immutable_file_number,
        };

        Ok(beacon)
    }
}

#[cfg(test)]
mod tests {
    use crate::chain_observer::{ChainAddress, ChainObserver, ChainObserverError, TxDatum};
    use crate::digesters::DumbImmutableFileObserver;
    use crate::entities::{Epoch, StakeDistribution};
    use anyhow::anyhow;

    use super::*;

    struct DumbChainObserver {}

    #[async_trait]
    impl ChainObserver for DumbChainObserver {
        async fn get_current_datums(
            &self,
            _address: &ChainAddress,
        ) -> Result<Vec<TxDatum>, ChainObserverError> {
            Ok(Vec::new())
        }

        async fn get_current_epoch(&self) -> Result<Option<Epoch>, ChainObserverError> {
            Ok(Some(Epoch(42)))
        }

        async fn get_current_stake_distribution(
            &self,
        ) -> Result<Option<StakeDistribution>, ChainObserverError> {
            Err(ChainObserverError::General(anyhow!(
                "this should not be called in the BeaconProvider"
            )))
        }
    }

    #[tokio::test]
    async fn test_beacon_ok() {
        let beacon_provider = BeaconProviderImpl::new(
            Arc::new(DumbChainObserver {}),
            Arc::new(DumbImmutableFileObserver::default()),
            CardanoNetwork::TestNet(42),
        );
        let beacon = beacon_provider.get_current_beacon().await.unwrap();

        assert_eq!(42, beacon.epoch);
        assert_eq!(500, beacon.immutable_file_number);
    }

    #[tokio::test]
    async fn test_beacon_error() {
        let immutable_observer = DumbImmutableFileObserver::default();
        immutable_observer.shall_return(None).await;
        let beacon_provider = BeaconProviderImpl::new(
            Arc::new(DumbChainObserver {}),
            Arc::new(immutable_observer),
            CardanoNetwork::TestNet(42),
        );

        let result = beacon_provider.get_current_beacon().await;
        assert!(result.is_err());
    }
}