mithril_client/
feedback.rs

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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! # Long task feedbacks
//!
//! Even with fast computer and network, some tasks can take more than a few
//! seconds to run (or even more than an hour for a snapshot download).
//!
//! Those tasks are:
//! - Snapshot download
//! - Certificate chain validation
//!
//! In order to have feedbacks for those tasks, a mechanism is available.
//!
//! Define your feedback receiver and implement the [FeedbackReceiver] trait to receive
//! [events][MithrilEvent] with the [`handle_event`][FeedbackReceiver::handle_event] method.
//! Then pass an instance of your receiver when building your `Client` using
//! [`ClientBuilder::add_feedback_receiver`][crate::ClientBuilder::add_feedback_receiver] method.
//!
//! # Example
//!
//! Using the provided [SlogFeedbackReceiver] to log the events using a [slog] logger.
//!
//! ```no_run
//! use std::sync::Arc;
//! # async fn run() -> mithril_client::MithrilResult<()> {
//! use mithril_client::{ClientBuilder, MessageBuilder, feedback::SlogFeedbackReceiver};
//!
//! let client = ClientBuilder::aggregator("YOUR_AGGREGATOR_ENDPOINT", "YOUR_GENESIS_VERIFICATION_KEY")
//!     .add_feedback_receiver(Arc::new(SlogFeedbackReceiver::new(build_logger())))
//!     .build()?;
//!
//! let _ = client.certificate().verify_chain("CERTIFICATE_HASH").await?;
//! #
//! #    Ok(())
//! # }
//!
//! pub fn build_logger() -> slog::Logger {
//!   use slog::Drain;
//!   let decorator = slog_term::TermDecorator::new().build();
//!   let drain = slog_term::FullFormat::new(decorator).build().fuse();
//!   let drain = slog_async::Async::new(drain).build().fuse();
//!
//!   slog::Logger::root(Arc::new(drain), slog::o!())
//! }
//! ```
//!
//! Running this code should yield the following logs (example run on _pre-release-preview_):
//!
//! ```shell
//! Nov 08 14:41:40.436 INFO Certificate chain validation started, certificate_chain_validation_id: ab623989-b0ac-4031-8522-1370958bbb4e
//! Nov 08 14:41:40.626 INFO Certificate validated, certificate_chain_validation_id: ab623989-b0ac-4031-8522-1370958bbb4e, certificate_hash: dd4d4299cfb817b5ee5987c3de7cf5f13bdcda69c968ef087effd550470dc081
//! Nov 08 14:42:05.477 INFO Certificate validated, certificate_chain_validation_id: ab623989-b0ac-4031-8522-1370958bbb4e, certificate_hash: 660b3d426a95303254bb255a56bed443616ea63c4d721ea77433b920d7ebdf62
//! Nov 08 14:42:05.477 INFO Certificate chain validated, certificate_chain_validation_id: ab623989-b0ac-4031-8522-1370958bbb4e
//! ```

use async_trait::async_trait;
use serde::Serialize;
use slog::{info, Logger};
use std::sync::{Arc, RwLock};
use strum::Display;
use uuid::Uuid;

/// Event that can be reported by a [FeedbackReceiver].
#[derive(Debug, Clone, Eq, PartialEq, Display, Serialize)]
#[strum(serialize_all = "PascalCase")]
#[serde(untagged)]
pub enum MithrilEvent {
    /// A snapshot download has started
    SnapshotDownloadStarted {
        /// Digest of the downloaded snapshot
        digest: String,
        /// Unique identifier used to track this specific snapshot download
        download_id: String,
        /// Size of the downloaded archive
        size: u64,
    },
    /// A snapshot download is in progress
    SnapshotDownloadProgress {
        /// Unique identifier used to track this specific snapshot download
        download_id: String,
        /// Number of bytes that have been downloaded
        downloaded_bytes: u64,
        /// Size of the downloaded archive
        size: u64,
    },
    /// A snapshot download has completed
    SnapshotDownloadCompleted {
        /// Unique identifier used to track this specific snapshot download
        download_id: String,
    },
    /// A certificate chain validation has started
    CertificateChainValidationStarted {
        /// Unique identifier used to track this specific certificate chain validation
        certificate_chain_validation_id: String,
    },
    /// An individual certificate of a chain have been validated.
    CertificateValidated {
        /// Unique identifier used to track this specific certificate chain validation
        certificate_chain_validation_id: String,
        /// The validated certificate hash
        certificate_hash: String,
    },
    /// An individual certificate of a chain have been fetched from the cache.
    CertificateFetchedFromCache {
        /// Unique identifier used to track this specific certificate chain validation
        certificate_chain_validation_id: String,
        /// The fetched certificate hash
        certificate_hash: String,
    },
    /// The whole certificate chain is valid.
    CertificateChainValidated {
        /// Unique identifier used to track this specific certificate chain validation
        certificate_chain_validation_id: String,
    },
}

