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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
use crate::{
    error::ProtocolError,
    event::ProtocolEvent,
    frame::{ITFrame, InitFrame, OTFrame},
    handshake::{ReliableDrain, ReliableSink},
    message::{ITMessage, ALLOC_BLOCK},
    metrics::{ProtocolMetricCache, RemoveReason},
    prio::PrioManager,
    types::{Bandwidth, Mid, Promises, Sid},
    util::SortedVec,
    RecvProtocol, SendProtocol, UnreliableDrain, UnreliableSink,
};
use async_trait::async_trait;
use bytes::BytesMut;
use hashbrown::HashMap;
use std::time::{Duration, Instant};
use tracing::info;
#[cfg(feature = "trace_pedantic")]
use tracing::trace;

#[derive(PartialEq, Eq)]
pub enum QuicDataFormatStream {
    Main,
    Reliable(Sid),
    Unreliable,
}

pub struct QuicDataFormat {
    pub stream: QuicDataFormatStream,
    pub data: BytesMut,
}

impl QuicDataFormat {
    fn with_main(buffer: &mut BytesMut) -> Self {
        Self {
            stream: QuicDataFormatStream::Main,
            data: buffer.split(),
        }
    }

    fn with_reliable(buffer: &mut BytesMut, sid: Sid) -> Self {
        Self {
            stream: QuicDataFormatStream::Reliable(sid),
            data: buffer.split(),
        }
    }

    fn with_unreliable(frame: OTFrame) -> Self {
        let mut buffer = BytesMut::new();
        frame.write_bytes(&mut buffer);
        Self {
            stream: QuicDataFormatStream::Unreliable,
            data: buffer,
        }
    }
}

/// QUIC implementation of [`SendProtocol`]
///
/// [`SendProtocol`]: crate::SendProtocol
#[derive(Debug)]
pub struct QuicSendProtocol<D>
where
    D: UnreliableDrain<DataFormat = QuicDataFormat>,
{
    main_buffer: BytesMut,
    reliable_buffers: SortedVec<Sid, BytesMut>,
    store: PrioManager,
    next_mid: Mid,
    closing_streams: Vec<Sid>,
    notify_closing_streams: Vec<Sid>,
    pending_shutdown: bool,
    drain: D,
    #[allow(dead_code)]
    last: Instant,
    metrics: ProtocolMetricCache,
}

/// QUIC implementation of [`RecvProtocol`]
///
/// [`RecvProtocol`]: crate::RecvProtocol
#[derive(Debug)]
pub struct QuicRecvProtocol<S>
where
    S: UnreliableSink<DataFormat = QuicDataFormat>,
{
    main_buffer: BytesMut,
    unreliable_buffer: BytesMut,
    reliable_buffers: SortedVec<Sid, BytesMut>,
    pending_reliable_buffers: Vec<(Sid, BytesMut)>,
    itmsg_allocator: BytesMut,
    incoming: HashMap<Mid, ITMessage>,
    sink: S,
    metrics: ProtocolMetricCache,
}

fn is_reliable(p: &Promises) -> bool {
    p.contains(Promises::ORDERED)
        || p.contains(Promises::CONSISTENCY)
        || p.contains(Promises::GUARANTEED_DELIVERY)
}

impl<D> QuicSendProtocol<D>
where
    D: UnreliableDrain<DataFormat = QuicDataFormat>,
{
    pub fn new(drain: D, metrics: ProtocolMetricCache) -> Self {
        Self {
            main_buffer: BytesMut::new(),
            reliable_buffers: SortedVec::default(),
            store: PrioManager::new(metrics.clone()),
            next_mid: 0u64,
            closing_streams: vec![],
            notify_closing_streams: vec![],
            pending_shutdown: false,
            drain,
            last: Instant::now(),
            metrics,
        }
    }

    /// returns all promises that this Protocol can take care of
    /// If you open a Stream anyway, unsupported promises are ignored.
    pub fn supported_promises() -> Promises {
        Promises::ORDERED
            | Promises::CONSISTENCY
            | Promises::GUARANTEED_DELIVERY
            | Promises::COMPRESSED
            | Promises::ENCRYPTED
    }
}

