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
//! Helpers for configuration validation.
//!
//! See [`config_validator`](../struct.Builder.html#method.config_validator).
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::slice::Iter;

use failure::{Backtrace, Error as FError, Fail};

/// An unknown-type validation error.
///
/// If the validation callback returns error with only a description, not a proper typed exception,
/// the description is turned into this if bundled into [`Error`](struct.Error.html).
#[derive(Debug, Fail)]
#[fail(display = "{}", _0)]
pub struct UntypedError(String);

/// An error caused by failed validation.
///
/// Carries all the errors that caused it to fail (publicly accessible).
#[derive(Debug)]
pub struct Error(pub Vec<FError>);

impl Display for Error {
    fn fmt(&self, formatter: &mut Formatter) -> FmtResult {
        write!(
            formatter,
            "Config validation failed with {} errors",
            self.0.len()
        )
    }
}

impl Fail for Error {
    // There may actually be multiple causes. But we just stick with the first one for lack of
    // better way to pick.
    fn cause(&self) -> Option<&dyn Fail> {
        self.0.get(0).map(FError::as_fail)
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.0.get(0).map(FError::backtrace)
    }
}

impl From<Results> for Error {
    fn from(results: Results) -> Self {
        let errors = results
            .0
            .into_iter()
            .filter_map(|res| match (res.level, res.error) {
                (Level::Error, Some(err)) => Some(err),
                (Level::Error, None) => Some(UntypedError(res.description).into()),
                _ => None,
            })
            .collect();
        Error(errors)
    }
}

/// A level of [`validation result`](struct.Result.html).
///
/// This determines the log level at which the result (message) will appear. It also can determine
/// to refuse the whole configuration.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Level {
    /// No message is logged.
    ///
    /// This makes sense if you only want to set an action to be attached to a validation result.
    Nothing,

    /// A message printed on info level.
    ///
    /// This likely means nothing is wrong, but maybe something the user might be interested in ‒
    /// like simpler way to express it, the fact this will get deprecated in next version...
    Hint,

    /// A message printed on warning level.
    ///
    /// Something is wrong, but the application still can continue, like one of several replicas
    /// are not stored where they should, or the configuration contains only one replica so any
    /// failure would make losing data.
    Warning,

    /// A message printed on error level and refused configuration.
    ///
    /// In addition to printing the message on error level, the whole configuration is considered
    /// invalid and the application either doesn't start (if it is the first configuration) or
    /// keeps the old one.
    Error,
}

impl Default for Level {
    fn default() -> Self {
        Level::Nothing
    }
}

/// A validation result.
///
/// The validator (see [`config_validator`](../struct.Builder.html#method.config_validator)) is
/// supposed to return an arbitrary number of these results. Each one can hold a message (with
/// varying severity) and optionally a success and failure actions.
#[derive(Default)]
pub struct Result {
    level: Level,
    description: String,
    error: Option<FError>,
    pub(crate) on_abort: Option<Box<FnMut()>>,
    pub(crate) on_success: Option<Box<FnMut()>>,
}

impl Result {
    /// Creates a result with given level and message.
    pub fn new<S: Into<String>>(level: Level, s: S) -> Self {
        Result {
            level,
            description: s.into(),
            ..Default::default()
        }
    }

    /// Creates a result without any message.
    pub fn nothing() -> Self {
        Self::new(Level::Nothing, "")
    }

    /// Creates a result with a hint.
    pub fn hint<S: Into<String>>(s: S) -> Self {
        Self::new(Level::Hint, s)
    }

    /// Creates a result with a warning.
    pub fn warning<S: Into<String>>(s: S) -> Self {
        Self::new(Level::Warning, s)
    }

    /// Creates an error result.
    ///
    /// An error result not only gets to the logs, it also marks the whole config as invalid.
    pub fn error<S: Into<String>>(s: S) -> Self {
        Self::new(Level::Error, s)
    }

    /// Creates an error result from an actual `Error`.
    ///
    /// The error then is logged with additional information.
    pub fn from_error(e: FError) -> Self {
        let mut me = Self::error(format!("{}", e));
        me.error = Some(e);
        me
    }

    /// Returns the result's level.
    pub fn level(&self) -> Level {
        self.level
    }

    /// Returns the message texts.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Returns an associated error if there's one.
    ///
    /// Note that the error text is already part of the [`description`](#method.description).
    pub fn detailed_error(&self) -> &Option<FError> {
        &self.error
    }

    /// Attaches (replaces) the success action.
    pub fn on_success<F: FnOnce() + 'static>(self, f: F) -> Self {
        let mut f = Some(f);
        let wrapper = move || (f.take().unwrap())();
        Self {
            on_success: Some(Box::new(wrapper)),
            ..self
        }
    }

    /// Attaches (replaces) the failure action.
    pub fn on_abort<F: FnOnce() + 'static>(self, f: F) -> Self {
        let mut f = Some(f);
        let wrapper = move || (f.take().unwrap())();
        Self {
            on_success: Some(Box::new(wrapper)),
            ..self
        }
    }
}

impl Debug for Result {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        fmt.debug_struct("ValidationResult")
            .field("level", &self.level)
            .field("description", &self.description)
            .field("error", &self.error)
            .field(
                "on_abort",
                if self.on_abort.is_some() {
                    &"Fn()"
                } else {
                    &"None"
                },
            )
            .field(
                "on_success",
                if self.on_success.is_some() {
                    &"Fn()"
                } else {
                    &"None"
                },
            )
            .finish()
    }
}

impl From<FError> for Result {
    fn from(e: FError) -> Self {
        Self::from_error(e)
    }
}

impl From<String> for Result {
    fn from(s: String) -> Self {
        Result {
            level: Level::Error,
            description: s,
            ..Default::default()
        }
    }
}

impl From<&'static str> for Result {
    fn from(s: &'static str) -> Self {
        Result {
            level: Level::Error,
            description: s.to_owned(),
            ..Default::default()
        }
    }
}

impl From<(Level, String)> for Result {
    fn from((level, s): (Level, String)) -> Self {
        Result {
            level,
            description: s,
            ..Default::default()
        }
    }
}

impl From<(Level, &'static str)> for Result {
    fn from((level, s): (Level, &'static str)) -> Self {
        Result {
            level,
            description: s.to_owned(),
            ..Default::default()
        }
    }
}

/// Multiple validation results.
///
/// A validator can actually return multiple results at once (to, for example, produce multiple
/// messages). This is a storage of multiple results which can be created by either converting a
/// single or iterator or by merging multiple `Results` objects.
#[derive(Debug, Default)]
pub struct Results(pub(crate) Vec<Result>);

impl Results {
    /// Creates an empty results storage.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends another bunch of results into this storage.
    pub fn merge<R: Into<Results>>(&mut self, other: R) {
        self.0.extend(other.into().0);
    }

    /// Iterates through the storage.
    pub fn iter(&self) -> Iter<Result> {
        self.into_iter()
    }

    /// The most severe level of all the results inside.
    pub fn max_level(&self) -> Option<Level> {
        self.iter().map(|r| r.level).max()
    }
}

impl<'a> IntoIterator for &'a Results {
    type Item = &'a Result;
    type IntoIter = Iter<'a, Result>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl From<Result> for Results {
    fn from(val: Result) -> Self {
        Results(vec![val])
    }
}

impl<I, It> From<I> for Results
where
    I: IntoIterator<Item = It>,
    It: Into<Result>,
{
    fn from(vals: I) -> Self {
        Results(vals.into_iter().map(Into::into).collect())
    }
}