netem-trace 0.5.0

A library for for generating network emulation trace.
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! This module contains some predefined rwnd trace models.
//!
//! Enabled with feature `rwnd-model` or `model`.
//!
//! ## Predefined models
//!
//! - [`StaticRwnd`]: A trace model with a single rwnd decision.
//! - [`RepeatedRwndPattern`]: A trace model with a repeated rwnd pattern.
//!
//! ## Step semantics
//!
//! A step carries two independent fields, `set_rcv_buf` and `app_read_bytes`,
//! and between them they say what the receiver does for the step's duration.
//! See [`RwndDecision`] for the full table; in short, `set_rcv_buf` states a
//! buffer the application keeps drained (so the window stays at that value),
//! and `app_read_bytes` states an application that reads only so much (so the
//! window decays as the backlog grows).
//!
//! A step carrying **both** resizes the buffer first and takes the read against
//! the new size. The window is then `set_rcv_buf - unread`, not pinned at
//! `set_rcv_buf`: stating a read means the application is the bottleneck, so the
//! "application keeps up" half of a buffer-only step no longer applies. The
//! unread backlog carries across the resize untouched, so a resize to at or
//! below the current backlog advertises a zero window until the application
//! catches up.
//!
//! ## Examples
//!
//! An example to build model from configuration:
//!
//! ```
//! # use netem_trace::model::StaticRwndConfig;
//! # use netem_trace::{Duration, RwndTrace};
//! let mut static_rwnd = StaticRwndConfig::new()
//!     .set_rcv_buf(65536)
//!     .app_read(1024)
//!     .duration(Duration::from_secs(1))
//!     .build();
//! let (decision, duration) = static_rwnd.next_rwnd().unwrap();
//! assert_eq!(decision.set_rcv_buf, Some(65536));
//! assert_eq!(decision.app_read_bytes, Some(1024));
//! assert_eq!(duration, Duration::from_secs(1));
//! assert_eq!(static_rwnd.next_rwnd(), None);
//! ```
//!
//! The step above carries both fields, so it resizes the buffer to 64 KiB and
//! then has the application read 1 KiB from it. The window that follows is
//! `65536 - unread` rather than a window pinned at 65536 -- compare the
//! buffer-only step below, which does pin it:
//!
//! ```
//! # use netem_trace::model::StaticRwndConfig;
//! # use netem_trace::{Duration, RwndTrace};
//! // Buffer only: the window is held at 65536 and the application keeps up.
//! let mut pinned = StaticRwndConfig::new()
//!     .set_rcv_buf(65536)
//!     .duration(Duration::from_secs(1))
//!     .build();
//! let (decision, _) = pinned.next_rwnd().unwrap();
//! assert_eq!(decision.set_rcv_buf, Some(65536));
//! assert_eq!(decision.app_read_bytes, None);
//!
//! // Both: same buffer, but the application now reads only 1 KiB per step, so
//! // the window follows the backlog instead of staying at 65536.
//! let mut app_limited = StaticRwndConfig::new()
//!     .set_rcv_buf(65536)
//!     .app_read(1024)
//!     .duration(Duration::from_secs(1))
//!     .build();
//! let (decision, _) = app_limited.next_rwnd().unwrap();
//! assert_eq!(decision.set_rcv_buf, Some(65536));
//! assert_eq!(decision.app_read_bytes, Some(1024));
//!
//! // Shrinking the buffer under a standing backlog is stated the same way; the
//! // window saturates at zero until the application reads its way back under it.
//! let mut shrink = StaticRwndConfig::new()
//!     .set_rcv_buf(8192)
//!     .app_read(0)
//!     .duration(Duration::from_secs(1))
//!     .build();
//! let (decision, _) = shrink.next_rwnd().unwrap();
//! assert_eq!(decision.set_rcv_buf, Some(8192));
//! assert_eq!(decision.app_read_bytes, Some(0));
//! ```
//!
//! A more common use case is to build model from a configuration file (e.g. json file):
//!
//! ```
//! # use netem_trace::model::{StaticRwndConfig, RwndTraceConfig};
//! # use netem_trace::{Duration, RwndTrace};
//! # #[cfg(feature = "human")]
//! # let config_file_content = "{\"RepeatedRwndPatternConfig\":{\"pattern\":[{\"StaticRwndConfig\":{\"duration\":\"1s\",\"set_rcv_buf\":65536}},{\"StaticRwndConfig\":{\"duration\":\"1s\",\"app_read_bytes\":1024}}],\"count\":2}}";
//! // The content would be "{\"RepeatedRwndPatternConfig\":{\"pattern\":[{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"set_rcv_buf\":65536}},{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"app_read_bytes\":1024}}],\"count\":2}}"
//! // if the `human` feature is not enabled.
//! # #[cfg(not(feature = "human"))]
//! let config_file_content = "{\"RepeatedRwndPatternConfig\":{\"pattern\":[{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"set_rcv_buf\":65536}},{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"app_read_bytes\":1024}}],\"count\":2}}";
//! let des: Box<dyn RwndTraceConfig> = serde_json::from_str(config_file_content).unwrap();
//! let mut model = des.into_model();
//! let (decision, _) = model.next_rwnd().unwrap();
//! assert_eq!(decision.set_rcv_buf, Some(65536));
//! let (decision, _) = model.next_rwnd().unwrap();
//! assert_eq!(decision.app_read_bytes, Some(1024));
//! ```
use crate::{Duration, RwndDecision, RwndTrace};
use dyn_clone::DynClone;

