s2n-quic-dc 0.87.0

Internal crate used by s2n-quic
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use crate::stream::testing;
use bolero::TypeGenerator;
use core::time::Duration;
use s2n_quic_core::stream::testing::Data;
use std::{io, panic::AssertUnwindSafe, sync::Arc};
use tokio::{
    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
    time::timeout,
};
use tracing::{info_span, Instrument};

#[derive(Clone, Debug, TypeGenerator)]
pub struct PairOp {
    pub server: Vec<StreamOp>,
    pub client: Vec<StreamOp>,
}

#[derive(Clone, Copy, Debug, TypeGenerator)]
pub enum StreamOp {
    Reader(ReaderOp),
    Writer(WriterOp),
    Sleep(#[generator(0..=100)] u8),
}

#[derive(Clone, Copy, Debug, TypeGenerator)]
pub enum ReaderOp {
    Read(u16),
    Drop { panic: bool },
}

impl ReaderOp {
    async fn apply<R: AsyncRead + Unpin>(
        &self,
        reader: &mut R,
        data: &mut Data,
        buffer: &mut [u8],
    ) -> io::Result<()> {
        match self {
            Self::Read(amount) => {
                let mut remaining = *amount as usize;
                loop {
                    let buffer_len = buffer.len().min(remaining);
                    let buffer = &mut buffer[..buffer_len];

                    let len = reader.read(buffer).await?;

                    // EOF
                    if len == 0 {
                        break;
                    }

                    data.receive(&[&buffer[..len]]);

                    remaining -= len;

                    if remaining == 0 {
                        break;
                    }
                }
                Ok(())
            }
            Self::Drop { .. } => {
                // no-op
                Ok(())
            }
        }
    }
}

#[derive(Clone, Copy, Debug, TypeGenerator)]
pub enum WriterOp {
    Write(u16),
    Shutdown,
    Drop { panic: bool },
}

impl WriterOp {
    async fn apply<W: AsyncWrite + Unpin>(
        &self,
        writer: &mut W,
        data: &mut Data,
    ) -> io::Result<()> {
        match self {
            Self::Write(amount) => {
                let mut chunks = [Default::default(), Default::default()];
                let chunk_len = data.send(*amount as usize, &mut chunks).unwrap();
                for chunk in &chunks[..chunk_len] {
                    writer.write_all(chunk).await?;
                }
                Ok(())
            }
            Self::Shutdown => writer.shutdown().await,
            Self::Drop { .. } => {
                // no-op
                Ok(())
            }
        }
    }
}

fn drop_while_panicking<T: 'static + Send>(value: T) {
    let value = AssertUnwindSafe(value);

    let _ = std::panic::catch_unwind(move || {
        let _value = value;
        // use resume_unwind instead of `panic` to avoid invoking the panic hook
        std::panic::resume_unwind(Box::new(()));
    });
}

pub struct Split<R, W>
where
    R: AsyncRead + Send + Unpin + 'static,
    W: AsyncWrite + Send + Unpin + 'static,
{
    reader: Option<R>,
    reader_data: Data,
    reader_buffer: Vec<u8>,
    writer: Option<W>,
    writer_data: Data,
}

impl<R, W> Split<R, W>
where
    R: AsyncRead + Send + Unpin + 'static,
    W: AsyncWrite + Send + Unpin + 'static,
{
    pub fn new(reader: R, writer: W) -> Self {
        Self {
            reader: Some(reader),
            reader_data: Data::new(u64::MAX),
            reader_buffer: vec![0u8; u16::MAX as _],
            writer: Some(writer),
            writer_data: Data::new(u64::MAX),
        }
    }

    pub async fn apply_all(&mut self, ops: &[StreamOp]) -> Result<outcome::Stats, outcome::Error> {
        for (op_index, op) in ops.iter().enumerate() {
            self.apply(op).await.map_err(|err| outcome::Error::Io {
                op_index,
                kind: err.kind(),
            })?;
        }
        let recv = self.reader_data.offset();
        let send = self.writer_data.offset();
        Ok(outcome::Stats { recv, send })
    }

    pub async fn apply(&mut self, op: &StreamOp) -> io::Result<()> {
        tracing::debug!(?op);
        match op {
            StreamOp::Reader(ReaderOp::Drop { panic }) => {
                if let Some(reader) = self.reader.take().filter(|_| *panic) {
                    drop_while_panicking(reader);
                }
            }
            StreamOp::Reader(op) => {
                if let Some(reader) = self.reader.as_mut() {
                    return op
                        .apply(reader, &mut self.reader_data, &mut self.reader_buffer)
                        .await;
                }
            }
            StreamOp::Writer(WriterOp::Drop { panic }) => {
                if let Some(writer) = self.writer.take().filter(|_| *panic) {
                    drop_while_panicking(writer);
                }
            }
            StreamOp::Writer(op) => {
                if let Some(writer) = self.writer.as_mut() {
                    return op.apply(writer, &mut self.writer_data).await;
                }
            }
            StreamOp::Sleep(ms) => {
                tokio::time::sleep(Duration::from_millis(*ms as _)).await;
            }
        }

        Ok(())
    }
}