impl MithrilEvent {
    /// Generate a random unique identifier to identify a snapshot download
    pub fn new_snapshot_download_id() -> String {
        Uuid::new_v4().to_string()
    }

    /// Generate a random unique identifier to identify a certificate chain validation
    pub fn new_certificate_chain_validation_id() -> String {
        Uuid::new_v4().to_string()
    }

    #[cfg(test)]
    pub(crate) fn event_id(&self) -> &str {
        match self {
            MithrilEvent::SnapshotDownloadStarted { download_id, .. } => download_id,
            MithrilEvent::SnapshotDownloadProgress { download_id, .. } => download_id,
            MithrilEvent::SnapshotDownloadCompleted { download_id } => download_id,
            MithrilEvent::CertificateChainValidationStarted {
                certificate_chain_validation_id,
            } => certificate_chain_validation_id,
            MithrilEvent::CertificateValidated {
                certificate_chain_validation_id,
                ..
            } => certificate_chain_validation_id,
            MithrilEvent::CertificateFetchedFromCache {
                certificate_chain_validation_id,
                ..
            } => certificate_chain_validation_id,
            MithrilEvent::CertificateChainValidated {
                certificate_chain_validation_id,
            } => certificate_chain_validation_id,
        }
    }
}

/// A sender of [MithrilEvent].
///
/// It uses Arc internally so it can be cloned at will.
#[derive(Clone)]
pub struct FeedbackSender {
    receivers: Vec<Arc<dyn FeedbackReceiver>>,
}

impl FeedbackSender {
    /// Create a new [FeedbackSender].
    pub fn new(receivers: &[Arc<dyn FeedbackReceiver>]) -> FeedbackSender {
        Self {
            receivers: receivers.to_vec(),
        }
    }

    /// Send the given event to the known receivers.
    pub async fn send_event(&self, event: MithrilEvent) {
        for receiver in &self.receivers {
            receiver.handle_event(event.clone()).await;
        }
    }
}

/// A receiver of [MithrilEvent].
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
pub trait FeedbackReceiver: Sync + Send {
    /// Callback called by a [FeedbackSender] when it needs to send an [event][MithrilEvent].
    async fn handle_event(&self, event: MithrilEvent);
}

/// A [FeedbackReceiver] that writes the event it receives in a [slog logger][Logger].
pub struct SlogFeedbackReceiver {
    logger: Logger,
}

impl SlogFeedbackReceiver {
    /// Create a new [SlogFeedbackReceiver].
    pub fn new(logger: Logger) -> SlogFeedbackReceiver {
        Self { logger }
    }
}

#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl FeedbackReceiver for SlogFeedbackReceiver {
    async fn handle_event(&self, event: MithrilEvent) {
        match event {
            MithrilEvent::SnapshotDownloadStarted {
                digest,
                download_id,
                size,
            } => {
                info!(
                    self.logger, "Snapshot download started";
                    "size" => size, "digest" => digest, "download_id" => download_id,
                );
            }
            MithrilEvent::SnapshotDownloadProgress {
                download_id,
                downloaded_bytes,
                size,
            } => {
                info!(
                    self.logger, "Snapshot download in progress ...";
                    "downloaded_bytes" => downloaded_bytes, "size" => size, "download_id" => download_id,
                );
            }
            MithrilEvent::SnapshotDownloadCompleted { download_id } => {
                info!(self.logger, "Snapshot download completed"; "download_id" => download_id);
            }
            MithrilEvent::CertificateChainValidationStarted {
                certificate_chain_validation_id,
            } => {
                info!(
                    self.logger, "Certificate chain validation started";
                    "certificate_chain_validation_id" => certificate_chain_validation_id,
                );
            }
            MithrilEvent::CertificateValidated {
                certificate_hash,
                certificate_chain_validation_id,
            } => {
                info!(
                    self.logger, "Certificate validated";
                    "certificate_hash" => certificate_hash,
                    "certificate_chain_validation_id" => certificate_chain_validation_id,
                );
            }
            MithrilEvent::CertificateFetchedFromCache {
                certificate_hash,
                certificate_chain_validation_id,
            } => {
                info!(
                    self.logger, "Cached";
                    "certificate_hash" => certificate_hash,
                    "certificate_chain_validation_id" => certificate_chain_validation_id,
                );
            }
            MithrilEvent::CertificateChainValidated {
                certificate_chain_validation_id,
            } => {
                info!(
                    self.logger, "Certificate chain validated";
                    "certificate_chain_validation_id" => certificate_chain_validation_id,
                );
            }
        };
    }
}

