proxima-primitives 0.1.0

The pipe algebra itself: the Pipe trait — an async In -> Result<Out, Err> that becomes a transform, source, sink or observe by choice of types — plus its three tier siblings (SendPipe, UnpinPipe, UnpinSendPipe), Handler, SourcePipe, the payload types Carry, ResponseStream and RequestStream (buffered bodies are plain Bytes), HeaderList, the sans-IO byte-stream traits, runtime-agnostic concurrency primitives, and the Replay/GenericStream transport seam. Everything else in proxima composes what is defined here.
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
use serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use crate::pipe::delay::{Delay, Dist};
#[cfg(feature = "std")]
use crate::pipe::filter::{FilterConfig, Predicate, RejectMode};
#[cfg(feature = "std")]
use crate::pipe::handler::{PipeHandle, into_handle};
#[cfg(feature = "std")]
use crate::pipe::mutate::{MutateOp, Mutation};
#[cfg(feature = "std")]
use crate::pipe::transform::{ResponseOp, Transform};
#[cfg(feature = "std")]
use crate::pipe::when::When;

#[cfg(feature = "std")]
const ERROR_SALT: u64 = 0x1111_1111_1111_1111;
#[cfg(feature = "std")]
const DROP_SALT: u64 = 0x2222_2222_2222_2222;
#[cfg(feature = "std")]
const LATENCY_SALT: u64 = 0x3333_3333_3333_3333;
#[cfg(feature = "std")]
const CORRUPT_SALT: u64 = 0x4444_4444_4444_4444;

/// A latency fault: with probability `prob`, sleep `ms` milliseconds before the
/// call reaches the inner pipe.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LatencyFault {
    pub prob: f64,
    pub ms: u64,
}

impl Default for LatencyFault {
    fn default() -> Self {
        Self { prob: 0.0, ms: 0 }
    }
}

/// A chaos preset: a bundle of independently-tunable fault probabilities plus a
/// base seed. Every part is optional/default-off.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ChaosConfig {
    #[serde(default)]
    pub error: f64,
    #[serde(default)]
    pub drop: f64,
    #[serde(default)]
    pub latency: LatencyFault,
    #[serde(default)]
    pub corrupt: f64,
    #[serde(default)]
    pub seed: u64,
}

impl Default for ChaosConfig {
    fn default() -> Self {
        Self {
            error: 0.0,
            drop: 0.0,
            latency: LatencyFault::default(),
            corrupt: 0.0,
            seed: 0,
        }
    }
}

impl ChaosConfig {
    #[cfg(feature = "std")]
    #[must_use]
    pub fn into_pipe(self, inner: PipeHandle) -> PipeHandle {
        let corrupt_seed = self.seed.wrapping_add(CORRUPT_SALT);
        let corrupted = if self.corrupt > 0.0 {
            let gate = When::prob(self.corrupt).seed(corrupt_seed);
            let op = MutateOp::new(Mutation::BitFlip { bits: 8 }, corrupt_seed).with_when(gate);
            into_handle(Transform::new(inner).with_response_op(ResponseOp::Mutate(op)))
        } else {
            inner
        };

        let latency_seed = self.seed.wrapping_add(LATENCY_SALT);
        let delayed = if self.latency.prob > 0.0 && self.latency.ms > 0 {
            let gate = When::prob(self.latency.prob).seed(latency_seed);
            into_handle(
                Delay::new(
                    corrupted,
                    Dist::Const {
                        ms: self.latency.ms,
                    },
                )
                .with_when(gate),
            )
        } else {
            corrupted
        };

        let drop_seed = self.seed.wrapping_add(DROP_SALT);
        let dropped = if self.drop > 0.0 {
            let gate = When::prob(self.drop).seed(drop_seed);
            FilterConfig {
                predicate: Predicate::unless(gate),
                on_reject: RejectMode::Drop,
            }
            .into_filter(delayed)
        } else {
            delayed
        };

        let error_seed = self.seed.wrapping_add(ERROR_SALT);
        if self.error > 0.0 {
            let gate = When::prob(self.error).seed(error_seed);
            FilterConfig {
                predicate: Predicate::unless(gate),
                on_reject: RejectMode::Error,
            }
            .into_filter(dropped)
        } else {
            dropped
        }
    }

    #[must_use]
    pub fn into_builder(self) -> ChaosBuilder {
        ChaosBuilder { config: self }
    }
}

