h3x 0.6.1

Peer-to-peer DHTTP/3 transport over 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
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
use std::{
    mem,
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};

use bytes::Bytes;
use futures::{Sink, Stream, StreamExt as _};
use tracing::Instrument;

use crate::{
    error::Code,
    quic::{
        self, BoxQuicStreamReader, BoxQuicStreamWriter, GetStreamIdExt as _, ResetStreamExt,
        StopStreamExt,
    },
    varint::VarInt,
};

fn stream_used_after_taken() -> ! {
    panic!("guarded QUIC stream used after being taken, this is a bug")
}

fn reader_closed_before_stream_id_observed() -> ! {
    panic!("guarded QUIC reader closed before stream id was observed, this is a bug")
}

fn writer_closed_before_stream_id_observed() -> ! {
    panic!("guarded QUIC writer closed before stream id was observed, this is a bug")
}

fn writer_used_after_closed() -> ! {
    panic!("guarded QUIC writer used after send side closed, this is a bug")
}

const READER_DROP_DRAIN_TIMEOUT: Duration = Duration::from_millis(100);
const READER_DROP_STOP_TIMEOUT: Duration = Duration::from_millis(100);
const READER_DROP_DRAIN_LIMIT: usize = 64 * 1024;

async fn drain_reader_on_drop(mut stream: BoxQuicStreamReader) {
    let drain_result = tokio::time::timeout(READER_DROP_DRAIN_TIMEOUT, async {
        let stream_id = stream.stream_id().await.ok();
        let mut bytes = 0usize;
        loop {
            match stream.next().await {
                Some(Ok(chunk)) => {
                    bytes = bytes.saturating_add(chunk.len());
                    if bytes > READER_DROP_DRAIN_LIMIT {
                        return (stream_id, false);
                    }
                }
                Some(Err(_)) | None => return (stream_id, true),
            }
        }
    })
    .await;
    let (stream_id, drained) = drain_result.unwrap_or((None, false));

    if drained {
        tracing::trace!(
            boundary = "quic-reader-drop",
            stream_id = ?stream_id.map(|id| id.into_inner()),
            "QUIC reader reached end while draining on drop"
        );
    } else {
        tracing::info!(
            boundary = "quic-reader-drop",
            stream_id = ?stream_id.map(|id| id.into_inner()),
            code = Code::H3_NO_ERROR.into_inner().into_inner(),
            "QUIC reader drop drain incomplete; sending STOP_SENDING"
        );
        if tokio::time::timeout(
            READER_DROP_STOP_TIMEOUT,
            stream.stop(Code::H3_NO_ERROR.into()),
        )
        .await
        .is_err()
        {
            tracing::warn!(
                boundary = "quic-reader-drop",
                stream_id = ?stream_id.map(|id| id.into_inner()),
                code = Code::H3_NO_ERROR.into_inner().into_inner(),
                "QUIC reader STOP_SENDING timed out; dropping stream"
            );
        }
    }
}

#[derive(Debug, Clone)]
pub(super) enum QuicWriterStateSnapshot {
    Open,
    Closed,
    Reset { code: VarInt },
    ConnectionClosed { source: quic::ConnectionError },
    Taken,
}

enum QuicReaderState {
    Open { stream: BoxQuicStreamReader },
    Closed,
    Reset { code: VarInt },
    ConnectionClosed { source: quic::ConnectionError },
    Taken,
}

impl QuicReaderState {
    fn open(stream: BoxQuicStreamReader) -> Self {
        Self::Open { stream }
    }

    fn take(&mut self) -> Self {
        mem::replace(self, Self::Taken)
    }
}

enum QuicWriterState {
    Open { stream: BoxQuicStreamWriter },
    Closed,
    Reset { code: VarInt },
    ConnectionClosed { source: quic::ConnectionError },
    Taken,
}

impl QuicWriterState {
    fn open(stream: BoxQuicStreamWriter) -> Self {
        Self::Open { stream }
    }

    fn take(&mut self) -> Self {
        mem::replace(self, Self::Taken)
    }

