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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! This module contains some predefined loss trace models.
//!
//! Enabled with feature `loss-model` or `model`.
//!
//! ## Predefined models
//!
//! - [`StaticLoss`]: A trace model with static loss.
//! - [`RepeatedLossPattern`]: A trace model with a repeated loss pattern.
//!
//! ## Examples
//!
//! An example to build model from configuration:
//!
//! ```
//! # use netem_trace::model::StaticLossConfig;
//! # use netem_trace::{LossPattern, Duration, LossTrace};
//! let mut static_loss = StaticLossConfig::new()
//!     .loss(vec![0.1, 0.2])
//!     .duration(Duration::from_secs(1))
//!     .build();
//! assert_eq!(static_loss.next_loss(), Some((vec![0.1, 0.2], Duration::from_secs(1))));
//! assert_eq!(static_loss.next_loss(), None);
//! ```
//!
//! A more common use case is to build model from a configuration file (e.g. json file):
//!
//! ```
//! # use netem_trace::model::{StaticLossConfig, LossTraceConfig};
//! # use netem_trace::{LossPattern, Duration, LossTrace};
//! # #[cfg(not(feature = "human"))]
//! let config_file_content = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":{\"secs\":1,\"nanos\":0}}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":{\"secs\":1,\"nanos\":0}}}],\"count\":2}}";
//! // The content would be "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}"
//! // if the `human` feature is enabled.
//! # #[cfg(feature = "human")]
//! # let config_file_content = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}";
//! let des: Box<dyn LossTraceConfig> = serde_json::from_str(config_file_content).unwrap();
//! let mut model = des.into_model();
//! assert_eq!(
//!     model.next_loss(),
//!     Some((vec![0.1, 0.2], Duration::from_secs(1)))
//! );
//! assert_eq!(
//!     model.next_loss(),
//!     Some((vec![0.2, 0.4], Duration::from_secs(1)))
//! );
//! assert_eq!(
//!     model.next_loss(),
//!     Some((vec![0.1, 0.2], Duration::from_secs(1)))
//! );
//! assert_eq!(
//!     model.next_loss(),
//!     Some((vec![0.2, 0.4], Duration::from_secs(1)))
//! );
//! assert_eq!(model.next_loss(), None);
//! ```
use crate::{Duration, LossPattern, LossTrace};
use dyn_clone::DynClone;
use std::collections::VecDeque;

/// This trait is used to convert a loss trace configuration into a loss trace model.
///
/// Since trace model is often configured with files and often has inner states which
/// is not suitable to be serialized/deserialized, this trait makes it possible to
/// separate the configuration part into a simple struct for serialization/deserialization, and
/// construct the model from the configuration.
#[cfg_attr(feature = "serde", typetag::serde)]
pub trait LossTraceConfig: DynClone {
    fn into_model(self: Box<Self>) -> Box<dyn LossTrace>;
}

dyn_clone::clone_trait_object!(LossTraceConfig);

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The model of a static loss trace.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::StaticLossConfig;
/// # use netem_trace::{LossPattern, Duration, LossTrace};
/// let mut static_loss = StaticLossConfig::new()
///     .loss(vec![0.1, 0.2])
///     .duration(Duration::from_secs(1))
///     .build();
/// assert_eq!(static_loss.next_loss(), Some((vec![0.1, 0.2], Duration::from_secs(1))));
/// assert_eq!(static_loss.next_loss(), None);
/// ```
#[derive(Debug, Clone)]
pub struct StaticLoss {
    pub loss: LossPattern,
    pub duration: Option<Duration>,
}

/// The configuration struct for [`StaticLoss`].
///
/// See [`StaticLoss`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Debug, Clone, Default)]
pub struct StaticLossConfig {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub loss: Option<LossPattern>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub duration: Option<Duration>,
}

/// The model contains an array of loss trace models.
///
/// Combines multiple loss trace models into one loss pattern,
/// and repeat the pattern for `count` times.
///
/// ## Examples
///
/// The most common use case is to read from a configuration file and
/// deserialize it into a [`RepeatedLossPatternConfig`]:
///
/// ```
/// # use netem_trace::model::{StaticLossConfig, LossTraceConfig};
/// # use netem_trace::{LossPattern, Duration, LossTrace};
/// # #[cfg(not(feature = "human"))]
/// let config_file_content = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":{\"secs\":1,\"nanos\":0}}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":{\"secs\":1,\"nanos\":0}}}],\"count\":2}}";
/// // The content would be "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}"
/// // if the `human` feature is enabled.
/// # #[cfg(feature = "human")]
/// # let config_file_content = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}";
/// let des: Box<dyn LossTraceConfig> = serde_json::from_str(config_file_content).unwrap();
/// let mut model = des.into_model();
/// assert_eq!(
///     model.next_loss(),
///     Some((vec![0.1, 0.2], Duration::from_secs(1)))
/// );
/// assert_eq!(
///     model.next_loss(),
///     Some((vec![0.2, 0.4], Duration::from_secs(1)))
/// );
/// assert_eq!(
///     model.next_loss(),
///     Some((vec![0.1, 0.2], Duration::from_secs(1)))
/// );
/// assert_eq!(
///     model.next_loss(),
///     Some((vec![0.2, 0.4], Duration::from_secs(1)))
/// );
/// assert_eq!(model.next_loss(), None);
/// ```
///
/// You can also build manually:
///
/// ```
/// # use netem_trace::model::{StaticLossConfig, LossTraceConfig, RepeatedLossPatternConfig};
/// # use netem_trace::{LossPattern, Duration, LossTrace};
/// let pat = vec![
///     Box::new(
///         StaticLossConfig::new()
///             .loss(vec![0.1, 0.2])
///             .duration(Duration::from_secs(1)),
///     ) as Box<dyn LossTraceConfig>,
///     Box::new(
///         StaticLossConfig::new()
///             .loss(vec![0.2, 0.4])
///             .duration(Duration::from_secs(1)),
///     ) as Box<dyn LossTraceConfig>,
/// ];
/// let ser = Box::new(RepeatedLossPatternConfig::new().pattern(pat).count(2)) as Box<dyn LossTraceConfig>;
/// let ser_str = serde_json::to_string(&ser).unwrap();
/// # #[cfg(not(feature = "human"))]
/// let json_str = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":{\"secs\":1,\"nanos\":0}}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":{\"secs\":1,\"nanos\":0}}}],\"count\":2}}";
/// // The json string would be "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}"
/// // if the `human` feature is enabled.
/// # #[cfg(feature = "human")]
/// # let json_str = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}";
/// assert_eq!(ser_str, json_str);
/// ```
pub struct RepeatedLossPattern {
    pub pattern: VecDeque<Box<dyn LossTrace>>,
}