pub trait StreamExt {
    type Reader: AsyncRead + Send + Unpin + 'static;
    type Writer: AsyncWrite + Send + Unpin + 'static;

    fn into_ops(self) -> Split<Self::Reader, Self::Writer>;
}

impl StreamExt for testing::tcp::Stream {
    type Reader = tokio::net::tcp::OwnedReadHalf;
    type Writer = tokio::net::tcp::OwnedWriteHalf;

    fn into_ops(self) -> Split<Self::Reader, Self::Writer> {
        let (reader, writer) = self.into_split();
        Split::new(reader, writer)
    }
}

impl StreamExt for crate::stream::application::Stream<crate::testing::NoopSubscriber> {
    type Reader = crate::stream::recv::application::Reader<crate::testing::NoopSubscriber>;
    type Writer = crate::stream::send::application::Writer<crate::testing::NoopSubscriber>;

    fn into_ops(self) -> Split<Self::Reader, Self::Writer> {
        let (reader, writer) = self.into_split();
        Split::new(reader, writer)
    }
}

struct Context {
    runtime: tokio::runtime::Runtime,
    tcp: Arc<testing::tcp::Context>,
    dcquic_tcp: Arc<AssertUnwindSafe<testing::dcquic::tcp::Context>>,
    dcquic_tcp_enabled: bool,
    dcquic_udp: Arc<AssertUnwindSafe<testing::dcquic::udp::Context>>,
    dcquic_udp_enabled: bool,
}

impl Default for Context {
    fn default() -> Self {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .unwrap();

        let (tcp, dcquic_tcp, dcquic_udp) = runtime.block_on(async {
            (
                Arc::new(testing::tcp::Context::new().await),
                Arc::new(AssertUnwindSafe(testing::dcquic::tcp::Context::new().await)),
                Arc::new(AssertUnwindSafe(testing::dcquic::udp::Context::new().await)),
            )
        });

        let protocols = std::env::var("DIFFERENTIAL_PROTOCOLS").unwrap_or_default();
        let protocols: Vec<_> = protocols.split(',').filter(|v| !v.is_empty()).collect();

        let dcquic_tcp_enabled = protocols.is_empty() || protocols.contains(&"tcp");
        let dcquic_udp_enabled = protocols.is_empty() || protocols.contains(&"udp");

        assert!(
            dcquic_tcp_enabled || dcquic_udp_enabled,
            "dcquic (either TCP or UDP) needs to be enabled for the test"
        );

        Self {
            runtime,
            tcp,
            dcquic_tcp,
            dcquic_tcp_enabled,
            dcquic_udp,
            dcquic_udp_enabled,
        }
    }
}

pub mod outcome {
    pub type Endpoint = Result<Result<Stats, Error>, Error>;

    pub type Outcome = Result<Endpoints, Error>;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    #[must_use]
    pub struct Endpoints {
        pub client: Endpoint,
        pub server: Endpoint,
    }

