mithril_aggregator/services/
signed_entity.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
//! ## SignedEntityService
//!
//! This service is responsible for dealing with [SignedEntity] type.
//! It creates [Artifact] that can be accessed by clients.
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use chrono::Utc;
use slog::{info, warn, Logger};
use std::sync::Arc;
use tokio::task::JoinHandle;

use mithril_common::{
    entities::{
        BlockNumber, CardanoDatabaseSnapshot, CardanoDbBeacon, CardanoStakeDistribution,
        CardanoTransactionsSnapshot, Certificate, Epoch, MithrilStakeDistribution, SignedEntity,
        SignedEntityType, SignedEntityTypeDiscriminants, Snapshot,
    },
    logging::LoggerExtensions,
    signable_builder::Artifact,
    signed_entity_type_lock::SignedEntityTypeLock,
    StdResult,
};

use crate::{
    artifact_builder::ArtifactBuilder,
    database::{record::SignedEntityRecord, repository::SignedEntityStorer},
    MetricsService,
};

/// ArtifactBuilder Service trait
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait SignedEntityService: Send + Sync {
    /// Create artifact for a signed entity type and a certificate
    async fn create_artifact(
        &self,
        signed_entity_type: SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<JoinHandle<StdResult<()>>>;

    /// Return a list of signed snapshots order by creation date descending.
    async fn get_last_signed_snapshots(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<Snapshot>>>;

    /// Return a signed snapshot
    async fn get_signed_snapshot_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<Snapshot>>>;

    /// Return a list of Cardano Database snapshots order by creation date descending.
    async fn get_last_signed_cardano_database_snapshots(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<CardanoDatabaseSnapshot>>>;

    /// Return a Cardano Database snapshot
    async fn get_signed_cardano_database_snapshot_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<CardanoDatabaseSnapshot>>>;

    /// Return a list of signed Mithril stake distribution ordered by creation
    /// date descending.
    async fn get_last_signed_mithril_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<MithrilStakeDistribution>>>;

    /// Return a signed Mithril stake distribution
    async fn get_signed_mithril_stake_distribution_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<MithrilStakeDistribution>>>;

    /// Return the last signed Cardano Transaction Snapshot.
    async fn get_last_cardano_transaction_snapshot(
        &self,
    ) -> StdResult<Option<SignedEntity<CardanoTransactionsSnapshot>>>;

    /// Return a list of signed Cardano stake distribution ordered by creation
    /// date descending.
    async fn get_last_signed_cardano_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<CardanoStakeDistribution>>>;
}

/// Mithril ArtifactBuilder Service
#[derive(Clone)]
pub struct MithrilSignedEntityService {
    signed_entity_storer: Arc<dyn SignedEntityStorer>,
    mithril_stake_distribution_artifact_builder:
        Arc<dyn ArtifactBuilder<Epoch, MithrilStakeDistribution>>,
    cardano_immutable_files_full_artifact_builder:
        Arc<dyn ArtifactBuilder<CardanoDbBeacon, Snapshot>>,
    cardano_transactions_artifact_builder:
        Arc<dyn ArtifactBuilder<BlockNumber, CardanoTransactionsSnapshot>>,
    signed_entity_type_lock: Arc<SignedEntityTypeLock>,
    cardano_stake_distribution_artifact_builder:
        Arc<dyn ArtifactBuilder<Epoch, CardanoStakeDistribution>>,
    cardano_database_artifact_builder:
        Arc<dyn ArtifactBuilder<CardanoDbBeacon, CardanoDatabaseSnapshot>>,
    metrics_service: Arc<MetricsService>,
    logger: Logger,
}

/// ArtifactsBuilder dependencies required by the [MithrilSignedEntityService].
pub struct SignedEntityServiceArtifactsDependencies {
    mithril_stake_distribution_artifact_builder:
        Arc<dyn ArtifactBuilder<Epoch, MithrilStakeDistribution>>,
    cardano_immutable_files_full_artifact_builder:
        Arc<dyn ArtifactBuilder<CardanoDbBeacon, Snapshot>>,
    cardano_transactions_artifact_builder:
        Arc<dyn ArtifactBuilder<BlockNumber, CardanoTransactionsSnapshot>>,
    cardano_stake_distribution_artifact_builder:
        Arc<dyn ArtifactBuilder<Epoch, CardanoStakeDistribution>>,
    cardano_database_artifact_builder:
        Arc<dyn ArtifactBuilder<CardanoDbBeacon, CardanoDatabaseSnapshot>>,
}

impl SignedEntityServiceArtifactsDependencies {
    /// Create a new instance of [SignedEntityServiceArtifactsDependencies].
    pub fn new(
        mithril_stake_distribution_artifact_builder: Arc<
            dyn ArtifactBuilder<Epoch, MithrilStakeDistribution>,
        >,
        cardano_immutable_files_full_artifact_builder: Arc<
            dyn ArtifactBuilder<CardanoDbBeacon, Snapshot>,
        >,
        cardano_transactions_artifact_builder: Arc<
            dyn ArtifactBuilder<BlockNumber, CardanoTransactionsSnapshot>,
        >,
        cardano_stake_distribution_artifact_builder: Arc<
            dyn ArtifactBuilder<Epoch, CardanoStakeDistribution>,
        >,
        cardano_database_artifact_builder: Arc<
            dyn ArtifactBuilder<CardanoDbBeacon, CardanoDatabaseSnapshot>,
        >,
    ) -> Self {
        Self {
            mithril_stake_distribution_artifact_builder,
            cardano_immutable_files_full_artifact_builder,
            cardano_transactions_artifact_builder,
            cardano_stake_distribution_artifact_builder,
            cardano_database_artifact_builder,
        }
    }
}

impl MithrilSignedEntityService {
    /// MithrilSignedEntityService factory
    pub fn new(
        signed_entity_storer: Arc<dyn SignedEntityStorer>,
        dependencies: SignedEntityServiceArtifactsDependencies,
        signed_entity_type_lock: Arc<SignedEntityTypeLock>,
        metrics_service: Arc<MetricsService>,
        logger: Logger,
    ) -> Self {
        Self {
            signed_entity_storer,
            mithril_stake_distribution_artifact_builder: dependencies
                .mithril_stake_distribution_artifact_builder,
            cardano_immutable_files_full_artifact_builder: dependencies
                .cardano_immutable_files_full_artifact_builder,
            cardano_transactions_artifact_builder: dependencies
                .cardano_transactions_artifact_builder,
            cardano_stake_distribution_artifact_builder: dependencies
                .cardano_stake_distribution_artifact_builder,
            cardano_database_artifact_builder: dependencies.cardano_database_artifact_builder,
            signed_entity_type_lock,
            metrics_service,
            logger: logger.new_with_component_name::<Self>(),
        }
    }

    async fn create_artifact_task(
        &self,
        signed_entity_type: SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<()> {
        info!(
            self.logger, ">> create_artifact_task";
            "signed_entity_type" => ?signed_entity_type, "certificate_hash" => &certificate.hash
        );

        let mut remaining_retries = 2;
        let artifact = loop {
            remaining_retries -= 1;

            match self
                .compute_artifact(signed_entity_type.clone(), certificate)
                .await
            {
                Err(error) if remaining_retries == 0 => break Err(error),
                Err(_error) => (),
                Ok(artifact) => break Ok(artifact),
            };
        }?;

        let signed_entity = SignedEntityRecord {
            signed_entity_id: artifact.get_id(),
            signed_entity_type: signed_entity_type.clone(),
            certificate_id: certificate.hash.clone(),
            artifact: serde_json::to_string(&artifact)?,
            created_at: Utc::now(),
        };

        self.signed_entity_storer
            .store_signed_entity(&signed_entity)
            .await
            .with_context(|| {
                format!(
                    "Signed Entity Service can not store signed entity with type: '{signed_entity_type}'"
                )
            })?;

        self.increment_artifact_total_produced_metric_since_startup(signed_entity_type);

        Ok(())
    }

    /// Compute artifact from signed entity type
    async fn compute_artifact(
        &self,
        signed_entity_type: SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<Arc<dyn Artifact>> {
        match signed_entity_type.clone() {
            SignedEntityType::MithrilStakeDistribution(epoch) => Ok(Arc::new(
                self.mithril_stake_distribution_artifact_builder
                    .compute_artifact(epoch, certificate)
                    .await
                    .with_context(|| {
                        format!(
                            "Signed Entity Service can not compute artifact for entity type: '{signed_entity_type}'"
                        )
                    })?,
            )),
            SignedEntityType::CardanoImmutableFilesFull(beacon) => Ok(Arc::new(
                self.cardano_immutable_files_full_artifact_builder
                    .compute_artifact(beacon.clone(), certificate)
                    .await
                    .with_context(|| {
                        format!(
                            "Signed Entity Service can not compute artifact for entity type: '{signed_entity_type}'"
                        )
                    })?,
            )),
            SignedEntityType::CardanoStakeDistribution(epoch) => Ok(Arc::new(
                self.cardano_stake_distribution_artifact_builder
                .compute_artifact(epoch, certificate)
                .await
                .with_context(|| {
                    format!(
                        "Signed Entity Service can not compute artifact for entity type: '{signed_entity_type}'"
                    )
                })?)),
            SignedEntityType::CardanoTransactions(_epoch, block_number) => Ok(Arc::new(
                self.cardano_transactions_artifact_builder
                    .compute_artifact(block_number, certificate)
                    .await
                    .with_context(|| {
                        format!(
                            "Signed Entity Service can not compute artifact for entity type: '{signed_entity_type}'"
                        )
                    })?,
            )),
            SignedEntityType::CardanoDatabase(beacon) => Ok(Arc::new(
                self.cardano_database_artifact_builder
                    .compute_artifact(beacon, certificate)
                    .await
                    .with_context(|| {
                        format!(
                            "Signed Entity Service can not compute artifact for entity type: '{signed_entity_type}'"
                        )
                    })?
            )),
        }
    }

    async fn get_last_signed_entities(
        &self,
        total: usize,
        discriminants: &SignedEntityTypeDiscriminants,
    ) -> StdResult<Vec<SignedEntityRecord>> {
        self.signed_entity_storer
            .get_last_signed_entities_by_type(discriminants, total)
            .await
            .with_context(|| {
                format!(
                    "Signed Entity Service can not get last signed entities with type: '{:?}'",
                    discriminants
                )
            })
    }

    fn increment_artifact_total_produced_metric_since_startup(
        &self,
        signed_entity_type: SignedEntityType,
    ) {
        let metrics = self.metrics_service.clone();
        let metric_counter = match signed_entity_type {
            SignedEntityType::MithrilStakeDistribution(_) => {
                metrics.get_artifact_mithril_stake_distribution_total_produced_since_startup()
            }
            SignedEntityType::CardanoImmutableFilesFull(_) => {
                metrics.get_artifact_cardano_immutable_files_full_total_produced_since_startup()
            }
            SignedEntityType::CardanoStakeDistribution(_) => {
                metrics.get_artifact_cardano_stake_distribution_total_produced_since_startup()
            }
            SignedEntityType::CardanoTransactions(_, _) => {
                metrics.get_artifact_cardano_transaction_total_produced_since_startup()
            }
            SignedEntityType::CardanoDatabase(_) => {
                metrics.get_artifact_cardano_database_total_produced_since_startup()
            }
        };

        metric_counter.increment();
    }
}

#[async_trait]
impl SignedEntityService for MithrilSignedEntityService {
    async fn create_artifact(
        &self,
        signed_entity_type: SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<JoinHandle<StdResult<()>>> {
        if self
            .signed_entity_type_lock
            .is_locked(&signed_entity_type)
            .await
        {
            return Err(anyhow!(
                "Signed entity type '{:?}' is already locked",
                signed_entity_type
            ));
        }

        let service = self.clone();
        let certificate_cloned = certificate.clone();
        service
            .signed_entity_type_lock
            .lock(&signed_entity_type)
            .await;

        Ok(tokio::task::spawn(async move {
            let signed_entity_type_clone = signed_entity_type.clone();
            let service_clone = service.clone();
            let result = tokio::task::spawn(async move {
                service_clone
                    .create_artifact_task(signed_entity_type_clone, &certificate_cloned)
                    .await
            })
            .await;
            service
                .signed_entity_type_lock
                .release(signed_entity_type.clone())
                .await;

            result.with_context(|| format!(
                "Signed Entity Service can not store signed entity with type: '{signed_entity_type}'"
            ))?.inspect_err(|e| warn!(service.logger, "Error while creating artifact"; "error" => ?e))
        }))
    }

    async fn get_last_signed_snapshots(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<Snapshot>>> {
        let signed_entities = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::CardanoImmutableFilesFull,
            )
            .await?
            .into_iter()
            .map(|record| record.try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(signed_entities)
    }

    async fn get_signed_snapshot_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<Snapshot>>> {
        let entity: Option<SignedEntity<Snapshot>> = match self
            .signed_entity_storer
            .get_signed_entity(signed_entity_id)
            .await
            .with_context(|| {
                format!(
                    "Signed Entity Service can not get signed entity with id: '{signed_entity_id}'"
                )
            })? {
            Some(entity) => Some(entity.try_into()?),
            None => None,
        };

        Ok(entity)
    }

    async fn get_last_signed_cardano_database_snapshots(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<CardanoDatabaseSnapshot>>> {
        let signed_entities = self
            .get_last_signed_entities(total, &SignedEntityTypeDiscriminants::CardanoDatabase)
            .await?
            .into_iter()
            .map(|record| record.try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(signed_entities)
    }

    async fn get_signed_cardano_database_snapshot_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<CardanoDatabaseSnapshot>>> {
        let entity: Option<SignedEntity<CardanoDatabaseSnapshot>> = match self
            .signed_entity_storer
            .get_signed_entity(signed_entity_id)
            .await
            .with_context(|| {
                format!(
                    "Signed Entity Service can not get signed entity with id: '{signed_entity_id}'"
                )
            })? {
            Some(entity) => Some(entity.try_into()?),
            None => None,
        };

        Ok(entity)
    }

    async fn get_last_signed_mithril_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<MithrilStakeDistribution>>> {
        let signed_entities = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::MithrilStakeDistribution,
            )
            .await?
            .into_iter()
            .map(|record| record.try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(signed_entities)
    }

    async fn get_signed_mithril_stake_distribution_by_id(
        &self,
        signed_entity_id: &str,
    ) -> StdResult<Option<SignedEntity<MithrilStakeDistribution>>> {
        let entity: Option<SignedEntity<MithrilStakeDistribution>> = match self
            .signed_entity_storer
            .get_signed_entity(signed_entity_id)
            .await
            .with_context(|| {
                format!(
                    "Signed Entity Service can not get signed entity with id: '{signed_entity_id}'"
                )
            })? {
            Some(entity) => Some(entity.try_into()?),
            None => None,
        };

        Ok(entity)
    }

    async fn get_last_cardano_transaction_snapshot(
        &self,
    ) -> StdResult<Option<SignedEntity<CardanoTransactionsSnapshot>>> {
        let mut signed_entities_records = self
            .get_last_signed_entities(1, &SignedEntityTypeDiscriminants::CardanoTransactions)
            .await?;

        match signed_entities_records.pop() {
            Some(record) => Ok(Some(record.try_into()?)),
            None => Ok(None),
        }
    }

    async fn get_last_signed_cardano_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<CardanoStakeDistribution>>> {
        let signed_entities = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::CardanoStakeDistribution,
            )
            .await?
            .into_iter()
            .map(|record| record.try_into())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(signed_entities)
    }
}

#[cfg(test)]
mod tests {
    use std::{sync::atomic::Ordering, time::Duration};

    use mithril_common::{
        entities::{CardanoTransactionsSnapshot, Epoch, StakeDistribution},
        signable_builder,
        test_utils::fake_data,
    };
    use mithril_metric::CounterValue;
    use serde::{de::DeserializeOwned, Serialize};
    use std::sync::atomic::AtomicBool;

    use crate::artifact_builder::MockArtifactBuilder;
    use crate::database::repository::MockSignedEntityStorer;
    use crate::test_tools::TestLogger;

    use super::*;

    fn create_stake_distribution(epoch: Epoch, signers: usize) -> MithrilStakeDistribution {
        MithrilStakeDistribution::new(
            epoch,
            fake_data::signers_with_stakes(signers),
            &fake_data::protocol_parameters(),
        )
    }

    fn create_cardano_stake_distribution(
        epoch: Epoch,
        stake_distribution: StakeDistribution,
    ) -> CardanoStakeDistribution {
        CardanoStakeDistribution::new(epoch, stake_distribution)
    }

    fn assert_expected<T>(expected: &T, artifact: &Arc<dyn Artifact>)
    where
        T: Serialize + DeserializeOwned,
    {
        let current: T = serde_json::from_str(&serde_json::to_string(&artifact).unwrap()).unwrap();
        assert_eq!(
            serde_json::to_string(&expected).unwrap(),
            serde_json::to_string(&current).unwrap()
        );
    }

    /// Struct that create mocks needed in tests and build objects injecting them.
    struct MockDependencyInjector {
        mock_signed_entity_storer: MockSignedEntityStorer,
        mock_mithril_stake_distribution_artifact_builder:
            MockArtifactBuilder<Epoch, MithrilStakeDistribution>,
        mock_cardano_immutable_files_full_artifact_builder:
            MockArtifactBuilder<CardanoDbBeacon, Snapshot>,
        mock_cardano_transactions_artifact_builder:
            MockArtifactBuilder<BlockNumber, CardanoTransactionsSnapshot>,
        mock_cardano_stake_distribution_artifact_builder:
            MockArtifactBuilder<Epoch, CardanoStakeDistribution>,
        mock_cardano_database_artifact_builder:
            MockArtifactBuilder<CardanoDbBeacon, CardanoDatabaseSnapshot>,
    }

    impl MockDependencyInjector {
        fn new() -> MockDependencyInjector {
            MockDependencyInjector {
                mock_signed_entity_storer: MockSignedEntityStorer::new(),
                mock_mithril_stake_distribution_artifact_builder: MockArtifactBuilder::<
                    Epoch,
                    MithrilStakeDistribution,
                >::new(),
                mock_cardano_immutable_files_full_artifact_builder: MockArtifactBuilder::<
                    CardanoDbBeacon,
                    Snapshot,
                >::new(),
                mock_cardano_transactions_artifact_builder: MockArtifactBuilder::<
                    BlockNumber,
                    CardanoTransactionsSnapshot,
                >::new(),
                mock_cardano_stake_distribution_artifact_builder: MockArtifactBuilder::<
                    Epoch,
                    CardanoStakeDistribution,
                >::new(),
                mock_cardano_database_artifact_builder: MockArtifactBuilder::<
                    CardanoDbBeacon,
                    CardanoDatabaseSnapshot,
                >::new(),
            }
        }

        fn build_artifact_builder_service(self) -> MithrilSignedEntityService {
            let dependencies = SignedEntityServiceArtifactsDependencies::new(
                Arc::new(self.mock_mithril_stake_distribution_artifact_builder),
                Arc::new(self.mock_cardano_immutable_files_full_artifact_builder),
                Arc::new(self.mock_cardano_transactions_artifact_builder),
                Arc::new(self.mock_cardano_stake_distribution_artifact_builder),
                Arc::new(self.mock_cardano_database_artifact_builder),
            );
            MithrilSignedEntityService::new(
                Arc::new(self.mock_signed_entity_storer),
                dependencies,
                Arc::new(SignedEntityTypeLock::default()),
                Arc::new(MetricsService::new(TestLogger::stdout()).unwrap()),
                TestLogger::stdout(),
            )
        }

        fn build_artifact_builder_service_with_time_consuming_process(
            mut self,
            atomic_stop: Arc<AtomicBool>,
        ) -> MithrilSignedEntityService {
            struct LongArtifactBuilder {
                atomic_stop: Arc<AtomicBool>,
                snapshot: Snapshot,
            }

            let snapshot = fake_data::snapshots(1).first().unwrap().to_owned();

            #[async_trait]
            impl ArtifactBuilder<CardanoDbBeacon, Snapshot> for LongArtifactBuilder {
                async fn compute_artifact(
                    &self,
                    _beacon: CardanoDbBeacon,
                    _certificate: &Certificate,
                ) -> StdResult<Snapshot> {
                    let mut max_iteration = 100;
                    while !self.atomic_stop.load(Ordering::Relaxed) {
                        max_iteration -= 1;
                        if max_iteration <= 0 {
                            return Err(anyhow!("Test should handle the stop"));
                        }
                        tokio::time::sleep(Duration::from_millis(10)).await;
                    }
                    Ok(self.snapshot.clone())
                }
            }
            let cardano_immutable_files_full_long_artifact_builder = LongArtifactBuilder {
                atomic_stop: atomic_stop.clone(),
                snapshot: snapshot.clone(),
            };

            let artifact_clone: Arc<dyn Artifact> = Arc::new(snapshot);
            let signed_entity_artifact = serde_json::to_string(&artifact_clone).unwrap();
            self.mock_signed_entity_storer
                .expect_store_signed_entity()
                .withf(move |signed_entity| signed_entity.artifact == signed_entity_artifact)
                .return_once(|_| Ok(()));

            let dependencies = SignedEntityServiceArtifactsDependencies::new(
                Arc::new(self.mock_mithril_stake_distribution_artifact_builder),
                Arc::new(cardano_immutable_files_full_long_artifact_builder),
                Arc::new(self.mock_cardano_transactions_artifact_builder),
                Arc::new(self.mock_cardano_stake_distribution_artifact_builder),
                Arc::new(self.mock_cardano_database_artifact_builder),
            );
            MithrilSignedEntityService::new(
                Arc::new(self.mock_signed_entity_storer),
                dependencies,
                Arc::new(SignedEntityTypeLock::default()),
                Arc::new(MetricsService::new(TestLogger::stdout()).unwrap()),
                TestLogger::stdout(),
            )
        }

        fn mock_artifact_processing<
            T: Artifact + Clone + Serialize + 'static,
            U: signable_builder::Beacon,
        >(
            &mut self,
            artifact: T,
            mock_that_provide_artifact: &dyn Fn(
                &mut MockDependencyInjector,
            ) -> &mut MockArtifactBuilder<U, T>,
        ) {
            {
                let artifact_cloned = artifact.clone();
                mock_that_provide_artifact(self)
                    .expect_compute_artifact()
                    .times(1)
                    .return_once(|_, _| Ok(artifact_cloned));
            }
            {
                let artifact_clone: Arc<dyn Artifact> = Arc::new(artifact.clone());
                let artifact_json = serde_json::to_string(&artifact_clone).unwrap();
                self.mock_signed_entity_storer
                    .expect_store_signed_entity()
                    .withf(move |signed_entity| signed_entity.artifact == artifact_json)
                    .return_once(|_| Ok(()));
            }
        }

        fn mock_stake_distribution_processing(&mut self, artifact: MithrilStakeDistribution) {
            self.mock_artifact_processing(artifact, &|mock_injector| {
                &mut mock_injector.mock_mithril_stake_distribution_artifact_builder
            });
        }
    }

    fn get_artifact_total_produced_metric_since_startup_counter_value(
        metrics_service: Arc<MetricsService>,
        signed_entity_type: &SignedEntityType,
    ) -> CounterValue {
        match signed_entity_type {
            SignedEntityType::MithrilStakeDistribution(_) => metrics_service
                .get_artifact_mithril_stake_distribution_total_produced_since_startup()
                .get(),
            SignedEntityType::CardanoImmutableFilesFull(_) => metrics_service
                .get_artifact_cardano_immutable_files_full_total_produced_since_startup()
                .get(),
            SignedEntityType::CardanoStakeDistribution(_) => metrics_service
                .get_artifact_cardano_stake_distribution_total_produced_since_startup()
                .get(),
            SignedEntityType::CardanoTransactions(_, _) => metrics_service
                .get_artifact_cardano_transaction_total_produced_since_startup()
                .get(),
            SignedEntityType::CardanoDatabase(_) => metrics_service
                .get_artifact_cardano_database_total_produced_since_startup()
                .get(),
        }
    }

    #[tokio::test]
    async fn build_mithril_stake_distribution_artifact_when_given_mithril_stake_distribution_entity_type(
    ) {
        let mut mock_container = MockDependencyInjector::new();

        let mithril_stake_distribution_expected = create_stake_distribution(Epoch(1), 5);

        mock_container
            .mock_mithril_stake_distribution_artifact_builder
            .expect_compute_artifact()
            .times(1)
            .returning(|_, _| Ok(create_stake_distribution(Epoch(1), 5)));

        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type = SignedEntityType::MithrilStakeDistribution(Epoch(1));
        let artifact = artifact_builder_service
            .compute_artifact(signed_entity_type.clone(), &certificate)
            .await
            .unwrap();

        assert_expected(&mithril_stake_distribution_expected, &artifact);
    }

    #[tokio::test]
    async fn should_store_the_artifact_when_creating_artifact_for_a_mithril_stake_distribution() {
        generic_test_that_the_artifact_is_stored(
            SignedEntityType::MithrilStakeDistribution(Epoch(1)),
            create_stake_distribution(Epoch(1), 5),
            &|mock_injector| &mut mock_injector.mock_mithril_stake_distribution_artifact_builder,
        )
        .await;
    }

    #[tokio::test]
    async fn build_cardano_stake_distribution_artifact_when_given_cardano_stake_distribution_entity_type(
    ) {
        let mut mock_container = MockDependencyInjector::new();

        let cardano_stake_distribution_expected = create_cardano_stake_distribution(
            Epoch(1),
            StakeDistribution::from([("pool-1".to_string(), 100)]),
        );

        mock_container
            .mock_cardano_stake_distribution_artifact_builder
            .expect_compute_artifact()
            .times(1)
            .returning(|_, _| {
                Ok(create_cardano_stake_distribution(
                    Epoch(1),
                    StakeDistribution::from([("pool-1".to_string(), 100)]),
                ))
            });

        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type = SignedEntityType::CardanoStakeDistribution(Epoch(1));
        let artifact = artifact_builder_service
            .compute_artifact(signed_entity_type.clone(), &certificate)
            .await
            .unwrap();

        assert_expected(&cardano_stake_distribution_expected, &artifact);
    }

    #[tokio::test]
    async fn should_store_the_artifact_when_creating_artifact_for_a_cardano_stake_distribution() {
        generic_test_that_the_artifact_is_stored(
            SignedEntityType::CardanoStakeDistribution(Epoch(1)),
            create_cardano_stake_distribution(
                Epoch(1),
                StakeDistribution::from([("pool-1".to_string(), 100)]),
            ),
            &|mock_injector| &mut mock_injector.mock_cardano_stake_distribution_artifact_builder,
        )
        .await;
    }

    #[tokio::test]
    async fn build_snapshot_artifact_when_given_cardano_immutable_files_full_entity_type() {
        let mut mock_container = MockDependencyInjector::new();

        let snapshot_expected = fake_data::snapshots(1).first().unwrap().to_owned();

        mock_container
            .mock_cardano_immutable_files_full_artifact_builder
            .expect_compute_artifact()
            .times(1)
            .returning(|_, _| Ok(fake_data::snapshots(1).first().unwrap().to_owned()));

        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());
        let artifact = artifact_builder_service
            .compute_artifact(signed_entity_type.clone(), &certificate)
            .await
            .unwrap();

        assert_expected(&snapshot_expected, &artifact);
    }

    #[tokio::test]
    async fn should_store_the_artifact_when_creating_artifact_for_a_cardano_immutable_files() {
        generic_test_that_the_artifact_is_stored(
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default()),
            fake_data::snapshots(1).first().unwrap().to_owned(),
            &|mock_injector| &mut mock_injector.mock_cardano_immutable_files_full_artifact_builder,
        )
        .await;
    }

    #[tokio::test]
    async fn build_cardano_transactions_snapshot_artifact_when_given_cardano_transactions_type() {
        let mut mock_container = MockDependencyInjector::new();

        let block_number = BlockNumber(151);
        let expected = CardanoTransactionsSnapshot::new("merkle_root".to_string(), block_number);

        mock_container
            .mock_cardano_transactions_artifact_builder
            .expect_compute_artifact()
            .times(1)
            .returning(move |_, _| {
                Ok(CardanoTransactionsSnapshot::new(
                    "merkle_root".to_string(),
                    block_number,
                ))
            });

        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type = SignedEntityType::CardanoTransactions(Epoch(1), block_number);
        let artifact = artifact_builder_service
            .compute_artifact(signed_entity_type.clone(), &certificate)
            .await
            .unwrap();

        assert_expected(&expected, &artifact);
    }

    #[tokio::test]
    async fn should_store_the_artifact_when_creating_artifact_for_cardano_transactions() {
        let block_number = BlockNumber(149);
        generic_test_that_the_artifact_is_stored(
            SignedEntityType::CardanoTransactions(Epoch(1), block_number),
            CardanoTransactionsSnapshot::new("merkle_root".to_string(), block_number),
            &|mock_injector| &mut mock_injector.mock_cardano_transactions_artifact_builder,
        )
        .await;
    }

    #[tokio::test]
    async fn build_cardano_database_artifact_when_given_cardano_database_entity_type() {
        let mut mock_container = MockDependencyInjector::new();

        let cardano_database_expected = fake_data::cardano_database_snapshots(1)
            .first()
            .unwrap()
            .to_owned();

        mock_container
            .mock_cardano_database_artifact_builder
            .expect_compute_artifact()
            .times(1)
            .returning(|_, _| {
                Ok(fake_data::cardano_database_snapshots(1)
                    .first()
                    .unwrap()
                    .to_owned())
            });

        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type = SignedEntityType::CardanoDatabase(CardanoDbBeacon::default());
        let artifact = artifact_builder_service
            .compute_artifact(signed_entity_type.clone(), &certificate)
            .await
            .unwrap();

        assert_expected(&cardano_database_expected, &artifact);
    }

    #[tokio::test]
    async fn should_store_the_artifact_when_creating_artifact_for_a_cardano_database() {
        generic_test_that_the_artifact_is_stored(
            SignedEntityType::CardanoDatabase(CardanoDbBeacon::default()),
            fake_data::cardano_database_snapshots(1)
                .first()
                .unwrap()
                .to_owned(),
            &|mock_injector| &mut mock_injector.mock_cardano_database_artifact_builder,
        )
        .await;
    }

    async fn generic_test_that_the_artifact_is_stored<
        T: Artifact + Clone + Serialize + 'static,
        U: signable_builder::Beacon,
    >(
        signed_entity_type: SignedEntityType,
        artifact: T,
        mock_that_provide_artifact: &dyn Fn(
            &mut MockDependencyInjector,
        ) -> &mut MockArtifactBuilder<U, T>,
    ) {
        let mut mock_container = MockDependencyInjector::new();
        {
            let artifact_clone: Arc<dyn Artifact> = Arc::new(artifact.clone());
            let signed_entity_artifact = serde_json::to_string(&artifact_clone).unwrap();
            mock_container
                .mock_signed_entity_storer
                .expect_store_signed_entity()
                .withf(move |signed_entity| signed_entity.artifact == signed_entity_artifact)
                .return_once(|_| Ok(()));
        }
        {
            let artifact_cloned = artifact.clone();
            mock_that_provide_artifact(&mut mock_container)
                .expect_compute_artifact()
                .times(1)
                .return_once(|_, _| Ok(artifact_cloned));
        }
        let artifact_builder_service = mock_container.build_artifact_builder_service();

        let certificate = fake_data::certificate("hash".to_string());
        let error_message = format!(
            "Create artifact should not fail for {} signed entity",
            std::any::type_name::<T>()
        );
        let error_message_str = error_message.as_str();

        let initial_counter_value = get_artifact_total_produced_metric_since_startup_counter_value(
            artifact_builder_service.metrics_service.clone(),
            &signed_entity_type,
        );

        artifact_builder_service
            .create_artifact_task(signed_entity_type.clone(), &certificate)
            .await
            .expect(error_message_str);

        assert_eq!(
            initial_counter_value + 1,
            get_artifact_total_produced_metric_since_startup_counter_value(
                artifact_builder_service.metrics_service.clone(),
                &signed_entity_type,
            )
        )
    }

    #[tokio::test]
    async fn create_artifact_for_two_signed_entity_types_in_sequence_not_blocking() {
        let atomic_stop = Arc::new(AtomicBool::new(false));
        let signed_entity_type_service = {
            let mut mock_container = MockDependencyInjector::new();

            let msd = create_stake_distribution(Epoch(1), 5);
            mock_container.mock_stake_distribution_processing(msd);

            mock_container
                .build_artifact_builder_service_with_time_consuming_process(atomic_stop.clone())
        };
        let certificate = fake_data::certificate("hash".to_string());

        let signed_entity_type_immutable =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());
        let first_task_that_never_finished = signed_entity_type_service
            .create_artifact(signed_entity_type_immutable, &certificate)
            .await
            .unwrap();

        let signed_entity_type_msd = SignedEntityType::MithrilStakeDistribution(Epoch(1));
        let second_task_that_finish_first = signed_entity_type_service
            .create_artifact(signed_entity_type_msd, &certificate)
            .await
            .unwrap();

        second_task_that_finish_first.await.unwrap().unwrap();
        assert!(!first_task_that_never_finished.is_finished());

        atomic_stop.swap(true, Ordering::Relaxed);
    }

    #[tokio::test]
    async fn create_artifact_lock_unlock_signed_entity_type_while_processing() {
        let atomic_stop = Arc::new(AtomicBool::new(false));
        let signed_entity_type_service = MockDependencyInjector::new()
            .build_artifact_builder_service_with_time_consuming_process(atomic_stop.clone());
        let certificate = fake_data::certificate("hash".to_string());

        let signed_entity_type_immutable =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());
        assert!(
            !signed_entity_type_service
                .signed_entity_type_lock
                .is_locked(&signed_entity_type_immutable)
                .await
        );
        let join_handle = signed_entity_type_service
            .create_artifact(signed_entity_type_immutable.clone(), &certificate)
            .await
            .unwrap();

        // Results are stored to finalize the task before assertions,
        // ensuring 'atomic_stop' is always assigned a new value.
        let is_locked = signed_entity_type_service
            .signed_entity_type_lock
            .is_locked(&signed_entity_type_immutable)
            .await;
        let is_finished = join_handle.is_finished();

        atomic_stop.swap(true, Ordering::Relaxed);
        join_handle.await.unwrap().unwrap();

        assert!(is_locked);
        assert!(!is_finished);

        assert!(
            !signed_entity_type_service
                .signed_entity_type_lock
                .is_locked(&signed_entity_type_immutable)
                .await
        );
    }

    #[tokio::test]
    async fn create_artifact_unlock_signed_entity_type_when_error() {
        let signed_entity_type_service = {
            let mut mock_container = MockDependencyInjector::new();
            mock_container
                .mock_cardano_immutable_files_full_artifact_builder
                .expect_compute_artifact()
                .returning(|_, _| Err(anyhow::anyhow!("Error while computing artifact")));

            mock_container.build_artifact_builder_service()
        };
        let certificate = fake_data::certificate("hash".to_string());

        let signed_entity_type_immutable =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());

        let join_handle = signed_entity_type_service
            .create_artifact(signed_entity_type_immutable.clone(), &certificate)
            .await
            .unwrap();

        let error = join_handle.await.unwrap().unwrap_err();
        assert!(
            error.to_string().contains("CardanoImmutableFilesFull"),
            "Error should contains CardanoImmutableFilesFull but was: {}",
            error
        );

        assert!(
            !signed_entity_type_service
                .signed_entity_type_lock
                .is_locked(&signed_entity_type_immutable)
                .await
        );
    }

    #[tokio::test]
    async fn create_artifact_unlock_signed_entity_type_when_panic() {
        let signed_entity_type_service =
            MockDependencyInjector::new().build_artifact_builder_service();
        let certificate = fake_data::certificate("hash".to_string());

        let signed_entity_type_immutable =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());

        let join_handle = signed_entity_type_service
            .create_artifact(signed_entity_type_immutable.clone(), &certificate)
            .await
            .unwrap();

        let error = join_handle.await.unwrap().unwrap_err();
        assert!(
            error.to_string().contains("CardanoImmutableFilesFull"),
            "Error should contains CardanoImmutableFilesFull but was: {}",
            error
        );

        assert!(
            !signed_entity_type_service
                .signed_entity_type_lock
                .is_locked(&signed_entity_type_immutable)
                .await
        );
    }

    #[tokio::test]
    async fn create_artifact_for_a_signed_entity_type_already_lock_return_error() {
        let atomic_stop = Arc::new(AtomicBool::new(false));
        let signed_entity_service = MockDependencyInjector::new()
            .build_artifact_builder_service_with_time_consuming_process(atomic_stop.clone());
        let certificate = fake_data::certificate("hash".to_string());
        let signed_entity_type_immutable =
            SignedEntityType::CardanoImmutableFilesFull(CardanoDbBeacon::default());

        signed_entity_service
            .create_artifact(signed_entity_type_immutable.clone(), &certificate)
            .await
            .unwrap();

        signed_entity_service
            .create_artifact(signed_entity_type_immutable, &certificate)
            .await
            .expect_err("Should return error when signed entity type is already locked");

        atomic_stop.swap(true, Ordering::Relaxed);
    }

    #[tokio::test]
    async fn metrics_counter_value_is_not_incremented_when_compute_artifact_error() {
        let signed_entity_service = {
            let mut mock_container = MockDependencyInjector::new();
            mock_container
                .mock_cardano_immutable_files_full_artifact_builder
                .expect_compute_artifact()
                .returning(|_, _| Err(anyhow!("Error while computing artifact")));

            mock_container.build_artifact_builder_service()
        };

        let signed_entity_type = SignedEntityType::MithrilStakeDistribution(Epoch(7));

        let initial_counter_value = get_artifact_total_produced_metric_since_startup_counter_value(
            signed_entity_service.metrics_service.clone(),
            &signed_entity_type,
        );

        signed_entity_service
            .create_artifact(
                signed_entity_type.clone(),
                &fake_data::certificate("hash".to_string()),
            )
            .await
            .unwrap();

        assert_eq!(
            initial_counter_value,
            get_artifact_total_produced_metric_since_startup_counter_value(
                signed_entity_service.metrics_service.clone(),
                &signed_entity_type,
            )
        );
    }

    #[tokio::test]
    async fn metrics_counter_value_is_not_incremented_when_store_signed_entity_error() {
        let signed_entity_service = {
            let mut mock_container = MockDependencyInjector::new();
            mock_container
                .mock_signed_entity_storer
                .expect_store_signed_entity()
                .returning(|_| Err(anyhow!("Error while storing signed entity")));

            mock_container.build_artifact_builder_service()
        };

        let signed_entity_type = SignedEntityType::MithrilStakeDistribution(Epoch(7));

        let initial_counter_value = get_artifact_total_produced_metric_since_startup_counter_value(
            signed_entity_service.metrics_service.clone(),
            &signed_entity_type,
        );

        signed_entity_service
            .create_artifact(
                signed_entity_type.clone(),
                &fake_data::certificate("hash".to_string()),
            )
            .await
            .unwrap();

        assert_eq!(
            initial_counter_value,
            get_artifact_total_produced_metric_since_startup_counter_value(
                signed_entity_service.metrics_service.clone(),
                &signed_entity_type,
            )
        );
    }
}