mithril_common/chain_observer/
builder.rs1use serde::{Deserialize, Serialize};
2use std::{fmt::Display, path::PathBuf, sync::Arc};
3use thiserror::Error;
4
5use crate::{chain_observer::ChainObserver, CardanoNetwork, StdResult};
6
7#[cfg(any(test, feature = "test_tools"))]
8use super::FakeObserver;
9use super::{CardanoCliChainObserver, CardanoCliRunner, PallasChainObserver};
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13#[serde(rename_all = "lowercase")]
14pub enum ChainObserverType {
15 #[serde(rename = "cardano-cli")]
17 CardanoCli,
18 Pallas,
20 #[cfg(any(test, feature = "test_tools"))]
22 Fake,
23}
24
25impl Display for ChainObserverType {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 match self {
28 Self::CardanoCli => write!(f, "cardano-cli"),
29 Self::Pallas => write!(f, "pallas"),
30 #[cfg(any(test, feature = "test_tools"))]
31 Self::Fake => write!(f, "fake"),
32 }
33 }
34}
35
36#[derive(Error, Debug)]
38pub enum ChainObserverBuilderError {
39 #[error("cardano cli runner is missing")]
41 MissingCardanoCliRunner,
42}
43
44pub struct ChainObserverBuilder {
46 chain_observer_type: ChainObserverType,
47 cardano_node_socket_path: PathBuf,
48 cardano_network: CardanoNetwork,
49 cardano_cli_runner: Option<Box<CardanoCliRunner>>,
50}
51
52impl ChainObserverBuilder {
53 pub fn new(
55 chain_observer_type: &ChainObserverType,
56 cardano_node_socket_path: &PathBuf,
57 cardano_node_network: &CardanoNetwork,
58 cardano_cli_runner: Option<&CardanoCliRunner>,
59 ) -> Self {
60 Self {
61 chain_observer_type: chain_observer_type.to_owned(),
62 cardano_node_socket_path: cardano_node_socket_path.to_owned(),
63 cardano_network: cardano_node_network.to_owned(),
64 cardano_cli_runner: cardano_cli_runner.map(|c| c.to_owned().into()),
65 }
66 }
67
68 pub fn build(&self) -> StdResult<Arc<dyn ChainObserver>> {
70 match self.chain_observer_type {
71 ChainObserverType::CardanoCli => Ok(Arc::new(CardanoCliChainObserver::new(
72 self.cardano_cli_runner
73 .as_ref()
74 .ok_or(ChainObserverBuilderError::MissingCardanoCliRunner)?
75 .to_owned(),
76 ))),
77 ChainObserverType::Pallas => {
78 let observer =
79 PallasChainObserver::new(&self.cardano_node_socket_path, self.cardano_network);
80 Ok(Arc::new(observer))
81 }
82 #[cfg(any(test, feature = "test_tools"))]
83 ChainObserverType::Fake => Ok(Arc::new(FakeObserver::default())),
84 }
85 }
86}