/// This trait is used to convert a rwnd trace configuration into a rwnd 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 RwndTraceConfig: DynClone + Send {
    fn into_model(self: Box<Self>) -> Box<dyn RwndTrace>;
}

dyn_clone::clone_trait_object!(RwndTraceConfig);

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

/// The model of a static rwnd trace: a single decision valid for one duration.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::StaticRwndConfig;
/// # use netem_trace::{Duration, RwndTrace};
/// let mut static_rwnd = StaticRwndConfig::new()
///     .set_rcv_buf(65536)
///     .duration(Duration::from_secs(1))
///     .build();
/// let (decision, duration) = static_rwnd.next_rwnd().unwrap();
/// assert_eq!(decision.set_rcv_buf, Some(65536));
/// assert_eq!(decision.app_read_bytes, None);
/// assert_eq!(duration, Duration::from_secs(1));
/// assert_eq!(static_rwnd.next_rwnd(), None);
/// ```
#[derive(Debug, Clone)]
pub struct StaticRwnd {
    pub decision: RwndDecision,
    pub duration: Option<Duration>,
}

/// The configuration struct for [`StaticRwnd`].
///
/// The serialized JSON form is **flat**: a step looks like
/// `{"duration":"1s","set_rcv_buf":65536}` or
/// `{"duration":"1s","app_read_bytes":1024}`, and may carry both keys.
///
/// The two fields are independent -- there is no invariant to enforce, so
/// `Serialize`/`Deserialize` are derived. A step with neither field is valid and
/// carries the previous configuration forward.
///
/// Unknown keys are rejected rather than ignored. The schema dropped
/// `rwnd_remaining`, and serde's default of skipping what it does not recognise
/// would turn a trace written against the old schema into a run of steps that
/// state nothing -- a replay that looks healthy while reproducing no receiver at
/// all. Failing to deserialize names the offending field instead.
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(default, deny_unknown_fields)
)]
#[derive(Debug, Clone, Default)]
pub struct StaticRwndConfig {
    #[cfg_attr(
        feature = "human",
        serde(with = "humantime_serde"),
        serde(skip_serializing_if = "Option::is_none")
    )]
    #[cfg_attr(
        all(feature = "serde", not(feature = "human")),
        serde(skip_serializing_if = "Option::is_none")
    )]
    pub duration: Option<Duration>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub set_rcv_buf: Option<u64>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub app_read_bytes: Option<u64>,
}