impl<S> QuicRecvProtocol<S>
where
    S: UnreliableSink<DataFormat = QuicDataFormat>,
{
    pub fn new(sink: S, metrics: ProtocolMetricCache) -> Self {
        Self {
            main_buffer: BytesMut::new(),
            unreliable_buffer: BytesMut::new(),
            reliable_buffers: SortedVec::default(),
            pending_reliable_buffers: vec![],
            itmsg_allocator: BytesMut::with_capacity(ALLOC_BLOCK),
            incoming: HashMap::new(),
            sink,
            metrics,
        }
    }

    async fn recv_into_stream(
        &mut self,
    ) -> Result<QuicDataFormatStream, ProtocolError<S::CustomErr>> {
        let chunk = self.sink.recv().await?;
        let buffer = match chunk.stream {
            QuicDataFormatStream::Main => &mut self.main_buffer,
            QuicDataFormatStream::Unreliable => &mut self.unreliable_buffer,
            QuicDataFormatStream::Reliable(id) => {
                match self.reliable_buffers.get_mut(&id) {
                    Some(buffer) => buffer,
                    None => {
                        self.pending_reliable_buffers.push((id, BytesMut::new()));
                        //Violated but will never happen
                        &mut self
                            .pending_reliable_buffers
                            .last_mut()
                            .ok_or(ProtocolError::Violated)?
                            .1
                    },
                }
            },
        };
        if buffer.is_empty() {
            *buffer = chunk.data
        } else {
            buffer.extend_from_slice(&chunk.data)
        }
        Ok(chunk.stream)
    }
}

#[async_trait]
impl<D> SendProtocol for QuicSendProtocol<D>
where
    D: UnreliableDrain<DataFormat = QuicDataFormat>,
{
    type CustomErr = D::CustomErr;

    fn notify_from_recv(&mut self, event: ProtocolEvent) {
        match event {
            ProtocolEvent::OpenStream {
                sid,
                prio,
                promises,
                guaranteed_bandwidth,
            } => {
                self.store
                    .open_stream(sid, prio, promises, guaranteed_bandwidth);
                if is_reliable(&promises) {
                    self.reliable_buffers.insert(sid, BytesMut::new());
                }
            },
            ProtocolEvent::CloseStream { sid } => {
                if !self.store.try_close_stream(sid) {
                    #[cfg(feature = "trace_pedantic")]
                    trace!(?sid, "hold back notify close stream");
                    self.notify_closing_streams.push(sid);
                }
            },
            _ => {},
        }
    }

    async fn send(&mut self, event: ProtocolEvent) -> Result<(), ProtocolError<Self::CustomErr>> {
        #[cfg(feature = "trace_pedantic")]
        trace!(?event, "send");
        match event {
            ProtocolEvent::OpenStream {
                sid,
                prio,
                promises,
                guaranteed_bandwidth,
            } => {
                self.store
                    .open_stream(sid, prio, promises, guaranteed_bandwidth);
                if is_reliable(&promises) {
                    self.reliable_buffers.insert(sid, BytesMut::new());
                    //Send a empty message to notify local drain of stream
                    self.drain
                        .send(QuicDataFormat::with_reliable(&mut BytesMut::new(), sid))
                        .await?;
                }
                event.to_frame().write_bytes(&mut self.main_buffer);
                self.drain
                    .send(QuicDataFormat::with_main(&mut self.main_buffer))
                    .await?;
            },
            ProtocolEvent::CloseStream { sid } => {
                if self.store.try_close_stream(sid) {
                    let _ = self.reliable_buffers.delete(&sid); //delete if it was reliable
                    event.to_frame().write_bytes(&mut self.main_buffer);
                    self.drain
                        .send(QuicDataFormat::with_main(&mut self.main_buffer))
                        .await?;
                } else {
                    #[cfg(feature = "trace_pedantic")]
                    trace!(?sid, "hold back close stream");
                    self.closing_streams.push(sid);
                }
            },
            ProtocolEvent::Shutdown => {
                if self.store.is_empty() {
                    event.to_frame().write_bytes(&mut self.main_buffer);
                    self.drain
                        .send(QuicDataFormat::with_main(&mut self.main_buffer))
                        .await?;
                } else {
                    #[cfg(feature = "trace_pedantic")]
                    trace!("hold back shutdown");
                    self.pending_shutdown = true;
                }
            },
            ProtocolEvent::Message { data, sid } => {
                self.metrics.smsg_ib(sid, data.len() as u64);
                self.store.add(data, self.next_mid, sid);
                self.next_mid += 1;
            },
        }
        Ok(())
    }

    async fn flush(
        &mut self,
        bandwidth: Bandwidth,
        dt: Duration,
    ) -> Result</* actual */ Bandwidth, ProtocolError<Self::CustomErr>> {
        let (frames, _) = self.store.grab(bandwidth, dt);
        //Todo: optimize reserve
        let mut data_frames = 0;
        let mut data_bandwidth = 0;
        for (sid, frame) in frames {
            if let OTFrame::Data { mid: _, data } = &frame {
                data_bandwidth += data.len();
                data_frames += 1;
            }
            match self.reliable_buffers.get_mut(&sid) {
                Some(buffer) => frame.write_bytes(buffer),
                None => {
                    self.drain
                        .send(QuicDataFormat::with_unreliable(frame))
                        .await?
                },
            }
        }
        for (sid, buffer) in self.reliable_buffers.data.iter_mut() {
            if !buffer.is_empty() {
                self.drain
                    .send(QuicDataFormat::with_reliable(buffer, *sid))
                    .await?;
            }
        }
        self.metrics
            .sdata_frames_b(data_frames, data_bandwidth as u64);

        let mut finished_streams = vec![];
        for (i, &sid) in self.closing_streams.iter().enumerate() {
            if self.store.try_close_stream(sid) {
                #[cfg(feature = "trace_pedantic")]
                trace!(?sid, "close stream, as it's now empty");
                OTFrame::CloseStream { sid }.write_bytes(&mut self.main_buffer);
                self.drain
                    .send(QuicDataFormat::with_main(&mut self.main_buffer))
                    .await?;
                finished_streams.push(i);
            }
        }
        for i in finished_streams.iter().rev() {
            self.closing_streams.remove(*i);
        }

        let mut finished_streams = vec![];
        for (i, sid) in self.notify_closing_streams.iter().enumerate() {
            if self.store.try_close_stream(*sid) {
                #[cfg(feature = "trace_pedantic")]
                trace!(?sid, "close stream, as it's now empty");
                finished_streams.push(i);
            }
        }
        for i in finished_streams.iter().rev() {
            self.notify_closing_streams.remove(*i);
        }

        if self.pending_shutdown && self.store.is_empty() {
            #[cfg(feature = "trace_pedantic")]
            trace!("shutdown, as it's now empty");
            OTFrame::Shutdown {}.write_bytes(&mut self.main_buffer);
            self.drain
                .send(QuicDataFormat::with_main(&mut self.main_buffer))
                .await?;
            self.pending_shutdown = false;
        }
        Ok(data_bandwidth as u64)
    }
}