    fn snapshot(&self) -> QuicWriterStateSnapshot {
        match self {
            Self::Open { .. } => QuicWriterStateSnapshot::Open,
            Self::Closed => QuicWriterStateSnapshot::Closed,
            Self::Reset { code } => QuicWriterStateSnapshot::Reset { code: *code },
            Self::ConnectionClosed { source } => QuicWriterStateSnapshot::ConnectionClosed {
                source: source.clone(),
            },
            Self::Taken => QuicWriterStateSnapshot::Taken,
        }
    }
}

// ---------------------------------------------------------------------------
// GuardQuicReader
// ---------------------------------------------------------------------------

/// A QUIC read stream wrapper that automatically stops the stream on drop
/// while the receive side is still open.
pub struct GuardQuicReader {
    stream_id: Option<VarInt>,
    state: QuicReaderState,
}

impl GuardQuicReader {
    pub fn new(inner: BoxQuicStreamReader) -> Self {
        Self {
            stream_id: None,
            state: QuicReaderState::open(inner),
        }
    }

    pub(super) fn set_stream_id(&mut self, stream_id: VarInt) {
        self.stream_id = Some(stream_id);
    }

    /// Take the stream lifecycle state, leaving this guard unusable.
    pub fn take(&mut self) -> Self {
        Self {
            stream_id: self.stream_id,
            state: self.state.take(),
        }
    }

    /// Consume this guard and return the protected stream without running drop cleanup.
    pub(super) fn into_inner(mut self) -> BoxQuicStreamReader {
        match self.state.take() {
            QuicReaderState::Open { stream } => stream,
            QuicReaderState::Closed => {
                panic!("closed guarded QUIC reader cannot be taken as an open stream")
            }
            QuicReaderState::Reset { .. } | QuicReaderState::ConnectionClosed { .. } => {
                panic!("failed guarded QUIC reader cannot be taken as an open stream")
            }
            QuicReaderState::Taken => stream_used_after_taken(),
        }
    }

    pub(super) fn mark_reset(&mut self, code: VarInt) {
        self.state = QuicReaderState::Reset { code };
    }

    pub(super) fn mark_connection_closed(&mut self, source: quic::ConnectionError) {
        self.state = QuicReaderState::ConnectionClosed { source };
    }

    fn mark_quic_error(&mut self, error: &quic::StreamError) {
        match error {
            quic::StreamError::Connection { source } => {
                self.mark_connection_closed(source.clone());
            }
            quic::StreamError::Reset { code } => {
                self.mark_reset(*code);
            }
        }
    }
}

impl Stream for GuardQuicReader {
    type Item = Result<Bytes, quic::StreamError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicReaderState::Open { stream } => stream.as_mut().poll_next(cx),
            QuicReaderState::Closed => return Poll::Ready(None),
            QuicReaderState::Reset { code } => {
                return Poll::Ready(Some(Err(quic::StreamError::Reset { code: *code })));
            }
            QuicReaderState::ConnectionClosed { source } => {
                return Poll::Ready(Some(Err(quic::StreamError::Connection {
                    source: source.clone(),
                })));
            }
            QuicReaderState::Taken => stream_used_after_taken(),
        };
        match result {
            Poll::Ready(None) => {
                this.state = QuicReaderState::Closed;
                Poll::Ready(None)
            }
            Poll::Ready(Some(Err(error))) => {
                this.mark_quic_error(&error);
                Poll::Ready(Some(Err(error)))
            }
            other => other,
        }
    }
}

impl quic::StopStream for GuardQuicReader {
    fn poll_stop(
        self: Pin<&mut Self>,
        cx: &mut Context,
        code: VarInt,
    ) -> Poll<Result<(), quic::StreamError>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicReaderState::Open { stream } => stream.as_mut().poll_stop(cx, code),
            QuicReaderState::Closed => return Poll::Ready(Ok(())),
            QuicReaderState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicReaderState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicReaderState::Taken => stream_used_after_taken(),
        };
        if let Poll::Ready(Err(error)) = result {
            this.mark_quic_error(&error);
            return Poll::Ready(Err(error));
        }
        result
    }
}

