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
use clap::Parser;
use indicatif::{HumanDuration, MultiProgress, ProgressBar, ProgressStyle};
use std::fmt;
use std::thread;
use std::time::Instant;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use thiserror::Error;
use valgrind::{Error as ValgrindError, ValgrindClient};
use vit_servicing_station_lib::utils::datetime::unix_timestamp_to_datetime;

#[derive(Parser, Debug)]
pub struct DeploymentValidateCommand {
    /// target address
    #[clap(long = "address")]
    pub address: String,
}

#[derive(Debug, EnumIter, Copy, Clone)]
enum Check {
    Fund,
    Proposals,
    Settings,
    VotePlan,
    Reviews,
    Challenges,
    BadGateway,
    Times,
}

impl fmt::Display for Check {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Check::Fund => write!(f, "[vit-ss] Fund endpoint check"),
            Check::Proposals => write!(f, "[vit-ss] Proposals endpoint check"),
            Check::Settings => write!(f, "[jormungandr] Settings endpoint check"),
            Check::VotePlan => write!(f, "[jormungandr] Vote plan endpoint"),
            Check::Reviews => write!(f, "[vit-ss] Reviews endpoint"),
            Check::Challenges => write!(f, "[vit-ss] Challenges endpoint"),
            Check::BadGateway => write!(f, "[proxy] Bad gateway check"),
            Check::Times => write!(f, "[vit-ss] Fund dates check"),
        }
    }
}

impl Check {
    pub fn execute(
        &self,
        wallet_backend: &ValgrindClient,
    ) -> std::result::Result<std::time::Duration, CheckError> {
        let mut started = Instant::now();

        match self {
            Self::Fund => wallet_backend
                .funds()
                .map(|_| started.elapsed())
                .map_err(Into::into),
            Self::Proposals => wallet_backend
                .proposals("direct")
                .map(|_| started.elapsed())
                .map_err(Into::into),
            Self::Settings => wallet_backend
                .settings()
                .map(|_| started.elapsed())
                .map_err(Into::into),
            Self::VotePlan => wallet_backend
                .vote_plan_statuses()
                .map(|_| started.elapsed())
                .map_err(Into::into),
            Self::Reviews => {
                let proposals = wallet_backend.proposals("direct")?;
                started = Instant::now();
                wallet_backend
                    .review(&proposals[0].proposal.proposal_id)
                    .map(|_| started.elapsed())
                    .map_err(Into::into)
            }
            Self::Challenges => wallet_backend
                .challenges()
                .map(|_| started.elapsed())
                .map_err(Into::into),
            Self::BadGateway => {
                let left = wallet_backend.funds()?;
                let right = wallet_backend.funds()?;

                if left != right {
                    Err(CheckError::Assert(
                        "two calls to funds return different response".to_string(),
                    ))
                } else {
                    Ok(started.elapsed())
                }
            }
            Self::Times => {
                let fund = wallet_backend.funds()?;

                let registration_date = unix_timestamp_to_datetime(fund.registration_snapshot_time);
                let fund_start_date = unix_timestamp_to_datetime(fund.fund_start_time);
                let fund_end_date = unix_timestamp_to_datetime(fund.fund_end_time);
                let next_fund_date = unix_timestamp_to_datetime(fund.next_fund_start_time);

                if registration_date > fund_start_date {
                    return Err(CheckError::Assert(
                        "registration_date is further in the future than fund_start_date"
                            .to_string(),
                    ));
                }
                if fund_start_date > fund_end_date {
                    return Err(CheckError::Assert(
                        "fund_start_date is further in the future than fund_end_date".to_string(),
                    ));
                }

                if fund_end_date > next_fund_date {
                    return Err(CheckError::Assert(
                        "fund_end_date is further in the future than next_fund_date".to_string(),
                    ));
                }
                Ok(started.elapsed())
            }
        }
    }
}

impl DeploymentValidateCommand {
    pub fn exec(self) -> Result<(), CheckError> {
        let started = Instant::now();
        let spinner_style = ProgressStyle::default_spinner()
            .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
            .template("{prefix:.bold.dim} {spinner} {wide_msg}");

        let commands: Vec<Check> = Check::iter().collect();
        let len = commands.len();
        let m = MultiProgress::new();

        let _handles: Vec<_> = commands
            .iter()
            .cloned()
            .enumerate()
            .map(|(i, command)| {
                let pb = m.add(ProgressBar::new(1));
                pb.set_style(spinner_style.clone());
                pb.set_prefix(&format!("[{}/{}]", i + 1, len));
                pb.set_message(&format!("{}...In progress", command));

                let address = self.address.clone();
                let wallet_backend = ValgrindClient::new(address, Default::default()).unwrap();
                thread::spawn(move || {
                    let finish_style =
                        ProgressStyle::default_spinner().template("{prefix:.bold.dim} {wide_msg}");

                    let result = command.execute(&wallet_backend);

                    pb.set_style(finish_style);

                    match result {
                        Ok(elapsed) => pb.finish_with_message(&format!(
                            "[Passed] {}. Duration: {} ms",
                            command,
                            elapsed.as_millis()
                        )),
                        Err(error) => pb.finish_with_message(&format!(
                            "[Failed] {}. Error: {}",
                            command, error
                        )),
                    };
                })
            })
            .collect();

        m.join().unwrap();

        println!();
        println!("Done in {}", HumanDuration(started.elapsed()));

        Ok(())
    }
}

#[derive(Debug, Error)]
pub enum CheckError {
    #[error(transparent)]
    WalletBackend(#[from] ValgrindError),
    #[error("{0}")]
    Assert(String),
}