/// A [FeedbackReceiver] that stacks the events that it receives in a vec.
///
/// Use it only for tests purpose.
pub struct StackFeedbackReceiver {
    stacked_events: RwLock<Vec<MithrilEvent>>,
}

impl StackFeedbackReceiver {
    /// Create a new [StackFeedbackReceiver].
    pub fn new() -> StackFeedbackReceiver {
        Self {
            stacked_events: RwLock::new(vec![]),
        }
    }

    /// Returns a copy of the stored stacked events.
    ///
    /// Will crash if it can't access the stored events.
    pub fn stacked_events(&self) -> Vec<MithrilEvent> {
        let events = self.stacked_events.read().unwrap();
        events.clone()
    }
}

impl Default for StackFeedbackReceiver {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl FeedbackReceiver for StackFeedbackReceiver {
    async fn handle_event(&self, event: MithrilEvent) {
        let mut events = self.stacked_events.write().unwrap();
        events.push(event);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::feedback::MithrilEvent::{SnapshotDownloadCompleted, SnapshotDownloadStarted};
    use std::time::Duration;
    use tokio::task::JoinSet;

    #[tokio::test]
    async fn send_event_same_thread() {
        let receiver = Arc::new(StackFeedbackReceiver::new());
        let sender = FeedbackSender::new(&[receiver.clone()]);

        sender
            .send_event(SnapshotDownloadStarted {
                digest: "digest".to_string(),
                download_id: "download_id".to_string(),
                size: 10,
            })
            .await;
        sender
            .send_event(SnapshotDownloadCompleted {
                download_id: "download_id".to_string(),
            })
            .await;

        assert_eq!(
            receiver.stacked_events(),
            vec![
                SnapshotDownloadStarted {
                    digest: "digest".to_string(),
                    download_id: "download_id".to_string(),
                    size: 10
                },
                SnapshotDownloadCompleted {
                    download_id: "download_id".to_string()
                }
            ]
        );
    }

    #[tokio::test]
    async fn send_event_multiple_thread() {
        let receiver = Arc::new(StackFeedbackReceiver::new());
        let sender = FeedbackSender::new(&[
            receiver.clone(),
            Arc::new(SlogFeedbackReceiver::new(crate::test_utils::test_logger())),
        ]);
        let sender2 = sender.clone();
        let mut join_set = JoinSet::new();

        join_set.spawn(async move {
            // Step 1:
            sender
                .send_event(SnapshotDownloadStarted {
                    digest: "digest1".to_string(),
                    download_id: "download1".to_string(),
                    size: 1,
                })
                .await;
            tokio::time::sleep(Duration::from_millis(2)).await;
            // Step 3:
            sender
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download3".to_string(),
                })
                .await;
            sender
                .send_event(SnapshotDownloadStarted {
                    digest: "digest2".to_string(),
                    download_id: "download2".to_string(),
                    size: 2,
                })
                .await;
        });