impl quic::GetStreamId for GuardQuicReader {
    fn poll_stream_id(
        self: Pin<&mut Self>,
        cx: &mut Context,
    ) -> Poll<Result<VarInt, quic::StreamError>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicReaderState::Open { stream } => {
                if let Some(stream_id) = this.stream_id {
                    return Poll::Ready(Ok(stream_id));
                }
                stream.as_mut().poll_stream_id(cx)
            }
            QuicReaderState::Closed => match this.stream_id {
                Some(stream_id) => return Poll::Ready(Ok(stream_id)),
                None => reader_closed_before_stream_id_observed(),
            },
            QuicReaderState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicReaderState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicReaderState::Taken => stream_used_after_taken(),
        };
        match result {
            Poll::Ready(Ok(stream_id)) => Poll::Ready(Ok(stream_id)),
            Poll::Ready(Err(error)) => {
                this.mark_quic_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for GuardQuicReader {
    fn drop(&mut self) {
        if let QuicReaderState::Open { stream } = self.state.take() {
            tokio::spawn(drain_reader_on_drop(stream).in_current_span());
        }
    }
}

// ---------------------------------------------------------------------------
// GuardQuicWriter
// ---------------------------------------------------------------------------

/// A QUIC write stream wrapper that automatically resets the stream on drop
/// while the send side is still open.
pub struct GuardQuicWriter {
    state: QuicWriterState,
}

impl GuardQuicWriter {
    pub fn new(inner: BoxQuicStreamWriter) -> Self {
        Self {
            state: QuicWriterState::open(inner),
        }
    }

    pub(super) fn state_snapshot(&self) -> QuicWriterStateSnapshot {
        self.state.snapshot()
    }

    pub(super) fn mark_reset(&mut self, code: VarInt) {
        self.state = QuicWriterState::Reset { code };
    }

    pub(super) fn mark_connection_closed(&mut self, source: quic::ConnectionError) {
        self.state = QuicWriterState::ConnectionClosed { source };
    }

    fn mark_quic_error(&mut self, error: &quic::StreamError) {
        match error {
            quic::StreamError::Connection { source } => {
                self.mark_connection_closed(source.clone());
            }
            quic::StreamError::Reset { code } => {
                self.mark_reset(*code);
            }
        }
    }

    /// Take the stream lifecycle state, leaving this guard unusable.
    pub fn take(&mut self) -> Self {
        Self {
            state: self.state.take(),
        }
    }
}

impl Sink<Bytes> for GuardQuicWriter {
    type Error = quic::StreamError;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().poll_ready(cx),
            QuicWriterState::Closed => writer_used_after_closed(),
            QuicWriterState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        if let Poll::Ready(Err(error)) = result {
            this.mark_quic_error(&error);
            return Poll::Ready(Err(error));
        }
        result
    }

    fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().start_send(item),
            QuicWriterState::Closed => writer_used_after_closed(),
            QuicWriterState::Reset { code } => {
                return Err(quic::StreamError::Reset { code: *code });
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Err(quic::StreamError::Connection {
                    source: source.clone(),
                });
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        if let Err(error) = &result {
            this.mark_quic_error(error);
        }
        result
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().poll_flush(cx),
            QuicWriterState::Closed => writer_used_after_closed(),
            QuicWriterState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        if let Poll::Ready(Err(error)) = result {
            this.mark_quic_error(&error);
            return Poll::Ready(Err(error));
        }
        result
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().poll_close(cx),
            QuicWriterState::Closed => writer_used_after_closed(),
            QuicWriterState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        match result {
            Poll::Ready(Ok(())) => {
                this.state = QuicWriterState::Closed;
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(error)) => {
                this.mark_quic_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl quic::ResetStream for GuardQuicWriter {
    fn poll_reset(
        self: Pin<&mut Self>,
        cx: &mut Context,
        code: VarInt,
    ) -> Poll<Result<(), quic::StreamError>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().poll_reset(cx, code),
            QuicWriterState::Closed => writer_used_after_closed(),
            QuicWriterState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        match result {
            Poll::Ready(Ok(())) => {
                this.state = QuicWriterState::Reset { code };
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(error)) => {
                this.mark_quic_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl quic::GetStreamId for GuardQuicWriter {
    fn poll_stream_id(
        self: Pin<&mut Self>,
        cx: &mut Context,
    ) -> Poll<Result<VarInt, quic::StreamError>> {
        let this = self.get_mut();
        let result = match &mut this.state {
            QuicWriterState::Open { stream } => stream.as_mut().poll_stream_id(cx),
            QuicWriterState::Closed => writer_closed_before_stream_id_observed(),
            QuicWriterState::Reset { code } => {
                return Poll::Ready(Err(quic::StreamError::Reset { code: *code }));
            }
            QuicWriterState::ConnectionClosed { source } => {
                return Poll::Ready(Err(quic::StreamError::Connection {
                    source: source.clone(),
                }));
            }
            QuicWriterState::Taken => stream_used_after_taken(),
        };
        match result {
            Poll::Ready(Ok(stream_id)) => Poll::Ready(Ok(stream_id)),
            Poll::Ready(Err(error)) => {
                this.mark_quic_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for GuardQuicWriter {
    fn drop(&mut self) {
        if let QuicWriterState::Open { mut stream } = self.state.take() {
            // Inherent termination: the task owns the only remaining stream
            // handle and exits once the committed RESET_STREAM operation
            // resolves or the underlying stream reports failure.
            tokio::spawn(
                async move {
                    _ = stream.reset(Code::H3_NO_ERROR.into()).await;
                }
                .in_current_span(),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::VecDeque,
        panic::{AssertUnwindSafe, catch_unwind},
        sync::{Arc, Mutex},
    };

    use futures::{SinkExt, StreamExt, future::poll_fn, task::noop_waker_ref};
    use tokio::{
        sync::mpsc,
        time::{Duration, timeout},
    };

    use super::*;
    use crate::quic::{GetStreamId, GetStreamIdExt, ResetStream, StopStream};

    fn stream_error(code: u32) -> quic::StreamError {
        quic::StreamError::Reset {
            code: VarInt::from_u32(code),
        }
    }

    fn no_op_cx() -> Context<'static> {
        Context::from_waker(noop_waker_ref())
    }

    fn assert_guard_panic(action: impl FnOnce()) {
        let panic = catch_unwind(AssertUnwindSafe(action))
            .expect_err("guard should panic after take or drop");
        let message = if let Some(message) = panic.downcast_ref::<&str>() {
            *message
        } else if let Some(message) = panic.downcast_ref::<String>() {
            message.as_str()
        } else {
            panic!("panic payload should be a string");
        };
        assert_eq!(
            message,
            "guarded QUIC stream used after being taken, this is a bug",
        );
    }

    async fn assert_no_code(mut rx: mpsc::UnboundedReceiver<VarInt>) {
        match timeout(Duration::from_millis(50), rx.recv()).await {
            Err(_) | Ok(None) => {}
            Ok(Some(code)) => panic!("unexpected stop/reset notification received: {code}"),
        }
    }

    type ReadPollResult = Option<Result<Bytes, quic::StreamError>>;
    type ReadPollQueue = Arc<Mutex<VecDeque<ReadPollResult>>>;
    type StopResultQueue = Arc<Mutex<VecDeque<Result<(), quic::StreamError>>>>;
    type SentItems = Arc<Mutex<Vec<Bytes>>>;

    #[derive(Clone)]
    struct ReaderState {
        stream_id: VarInt,
        next_results: ReadPollQueue,
        stop_results: StopResultQueue,
    }

    struct TestReader {
        state: ReaderState,
        stop_tx: mpsc::UnboundedSender<VarInt>,
    }

    struct PendingStreamIdReader {
        stop_tx: mpsc::UnboundedSender<VarInt>,
    }

    struct PendingStopReader {
        stream_id: VarInt,
        stop_tx: Option<mpsc::UnboundedSender<VarInt>>,
        drop_tx: Option<mpsc::UnboundedSender<()>>,
    }

    impl Stream for PendingStreamIdReader {
        type Item = Result<Bytes, quic::StreamError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Pending
        }
    }

    impl quic::StopStream for PendingStreamIdReader {
        fn poll_stop(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            self.get_mut()
                .stop_tx
                .send(code)
                .expect("reader stop receiver should still be alive");
            Poll::Ready(Ok(()))
        }
    }

    impl quic::GetStreamId for PendingStreamIdReader {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Pending
        }
    }

    impl Stream for PendingStopReader {
        type Item = Result<Bytes, quic::StreamError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Pending
        }
    }

    impl quic::StopStream for PendingStopReader {
        fn poll_stop(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            if let Some(stop_tx) = self.get_mut().stop_tx.take() {
                stop_tx
                    .send(code)
                    .expect("reader stop receiver should still be alive");
            }
            Poll::Pending
        }
    }

    impl quic::GetStreamId for PendingStopReader {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Ready(Ok(self.get_mut().stream_id))
        }
    }

    impl Drop for PendingStopReader {
        fn drop(&mut self) {
            if let Some(drop_tx) = self.drop_tx.take() {
                _ = drop_tx.send(());
            }
        }
    }

    impl Stream for TestReader {
        type Item = Result<Bytes, quic::StreamError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            let next = self
                .state
                .next_results
                .lock()
                .expect("reader next queue lock should not be poisoned")
                .pop_front()
                .unwrap_or(None);
            Poll::Ready(next)
        }
    }

    impl quic::StopStream for TestReader {
        fn poll_stop(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            self.stop_tx
                .send(code)
                .expect("reader stop receiver should still be alive");
            let result = self
                .state
                .stop_results
                .lock()
                .expect("reader stop queue lock should not be poisoned")
                .pop_front()
                .unwrap_or(Ok(()));
            Poll::Ready(result)
        }
    }

    impl quic::GetStreamId for TestReader {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Ready(Ok(self.state.stream_id))
        }
    }

    fn reader_guard(
        stream_id: u32,
        next_results: impl IntoIterator<Item = Option<Result<Bytes, quic::StreamError>>>,
        stop_results: impl IntoIterator<Item = Result<(), quic::StreamError>>,
    ) -> (GuardQuicReader, mpsc::UnboundedReceiver<VarInt>) {
        let state = ReaderState {
            stream_id: VarInt::from_u32(stream_id),
            next_results: Arc::new(Mutex::new(next_results.into_iter().collect())),
            stop_results: Arc::new(Mutex::new(stop_results.into_iter().collect())),
        };
        let (stop_tx, stop_rx) = mpsc::unbounded_channel();
        (
            GuardQuicReader::new(Box::pin(TestReader { state, stop_tx })),
            stop_rx,
        )
    }

    #[derive(Clone)]
    struct WriterState {
        stream_id: VarInt,
        sent_items: SentItems,
        close_results: StopResultQueue,
        reset_results: StopResultQueue,
    }

    struct TestWriter {
        state: WriterState,
        reset_tx: mpsc::UnboundedSender<VarInt>,
    }

    impl Sink<Bytes> for TestWriter {
        type Error = quic::StreamError;

        fn poll_ready(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
            self.state
                .sent_items
                .lock()
                .expect("writer sent-items lock should not be poisoned")
                .push(item);
            Ok(())
        }

        fn poll_flush(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            let result = self
                .state
                .close_results
                .lock()
                .expect("writer close queue lock should not be poisoned")
                .pop_front()
                .unwrap_or(Ok(()));
            Poll::Ready(result)
        }
    }

    impl quic::ResetStream for TestWriter {
        fn poll_reset(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            self.reset_tx
                .send(code)
                .expect("writer reset receiver should still be alive");
            let result = self
                .state
                .reset_results
                .lock()
                .expect("writer reset queue lock should not be poisoned")
                .pop_front()
                .unwrap_or(Ok(()));
            Poll::Ready(result)
        }
    }

    impl quic::GetStreamId for TestWriter {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Ready(Ok(self.state.stream_id))
        }
    }

    fn writer_guard(
        stream_id: u32,
        close_results: impl IntoIterator<Item = Result<(), quic::StreamError>>,
        reset_results: impl IntoIterator<Item = Result<(), quic::StreamError>>,
    ) -> (GuardQuicWriter, SentItems, mpsc::UnboundedReceiver<VarInt>) {
        let sent_items = Arc::new(Mutex::new(Vec::new()));
        let state = WriterState {
            stream_id: VarInt::from_u32(stream_id),
            sent_items: sent_items.clone(),
            close_results: Arc::new(Mutex::new(close_results.into_iter().collect())),
            reset_results: Arc::new(Mutex::new(reset_results.into_iter().collect())),
        };
        let (reset_tx, reset_rx) = mpsc::unbounded_channel();
        (
            GuardQuicWriter::new(Box::pin(TestWriter { state, reset_tx })),
            sent_items,
            reset_rx,
        )
    }

    struct DropNotifyingReader {
        stream_id: VarInt,
        next_results: VecDeque<Option<Result<Bytes, quic::StreamError>>>,
        stop_tx: mpsc::UnboundedSender<VarInt>,
        drop_tx: Option<mpsc::UnboundedSender<()>>,
    }

    impl Stream for DropNotifyingReader {
        type Item = Result<Bytes, quic::StreamError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Ready(self.get_mut().next_results.pop_front().unwrap_or(None))
        }
    }

    impl quic::StopStream for DropNotifyingReader {
        fn poll_stop(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            self.get_mut()
                .stop_tx
                .send(code)
                .expect("reader stop receiver should still be alive");
            Poll::Ready(Ok(()))
        }
    }

    impl quic::GetStreamId for DropNotifyingReader {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Ready(Ok(self.get_mut().stream_id))
        }
    }

    impl Drop for DropNotifyingReader {
        fn drop(&mut self) {
            if let Some(drop_tx) = self.drop_tx.take() {
                _ = drop_tx.send(());
            }
        }
    }

    struct DropNotifyingWriter {
        stream_id: VarInt,
        close_results: VecDeque<Result<(), quic::StreamError>>,
        reset_results: VecDeque<Result<(), quic::StreamError>>,
        reset_tx: mpsc::UnboundedSender<VarInt>,
        drop_tx: Option<mpsc::UnboundedSender<()>>,
    }

    impl Sink<Bytes> for DropNotifyingWriter {
        type Error = quic::StreamError;

        fn poll_ready(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn start_send(self: Pin<&mut Self>, _item: Bytes) -> Result<(), Self::Error> {
            Ok(())
        }

        fn poll_flush(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(self.get_mut().close_results.pop_front().unwrap_or(Ok(())))
        }
    }

    impl quic::ResetStream for DropNotifyingWriter {
        fn poll_reset(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            let this = self.get_mut();
            this.reset_tx
                .send(code)
                .expect("writer reset receiver should still be alive");
            Poll::Ready(this.reset_results.pop_front().unwrap_or(Ok(())))
        }
    }

    impl quic::GetStreamId for DropNotifyingWriter {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            Poll::Ready(Ok(self.get_mut().stream_id))
        }
    }

    impl Drop for DropNotifyingWriter {
        fn drop(&mut self) {
            if let Some(drop_tx) = self.drop_tx.take() {
                _ = drop_tx.send(());
            }
        }
    }

    #[tokio::test]
    async fn reader_take_moves_inner_stream_and_panics_on_original_use() {
        let (mut guard, stop_rx) = reader_guard(7, [], [Ok(())]);
        guard.set_stream_id(VarInt::from_u32(7));
        let mut taken = GuardQuicReader::take(&mut guard);

        assert_eq!(
            taken
                .stream_id()
                .await
                .expect("taken reader should expose stream id"),
            VarInt::from_u32(7),
        );

        let mut cx = no_op_cx();
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_next(&mut cx);
        });
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_stop(&mut cx, VarInt::from_u32(1));
        });
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_stream_id(&mut cx);
        });

        drop(guard);
        drop(taken);

        assert_no_code(stop_rx).await;
    }

    #[tokio::test]
    async fn reader_eof_marks_completed_and_drop_skips_stop() {
        let (mut guard, stop_rx) = reader_guard(11, [None], []);

        assert!(guard.next().await.is_none());

        drop(guard);
        assert_no_code(stop_rx).await;
    }

    #[tokio::test]
    async fn reader_eof_releases_inner_stream_immediately() {
        let (stop_tx, _stop_rx) = mpsc::unbounded_channel();
        let (drop_tx, mut drop_rx) = mpsc::unbounded_channel();
        let mut guard = GuardQuicReader::new(Box::pin(DropNotifyingReader {
            stream_id: VarInt::from_u32(111),
            next_results: [None].into_iter().collect(),
            stop_tx,
            drop_tx: Some(drop_tx),
        }));

        assert!(guard.next().await.is_none());

        timeout(Duration::from_secs(1), drop_rx.recv())
            .await
            .expect("inner reader should be released on EOF")
            .expect("inner reader drop should be observed");
    }

    #[tokio::test]
    async fn reader_stop_ok_allows_drop_cleanup_to_drain_eof() {
        let (mut guard, mut stop_rx) = reader_guard(12, [], [Ok(())]);

        poll_fn(|cx| Pin::new(&mut guard).poll_stop(cx, VarInt::from_u32(33)))
            .await
            .expect("stop should succeed");
        assert_eq!(
            timeout(Duration::from_secs(1), stop_rx.recv())
                .await
                .expect("stop call should notify")
                .expect("stop code should be present"),
            VarInt::from_u32(33),
        );

        drop(guard);
        assert_no_code(stop_rx).await;
    }

    #[tokio::test]
    async fn reader_stop_error_transitions_to_reset_and_skips_drop_cleanup() {
        let (mut guard, mut stop_rx) = reader_guard(13, [], [Err(stream_error(44)), Ok(())]);

        let error = poll_fn(|cx| Pin::new(&mut guard).poll_stop(cx, VarInt::from_u32(55)))
            .await
            .expect_err("explicit stop should fail");
        assert!(matches!(
            error,
            quic::StreamError::Reset { code } if code == VarInt::from_u32(44)
        ));
        assert_eq!(
            timeout(Duration::from_secs(1), stop_rx.recv())
                .await
                .expect("failing stop should notify")
                .expect("stop code should be present"),
            VarInt::from_u32(55),
        );

        drop(guard);
        assert_no_code(stop_rx).await;
    }

    #[tokio::test]
    async fn reader_drop_timeout_covers_pending_stream_id_lookup() {
        let (stop_tx, mut stop_rx) = mpsc::unbounded_channel();
        let guard = GuardQuicReader::new(Box::pin(PendingStreamIdReader { stop_tx }));

        drop(guard);

        assert_eq!(
            timeout(Duration::from_secs(1), stop_rx.recv())
                .await
                .expect("drop cleanup should time out pending stream id lookup")
                .expect("drop cleanup should send stop code"),
            Code::H3_NO_ERROR.into_inner(),
        );
    }

    #[tokio::test]
    async fn reader_drop_timeout_covers_pending_stop() {
        let (stop_tx, mut stop_rx) = mpsc::unbounded_channel();
        let (drop_tx, mut drop_rx) = mpsc::unbounded_channel();
        let guard = GuardQuicReader::new(Box::pin(PendingStopReader {
            stream_id: VarInt::from_u32(112),
            stop_tx: Some(stop_tx),
            drop_tx: Some(drop_tx),
        }));

        drop(guard);

        assert_eq!(
            timeout(Duration::from_secs(1), stop_rx.recv())
                .await
                .expect("drop cleanup should attempt STOP_SENDING")
                .expect("stop code should be present"),
            Code::H3_NO_ERROR.into_inner(),
        );
        timeout(Duration::from_secs(1), drop_rx.recv())
            .await
            .expect("drop cleanup should time out pending STOP_SENDING")
            .expect("inner reader drop should be observed");
    }

    #[tokio::test]
    async fn writer_take_moves_inner_stream_and_panics_on_original_use() {
        let (mut guard, sent_items, reset_rx) = writer_guard(8, [], [Ok(())]);
        let mut taken = GuardQuicWriter::take(&mut guard);

        assert_eq!(
            taken
                .stream_id()
                .await
                .expect("taken writer should expose stream id"),
            VarInt::from_u32(8),
        );
        taken
            .send(Bytes::from_static(b"hello"))
            .await
            .expect("taken writer should accept sends");
        assert_eq!(
            sent_items
                .lock()
                .expect("sent-items lock should not be poisoned")
                .as_slice(),
            &[Bytes::from_static(b"hello")],
        );

        let mut cx = no_op_cx();
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_ready(&mut cx);
        });
        assert_guard_panic(|| {
            Pin::new(&mut guard)
                .start_send(Bytes::from_static(b"panic"))
                .expect("start_send should panic before returning");
        });
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_flush(&mut cx);
        });
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_close(&mut cx);
        });
        assert_guard_panic(|| {
            let _ = Pin::new(&mut guard).poll_reset(&mut cx, VarInt::from_u32(2));
        });

        drop(guard);
        drop(taken);

        assert_eq!(
            timeout(Duration::from_secs(1), async move {
                let mut reset_rx = reset_rx;
                reset_rx.recv().await
            })
            .await
            .expect("writer drop cleanup should run")
            .expect("writer reset code should be sent"),
            VarInt::from(Code::H3_NO_ERROR),
        );
    }

    #[tokio::test]
    async fn writer_close_ok_marks_completed_and_drop_skips_reset() {
        let (mut guard, _, reset_rx) = writer_guard(21, [Ok(())], []);

        guard.close().await.expect("close should succeed");

        drop(guard);
        assert_no_code(reset_rx).await;
    }

    #[tokio::test]
    async fn writer_close_releases_inner_stream_immediately() {
        let (reset_tx, _reset_rx) = mpsc::unbounded_channel();
        let (drop_tx, mut drop_rx) = mpsc::unbounded_channel();
        let mut guard = GuardQuicWriter::new(Box::pin(DropNotifyingWriter {
            stream_id: VarInt::from_u32(121),
            close_results: [Ok(())].into_iter().collect(),
            reset_results: [].into_iter().collect(),
            reset_tx,
            drop_tx: Some(drop_tx),
        }));

        guard.close().await.expect("close should succeed");

        timeout(Duration::from_secs(1), drop_rx.recv())
            .await
            .expect("inner writer should be released on close")
            .expect("inner writer drop should be observed");
    }

    #[tokio::test]
    async fn writer_reset_ok_marks_completed_and_drop_skips_second_reset() {
        let (mut guard, _, mut reset_rx) = writer_guard(22, [], [Ok(())]);

        poll_fn(|cx| Pin::new(&mut guard).poll_reset(cx, VarInt::from_u32(66)))
            .await
            .expect("reset should succeed");
        assert_eq!(
            timeout(Duration::from_secs(1), reset_rx.recv())
                .await
                .expect("reset call should notify")
                .expect("reset code should be present"),
            VarInt::from_u32(66),
        );

        drop(guard);
        assert_no_code(reset_rx).await;
    }

    #[tokio::test]
    async fn writer_reset_releases_inner_stream_immediately() {
        let (reset_tx, mut reset_rx) = mpsc::unbounded_channel();
        let (drop_tx, mut drop_rx) = mpsc::unbounded_channel();
        let mut guard = GuardQuicWriter::new(Box::pin(DropNotifyingWriter {
            stream_id: VarInt::from_u32(122),
            close_results: [].into_iter().collect(),
            reset_results: [Ok(())].into_iter().collect(),
            reset_tx,
            drop_tx: Some(drop_tx),
        }));

        poll_fn(|cx| Pin::new(&mut guard).poll_reset(cx, VarInt::from_u32(77)))
            .await
            .expect("reset should succeed");
        assert_eq!(
            timeout(Duration::from_secs(1), reset_rx.recv())
                .await
                .expect("reset call should notify")
                .expect("reset code should be present"),
            VarInt::from_u32(77),
        );
        timeout(Duration::from_secs(1), drop_rx.recv())
            .await
            .expect("inner writer should be released on reset")
            .expect("inner writer drop should be observed");
    }

    #[tokio::test]
    async fn writer_close_error_transitions_to_reset_and_skips_drop_cleanup() {
        let (mut guard, _, reset_rx) = writer_guard(23, [Err(stream_error(77))], [Ok(())]);

        let error = guard.close().await.expect_err("close should fail");
        assert!(matches!(
            error,
            quic::StreamError::Reset { code } if code == VarInt::from_u32(77)
        ));

        drop(guard);
        assert_no_code(reset_rx).await;
    }
}