/// The configuration struct for [`RepeatedLossPattern`].
///
/// See [`RepeatedLossPattern`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Clone)]
pub struct RepeatedLossPatternConfig {
    pub pattern: Vec<Box<dyn LossTraceConfig>>,
    pub count: usize,
}

impl LossTrace for StaticLoss {
    fn next_loss(&mut self) -> Option<(LossPattern, Duration)> {
        if let Some(duration) = self.duration.take() {
            if duration.is_zero() {
                None
            } else {
                Some((self.loss.clone(), duration))
            }
        } else {
            None
        }
    }
}

impl LossTrace for RepeatedLossPattern {
    fn next_loss(&mut self) -> Option<(LossPattern, Duration)> {
        if self.pattern.is_empty() {
            None
        } else {
            match self.pattern[0].next_loss() {
                Some((loss, duration)) => Some((loss, duration)),
                None => {
                    self.pattern.pop_front();
                    self.next_loss()
                }
            }
        }
    }
}

impl StaticLossConfig {
    pub fn new() -> Self {
        Self {
            loss: None,
            duration: None,
        }
    }

    pub fn loss(mut self, loss: LossPattern) -> Self {
        self.loss = Some(loss);
        self
    }

    pub fn duration(mut self, duration: Duration) -> Self {
        self.duration = Some(duration);
        self
    }

    pub fn build(self) -> StaticLoss {
        StaticLoss {
            loss: self.loss.unwrap_or_else(|| vec![0.1, 0.2]),
            duration: Some(self.duration.unwrap_or_else(|| Duration::from_secs(1))),
        }
    }
}

impl RepeatedLossPatternConfig {
    pub fn new() -> Self {
        Self {
            pattern: vec![],
            count: 1,
        }
    }

    pub fn pattern(mut self, pattern: Vec<Box<dyn LossTraceConfig>>) -> Self {
        self.pattern = pattern;
        self
    }

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

    pub fn build(self) -> RepeatedLossPattern {
        let pattern = vec![self.pattern; self.count]
            .drain(..)
            .flatten()
            .map(|config| config.into_model())
            .collect();
        RepeatedLossPattern { pattern }
    }
}

macro_rules! impl_loss_trace_config {
    ($name:ident) => {
        #[cfg_attr(feature = "serde", typetag::serde)]
        impl LossTraceConfig for $name {
            fn into_model(self: Box<$name>) -> Box<dyn LossTrace> {
                Box::new(self.build())
            }
        }
    };
}

impl_loss_trace_config!(StaticLossConfig);
impl_loss_trace_config!(RepeatedLossPatternConfig);

#[cfg(test)]
mod test {
    use super::*;
    use crate::model::StaticLossConfig;
    use crate::LossTrace;

    #[test]
    fn test_static_loss_model() {
        let mut static_loss = StaticLossConfig::new()
            .loss(vec![0.1, 0.2])
            .duration(Duration::from_secs(1))
            .build();
        assert_eq!(
            static_loss.next_loss(),
            Some((vec![0.1, 0.2], Duration::from_secs(1)))
        );
        assert_eq!(static_loss.next_loss(), None);
    }

    #[test]
    fn test_serde() {
        let a = vec![
            Box::new(
                StaticLossConfig::new()
                    .loss(vec![0.1, 0.2])
                    .duration(Duration::from_secs(1)),
            ) as Box<dyn LossTraceConfig>,
            Box::new(
                StaticLossConfig::new()
                    .loss(vec![0.2, 0.4])
                    .duration(Duration::from_secs(1)),
            ) as Box<dyn LossTraceConfig>,
        ];
        let ser = Box::new(RepeatedLossPatternConfig::new().pattern(a).count(2))
            as Box<dyn LossTraceConfig>;
        let ser_str = serde_json::to_string(&ser).unwrap();
        #[cfg(not(feature = "human"))]
        let des_str = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":{\"secs\":1,\"nanos\":0}}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":{\"secs\":1,\"nanos\":0}}}],\"count\":2}}";
        #[cfg(feature = "human")]
        let des_str = "{\"RepeatedLossPatternConfig\":{\"pattern\":[{\"StaticLossConfig\":{\"loss\":[0.1,0.2],\"duration\":\"1s\"}},{\"StaticLossConfig\":{\"loss\":[0.2,0.4],\"duration\":\"1s\"}}],\"count\":2}}";
        assert_eq!(ser_str, des_str);
        let des: Box<dyn LossTraceConfig> = serde_json::from_str(des_str).unwrap();
        let mut model = des.into_model();
        assert_eq!(
            model.next_loss(),
            Some((vec![0.1, 0.2], Duration::from_secs(1)))
        );
    }
}