#[async_trait]
impl<S> RecvProtocol for QuicRecvProtocol<S>
where
    S: UnreliableSink<DataFormat = QuicDataFormat>,
{
    type CustomErr = S::CustomErr;

    async fn recv(&mut self) -> Result<ProtocolEvent, ProtocolError<Self::CustomErr>> {
        'outer: loop {
            match ITFrame::read_frame(&mut self.main_buffer) {
                Ok(Some(frame)) => {
                    #[cfg(feature = "trace_pedantic")]
                    trace!(?frame, "recv");
                    match frame {
                        ITFrame::Shutdown => break 'outer Ok(ProtocolEvent::Shutdown),
                        ITFrame::OpenStream {
                            sid,
                            prio,
                            promises,
                            guaranteed_bandwidth,
                        } => {
                            if is_reliable(&promises) {
                                self.reliable_buffers.insert(sid, BytesMut::new());
                            }
                            break 'outer Ok(ProtocolEvent::OpenStream {
                                sid,
                                prio: prio.min(crate::types::HIGHEST_PRIO),
                                promises,
                                guaranteed_bandwidth,
                            });
                        },
                        ITFrame::CloseStream { sid } => {
                            //FIXME: defer close!
                            //let _ = self.reliable_buffers.delete(sid); // if it was reliable
                            break 'outer Ok(ProtocolEvent::CloseStream { sid });
                        },
                        _ => break 'outer Err(ProtocolError::Violated),
                    };
                },
                Ok(None) => {},
                Err(()) => return Err(ProtocolError::Violated),
            }

            // try to order pending
            let mut pending_violated = false;
            let mut reliable = vec![];

            self.pending_reliable_buffers.retain(|(_, buffer)| {
                // try to get Sid without touching buffer
                let mut testbuffer = buffer.clone();
                match ITFrame::read_frame(&mut testbuffer) {
                    Ok(Some(ITFrame::DataHeader {
                        sid,
                        mid: _,
                        length: _,
                    })) => {
                        reliable.push((sid, buffer.clone()));
                        false
                    },
                    Ok(Some(_)) | Err(_) => {
                        pending_violated = true;
                        false
                    },
                    Ok(None) => true,
                }
            });

            if pending_violated {
                break 'outer Err(ProtocolError::Violated);
            }
            for (sid, buffer) in reliable.into_iter() {
                self.reliable_buffers.insert(sid, buffer)
            }

            let mut iter = self
                .reliable_buffers
                .data
                .iter_mut()
                .map(|(_, b)| (b, true))
                .collect::<Vec<_>>();
            iter.push((&mut self.unreliable_buffer, false));

            for (buffer, reliable) in iter {
                loop {
                    match ITFrame::read_frame(buffer) {
                        Ok(Some(frame)) => {
                            #[cfg(feature = "trace_pedantic")]
                            trace!(?frame, "recv");
                            match frame {
                                ITFrame::DataHeader { sid, mid, length } => {
                                    let m = ITMessage::new(sid, length, &mut self.itmsg_allocator);
                                    self.metrics.rmsg_ib(sid, length);
                                    self.incoming.insert(mid, m);
                                },
                                ITFrame::Data { mid, data } => {
                                    self.metrics.rdata_frames_b(data.len() as u64);
                                    let m = match self.incoming.get_mut(&mid) {
                                        Some(m) => m,
                                        None => {
                                            if reliable {
                                                info!(
                                                    ?mid,
                                                    "protocol violation by remote side: send Data \
                                                     before Header"
                                                );
                                                break 'outer Err(ProtocolError::Violated);
                                            } else {
                                                //TODO: cleanup old messages from time to time
                                                continue;
                                            }
                                        },
                                    };
                                    m.data.extend_from_slice(&data);
                                    if m.data.len() == m.length as usize {
                                        // finished, yay
                                        let m = self
                                            .incoming
                                            .remove(&mid)
                                            .ok_or(ProtocolError::Violated)?;
                                        self.metrics.rmsg_ob(
                                            m.sid,
                                            RemoveReason::Finished,
                                            m.data.len() as u64,
                                        );
                                        break 'outer Ok(ProtocolEvent::Message {
                                            sid: m.sid,
                                            data: m.data.freeze(),
                                        });
                                    }
                                },
                                _ => break 'outer Err(ProtocolError::Violated),
                            };
                        },
                        Ok(None) => break, //inner => read more data
                        Err(()) => return Err(ProtocolError::Violated),
                    }
                }
            }

            self.recv_into_stream().await?;
        }
    }
}

