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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//! A client to retrieve Cardano stake distributions data from an Aggregator.
//!
//! In order to do so it defines a [CardanoStakeDistributionClient] which exposes the following features:
//!  - [get][CardanoStakeDistributionClient::get]: get a Cardano stake distribution data from its hash
//!  - [get_by_epoch][CardanoStakeDistributionClient::get_by_epoch]: get a Cardano stake distribution data from its epoch
//!  - [list][CardanoStakeDistributionClient::list]: get the list of available Cardano stake distribution
//!
//! # Get a Cardano stake distribution
//!
//! To get a Cardano stake distribution using the [ClientBuilder][crate::client::ClientBuilder].
//!
//! ```no_run
//! # async fn run() -> mithril_client::MithrilResult<()> {
//! use mithril_client::ClientBuilder;
//!
//! let client = ClientBuilder::aggregator("YOUR_AGGREGATOR_ENDPOINT", "YOUR_GENESIS_VERIFICATION_KEY").build()?;
//! let cardano_stake_distribution = client.cardano_stake_distribution().get("CARDANO_STAKE_DISTRIBUTION_HASH").await?.unwrap();
//!
//! println!(
//!     "Cardano stake distribution hash={}, epoch={}, stake_distribution={:?}",
//!     cardano_stake_distribution.hash,
//!     cardano_stake_distribution.epoch,
//!     cardano_stake_distribution.stake_distribution
//! );
//! #    Ok(())
//! # }
//! ```
//!
//! # List available Cardano stake distributions
//!
//! To list available Cardano stake distributions using the [ClientBuilder][crate::client::ClientBuilder].
//!
//! ```no_run
//! # async fn run() -> mithril_client::MithrilResult<()> {
//! use mithril_client::ClientBuilder;
//!
//! let client = ClientBuilder::aggregator("YOUR_AGGREGATOR_ENDPOINT", "YOUR_GENESIS_VERIFICATION_KEY").build()?;
//! let cardano_stake_distributions = client.cardano_stake_distribution().list().await?;
//!
//! for cardano_stake_distribution in cardano_stake_distributions {
//!     println!("Cardano stake distribution hash={}, epoch={}", cardano_stake_distribution.hash, cardano_stake_distribution.epoch);
//! }
//! #    Ok(())
//! # }
//! ```
//!
//! # Get a Cardano stake distribution by epoch
//!
//! To get a Cardano stake distribution by epoch using the [ClientBuilder][crate::client::ClientBuilder].
//! The epoch represents the epoch at the end of which the Cardano stake distribution is computed by the Cardano node
//!
//! ```no_run
//! # async fn run() -> mithril_client::MithrilResult<()> {
//! use mithril_client::ClientBuilder;
//! use mithril_client::common::Epoch;
//!
//! let client = ClientBuilder::aggregator("YOUR_AGGREGATOR_ENDPOINT", "YOUR_GENESIS_VERIFICATION_KEY").build()?;
//! let cardano_stake_distribution = client.cardano_stake_distribution().get_by_epoch(Epoch(500)).await?.unwrap();
//!
//! println!(
//!     "Cardano stake distribution hash={}, epoch={}, stake_distribution={:?}",
//!     cardano_stake_distribution.hash,
//!     cardano_stake_distribution.epoch,
//!     cardano_stake_distribution.stake_distribution
//! );
//! #    Ok(())
//! # }
//! ```

use anyhow::Context;
use std::sync::Arc;

use crate::aggregator_client::{AggregatorClient, AggregatorClientError, AggregatorRequest};
use crate::common::Epoch;
use crate::{CardanoStakeDistribution, CardanoStakeDistributionListItem, MithrilResult};

/// HTTP client for CardanoStakeDistribution API from the Aggregator
pub struct CardanoStakeDistributionClient {
    aggregator_client: Arc<dyn AggregatorClient>,
}

impl CardanoStakeDistributionClient {
    /// Constructs a new `CardanoStakeDistribution`.
    pub fn new(aggregator_client: Arc<dyn AggregatorClient>) -> Self {
        Self { aggregator_client }
    }

