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
mod job;

use assert_fs::fixture::PathChild;
use assert_fs::TempDir;
pub use job::JobParameters;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::Path;
use std::path::PathBuf;
use thiserror::Error;

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Configuration {
    #[serde(flatten)]
    pub inner: scheduler_service_lib::Configuration,
    #[serde(rename = "voting-tools")]
    pub voting_tools: VotingToolsParams,
}

impl Configuration {
    pub fn set_token(&mut self, token: Option<String>) {
        self.inner.api_token = token;
    }

    pub fn result_dir(&self) -> PathBuf {
        self.inner.result_dir.clone()
    }

    pub fn address_mut(&mut self) -> &mut SocketAddr {
        &mut self.inner.address
    }

    pub fn address(&self) -> &SocketAddr {
        &self.inner.address
    }
}

#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct ConfigurationBuilder {
    configuration: Configuration,
}

impl ConfigurationBuilder {
    pub fn with_port(mut self, port: u16) -> Self {
        self.configuration.inner.address.set_port(port);
        self
    }

    pub fn with_result_dir<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.configuration.inner.result_dir = path.as_ref().to_path_buf();
        self
    }

    pub fn with_tmp_result_dir(self, tmp: &TempDir) -> Self {
        self.with_result_dir(tmp.child("snapshot_result").path())
    }

    pub fn with_voting_tools_params(mut self, voting_tools: VotingToolsParams) -> Self {
        self.configuration.voting_tools = voting_tools;
        self
    }

    pub fn build(self) -> Configuration {
        self.configuration
    }
}

impl Default for Configuration {
    fn default() -> Self {
        Self {
            inner: scheduler_service_lib::Configuration {
                result_dir: Path::new(".").to_path_buf(),
                address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070),
                api_token: None,
                admin_token: None,
            },
            voting_tools: VotingToolsParams {
                bin: None,
                nix_branch: None,
                network: NetworkType::Mainnet,
                db: "".to_string(),
                db_user: "".to_string(),
                db_pass: "".to_string(),
                db_host: "".to_string(),
                additional_params: None,
            },
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct VotingToolsParams {
    /// binary name
    pub bin: Option<String>,
    /// in some occasion we need to run voting-tools via some dependency management
    #[serde(rename = "nix-branch")]
    pub nix_branch: Option<String>,
    /// network type
    pub network: NetworkType,
    /// db name
    pub db: String,
    #[serde(rename = "db-user")]
    /// db user
    pub db_user: String,
    #[serde(rename = "db-pass")]
    /// db pass
    pub db_pass: String,
    /// db host
    #[serde(rename = "db-host")]
    pub db_host: String,
    /// additional parameters
    pub additional_params: Option<Vec<String>>,
}

impl VotingToolsParams {
    pub fn command(&self) -> Result<std::process::Command, Error> {
        if let Some(bin) = &self.bin {
            return Ok(std::process::Command::new(bin));
        } else if let Some(nix_branch) = &self.nix_branch {
            let mut command = std::process::Command::new("nix");
            command.arg("run");
            command.arg(nix_branch);
            command.arg("--");
            return Ok(command);
        }
        Err(Error::WrongVotingToolsConfiguration)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub enum NetworkType {
    #[serde(rename = "mainnet")]
    Mainnet,
    #[serde(rename = "testnet")]
    Testnet(u32),
}

pub fn read_config<P: AsRef<Path>>(config: P) -> Result<Configuration, Error> {
    let contents = std::fs::read_to_string(&config)?;
    serde_json::from_str(&contents).map_err(Into::into)
}

pub fn write_config<P: AsRef<Path>>(config: Configuration, path: P) -> Result<(), Error> {
    use std::io::Write;
    let mut file = std::fs::File::create(&path)?;
    file.write_all(serde_json::to_string_pretty(&config)?.as_bytes())
        .map_err(Into::into)
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("cannot parse configuration")]
    CannotParseConfiguration(#[from] serde_json::Error),
    #[error("cannot read configuration: {0:?}")]
    CannotReadConfiguration(PathBuf),
    #[error("cannot spawn command")]
    CannotSpawnCommand(#[from] std::io::Error),
    #[error("cannot find voting tools at {0:?}")]
    CannotFindVotingTools(PathBuf),
    #[error("no 'bin' or 'run-through' defined in voting tools")]
    WrongVotingToolsConfiguration,
    #[error("result folder does not exists at {0:?}")]
    ResultFolderDoesNotExists(PathBuf),
}