h3x 0.2.0

High-performance zero-copy DHTTP/3 implementation
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
//! [`IpcWriteStream`] — per-stream socketpair write half with pull-based flow control.
//!
//! Wraps the write direction of a `SOCK_STREAM` socketpair, encoding the pipe
//! framing protocol and exposing it as `Sink<Bytes, Error = StreamError>` +
//! [`CancelStream`] + [`GetStreamId`], satisfying [`quic::WriteStream`].
//!
//! # Flow control
//!
//! The writer may only send data after the peer reader has granted permission
//! via a `PULL` frame.  The protocol is strictly serial: each `PULL` permits
//! exactly one `PUSH` frame.  `poll_ready` returns `Pending` when no `PULL`
//! has been received, and resumes once one arrives.
//!
//! # Flush / Close semantics
//!
//! - `poll_flush` — flushes the pending PUSH frame via vectored I/O.
//! - `poll_close` — flushes remaining data, then shuts down the write half
//!   (`SHUT_WR`), which the remote side observes as EOF (equivalent to QUIC FIN).

use std::{
    ops::ControlFlow,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use bytes::Bytes;
use futures::Sink;
use tokio::{
    io::AsyncWrite,
    net::{
        UnixStream,
        unix::{OwnedReadHalf, OwnedWriteHalf},
    },
};
use tokio_util::codec::FramedRead;

use super::{
    codec::{Frame, StreamCodec, TAG_CANCEL, TAG_CONN_CLOSED},
    state::{
        PendingPush, PipeState, Step, Transition, check_lifecycle, drain, encode_control,
        flush_pending,
    },
};
use crate::{
    quic::{self, CancelStream, GetStreamId, StreamError},
    varint::VarInt,
};

/// Active-state fields for the writer.
struct WriterLive {
    read: FramedRead<OwnedReadHalf, StreamCodec>,
    write: OwnedWriteHalf,
    lifecycle: Arc<dyn quic::DynLifecycle>,
    pulled: bool,
    pending: Option<PendingPush>,
}

impl WriterLive {
    /// Drain inbound control frames and check the lifecycle.
    ///
    /// - `PULL` → grant send permission
    /// - `STOP(code)` → peer requests reset
    /// - `CONN_CLOSED` → connection died
    /// - others → ignore
    ///
    /// On read-close: sends best-effort `CONN_CLOSED` (only when no partial
    /// PUSH is in flight) and transitions to `ConnDied`.  The pipe EOF is
    /// treated as authoritative — no more `PULL` frames can ever arrive —
    /// even if `lifecycle.check()` has not yet been updated.
    fn drain_and_check(&mut self, cx: &mut Context<'_>) -> Step<()> {
        let outcome = drain(&mut self.read, cx, |frame| match frame {
            Frame::Pull => {
                self.pulled = true;
                ControlFlow::Continue(())
            }
            Frame::Stop(code) => ControlFlow::Break(Transition::Reset(code)),
            Frame::ConnClosed => ControlFlow::Break(Transition::ConnDied(self.lifecycle.clone())),
            _ => ControlFlow::Continue(()),
        });

        outcome.resolve(|| {
            // Pipe read half is closed: the peer bridge task has exited
            // (either because the connection died or because it finished).
            // No more PULL frames can ever arrive, so continuing would
            // deadlock poll_ready.  Transition unconditionally.
            if self.pending.is_none() {
                let _ = Pin::new(&mut self.write).poll_write(cx, &[TAG_CONN_CLOSED]);
            }
            Step::Transition(Transition::ConnDied(self.lifecycle.clone()))
        })
    }

    /// `poll_ready` step: drain control → eagerly flush pending → check pulled.
    ///
    /// Callers (e.g. `SinkWriter::poll_write`) may call `poll_ready` after
    /// `start_send` without an intervening `poll_flush`.  To avoid deadlock
    /// we eagerly flush pending PUSH data here, ensuring the bridge-writer
    /// can receive it and send the next PULL.
    fn step_poll_ready(&mut self, cx: &mut Context<'_>) -> Step<()> {
        let step = self.drain_and_check(cx);
        step.and_then(|()| {
            // Eagerly flush any pending PUSH — prevents deadlock when the
            // caller skips poll_flush between start_send and poll_ready.
            if self.pending.is_some() {
                match flush_pending(&mut self.write, &self.lifecycle, &mut self.pending, cx) {
                    Step::Transition(t) => return Step::Transition(t),
                    Step::Pending | Step::Done(()) => {}
                }
            }

            if self.pulled && self.pending.is_none() {
                Step::Done(())
            } else {
                Step::Pending
            }
        })
    }

    /// `poll_flush` step: drain control → flush pending PUSH via vectored I/O.
    fn step_poll_flush(&mut self, cx: &mut Context<'_>) -> Step<()> {
        let step = self.drain_and_check(cx);
        step.and_then(|()| flush_pending(&mut self.write, &self.lifecycle, &mut self.pending, cx))
    }

    /// `poll_close` step: flush pending data → shutdown write half (SHUT_WR).
    fn step_poll_close(&mut self, cx: &mut Context<'_>) -> Step<()> {
        let Self {
            write,
            lifecycle,
            pending,
            ..
        } = self;
        flush_pending(write, lifecycle, pending, cx).and_then(|()| {
            match Pin::new(&mut *write).poll_shutdown(cx) {
                Poll::Ready(Ok(())) => Step::Transition(Transition::Finish),
                Poll::Ready(Err(e)) => {
                    tracing::debug!(%e, "pipe write error during close shutdown");
                    check_lifecycle(lifecycle, Step::Transition(Transition::Finish))
                }
                Poll::Pending => Step::Pending,
            }
        })
    }

    /// `poll_cancel` step: discard pending data → best-effort CANCEL → shutdown.
    fn step_poll_cancel(&mut self, code: VarInt, cx: &mut Context<'_>) -> Step<()> {
        self.pending = None;
        let (buf, len) = encode_control(TAG_CANCEL, code);
        let _ = Pin::new(&mut self.write).poll_write(cx, &buf[..len]);
        match Pin::new(&mut self.write).poll_shutdown(cx) {
            Poll::Ready(_) => Step::Transition(Transition::Finish),
            Poll::Pending => Step::Pending,
        }
    }
}

// ── IpcWriteStream ──────────────────────────────────────────────────────────────

/// IPC write stream backed by a per-stream Unix socketpair.
///
/// Sends PUSH frames through the write half of the socketpair.
/// Reads PULL/STOP/CONN_CLOSED frames from the read half for flow control
/// and lifecycle signals.
pub struct IpcWriteStream {
    stream_id: VarInt,
    state: PipeState<WriterLive>,
}

impl IpcWriteStream {
    /// Create a new writer from a `tokio::net::UnixStream`.
    pub fn new(
        stream_id: VarInt,
        socket: UnixStream,
        lifecycle: Arc<dyn quic::DynLifecycle>,
    ) -> Self {
        let (read_half, write_half) = socket.into_split();
        Self {
            stream_id,
            state: PipeState::Live(WriterLive {
                read: FramedRead::new(read_half, StreamCodec::new()),
                write: write_half,
                lifecycle,
                pulled: false,
                pending: None,
            }),
        }
    }
}

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

impl Sink<Bytes> for IpcWriteStream {
    type Error = StreamError;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), StreamError>> {
        let this = self.get_mut();
        loop {
            if let Some(poll) = this.state.poll_non_live(cx) {
                return poll.map(|r| {
                    r.and(Err(StreamError::Reset {
                        code: VarInt::default(),
                    }))
                });
            }
            let live = this.state.live_mut().unwrap();
            match live.step_poll_ready(cx) {
                Step::Done(()) => return Poll::Ready(Ok(())),
                Step::Pending => return Poll::Pending,
                Step::Transition(t) => this.state.apply(t, cx),
            }
        }
    }

    fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), StreamError> {
        let this = self.get_mut();
        let PipeState::Live(live) = &mut this.state else {
            return Err(StreamError::Reset {
                code: VarInt::default(),
            });
        };
        if !live.pulled || live.pending.is_some() {
            return Err(StreamError::Reset {
                code: VarInt::default(),
            });
        }
        live.pending = Some(PendingPush::new(item)?);
        live.pulled = false;
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), StreamError>> {
        let this = self.get_mut();
        loop {
            if let Some(poll) = this.state.poll_non_live(cx) {
                return poll.map(|r| {
                    r.and(Err(StreamError::Reset {
                        code: VarInt::default(),
                    }))
                });
            }
            let live = this.state.live_mut().unwrap();
            match live.step_poll_flush(cx) {
                Step::Done(()) => return Poll::Ready(Ok(())),
                Step::Pending => return Poll::Pending,
                Step::Transition(t) => this.state.apply(t, cx),
            }
        }
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), StreamError>> {
        let this = self.get_mut();
        loop {
            if let Some(poll) = this.state.poll_non_live(cx) {
                // Dead(Ok(())) = clean close succeeded; Dead(Err(_)) = already failed.
                return poll;
            }
            let live = this.state.live_mut().unwrap();
            match live.step_poll_close(cx) {
                Step::Done(()) => return Poll::Ready(Ok(())),
                Step::Pending => return Poll::Pending,
                Step::Transition(t) => this.state.apply(t, cx),
            }
        }
    }
}