        join_set.spawn(async move {
            // Step 2:
            sender2
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download1".to_string(),
                })
                .await;
            sender2
                .send_event(SnapshotDownloadStarted {
                    digest: "digest3".to_string(),
                    download_id: "download3".to_string(),
                    size: 3,
                })
                .await;
            tokio::time::sleep(Duration::from_millis(5)).await;
            // Step 4:
            sender2
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download2".to_string(),
                })
                .await;
        });

        while let Some(res) = join_set.join_next().await {
            res.unwrap();
        }

        assert_eq!(
            receiver.stacked_events(),
            vec![
                SnapshotDownloadStarted {
                    digest: "digest1".to_string(),
                    download_id: "download1".to_string(),
                    size: 1
                },
                SnapshotDownloadCompleted {
                    download_id: "download1".to_string()
                },
                SnapshotDownloadStarted {
                    digest: "digest3".to_string(),
                    download_id: "download3".to_string(),
                    size: 3
                },
                SnapshotDownloadCompleted {
                    download_id: "download3".to_string()
                },
                SnapshotDownloadStarted {
                    digest: "digest2".to_string(),
                    download_id: "download2".to_string(),
                    size: 2
                },
                SnapshotDownloadCompleted {
                    download_id: "download2".to_string()
                },
            ]
        );
    }

    #[tokio::test]
    async fn send_event_in_one_thread_and_receive_in_another_thread() {
        let receiver = Arc::new(StackFeedbackReceiver::new());
        let receiver2 = receiver.clone();
        let sender = FeedbackSender::new(&[receiver.clone()]);
        let mut join_set = JoinSet::new();

        join_set.spawn(async move {
            // Step 1:
            sender
                .send_event(SnapshotDownloadStarted {
                    digest: "digest1".to_string(),
                    download_id: "download1".to_string(),
                    size: 1,
                })
                .await;
            tokio::time::sleep(Duration::from_millis(10)).await;

            // Step 2:
            sender
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download1".to_string(),
                })
                .await;
            sender
                .send_event(SnapshotDownloadStarted {
                    digest: "digest2".to_string(),
                    download_id: "download2".to_string(),
                    size: 2,
                })
                .await;
            tokio::time::sleep(Duration::from_millis(10)).await;

            // Step 3:
            sender
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download2".to_string(),
                })
                .await;
            sender
                .send_event(SnapshotDownloadStarted {
                    digest: "digest3".to_string(),
                    download_id: "download3".to_string(),
                    size: 3,
                })
                .await;
            tokio::time::sleep(Duration::from_millis(10)).await;

            // Final step:
            sender
                .send_event(SnapshotDownloadCompleted {
                    download_id: "download3".to_string(),
                })
                .await;
        });

        join_set.spawn(async move {
            // Little sleep to wait for step 1 completion
            tokio::time::sleep(Duration::from_millis(3)).await;
            assert_eq!(
                receiver2.stacked_events(),
                vec![SnapshotDownloadStarted {
                    digest: "digest1".to_string(),
                    download_id: "download1".to_string(),
                    size: 1
                },]
            );

            // Wait for step 2 completion
            tokio::time::sleep(Duration::from_millis(10)).await;
            assert_eq!(
                receiver2.stacked_events(),
                vec![
                    SnapshotDownloadStarted {
                        digest: "digest1".to_string(),
                        download_id: "download1".to_string(),
                        size: 1
                    },
                    SnapshotDownloadCompleted {
                        download_id: "download1".to_string()
                    },
                    SnapshotDownloadStarted {
                        digest: "digest2".to_string(),
                        download_id: "download2".to_string(),
                        size: 2
                    },
                ]
            );

            // Wait for step 3 completion
            tokio::time::sleep(Duration::from_millis(10)).await;
            assert_eq!(
                receiver2.stacked_events(),
                vec![
                    SnapshotDownloadStarted {
                        digest: "digest1".to_string(),
                        download_id: "download1".to_string(),
                        size: 1
                    },
                    SnapshotDownloadCompleted {
                        download_id: "download1".to_string()
                    },
                    SnapshotDownloadStarted {
                        digest: "digest2".to_string(),
                        download_id: "download2".to_string(),
                        size: 2
                    },
                    SnapshotDownloadCompleted {
                        download_id: "download2".to_string()
                    },
                    SnapshotDownloadStarted {
                        digest: "digest3".to_string(),
                        download_id: "download3".to_string(),
                        size: 3
                    },
                ]
            );
        });

        while let Some(res) = join_set.join_next().await {
            res.unwrap();
        }

        assert_eq!(
            receiver.stacked_events(),
            vec![
                SnapshotDownloadStarted {
                    digest: "digest1".to_string(),
                    download_id: "download1".to_string(),
                    size: 1
                },
                SnapshotDownloadCompleted {
                    download_id: "download1".to_string()
                },
                SnapshotDownloadStarted {
                    digest: "digest2".to_string(),
                    download_id: "download2".to_string(),
                    size: 2
                },
                SnapshotDownloadCompleted {
                    download_id: "download2".to_string()
                },
                SnapshotDownloadStarted {
                    digest: "digest3".to_string(),
                    download_id: "download3".to_string(),
                    size: 3
                },
                SnapshotDownloadCompleted {
                    download_id: "download3".to_string()
                },
            ]
        );
    }
}