mithril_common/
ticker_service.rs

1//! ## Ticker Service
2//!
3//! This service read time information from the chain and helps create beacons
4//! for every message types.
5
6use anyhow::{anyhow, Context};
7use async_trait::async_trait;
8use std::sync::Arc;
9use thiserror::Error;
10
11use crate::chain_observer::ChainObserver;
12use crate::digesters::ImmutableFileObserver;
13use crate::entities::{Epoch, TimePoint};
14use crate::StdResult;
15
16/// ## TickerService
17///
18/// This service is responsible for giving the right time information to other
19/// services. It reads data either from the Chain or the filesystem to create
20/// beacons for each message type.
21#[async_trait]
22pub trait TickerService
23where
24    Self: Sync + Send,
25{
26    /// Get the current [Epoch] of the cardano node.
27    async fn get_current_epoch(&self) -> StdResult<Epoch> {
28        self.get_current_time_point()
29            .await
30            .map(|time_point| time_point.epoch)
31    }
32
33    /// Get the current [TimePoint] of the cardano node.
34    async fn get_current_time_point(&self) -> StdResult<TimePoint>;
35}
36
37/// [TickerService] related errors.
38#[derive(Error, Debug)]
39pub enum TickerServiceError {
40    /// Raised when reading the current epoch succeeded but yielded no result.
41    #[error("No epoch yielded by the chain observer, is your cardano node ready?")]
42    NoEpoch,
43
44    /// Raised when reading the current chain point succeeded but yielded no result.
45    #[error("No chain point yielded by the chain observer, is your cardano node ready?")]
46    NoChainPoint,
47}
48
49/// A [TickerService] using a [ChainObserver] and a [ImmutableFileObserver].
50pub struct MithrilTickerService {
51    chain_observer: Arc<dyn ChainObserver>,
52    immutable_observer: Arc<dyn ImmutableFileObserver>,
53}
54
55impl MithrilTickerService {
56    /// [MithrilTickerService] factory.
57    pub fn new(
58        chain_observer: Arc<dyn ChainObserver>,
59        immutable_observer: Arc<dyn ImmutableFileObserver>,
60    ) -> Self {
61        Self {
62            chain_observer,
63            immutable_observer,
64        }
65    }
66}
67
68#[async_trait]
69impl TickerService for MithrilTickerService {
70    async fn get_current_time_point(&self) -> StdResult<TimePoint> {
71        let epoch = self
72            .chain_observer
73            .get_current_epoch()
74            .await
75            .map_err(|e| anyhow!(e))
76            .with_context(|| "TimePoint Provider can not get current epoch")?
77            .ok_or(TickerServiceError::NoEpoch)?;
78
79        let immutable_file_number = self
80            .immutable_observer
81            .get_last_immutable_number()
82            .await
83            .with_context(|| {
84                format!(
85                    "TimePoint Provider can not get last immutable file number for epoch: '{epoch}'"
86                )
87            })?;
88
89        let chain_point = self
90            .chain_observer
91            .get_current_chain_point()
92            .await
93            .map_err(|e| anyhow!(e))
94            .with_context(|| "TimePoint Provider can not get current chain point")?
95            .ok_or(TickerServiceError::NoChainPoint)?;
96
97        Ok(TimePoint {
98            epoch,
99            immutable_file_number,
100            chain_point,
101        })
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use crate::chain_observer::{ChainAddress, ChainObserver, ChainObserverError, TxDatum};
108    use crate::digesters::DumbImmutableFileObserver;
109    use crate::entities::{BlockNumber, ChainPoint, Epoch, SlotNumber, StakeDistribution};
110    use anyhow::anyhow;
111
112    use super::*;
113
114    struct DumbChainObserver {}
115
116    #[async_trait]
117    impl ChainObserver for DumbChainObserver {
118        async fn get_current_datums(
119            &self,
120            _address: &ChainAddress,
121        ) -> Result<Vec<TxDatum>, ChainObserverError> {
122            Ok(Vec::new())
123        }
124
125        async fn get_current_era(&self) -> Result<Option<String>, ChainObserverError> {
126            Ok(Some(String::new()))
127        }
128
129        async fn get_current_epoch(&self) -> Result<Option<Epoch>, ChainObserverError> {
130            Ok(Some(Epoch(42)))
131        }
132
133        async fn get_current_chain_point(&self) -> Result<Option<ChainPoint>, ChainObserverError> {
134            Ok(Some(ChainPoint {
135                slot_number: SlotNumber(800),
136                block_number: BlockNumber(51),
137                block_hash: "1b69b3202fbe500".to_string(),
138            }))
139        }
140
141        async fn get_current_stake_distribution(
142            &self,
143        ) -> Result<Option<StakeDistribution>, ChainObserverError> {
144            Err(ChainObserverError::General(anyhow!(
145                "this should not be called in the TimePointProvider"
146            )))
147        }
148    }
149
150    #[tokio::test]
151    async fn test_get_current_epoch() {
152        let ticker_service = MithrilTickerService::new(
153            Arc::new(DumbChainObserver {}),
154            Arc::new(DumbImmutableFileObserver::default()),
155        );
156        let epoch = ticker_service.get_current_epoch().await.unwrap();
157
158        assert_eq!(Epoch(42), epoch);
159    }
160
161    #[tokio::test]
162    async fn test_happy_path() {
163        let ticker_service = MithrilTickerService::new(
164            Arc::new(DumbChainObserver {}),
165            Arc::new(DumbImmutableFileObserver::default()),
166        );
167        let time_point = ticker_service.get_current_time_point().await.unwrap();
168
169        assert_eq!(
170            TimePoint::new(
171                42,
172                500,
173                ChainPoint {
174                    slot_number: SlotNumber(800),
175                    block_number: BlockNumber(51),
176                    block_hash: "1b69b3202fbe500".to_string(),
177                },
178            ),
179            time_point
180        );
181    }
182
183    #[tokio::test]
184    async fn test_error_from_dependency() {
185        let immutable_observer = DumbImmutableFileObserver::default();
186        immutable_observer.shall_return(None).await;
187        let ticker_service =
188            MithrilTickerService::new(Arc::new(DumbChainObserver {}), Arc::new(immutable_observer));
189
190        let result = ticker_service.get_current_time_point().await;
191        assert!(result.is_err());
192    }
193}