mithril_ticker/
ticker_service.rs1use anyhow::{Context, anyhow};
7use async_trait::async_trait;
8use std::sync::Arc;
9use thiserror::Error;
10
11use mithril_cardano_node_chain::chain_observer::ChainObserver;
12use mithril_cardano_node_internal_database::ImmutableFileObserver;
13use mithril_common::StdResult;
14use mithril_common::entities::{Epoch, TimePoint};
15
16#[async_trait]
22pub trait TickerService
23where
24 Self: Sync + Send,
25{
26 async fn get_current_epoch(&self) -> StdResult<Epoch> {
28 self.get_current_time_point().await.map(|time_point| time_point.epoch)
29 }
30
31 async fn get_current_time_point(&self) -> StdResult<TimePoint>;
33}
34
35#[derive(Error, Debug)]
37pub enum TickerServiceError {
38 #[error("No epoch yielded by the chain observer, is your cardano node ready?")]
40 NoEpoch,
41
42 #[error("No chain point yielded by the chain observer, is your cardano node ready?")]
44 NoChainPoint,
45}
46
47pub struct MithrilTickerService {
49 chain_observer: Arc<dyn ChainObserver>,
50 immutable_observer: Arc<dyn ImmutableFileObserver>,
51}
52
53impl MithrilTickerService {
54 pub fn new(
56 chain_observer: Arc<dyn ChainObserver>,
57 immutable_observer: Arc<dyn ImmutableFileObserver>,
58 ) -> Self {
59 Self {
60 chain_observer,
61 immutable_observer,
62 }
63 }
64}
65
66#[async_trait]
67impl TickerService for MithrilTickerService {
68 async fn get_current_time_point(&self) -> StdResult<TimePoint> {
69 let epoch = self
70 .chain_observer
71 .get_current_epoch()
72 .await
73 .map_err(|e| anyhow!(e))
74 .with_context(|| "TimePoint Provider can not get current epoch")?
75 .ok_or(TickerServiceError::NoEpoch)?;
76
77 let immutable_file_number = self
78 .immutable_observer
79 .get_last_immutable_number()
80 .await
81 .with_context(|| {
82 format!(
83 "TimePoint Provider can not get last immutable file number for epoch: '{epoch}'"
84 )
85 })?;
86
87 let chain_point = self
88 .chain_observer
89 .get_current_chain_point()
90 .await
91 .map_err(|e| anyhow!(e))
92 .with_context(|| "TimePoint Provider can not get current chain point")?
93 .ok_or(TickerServiceError::NoChainPoint)?;
94
95 Ok(TimePoint {
96 epoch,
97 immutable_file_number,
98 chain_point,
99 })
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use anyhow::anyhow;
106
107 use mithril_cardano_node_chain::chain_observer::{ChainObserver, ChainObserverError};
108 use mithril_cardano_node_chain::entities::{ChainAddress, TxDatum};
109 use mithril_cardano_node_internal_database::test::double::DumbImmutableFileObserver;
110 use mithril_common::entities::{BlockNumber, ChainPoint, Epoch, SlotNumber, StakeDistribution};
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}