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
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! The node manager that takes care of sending requests with healthy nodes and quorum if enabled

use std::{
    collections::HashSet,
    sync::{Arc, RwLock},
    time::Duration,
};

use serde::{Deserialize, Serialize};
use url::Url;

use crate::{
    constants::{DEFAULT_MIN_QUORUM_SIZE, DEFAULT_QUORUM_THRESHOLD, NODE_SYNC_INTERVAL},
    error::{Error, Result},
    node_manager::{
        http_client::HttpClient,
        node::{Node, NodeAuth, NodeDto},
        NodeManager,
    },
};

/// Node manager builder
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct NodeManagerBuilder {
    /// Node which will be tried first for all requests
    #[serde(rename = "primaryNode")]
    pub primary_node: Option<NodeDto>,
    /// Node which will be tried first when using remote PoW, even before the primary_node
    #[serde(rename = "primaryPowNode")]
    pub primary_pow_node: Option<NodeDto>,
    /// Nodes
    #[serde(default)]
    pub nodes: HashSet<NodeDto>,
    /// Permanodes
    pub permanodes: Option<HashSet<NodeDto>>,
    /// If node syncing is enabled
    #[serde(rename = "nodeSyncEnabled", default = "default_node_sync_enabled")]
    pub node_sync_enabled: bool,
    /// Interval in which nodes will be checked for their sync status and the [NetworkInfo] gets updated
    #[serde(rename = "nodeSyncInterval", default = "default_node_sync_interval")]
    pub node_sync_interval: Duration,
    /// If node quorum is enabled. Will compare the responses from multiple nodes and only returns the response if
    /// `quorum_threshold`% of the nodes return the same one
    #[serde(default)]
    pub quorum: bool,
    /// Minimum amount of nodes required for request when quorum is enabled
    #[serde(rename = "minQuorumSize", default = "default_min_quorum_size")]
    pub min_quorum_size: usize,
    /// % of nodes that have to return the same response so it gets accepted
    #[serde(rename = "quorumThreshold", default = "default_quorum_threshold")]
    pub quorum_threshold: usize,
}

fn default_node_sync_enabled() -> bool {
    true
}

fn default_node_sync_interval() -> Duration {
    NODE_SYNC_INTERVAL
}

fn default_min_quorum_size() -> usize {
    DEFAULT_MIN_QUORUM_SIZE
}

fn default_quorum_threshold() -> usize {
    DEFAULT_QUORUM_THRESHOLD
}

impl NodeManagerBuilder {
    pub(crate) fn new() -> Self {
        Default::default()
    }

    pub(crate) fn with_node(mut self, url: &str) -> Result<Self> {
        let url = validate_url(Url::parse(url)?)?;
        self.nodes.insert(NodeDto::Node(Node {
            url,
            auth: None,
            disabled: false,
        }));
        Ok(self)
    }

    pub(crate) fn with_primary_node(mut self, url: &str, auth: Option<NodeAuth>) -> Result<Self> {
        let mut url = validate_url(Url::parse(url)?)?;
        if let Some(auth) = &auth {
            if let Some((name, password)) = &auth.basic_auth_name_pwd {
                url.set_username(name)
                    .map_err(|_| crate::Error::UrlAuthError("username"))?;
                url.set_password(Some(password))
                    .map_err(|_| crate::Error::UrlAuthError("password"))?;
            }
        }
        self.primary_node.replace(NodeDto::Node(Node {
            url,
            auth,
            disabled: false,
        }));
        Ok(self)
    }

    pub(crate) fn with_primary_pow_node(mut self, url: &str, auth: Option<NodeAuth>) -> Result<Self> {
        let mut url = validate_url(Url::parse(url)?)?;
        if let Some(auth) = &auth {
            if let Some((name, password)) = &auth.basic_auth_name_pwd {
                url.set_username(name)
                    .map_err(|_| crate::Error::UrlAuthError("username"))?;
                url.set_password(Some(password))
                    .map_err(|_| crate::Error::UrlAuthError("password"))?;
            }
        }
        self.primary_pow_node.replace(NodeDto::Node(Node {
            url,
            auth,
            disabled: false,
        }));
        Ok(self)
    }