#[async_trait]
impl<D> ReliableDrain for QuicSendProtocol<D>
where
    D: UnreliableDrain<DataFormat = QuicDataFormat>,
{
    type CustomErr = D::CustomErr;

    async fn send(&mut self, frame: InitFrame) -> Result<(), ProtocolError<Self::CustomErr>> {
        self.main_buffer.reserve(500);
        frame.write_bytes(&mut self.main_buffer);
        self.drain
            .send(QuicDataFormat::with_main(&mut self.main_buffer))
            .await
    }
}

#[async_trait]
impl<S> ReliableSink for QuicRecvProtocol<S>
where
    S: UnreliableSink<DataFormat = QuicDataFormat>,
{
    type CustomErr = S::CustomErr;

    async fn recv(&mut self) -> Result<InitFrame, ProtocolError<Self::CustomErr>> {
        while self.main_buffer.len() < 100 {
            if self.recv_into_stream().await? == QuicDataFormatStream::Main {
                if let Some(frame) = InitFrame::read_frame(&mut self.main_buffer) {
                    return Ok(frame);
                }
            }
        }
        Err(ProtocolError::Violated)
    }
}

#[cfg(test)]
mod test_utils {
    //Quic protocol based on Channel
    use super::*;
    use crate::metrics::{ProtocolMetricCache, ProtocolMetrics};
    use async_channel::*;
    use std::sync::Arc;