impl CancelStream for IpcWriteStream {
    fn poll_cancel(
        self: Pin<&mut Self>,
        cx: &mut Context,
        code: VarInt,
    ) -> Poll<Result<(), StreamError>> {
        let this = self.get_mut();
        loop {
            if let Some(poll) = this.state.poll_non_live(cx) {
                // Already dead — cancel is a no-op.
                let _ = poll;
                return Poll::Ready(Ok(()));
            }
            let live = this.state.live_mut().unwrap();
            match live.step_poll_cancel(code, cx) {
                Step::Done(()) => return Poll::Ready(Ok(())),
                Step::Pending => return Poll::Pending,
                Step::Transition(t) => this.state.apply(t, cx),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        borrow::Cow,
        future::pending,
        pin::Pin,
        sync::Arc,
        task::{Context, Poll},
    };

    use bytes::Bytes;
    use futures::{Sink, SinkExt, StreamExt, future::poll_fn, task::noop_waker_ref};
    use tokio::{
        net::{
            UnixStream,
            unix::{OwnedReadHalf, OwnedWriteHalf},
        },
        time::{Duration, timeout},
    };
    use tokio_util::codec::{FramedRead, FramedWrite};

    use super::*;
    use crate::quic::{CancelStream, ConnectionError};

    struct TestLifecycle {
        terminal: Option<ConnectionError>,
    }

    impl quic::Lifecycle for TestLifecycle {
        fn close(&self, _code: crate::error::Code, _reason: Cow<'static, str>) {}

        fn check(&self) -> Result<(), ConnectionError> {
            match &self.terminal {
                Some(err) => Err(err.clone()),
                None => Ok(()),
            }
        }

        async fn closed(&self) -> ConnectionError {
            match &self.terminal {
                Some(err) => err.clone(),
                None => pending().await,
            }
        }
    }

    fn test_connection_error(reason: &str) -> ConnectionError {
        ConnectionError::Transport {
            source: quic::TransportError {
                kind: VarInt::from_u32(0x31),
                frame_type: VarInt::from_u32(0x32),
                reason: reason.to_owned().into(),
            },
        }
    }

    fn alive_lifecycle() -> Arc<dyn quic::DynLifecycle> {
        Arc::new(TestLifecycle { terminal: None })
    }

    fn dead_lifecycle(reason: &str) -> Arc<dyn quic::DynLifecycle> {
        Arc::new(TestLifecycle {
            terminal: Some(test_connection_error(reason)),
        })
    }

    async fn setup_writer_with_lifecycle(
        lifecycle: Arc<dyn quic::DynLifecycle>,
    ) -> (
        IpcWriteStream,
        FramedWrite<OwnedWriteHalf, StreamCodec>,
        FramedRead<OwnedReadHalf, StreamCodec>,
    ) {
        let (writer_side, peer_side) = UnixStream::pair().unwrap();
        let (peer_read, peer_write) = peer_side.into_split();

        let writer = IpcWriteStream::new(VarInt::from_u32(1), writer_side, lifecycle);

        (
            writer,
            FramedWrite::new(peer_write, StreamCodec::new()),
            FramedRead::new(peer_read, StreamCodec::new()),
        )
    }

    async fn setup_writer() -> (
        IpcWriteStream,
        FramedWrite<OwnedWriteHalf, StreamCodec>,
        FramedRead<OwnedReadHalf, StreamCodec>,
    ) {
        setup_writer_with_lifecycle(alive_lifecycle()).await
    }

    fn poll_ready_once(writer: &mut IpcWriteStream) -> Poll<Result<(), StreamError>> {
        let waker = noop_waker_ref();
        let mut cx = Context::from_waker(waker);
        Pin::new(writer).poll_ready(&mut cx)
    }

    #[tokio::test]
    async fn poll_ready_pending_without_pull() {
        let (mut writer, _peer_ctrl, _peer_data) = setup_writer().await;
        assert!(poll_ready_once(&mut writer).is_pending());
    }

    #[tokio::test]
    async fn pull_then_send_data_roundtrip() {
        let (mut writer, mut peer_ctrl, mut peer_data) = setup_writer().await;

        peer_ctrl.send(Frame::Pull).await.unwrap();

        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"hello pipe"))
            .unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_flush(cx))
            .await
            .unwrap();

        let frame = peer_data.next().await.unwrap().unwrap();
        assert_eq!(frame, Frame::Push(Bytes::from_static(b"hello pipe")));
    }