/// Start a fluent chaos preset.
#[must_use]
pub fn chaos() -> ChaosBuilder {
    ChaosBuilder {
        config: ChaosConfig::default(),
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChaosBuilder {
    config: ChaosConfig,
}

impl ChaosBuilder {
    #[must_use]
    pub fn error(mut self, prob: f64) -> Self {
        self.config.error = prob.clamp(0.0, 1.0);
        self
    }

    #[must_use]
    pub fn drop(mut self, prob: f64) -> Self {
        self.config.drop = prob.clamp(0.0, 1.0);
        self
    }

    #[must_use]
    pub fn latency(mut self, prob: f64, ms: u64) -> Self {
        self.config.latency = LatencyFault {
            prob: prob.clamp(0.0, 1.0),
            ms,
        };
        self
    }

    #[must_use]
    pub fn corrupt(mut self, prob: f64) -> Self {
        self.config.corrupt = prob.clamp(0.0, 1.0);
        self
    }

    #[must_use]
    pub fn seed(mut self, seed: u64) -> Self {
        self.config.seed = seed;
        self
    }

    #[must_use]
    pub fn to_config(&self) -> ChaosConfig {
        self.config
    }

    #[cfg(feature = "std")]
    #[must_use]
    pub fn into_pipe(self, inner: PipeHandle) -> PipeHandle {
        self.config.into_pipe(inner)
    }
}

// `#[proxima::test]` pulls in the `proxima` dev-dependency, which the
// loom build keeps out of the graph (see
// `[target.'cfg(not(loom))'.dev-dependencies]` in Cargo.toml); these
// tests are unrelated to the Notify/watch loom protocol.
#[cfg(all(test, not(loom)))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use std::future::Future;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};

    use crate::pipe::SendPipe;
    use bytes::Bytes;
    use proxima_core::ProximaError;

    use crate::pipe::handler::into_handle;
    use crate::pipe::request::{Request, Response};

    use super::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Outcome {
        Errored,
        Dropped,
        Corrupted,
        Clean,
    }

    #[derive(Clone)]
    struct Echo {
        reached: Arc<AtomicU64>,
    }

    impl SendPipe for Echo {
        type In = Request<Bytes>;
        type Out = Response<Bytes>;
        type Err = ProximaError;

        fn call(
            &self,
            request: Request<Bytes>,
        ) -> impl Future<Output = Result<Response<Bytes>, ProximaError>> + Send {
            let reached = self.reached.clone();
            async move {
                reached.fetch_add(1, Ordering::Relaxed);
                let (_, body) = request.body_bytes().await?;
                Ok(Response::new(200).with_body(body))
            }
        }
    }

    const PAYLOAD: &[u8] = b"the quick brown fox jumps over the lazy dog";

    fn build_request() -> Request<Bytes> {
        Request::builder()
            .method("POST")
            .path("/")
            .body(Bytes::from_static(PAYLOAD))
            .build()
            .expect("builder")
    }

    async fn drive_once(pipe: &PipeHandle) -> Outcome {
        // a reject now lives entirely in the `Err` channel (no more sentinel
        // `Ok(403)`): `RejectMode::Drop` builds `ProximaError::Forbidden`,
        // `RejectMode::Error` builds `ProximaError::Config` — same two
        // observable outcomes, distinguished by which error it is.
        match SendPipe::call(pipe, build_request()).await {
            Err(ProximaError::Forbidden(_)) => Outcome::Dropped,
            Err(_) => Outcome::Errored,
            Ok(response) => {
                let body = response.collect_body().await.expect("body");
                if &body[..] == PAYLOAD {
                    Outcome::Clean
                } else {
                    Outcome::Corrupted
                }
            }
        }
    }

    async fn drive_sequence(config: ChaosConfig, count: usize) -> Vec<Outcome> {
        let pipe = config.into_pipe(into_handle(Echo {
            reached: Arc::new(AtomicU64::new(0)),
        }));
        let mut outcomes = Vec::with_capacity(count);
        for _ in 0..count {
            outcomes.push(drive_once(&pipe).await);
        }
        outcomes
    }

    #[proxima::test]
    async fn same_seed_reproduces_the_identical_fault_sequence() {
        let config = ChaosConfig {
            error: 0.2,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 5 },
            corrupt: 0.3,
            seed: 0xC0FFEE,
        };

        let first = drive_sequence(config, 200).await;
        let second = drive_sequence(config, 200).await;

        assert_eq!(
            first, second,
            "same seed must replay the identical fault sequence bit-for-bit"
        );
    }

    #[proxima::test]
    async fn a_different_seed_yields_a_different_sequence() {
        let base = ChaosConfig {
            error: 0.2,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 5 },
            corrupt: 0.3,
            seed: 1,
        };
        let other = ChaosConfig { seed: 2, ..base };

        let left = drive_sequence(base, 200).await;
        let right = drive_sequence(other, 200).await;

        assert_ne!(
            left, right,
            "a different seed must diverge somewhere in the sequence"
        );
    }

    #[proxima::test]
    async fn every_fault_type_is_reachable() {
        let config = ChaosConfig {
            error: 0.2,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 5 },
            corrupt: 0.3,
            seed: 0xABCD,
        };
        let outcomes = drive_sequence(config, 500).await;

        assert!(
            outcomes.contains(&Outcome::Errored),
            "error fault must be reachable"
        );
        assert!(
            outcomes.contains(&Outcome::Dropped),
            "drop fault must be reachable"
        );
        assert!(
            outcomes.contains(&Outcome::Corrupted),
            "corrupt fault must be reachable"
        );
        assert!(
            outcomes.contains(&Outcome::Clean),
            "a clean pass-through must be reachable"
        );
    }

    #[proxima::test]
    async fn an_all_default_preset_is_a_transparent_pass_through() {
        let reached = Arc::new(AtomicU64::new(0));
        let pipe = ChaosConfig::default().into_pipe(into_handle(Echo {
            reached: reached.clone(),
        }));

        for _ in 0..32 {
            assert_eq!(
                drive_once(&pipe).await,
                Outcome::Clean,
                "default chaos never injects a fault"
            );
        }
        assert_eq!(
            reached.load(Ordering::Relaxed),
            32,
            "every call reaches the inner pipe untouched"
        );
    }

    #[proxima::test]
    async fn error_only_preset_short_circuits_before_the_inner_pipe() {
        let reached = Arc::new(AtomicU64::new(0));
        let config = ChaosConfig {
            error: 1.0,
            seed: 7,
            ..ChaosConfig::default()
        };
        let pipe = config.into_pipe(into_handle(Echo {
            reached: reached.clone(),
        }));

        for _ in 0..16 {
            assert_eq!(
                drive_once(&pipe).await,
                Outcome::Errored,
                "prob 1.0 error fires every call"
            );
        }
        assert_eq!(
            reached.load(Ordering::Relaxed),
            0,
            "an injected error never reaches the inner pipe"
        );
    }

    #[test]
    fn fluent_builder_matches_the_config() {
        let built = chaos()
            .error(0.1)
            .drop(0.2)
            .latency(0.3, 25)
            .corrupt(0.4)
            .seed(0xC0FFEE)
            .to_config();

        let expected = ChaosConfig {
            error: 0.1,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 25 },
            corrupt: 0.4,
            seed: 0xC0FFEE,
        };
        assert_eq!(
            built, expected,
            "the fluent builder produces the same config"
        );
    }

    #[test]
    fn config_builder_round_trip_parity() {
        let config = ChaosConfig {
            error: 0.1,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 25 },
            corrupt: 0.4,
            seed: 0xC0FFEE,
        };

        let back = config.into_builder().to_config();
        let json = serde_json::to_value(config).expect("serialize");
        let parsed: ChaosConfig = serde_json::from_value(json).expect("deserialize");

        assert_eq!(
            back, config,
            "builder projects back to the originating config"
        );
        assert_eq!(parsed, config, "serde round-trip is lossless");
    }

    #[test]
    fn omitted_fields_default_off() {
        let value = serde_json::json!({ "seed": 99 });
        let config: ChaosConfig = serde_json::from_value(value).expect("deserialize");
        assert_eq!(
            config,
            ChaosConfig {
                seed: 99,
                ..ChaosConfig::default()
            },
            "absent faults default off"
        );
    }

    #[proxima::test]
    async fn fluent_and_config_expand_to_the_same_sequence() {
        let config = ChaosConfig {
            error: 0.2,
            drop: 0.2,
            latency: LatencyFault { prob: 0.3, ms: 5 },
            corrupt: 0.3,
            seed: 0x5EED,
        };
        let from_config = drive_sequence(config, 128).await;
        let from_fluent = drive_sequence(config.into_builder().to_config(), 128).await;
        assert_eq!(
            from_config, from_fluent,
            "both surfaces expand to the identical fault sequence"
        );
    }
}