/// The model contains an array of rwnd trace models.
///
/// Combine multiple rwnd trace models into one rwnd pattern,
/// and repeat the pattern for `count` times.
///
/// If `count` is 0, the pattern will be repeated forever.
///
/// ## Examples
///
/// The most common use case is to read from a configuration file and
/// deserialize it into a [`RepeatedRwndPatternConfig`]:
///
/// ```
/// # use netem_trace::model::{StaticRwndConfig, RwndTraceConfig};
/// # use netem_trace::{Duration, RwndTrace};
/// # #[cfg(feature = "human")]
/// # let config_file_content = "{\"RepeatedRwndPatternConfig\":{\"pattern\":[{\"StaticRwndConfig\":{\"duration\":\"1s\",\"set_rcv_buf\":65536,\"app_read_bytes\":1024}}],\"count\":2}}";
/// # #[cfg(not(feature = "human"))]
/// let config_file_content = "{\"RepeatedRwndPatternConfig\":{\"pattern\":[{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"set_rcv_buf\":65536,\"app_read_bytes\":1024}}],\"count\":2}}";
/// let des: Box<dyn RwndTraceConfig> = serde_json::from_str(config_file_content).unwrap();
/// let mut model = des.into_model();
/// let (decision, _) = model.next_rwnd().unwrap();
/// assert_eq!(decision.set_rcv_buf, Some(65536));
/// assert_eq!(decision.app_read_bytes, Some(1024));
/// ```
pub struct RepeatedRwndPattern {
    pub pattern: Vec<Box<dyn RwndTraceConfig>>,
    pub count: usize,
    current_model: Option<Box<dyn RwndTrace>>,
    current_cycle: usize,
    current_pattern: usize,
}

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

impl RwndTrace for StaticRwnd {
    fn next_rwnd(&mut self) -> Option<(RwndDecision, Duration)> {
        if let Some(duration) = self.duration.take() {
            if duration.is_zero() {
                None
            } else {
                Some((self.decision, duration))
            }
        } else {
            None
        }
    }
}

impl RwndTrace for RepeatedRwndPattern {
    fn next_rwnd(&mut self) -> Option<(RwndDecision, Duration)> {
        let pattern_len = self.pattern.len();
        // Allow at most pattern_len + 1 consecutive inner-None results before
        // giving up. The +1 covers a possibly-exhausted current_model at entry;
        // after that, each remaining slot is a fresh clone whose behaviour is
        // deterministic. If all pattern_len fresh clones return None, the
        // pattern will never produce a value regardless of count.
        let mut budget = pattern_len + 1;
        loop {
            if pattern_len == 0 || (self.count != 0 && self.current_cycle >= self.count) {
                return None;
            }
            if budget == 0 {
                return None;
            }
            if self.current_model.is_none() {
                self.current_model = Some(self.pattern[self.current_pattern].clone().into_model());
            }
            match self.current_model.as_mut().unwrap().next_rwnd() {
                Some(item) => return Some(item),
                None => {
                    self.current_model = None;
                    budget -= 1;
                    self.current_pattern += 1;
                    if self.current_pattern >= pattern_len {
                        self.current_pattern = 0;
                        self.current_cycle += 1;
                        if self.count != 0 && self.current_cycle >= self.count {
                            return None;
                        }
                    }
                }
            }
        }
    }
}

impl StaticRwndConfig {
    pub fn new() -> Self {
        Self {
            duration: None,
            set_rcv_buf: None,
            app_read_bytes: None,
        }
    }

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

    /// Size the receive buffer.
    ///
    /// On its own this also holds the advertised window at that value, with the
    /// application draining continuously. Combined with [`Self::app_read`] it
    /// only sets the size: the resize applies first, the read is taken against
    /// the new size, and the window then follows `set_rcv_buf - unread` rather
    /// than being pinned.
    pub fn set_rcv_buf(mut self, set_rcv_buf: u64) -> Self {
        self.set_rcv_buf = Some(set_rcv_buf);
        self
    }