    impl Endpoints {
        pub fn did_panic(&self) -> bool {
            let Self { client, server } = self;

            [client, server]
                .iter()
                .filter_map(|res| res.err())
                .any(|err| matches!(err, Error::Panic))
        }
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Stats {
        pub recv: u64,
        pub send: u64,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum Error {
        Panic,
        Timeout,
        Io {
            op_index: usize,
            kind: std::io::ErrorKind,
        },
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    #[must_use]
    pub struct Set {
        pub tcp: Outcome,
        pub dcquic_tcp: Option<Outcome>,
        pub dcquic_udp: Option<Outcome>,
    }

    impl Set {
        pub fn unwrap(self) -> Outcome {
            self.assert_ok();
            self.tcp
        }

        pub fn log_err(&self, input: &super::PairOp) {
            if !self.is_ok() {
                tracing::error!("{input:#?}\nPRODUCED: {:#?}", self);
            }
        }

        pub fn assert_ok(&self) {
            assert!(self.is_ok(), "{self:#?}");
        }

        pub fn is_ok(&self) -> bool {
            let Self {
                tcp,
                dcquic_tcp,
                dcquic_udp,
            } = self;

            // the task should never panic
            let mut matches = !self.did_panic();

            for outcome in [dcquic_tcp, dcquic_udp].into_iter().flatten() {
                matches &= tcp == outcome;
            }

            matches
        }

        pub fn did_panic(&self) -> bool {
            let Self {
                tcp,
                dcquic_tcp,
                dcquic_udp,
            } = self;

            [dcquic_tcp, dcquic_udp]
                .into_iter()
                .flatten()
                .chain(core::iter::once(tcp))
                .any(|outcome| match outcome {
                    Ok(endpoint) => endpoint.did_panic(),
                    Err(err) => matches!(err, Error::Panic),
                })
        }
    }
}

impl Context {
    pub fn run(&self, pair: &PairOp) -> outcome::Set {
        let client_ops = Arc::new(pair.client.clone());
        let server_ops = Arc::new(pair.server.clone());

        async fn apply<S: StreamExt>(
            stream: S,
            ops: Arc<Vec<StreamOp>>,
        ) -> Result<outcome::Stats, outcome::Error> {
            let mut stream = stream.into_ops();
            let stream = stream.apply_all(&ops);
            let stream = timeout(Duration::from_secs(5), stream);

            stream
                .await
                .map_err(|_| outcome::Error::Timeout)
                .and_then(|res| res)
        }

        macro_rules! run {
            ($context:ident) => {{
                let context = self.$context.clone();
                let client_ops = client_ops.clone();
                let server_ops = server_ops.clone();

                let task = tokio::spawn(
                    async move {
                        tracing::trace!(stringify!($context));

                        let (client, server) = context.pair().await;

                        let client = tokio::spawn(
                            apply(client, client_ops).instrument(info_span!("client")),
                        );

                        let server = tokio::spawn(
                            apply(server, server_ops).instrument(info_span!("server")),
                        );

                        let client = client.await.map_err(|_err| outcome::Error::Panic);
                        let server = server.await.map_err(|_err| outcome::Error::Panic);

                        outcome::Endpoints { client, server }
                    }
                    .instrument(info_span!(stringify!($context))),
                );

                async move { task.await.map_err(|_| outcome::Error::Panic) }
            }};
            ($context:ident, $enabled:expr) => {{
                let task = if $enabled { Some(run!($context)) } else { None };

                async move {
                    if let Some(task) = task {
                        Some(task.await)
                    } else {
                        None
                    }
                }
            }};
        }

        self.runtime.block_on(async {
            let tcp = run!(tcp);
            let dcquic_tcp = run!(dcquic_tcp, self.dcquic_tcp_enabled);
            let dcquic_udp = run!(dcquic_udp, self.dcquic_udp_enabled);

            let tcp = tcp.await;
            let dcquic_tcp = dcquic_tcp.await;
            let dcquic_udp = dcquic_udp.await;

            outcome::Set {
                tcp,
                dcquic_tcp,
                dcquic_udp,
            }
        })
    }
}

/// NOTE: because the runtime is created outside of the test, ASAN will detect leaks with this
/// test. These checks need to be disabled by setting `env ASAN_OPTIONS=detect_leaks=0`.
#[test]
#[cfg_attr(not(fuzzing), ignore = "several differences need to be addressed")]
fn test() {
    let find_panics = std::env::var("DIFFERENTIAL_PANIC_ONLY").is_ok();
    let print_errors = std::env::var("DIFFERENTIAL_PRINT_ERRORS").is_ok();

    let context = Context::default();

    bolero::check!()
        .with_type::<PairOp>()
        .with_shrink_time(Duration::from_secs(60))
        .with_test_time(Duration::from_secs(60))
        .for_each(|pair| {
            let outcome = context.run(pair);

            // if we're only looking for panics then just check that
            if find_panics {
                assert!(!outcome.did_panic(), "{outcome:#?}");
                return;
            }

            // if we're wanting to explore any errors then print and keep going
            if print_errors {
                outcome.log_err(pair);
                return;
            }

            // otherwise assert the outcome is correct
            outcome.assert_ok();
        });
}

#[test]
fn request_response_test() {
    let context = Context::default();

    // overread by one byte. otherwise, the OS scheduler may let the socket close
    // before the peer gets a chance to call `shutdown`.
    let overread = 1;

    let ops = PairOp {
        server: vec![
            StreamOp::Reader(ReaderOp::Read(100 + overread)),
            StreamOp::Writer(WriterOp::Write(200)),
            StreamOp::Writer(WriterOp::Shutdown),
        ],
        client: vec![
            StreamOp::Writer(WriterOp::Write(100)),
            StreamOp::Writer(WriterOp::Shutdown),
            StreamOp::Reader(ReaderOp::Read(200 + overread)),
        ],
    };

    let outcome = context.run(&ops);

    insta::assert_debug_snapshot!(outcome.unwrap());
}