    /// Fetch a list of signed CardanoStakeDistribution
    pub async fn list(&self) -> MithrilResult<Vec<CardanoStakeDistributionListItem>> {
        let response = self
            .aggregator_client
            .get_content(AggregatorRequest::ListCardanoStakeDistributions)
            .await
            .with_context(|| "CardanoStakeDistribution client can not get the artifact list")?;
        let items = serde_json::from_str::<Vec<CardanoStakeDistributionListItem>>(&response)
            .with_context(|| "CardanoStakeDistribution client can not deserialize artifact list")?;

        Ok(items)
    }

    /// Get the given Cardano stake distribution data by hash.
    pub async fn get(&self, hash: &str) -> MithrilResult<Option<CardanoStakeDistribution>> {
        self.fetch_with_aggregator_request(AggregatorRequest::GetCardanoStakeDistribution {
            hash: hash.to_string(),
        })
        .await
    }

    /// Get the given Cardano stake distribution data by epoch.
    pub async fn get_by_epoch(
        &self,
        epoch: Epoch,
    ) -> MithrilResult<Option<CardanoStakeDistribution>> {
        self.fetch_with_aggregator_request(AggregatorRequest::GetCardanoStakeDistributionByEpoch {
            epoch,
        })
        .await
    }

    /// Fetch the given Cardano stake distribution data with an aggregator request.
    /// If it cannot be found, a None is returned.
    async fn fetch_with_aggregator_request(
        &self,
        request: AggregatorRequest,
    ) -> MithrilResult<Option<CardanoStakeDistribution>> {
        match self.aggregator_client.get_content(request).await {
            Ok(content) => {
                let cardano_stake_distribution: CardanoStakeDistribution =
                    serde_json::from_str(&content).with_context(|| {
                        "CardanoStakeDistribution client can not deserialize artifact"
                    })?;

                Ok(Some(cardano_stake_distribution))
            }
            Err(AggregatorClientError::RemoteServerLogical(_)) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use anyhow::anyhow;
    use chrono::{DateTime, Utc};
    use mockall::predicate::eq;

    use crate::aggregator_client::MockAggregatorHTTPClient;
    use crate::common::StakeDistribution;

    use super::*;

    fn fake_messages() -> Vec<CardanoStakeDistributionListItem> {
        vec![
            CardanoStakeDistributionListItem {
                epoch: Epoch(1),
                hash: "hash-123".to_string(),
                certificate_hash: "cert-hash-123".to_string(),
                created_at: DateTime::parse_from_rfc3339("2024-08-06T12:13:05.618857482Z")
                    .unwrap()
                    .with_timezone(&Utc),
            },
            CardanoStakeDistributionListItem {
                epoch: Epoch(2),
                hash: "hash-456".to_string(),
                certificate_hash: "cert-hash-456".to_string(),
                created_at: DateTime::parse_from_rfc3339("2024-08-06T12:13:05.618857482Z")
                    .unwrap()
                    .with_timezone(&Utc),
            },
        ]
    }

    #[tokio::test]
    async fn list_mithril_stake_distributions_returns_messages() {
        let message = fake_messages();
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .with(eq(AggregatorRequest::ListCardanoStakeDistributions))
            .return_once(move |_| Ok(serde_json::to_string(&message).unwrap()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        let messages = client.list().await.unwrap();

        assert_eq!(2, messages.len());
        assert_eq!("hash-123".to_string(), messages[0].hash);
        assert_eq!("hash-456".to_string(), messages[1].hash);
    }

    #[tokio::test]
    async fn list_mithril_stake_distributions_returns_error_when_invalid_json_structure_in_response(
    ) {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .return_once(move |_| Ok("invalid json structure".to_string()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        client
            .list()
            .await
            .expect_err("List Cardano stake distributions should return an error");
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_returns_message() {
        let expected_stake_distribution = StakeDistribution::from([("pool123".to_string(), 123)]);
        let message = CardanoStakeDistribution {
            epoch: Epoch(3),
            hash: "hash-123".to_string(),
            certificate_hash: "certificate-hash-123".to_string(),
            stake_distribution: expected_stake_distribution.clone(),
            created_at: DateTime::<Utc>::default(),
        };
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .with(eq(AggregatorRequest::GetCardanoStakeDistribution {
                hash: "hash-123".to_string(),
            }))
            .return_once(move |_| Ok(serde_json::to_string(&message).unwrap()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        let cardano_stake_distribution = client
            .get("hash-123")
            .await
            .unwrap()
            .expect("This test returns a Cardano stake distribution");

        assert_eq!("hash-123".to_string(), cardano_stake_distribution.hash);
        assert_eq!(Epoch(3), cardano_stake_distribution.epoch);
        assert_eq!(
            expected_stake_distribution,
            cardano_stake_distribution.stake_distribution
        );
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_returns_error_when_invalid_json_structure_in_response()
    {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .return_once(move |_| Ok("invalid json structure".to_string()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        client
            .get("hash-123")
            .await
            .expect_err("Get Cardano stake distribution should return an error");
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_returns_none_when_not_found_or_remote_server_logical_error(
    ) {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client.expect_get_content().return_once(move |_| {
            Err(AggregatorClientError::RemoteServerLogical(anyhow!(
                "not found"
            )))
        });
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        let result = client.get("hash-123").await.unwrap();

        assert!(result.is_none());
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_returns_error() {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .return_once(move |_| Err(AggregatorClientError::SubsystemError(anyhow!("error"))));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        client
            .get("hash-123")
            .await
            .expect_err("Get Cardano stake distribution should return an error");
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_by_epoch_returns_message() {
        let expected_stake_distribution = StakeDistribution::from([("pool123".to_string(), 123)]);
        let message = CardanoStakeDistribution {
            epoch: Epoch(3),
            hash: "hash-123".to_string(),
            certificate_hash: "certificate-hash-123".to_string(),
            stake_distribution: expected_stake_distribution.clone(),
            created_at: DateTime::<Utc>::default(),
        };
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .with(eq(AggregatorRequest::GetCardanoStakeDistributionByEpoch {
                epoch: Epoch(3),
            }))
            .return_once(move |_| Ok(serde_json::to_string(&message).unwrap()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        let cardano_stake_distribution = client
            .get_by_epoch(Epoch(3))
            .await
            .unwrap()
            .expect("This test returns a Cardano stake distribution");

        assert_eq!("hash-123".to_string(), cardano_stake_distribution.hash);
        assert_eq!(Epoch(3), cardano_stake_distribution.epoch);
        assert_eq!(
            expected_stake_distribution,
            cardano_stake_distribution.stake_distribution
        );
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_by_epoch_returns_error_when_invalid_json_structure_in_response(
    ) {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .return_once(move |_| Ok("invalid json structure".to_string()));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        client
            .get_by_epoch(Epoch(3))
            .await
            .expect_err("Get Cardano stake distribution by epoch should return an error");
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_by_epoch_returns_none_when_not_found_or_remote_server_logical_error(
    ) {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client.expect_get_content().return_once(move |_| {
            Err(AggregatorClientError::RemoteServerLogical(anyhow!(
                "not found"
            )))
        });
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        let result = client.get_by_epoch(Epoch(3)).await.unwrap();

        assert!(result.is_none());
    }

    #[tokio::test]
    async fn get_cardano_stake_distribution_by_epoch_returns_error() {
        let mut http_client = MockAggregatorHTTPClient::new();
        http_client
            .expect_get_content()
            .return_once(move |_| Err(AggregatorClientError::SubsystemError(anyhow!("error"))));
        let client = CardanoStakeDistributionClient::new(Arc::new(http_client));

        client
            .get_by_epoch(Epoch(3))
            .await
            .expect_err("Get Cardano stake distribution by epoch should return an error");
    }
}