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
//! ## 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, Logger};
use std::sync::Arc;
use tokio::task::JoinHandle;

use mithril_common::{
    entities::{
        BlockNumber, 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},
};

/// 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 list of signed Mithril stake distribution order by creation
    /// date descending.
    async fn get_last_signed_mithril_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<MithrilStakeDistribution>>>;

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

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

    /// 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 a list of signed Cardano stake distribution order 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>>,
    logger: Logger,
}

impl MithrilSignedEntityService {
    /// MithrilSignedEntityService factory
    pub fn new(
        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>,
        >,
        logger: Logger,
    ) -> Self {
        Self {
            signed_entity_storer,
            mithril_stake_distribution_artifact_builder,
            cardano_immutable_files_full_artifact_builder,
            cardano_transactions_artifact_builder,
            signed_entity_type_lock,
            cardano_stake_distribution_artifact_builder,
            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}'"
                )
            })?;
        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}'"
                        )
                    })?,
            )),
        }
    }

    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
                )
            })
    }
}

#[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}'"
            ))?
        }))
    }

    async fn get_last_signed_snapshots(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<Snapshot>>> {
        let signed_entities_records = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::CardanoImmutableFilesFull,
            )
            .await?;
        let mut signed_entities: Vec<SignedEntity<Snapshot>> = Vec::new();

        for record in signed_entities_records {
            signed_entities.push(record.try_into()?);
        }

        Ok(signed_entities)
    }

    async fn get_last_signed_mithril_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<MithrilStakeDistribution>>> {
        let signed_entities_records = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::MithrilStakeDistribution,
            )
            .await?;
        let mut signed_entities: Vec<SignedEntity<MithrilStakeDistribution>> = Vec::new();

        for record in signed_entities_records {
            signed_entities.push(record.try_into()?);
        }

        Ok(signed_entities)
    }

    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_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_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_signed_cardano_stake_distributions(
        &self,
        total: usize,
    ) -> StdResult<Vec<SignedEntity<CardanoStakeDistribution>>> {
        let signed_entities_records = self
            .get_last_signed_entities(
                total,
                &SignedEntityTypeDiscriminants::CardanoStakeDistribution,
            )
            .await?;
        let mut signed_entities: Vec<SignedEntity<CardanoStakeDistribution>> = Vec::new();

        for record in signed_entities_records {
            signed_entities.push(record.try_into()?);
        }

        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 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>,
    }

    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(),
            }
        }

        fn build_artifact_builder_service(self) -> MithrilSignedEntityService {
            MithrilSignedEntityService::new(
                Arc::new(self.mock_signed_entity_storer),
                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(SignedEntityTypeLock::default()),
                Arc::new(self.mock_cardano_stake_distribution_artifact_builder),
                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(()));

            MithrilSignedEntityService::new(
                Arc::new(self.mock_signed_entity_storer),
                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(SignedEntityTypeLock::default()),
                Arc::new(self.mock_cardano_stake_distribution_artifact_builder),
                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
            });
        }
    }

    #[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;
    }

    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();

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

    #[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);
    }
}