    #[tokio::test]
    async fn pull_permission_consumed_per_data_frame() {
        let (mut writer, mut peer_ctrl, mut peer_data) = setup_writer().await;

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"first"))
            .unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_flush(cx))
            .await
            .unwrap();
        let _ = peer_data.next().await.unwrap().unwrap();

        assert!(poll_ready_once(&mut writer).is_pending());

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"second"))
            .unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_flush(cx))
            .await
            .unwrap();

        let frame = peer_data.next().await.unwrap().unwrap();
        assert_eq!(frame, Frame::Push(Bytes::from_static(b"second")));
    }

    #[tokio::test]
    async fn start_send_without_pull_returns_reset() {
        let (mut writer, _peer_ctrl, _peer_data) = setup_writer().await;

        let err = Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"no-pull"))
            .unwrap_err();
        assert!(matches!(err, StreamError::Reset { .. }));
    }

    #[tokio::test]
    async fn start_send_twice_without_flush_returns_reset() {
        let (mut writer, mut peer_ctrl, _peer_data) = setup_writer().await;

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();

        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"first"))
            .unwrap();
        let err = Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"second"))
            .unwrap_err();
        assert!(matches!(err, StreamError::Reset { .. }));
    }

    #[tokio::test]
    async fn poll_close_flushes_pending_push_and_shuts_down() {
        let (mut writer, mut peer_ctrl, mut peer_data) = setup_writer().await;

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"close-payload"))
            .unwrap();

        poll_fn(|cx| Pin::new(&mut writer).poll_close(cx))
            .await
            .unwrap();

        assert_eq!(
            peer_data.next().await.unwrap().unwrap(),
            Frame::Push(Bytes::from_static(b"close-payload"))
        );
        let eof = timeout(Duration::from_millis(200), peer_data.next())
            .await
            .expect("expected EOF after poll_close");
        assert!(eof.is_none());
    }

    #[tokio::test]
    async fn poll_cancel_sends_cancel_and_discards_pending_push() {
        let (mut writer, mut peer_ctrl, mut peer_data) = setup_writer().await;
        let code = VarInt::from_u32(77);

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"discard-me"))
            .unwrap();

        poll_fn(|cx| Pin::new(&mut writer).poll_cancel(cx, code))
            .await
            .unwrap();

        assert_eq!(
            peer_data.next().await.unwrap().unwrap(),
            Frame::Cancel(code)
        );
        let eof = timeout(Duration::from_millis(200), peer_data.next())
            .await
            .expect("expected EOF after poll_cancel");
        assert!(eof.is_none());
    }

    #[tokio::test]
    async fn stop_frame_turns_writer_into_reset() {
        let (mut writer, mut peer_ctrl, _peer_data) = setup_writer().await;

        peer_ctrl
            .send(Frame::Stop(VarInt::from_u32(7)))
            .await
            .unwrap();

        let err = poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap_err();
        match err {
            StreamError::Reset { code } => assert_eq!(code, VarInt::from_u32(7)),
            other => panic!("expected reset error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn conn_closed_frame_with_dead_lifecycle_returns_connection_error() {
        let (mut writer, mut peer_ctrl, _peer_data) =
            setup_writer_with_lifecycle(dead_lifecycle("writer conn closed")).await;

        peer_ctrl.send(Frame::ConnClosed).await.unwrap();
        let err = poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap_err();
        assert!(matches!(err, StreamError::Connection { .. }));
    }

    #[tokio::test]
    async fn read_eof_with_dead_lifecycle_sends_conn_closed_when_no_pending() {
        let (mut writer, peer_ctrl, mut peer_data) =
            setup_writer_with_lifecycle(dead_lifecycle("writer eof dead")).await;

        drop(peer_ctrl);
        let err = poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap_err();
        assert!(matches!(err, StreamError::Connection { .. }));

        let frame = timeout(Duration::from_millis(200), peer_data.next())
            .await
            .expect("expected CONN_CLOSED frame")
            .expect("expected a frame")
            .expect("expected successful decode");
        assert_eq!(frame, Frame::ConnClosed);
    }

    #[tokio::test]
    async fn conn_closed_with_pending_push_returns_connection_error_without_conn_closed_echo() {
        let (mut writer, mut peer_ctrl, mut peer_data) =
            setup_writer_with_lifecycle(dead_lifecycle("writer eof with pending")).await;

        peer_ctrl.send(Frame::Pull).await.unwrap();
        poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap();
        Pin::new(&mut writer)
            .start_send(Bytes::from_static(b"in-flight"))
            .unwrap();

        peer_ctrl.send(Frame::ConnClosed).await.unwrap();
        let flush_result = poll_fn(|cx| Pin::new(&mut writer).poll_flush(cx)).await;
        if let Err(err) = flush_result {
            assert!(matches!(err, StreamError::Connection { .. }));
        }

        if let Ok(Some(Ok(frame))) = timeout(Duration::from_millis(50), peer_data.next()).await {
            assert_ne!(frame, Frame::ConnClosed);
        }
    }

    #[tokio::test]
    async fn unexpected_cancel_frame_is_ignored_while_waiting_for_pull() {
        let (mut writer, mut peer_ctrl, _peer_data) = setup_writer().await;

        peer_ctrl
            .send(Frame::Cancel(VarInt::from_u32(1)))
            .await
            .unwrap();
        assert!(poll_ready_once(&mut writer).is_pending());
    }

    #[tokio::test]
    async fn cancel_is_noop_after_writer_is_dead() {
        let (mut writer, mut peer_ctrl, _peer_data) = setup_writer().await;

        peer_ctrl
            .send(Frame::Stop(VarInt::from_u32(123)))
            .await
            .unwrap();
        let _ = poll_fn(|cx| Pin::new(&mut writer).poll_ready(cx))
            .await
            .unwrap_err();

        poll_fn(|cx| Pin::new(&mut writer).poll_cancel(cx, VarInt::from_u32(9)))
            .await
            .unwrap();
    }
}