    /// The application reads exactly this many bytes over the step, then stops.
    ///
    /// The window follows from what is left unread of the standing buffer, or
    /// of the buffer this step sets when combined with [`Self::set_rcv_buf`].
    /// The backlog carries across such a resize untouched, so the window
    /// saturates at zero if the new size is at or below it.
    pub fn app_read(mut self, bytes: u64) -> Self {
        self.app_read_bytes = Some(bytes);
        self
    }

    pub fn build(self) -> StaticRwnd {
        StaticRwnd {
            decision: RwndDecision {
                set_rcv_buf: self.set_rcv_buf,
                app_read_bytes: self.app_read_bytes,
            },
            duration: Some(self.duration.unwrap_or_else(|| Duration::from_secs(1))),
        }
    }
}

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

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

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

    pub fn build(self) -> RepeatedRwndPattern {
        RepeatedRwndPattern {
            pattern: self.pattern,
            count: self.count,
            current_model: None,
            current_cycle: 0,
            current_pattern: 0,
        }
    }
}

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

impl_rwnd_trace_config!(StaticRwndConfig);
impl_rwnd_trace_config!(RepeatedRwndPatternConfig);

#[cfg(test)]
mod test {
    use super::*;
    use crate::RwndTrace;

    /// Both fields on one step: the buffer is resized and the read is taken
    /// against the new size, so the decision carries both rather than one
    /// overriding the other.
    #[test]
    fn test_static_rwnd_model_buffer_and_app_read() {
        let mut static_rwnd = StaticRwndConfig::new()
            .set_rcv_buf(65536)
            .app_read(1024)
            .duration(Duration::from_secs(1))
            .build();
        let (decision, duration) = static_rwnd.next_rwnd().unwrap();
        assert_eq!(decision.set_rcv_buf, Some(65536));
        assert_eq!(decision.app_read_bytes, Some(1024));
        assert_eq!(duration, Duration::from_secs(1));
        assert_eq!(static_rwnd.next_rwnd(), None);
    }

    /// A buffer on its own is a complete statement: the window sits there and
    /// the application keeps up. This is what used to need `rwnd_remaining`.
    #[test]
    fn test_static_rwnd_model_buffer_only() {
        let mut static_rwnd = StaticRwndConfig::new()
            .set_rcv_buf(32768)
            .duration(Duration::from_secs(2))
            .build();
        let (decision, duration) = static_rwnd.next_rwnd().unwrap();
        assert_eq!(decision.set_rcv_buf, Some(32768));
        assert_eq!(decision.app_read_bytes, None);
        assert_eq!(duration, Duration::from_secs(2));
        assert_eq!(static_rwnd.next_rwnd(), None);
    }

    /// A step may carry neither field, and then it simply holds whatever the
    /// previous step configured for its duration.
    #[test]
    fn test_static_rwnd_model_carries_forward() {
        let mut model = StaticRwndConfig::new()
            .duration(Duration::from_secs(1))
            .build();
        let (decision, duration) = model.next_rwnd().unwrap();
        assert_eq!(decision.set_rcv_buf, None);
        assert_eq!(decision.app_read_bytes, None);
        assert_eq!(duration, Duration::from_secs(1));
    }