    pub struct QuicDrain {
        pub sender: Sender<QuicDataFormat>,
        pub drop_ratio: f32,
    }

    pub struct QuicSink {
        pub receiver: Receiver<QuicDataFormat>,
    }

    /// emulate Quic protocol on Channels
    pub fn quic_bound(
        cap: usize,
        drop_ratio: f32,
        metrics: Option<ProtocolMetricCache>,
    ) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
        let (s1, r1) = bounded(cap);
        let (s2, r2) = bounded(cap);
        let m = metrics.unwrap_or_else(|| {
            ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
        });
        [
            (
                QuicSendProtocol::new(
                    QuicDrain {
                        sender: s1,
                        drop_ratio,
                    },
                    m.clone(),
                ),
                QuicRecvProtocol::new(QuicSink { receiver: r2 }, m.clone()),
            ),
            (
                QuicSendProtocol::new(
                    QuicDrain {
                        sender: s2,
                        drop_ratio,
                    },
                    m.clone(),
                ),
                QuicRecvProtocol::new(QuicSink { receiver: r1 }, m),
            ),
        ]
    }

    #[async_trait]
    impl UnreliableDrain for QuicDrain {
        type CustomErr = ();
        type DataFormat = QuicDataFormat;

        async fn send(
            &mut self,
            data: Self::DataFormat,
        ) -> Result<(), ProtocolError<Self::CustomErr>> {
            use rand::Rng;
            if matches!(data.stream, QuicDataFormatStream::Unreliable)
                && rand::thread_rng().gen::<f32>() < self.drop_ratio
            {
                return Ok(());
            }
            self.sender
                .send(data)
                .await
                .map_err(|_| ProtocolError::Custom(()))
        }
    }

    #[async_trait]
    impl UnreliableSink for QuicSink {
        type CustomErr = ();
        type DataFormat = QuicDataFormat;

        async fn recv(&mut self) -> Result<Self::DataFormat, ProtocolError<Self::CustomErr>> {
            self.receiver
                .recv()
                .await
                .map_err(|_| ProtocolError::Custom(()))
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        error::ProtocolError,
        frame::OTFrame,
        metrics::{ProtocolMetricCache, ProtocolMetrics, RemoveReason},
        quic::{test_utils::*, QuicDataFormat},
        types::{Pid, Promises, Sid, STREAM_ID_OFFSET1, STREAM_ID_OFFSET2},
        InitProtocol, ProtocolEvent, RecvProtocol, SendProtocol,
    };
    use bytes::{Bytes, BytesMut};
    use std::{sync::Arc, time::Duration};

    #[tokio::test]
    async fn handshake_all_good() {
        let [mut p1, mut p2] = quic_bound(10, 0.5, None);
        let r1 = tokio::spawn(async move { p1.initialize(true, Pid::fake(2), 1337).await });
        let r2 = tokio::spawn(async move { p2.initialize(false, Pid::fake(3), 42).await });
        let (r1, r2) = tokio::join!(r1, r2);
        assert_eq!(r1.unwrap(), Ok((Pid::fake(3), STREAM_ID_OFFSET1, 42)));
        assert_eq!(r2.unwrap(), Ok((Pid::fake(2), STREAM_ID_OFFSET2, 1337)));
    }

    #[tokio::test]
    async fn open_stream() {
        let [p1, p2] = quic_bound(10, 0.5, None);
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid: Sid::new(10),
            prio: 0u8,
            promises: Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        };
        s.send(event.clone()).await.unwrap();
        let e = r.recv().await.unwrap();
        assert_eq!(event, e);
    }

    #[tokio::test]
    async fn send_short_msg() {
        let [p1, p2] = quic_bound(10, 0.5, None);
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid: Sid::new(10),
            prio: 3u8,
            promises: Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        };
        s.send(event).await.unwrap();
        let _ = r.recv().await.unwrap();
        let event = ProtocolEvent::Message {
            sid: Sid::new(10),
            data: Bytes::from(&[188u8; 600][..]),
        };
        s.send(event.clone()).await.unwrap();
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert_eq!(event, e);
        // 2nd short message
        let event = ProtocolEvent::Message {
            sid: Sid::new(10),
            data: Bytes::from(&[7u8; 30][..]),
        };
        s.send(event.clone()).await.unwrap();
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert_eq!(event, e)
    }

    #[tokio::test]
    async fn send_long_msg() {
        let mut metrics =
            ProtocolMetricCache::new("long_quic", Arc::new(ProtocolMetrics::new().unwrap()));
        let sid = Sid::new(1);
        let [p1, p2] = quic_bound(10000, 0.5, Some(metrics.clone()));
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED | Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        };
        s.send(event).await.unwrap();
        let _ = r.recv().await.unwrap();
        let event = ProtocolEvent::Message {
            sid,
            data: Bytes::from(&[99u8; 500_000][..]),
        };
        s.send(event.clone()).await.unwrap();
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert_eq!(event, e);
        metrics.assert_msg(sid, 1, RemoveReason::Finished);
        metrics.assert_msg_bytes(sid, 500_000, RemoveReason::Finished);
        metrics.assert_data_frames(358);
        metrics.assert_data_frames_bytes(500_000);
    }

    #[tokio::test]
    async fn msg_finishes_after_close() {
        let sid = Sid::new(1);
        let [p1, p2] = quic_bound(10000, 0.5, None);
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED | Promises::ORDERED,
            guaranteed_bandwidth: 0,
        };
        s.send(event).await.unwrap();
        let _ = r.recv().await.unwrap();
        let event = ProtocolEvent::Message {
            sid,
            data: Bytes::from(&[99u8; 500_000][..]),
        };
        s.send(event).await.unwrap();
        let event = ProtocolEvent::CloseStream { sid };
        s.send(event).await.unwrap();
        //send
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Message { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::CloseStream { .. }));
    }

    #[tokio::test]
    async fn msg_finishes_after_shutdown() {
        let sid = Sid::new(1);
        let [p1, p2] = quic_bound(10000, 0.5, None);
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED | Promises::ORDERED,
            guaranteed_bandwidth: 0,
        };
        s.send(event).await.unwrap();
        let _ = r.recv().await.unwrap();
        let event = ProtocolEvent::Message {
            sid,
            data: Bytes::from(&[99u8; 500_000][..]),
        };
        s.send(event).await.unwrap();
        let event = ProtocolEvent::Shutdown {};
        s.send(event).await.unwrap();
        let event = ProtocolEvent::CloseStream { sid };
        s.send(event).await.unwrap();
        //send
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Message { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::CloseStream { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Shutdown { .. }));
    }

    #[tokio::test]
    async fn msg_finishes_after_drop() {
        let sid = Sid::new(1);
        let [p1, p2] = quic_bound(10000, 0.5, None);
        let (mut s, mut r) = (p1.0, p2.1);
        let event = ProtocolEvent::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED | Promises::ORDERED,
            guaranteed_bandwidth: 0,
        };
        s.send(event).await.unwrap();
        let event = ProtocolEvent::Message {
            sid,
            data: Bytes::from(&[99u8; 500_000][..]),
        };
        s.send(event).await.unwrap();
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let event = ProtocolEvent::Message {
            sid,
            data: Bytes::from(&[100u8; 500_000][..]),
        };
        s.send(event).await.unwrap();
        s.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        drop(s);
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::OpenStream { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Message { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Message { .. }));
    }

    #[tokio::test]
    async fn header_and_data_in_seperate_msg() {
        let sid = Sid::new(1);
        let (s, r) = async_channel::bounded(10);
        let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
        let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());

        const DATA1: &[u8; 69] =
            b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
        const DATA2: &[u8; 95] = b"in one chunk and (DATA and CLOSE_STREAM) in the second chunk. and then keep the connection open";
        let mut bytes = BytesMut::with_capacity(1500);
        OTFrame::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED | Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        }
        .write_bytes(&mut bytes);
        s.send(QuicDataFormat::with_main(&mut bytes)).await.unwrap();

        OTFrame::DataHeader {
            mid: 99,
            sid,
            length: (DATA1.len() + DATA2.len()) as u64,
        }
        .write_bytes(&mut bytes);
        s.send(QuicDataFormat::with_reliable(&mut bytes, sid))
            .await
            .unwrap();

        OTFrame::Data {
            mid: 99,
            data: Bytes::from(&DATA1[..]),
        }
        .write_bytes(&mut bytes);
        OTFrame::Data {
            mid: 99,
            data: Bytes::from(&DATA2[..]),
        }
        .write_bytes(&mut bytes);
        s.send(QuicDataFormat::with_reliable(&mut bytes, sid))
            .await
            .unwrap();

        OTFrame::CloseStream { sid }.write_bytes(&mut bytes);
        s.send(QuicDataFormat::with_main(&mut bytes)).await.unwrap();

        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::OpenStream { .. }));
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::Message { .. }));

        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::CloseStream { .. }));
    }

    #[tokio::test]
    async fn drop_sink_while_recv() {
        let sid = Sid::new(1);
        let (s, r) = async_channel::bounded(10);
        let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
        let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());

        let mut bytes = BytesMut::with_capacity(1500);
        OTFrame::OpenStream {
            sid,
            prio: 5u8,
            promises: Promises::COMPRESSED,
            guaranteed_bandwidth: 1_000_000,
        }
        .write_bytes(&mut bytes);
        s.send(QuicDataFormat::with_main(&mut bytes)).await.unwrap();
        let e = r.recv().await.unwrap();
        assert!(matches!(e, ProtocolEvent::OpenStream { .. }));

        let e = tokio::spawn(async move { r.recv().await });
        drop(s);

        let e = e.await.unwrap();
        assert_eq!(e, Err(ProtocolError::Custom(())));
    }

    #[tokio::test]
    #[should_panic]
    async fn send_on_stream_from_remote_without_notify() {
        //remote opens stream
        //we send on it
        let [mut p1, mut p2] = quic_bound(10, 0.5, None);
        let event = ProtocolEvent::OpenStream {
            sid: Sid::new(10),
            prio: 3u8,
            promises: Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        };
        p1.0.send(event).await.unwrap();
        let _ = p2.1.recv().await.unwrap();
        let event = ProtocolEvent::Message {
            sid: Sid::new(10),
            data: Bytes::from(&[188u8; 600][..]),
        };
        p2.0.send(event.clone()).await.unwrap();
        p2.0.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = p1.1.recv().await.unwrap();
        assert_eq!(event, e);
    }

    #[tokio::test]
    async fn send_on_stream_from_remote() {
        //remote opens stream
        //we send on it
        let [mut p1, mut p2] = quic_bound(10, 0.5, None);
        let event = ProtocolEvent::OpenStream {
            sid: Sid::new(10),
            prio: 3u8,
            promises: Promises::ORDERED,
            guaranteed_bandwidth: 1_000_000,
        };
        p1.0.send(event).await.unwrap();
        let e = p2.1.recv().await.unwrap();
        p2.0.notify_from_recv(e);
        let event = ProtocolEvent::Message {
            sid: Sid::new(10),
            data: Bytes::from(&[188u8; 600][..]),
        };
        p2.0.send(event.clone()).await.unwrap();
        p2.0.flush(1_000_000, Duration::from_secs(1)).await.unwrap();
        let e = p1.1.recv().await.unwrap();
        assert_eq!(event, e);
    }

    #[tokio::test]
    async fn unrealiable_test() {
        const MIN_CHECK: usize = 10;
        const COUNT: usize = 10_000;
        //We send COUNT msg with 50% of be send each. we check that >= MIN_CHECK && !=
        // COUNT reach their target

        let [mut p1, mut p2] = quic_bound(
            COUNT * 2 - 1, /* 2 times as it is HEADER + DATA but -1 as we want to see not all
                            * succeed */
            0.5,
            None,
        );
        let event = ProtocolEvent::OpenStream {
            sid: Sid::new(1337),
            prio: 3u8,
            promises: Promises::empty(), /* on purpose! */
            guaranteed_bandwidth: 1_000_000,
        };
        p1.0.send(event).await.unwrap();
        let e = p2.1.recv().await.unwrap();
        p2.0.notify_from_recv(e);
        let event = ProtocolEvent::Message {
            sid: Sid::new(1337),
            data: Bytes::from(&[188u8; 600][..]),
        };
        for _ in 0..COUNT {
            p2.0.send(event.clone()).await.unwrap();
        }
        p2.0.flush(1_000_000_000, Duration::from_secs(1))
            .await
            .unwrap();
        for _ in 0..COUNT {
            p2.0.send(event.clone()).await.unwrap();
        }
        for _ in 0..MIN_CHECK {
            let e = p1.1.recv().await.unwrap();
            assert_eq!(event, e);
        }
    }
}