    pub(crate) fn with_permanode(mut self, url: &str, auth: Option<NodeAuth>) -> Result<Self> {
        let mut url = validate_url(Url::parse(url)?)?;
        if let Some(auth) = &auth {
            if let Some((name, password)) = &auth.basic_auth_name_pwd {
                url.set_username(name)
                    .map_err(|_| crate::Error::UrlAuthError("username"))?;
                url.set_password(Some(password))
                    .map_err(|_| crate::Error::UrlAuthError("password"))?;
            }
        }
        match self.permanodes {
            Some(ref mut permanodes) => {
                permanodes.insert(NodeDto::Node(Node {
                    url,
                    auth,
                    disabled: false,
                }));
            }
            None => {
                let mut permanodes = HashSet::new();
                permanodes.insert(NodeDto::Node(Node {
                    url,
                    auth,
                    disabled: false,
                }));
                self.permanodes.replace(permanodes);
            }
        }
        Ok(self)
    }

    pub(crate) fn with_node_sync_disabled(mut self) -> Self {
        self.node_sync_enabled = false;
        self
    }

    pub(crate) fn with_node_auth(mut self, url: &str, auth: Option<NodeAuth>) -> Result<Self> {
        let mut url = validate_url(Url::parse(url)?)?;
        if let Some(auth) = &auth {
            if let Some((name, password)) = &auth.basic_auth_name_pwd {
                url.set_username(name)
                    .map_err(|_| crate::Error::UrlAuthError("username"))?;
                url.set_password(Some(password))
                    .map_err(|_| crate::Error::UrlAuthError("password"))?;
            }
        }
        self.nodes.insert(NodeDto::Node(Node {
            url,
            auth,
            disabled: false,
        }));
        Ok(self)
    }

    pub(crate) fn with_nodes(mut self, urls: &[&str]) -> Result<Self> {
        for url in urls {
            let url = validate_url(Url::parse(url)?)?;
            self.nodes.insert(NodeDto::Node(Node {
                url,
                auth: None,
                disabled: false,
            }));
        }
        Ok(self)
    }

    pub(crate) fn with_node_sync_interval(mut self, node_sync_interval: Duration) -> Self {
        self.node_sync_interval = node_sync_interval;
        self
    }

    pub(crate) fn with_quorum(mut self, quorum: bool) -> Self {
        self.quorum = quorum;
        self
    }

    pub(crate) fn with_min_quorum_size(mut self, min_quorum_size: usize) -> Self {
        self.min_quorum_size = min_quorum_size;
        self
    }

    pub(crate) fn with_quorum_threshold(mut self, threshold: usize) -> Self {
        self.quorum_threshold = threshold;
        self
    }

    pub(crate) fn build(self, healthy_nodes: Arc<RwLock<HashSet<Node>>>) -> NodeManager {
        NodeManager {
            primary_node: self.primary_node.map(|node| node.into()),
            primary_pow_node: self.primary_pow_node.map(|node| node.into()),
            nodes: self.nodes.into_iter().map(|node| node.into()).collect(),
            permanodes: self
                .permanodes
                .map(|nodes| nodes.into_iter().map(|node| node.into()).collect()),
            node_sync_enabled: self.node_sync_enabled,
            node_sync_interval: self.node_sync_interval,
            healthy_nodes,
            quorum: self.quorum,
            min_quorum_size: self.min_quorum_size,
            quorum_threshold: self.quorum_threshold,
            http_client: HttpClient::new(),
        }
    }
}

impl Default for NodeManagerBuilder {
    fn default() -> Self {
        Self {
            primary_node: None,
            primary_pow_node: None,
            nodes: HashSet::new(),
            permanodes: None,
            node_sync_enabled: true,
            node_sync_interval: NODE_SYNC_INTERVAL,
            quorum: false,
            min_quorum_size: DEFAULT_MIN_QUORUM_SIZE,
            quorum_threshold: DEFAULT_QUORUM_THRESHOLD,
        }
    }
}

/// Validates if the url starts with http or https
pub fn validate_url(url: Url) -> Result<Url> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Err(Error::UrlValidationError(format!("invalid scheme: {}", url.scheme())));
    }
    Ok(url)
}