    #[test]
    fn test_repeated_rwnd_pattern() {
        let pat = vec![
            Box::new(
                StaticRwndConfig::new()
                    .set_rcv_buf(65536)
                    .duration(Duration::from_secs(1)),
            ) as Box<dyn RwndTraceConfig>,
            Box::new(
                StaticRwndConfig::new()
                    .app_read(1024)
                    .duration(Duration::from_secs(1)),
            ) as Box<dyn RwndTraceConfig>,
        ];
        let mut model = RepeatedRwndPatternConfig::new()
            .pattern(pat)
            .count(2)
            .build();
        let next = model.next_rwnd().unwrap();
        assert_eq!(next.0.set_rcv_buf, Some(65536));
        assert_eq!(next.1, Duration::from_secs(1));
        assert_eq!(model.next_rwnd().unwrap().0.app_read_bytes, Some(1024));
        assert_eq!(model.next_rwnd().unwrap().0.set_rcv_buf, Some(65536));
        assert_eq!(model.next_rwnd().unwrap().0.app_read_bytes, Some(1024));
        assert_eq!(model.next_rwnd(), None);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_roundtrip_buffer_only() {
        let cfg = Box::new(
            StaticRwndConfig::new()
                .set_rcv_buf(65536)
                .duration(Duration::from_secs(1)),
        ) as Box<dyn RwndTraceConfig>;
        let ser_str = serde_json::to_string(&cfg).unwrap();
        #[cfg(feature = "human")]
        let expected = "{\"StaticRwndConfig\":{\"duration\":\"1s\",\"set_rcv_buf\":65536}}";
        #[cfg(not(feature = "human"))]
        let expected =
            "{\"StaticRwndConfig\":{\"duration\":{\"secs\":1,\"nanos\":0},\"set_rcv_buf\":65536}}";
        assert_eq!(ser_str, expected);

        let des: Box<dyn RwndTraceConfig> = serde_json::from_str(&ser_str).unwrap();
        let mut model = des.into_model();
        let (decision, duration) = model.next_rwnd().unwrap();
        assert_eq!(decision.set_rcv_buf, Some(65536));
        assert_eq!(decision.app_read_bytes, None);
        assert_eq!(duration, Duration::from_secs(1));
    }

    /// Both keys on one step is legal now, and round-trips.
    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_roundtrip_both_fields() {
        let json = "{\"StaticRwndConfig\":{\"set_rcv_buf\":131072,\"app_read_bytes\":4096}}";
        let des: Box<dyn RwndTraceConfig> = serde_json::from_str(json).unwrap();
        let mut model = des.into_model();
        let (decision, _) = model.next_rwnd().unwrap();
        assert_eq!(decision.set_rcv_buf, Some(131072));
        assert_eq!(decision.app_read_bytes, Some(4096));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_omits_absent_fields() {
        let cfg = Box::new(StaticRwndConfig::new().app_read(0)) as Box<dyn RwndTraceConfig>;
        let ser_str = serde_json::to_string(&cfg).unwrap();
        assert!(!ser_str.contains("set_rcv_buf"), "got: {ser_str}");
        assert!(ser_str.contains("app_read_bytes"), "got: {ser_str}");
    }

    /// A trace written against the old schema names a field that no longer
    /// exists. Rejecting it is the point: silently ignoring `rwnd_remaining`
    /// would turn every window step into a no-op and replay a trace that says
    /// nothing, which looks like a healthy run producing wrong numbers.
    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_rejects_the_old_rwnd_remaining_field() {
        let json = "{\"StaticRwndConfig\":{\"rwnd_remaining\":32768}}";
        let result: Result<Box<dyn RwndTraceConfig>, _> = serde_json::from_str(json);
        let err = result
            .err()
            .expect("a trace using the removed field should not deserialize")
            .to_string();
        assert!(err.contains("rwnd_remaining"), "got: {err}");
    }

    #[test]
    fn test_repeated_rwnd_pattern_all_zero_duration_terminates() {
        // All inner models have duration == 0 and return None immediately.
        // With count == 0 (infinite repeat) a recursive implementation would
        // spin forever; the loop-based one must return None promptly.
        let pat = vec![
            Box::new(
                StaticRwndConfig::new()
                    .app_read(1024)
                    .duration(Duration::ZERO),
            ) as Box<dyn RwndTraceConfig>,
            Box::new(
                StaticRwndConfig::new()
                    .set_rcv_buf(32768)
                    .duration(Duration::ZERO),
            ) as Box<dyn RwndTraceConfig>,
        ];
        let mut model = RepeatedRwndPatternConfig::new()
            .pattern(pat)
            .count(0) // infinite
            .build();
        assert_eq!(model.next_rwnd(), None);
    }
}