quietquic 0.1.0-alpha.3

A PSK-authenticated variant of QUIC that remains silent to unauthorized connection attempts
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
// SPDX-License-Identifier: 0BSD
//! Post-handshake connection and stream handles, shared by client and server.
//!
//! In sans-IO `quinn-proto`, the DRIVER owns the `quinn_proto::Connection` and
//! must pump it continuously (poll_transmit → socket, feed inbound datagrams,
//! service timers, drain app events). Application code cannot hold the
//! `Connection` directly without stalling that pump. So [`Connection`] and
//! [`SendStream`] / [`RecvStream`] here are *lightweight handles*: they send
//! commands to the driver over a [`tokio::sync::mpsc`] channel and await replies over
//! [`tokio::sync::oneshot`] channels. The driver applies each command against
//! the owned `quinn_proto::Connection` inside its event loop and routes stream
//! events back.
//!
//! This module is deliberately transport-agnostic: the server driver
//! ([`crate::server`]) and the client driver ([`crate::client`]) both translate
//! the same `Cmd`s, so the stream plumbing is written once and lives in
//! neither `server.rs` nor `client.rs`.
//!
//! # Why the *parking* lives here and not in the core
//!
//! `quietquic_proto` is sans-IO: it cannot wait for anything, so its
//! `ConnState::stream_read` answers `Read(n)` / `Blocked` / `Finished` right
//! now and never completes later. But this crate's public API promises
//! `RecvStream::read_to_end(limit).await` — a call that *does* complete later.
//! The difference between those two shapes is exactly `Parked`: the map of
//! handle operations that have been offered to the core, come back `Blocked`,
//! and are now waiting for the [`quietquic_proto::outcome::Event`] that says
//! "try again". The driver owns one `Parked` per live connection and services
//! it from its event dispatch; the core stays free of channels and runtimes.
//!
//! # Forward-compat seam ([`Connection::quinn_connection`])
//!
//! HTTP/3 (`h3`) and other stream protocols need a handle onto the underlying
//! QUIC connection to open/accept streams and drive protocol frames. Because the
//! driver — not the application — owns the `quinn_proto::Connection`, we cannot
//! hand out a `&quinn_proto::Connection` reference (it lives on another task,
//! mutated behind the command channel). Instead [`Connection::quinn_connection`]
//! returns a [`QuinnHandle`]: the minimal, `Clone`able command surface an
//! `h3`-style layer needs (open/accept bidirectional streams, read/write/finish
//! by `StreamId`) without ever touching the cloaking/pre-filter layer. See
//! [`QuinnHandle`] for the shape and the rationale.

use std::collections::{HashMap, VecDeque};
use std::time::Instant;

use bytes::Bytes;
use quietquic_proto::conn::{ConnState as CoreConn, SendFin};
use quietquic_proto::outcome::{ConnectionHandle, ReadOutcome, WriteOutcome};
use quinn_proto::{StreamId, VarInt};
use tokio::sync::{mpsc, oneshot, watch};

/// Errors surfaced by [`Connection`], [`SendStream`], and [`RecvStream`]
/// operations.
///
/// The enum itself lives in the sans-IO core (`quietquic_proto::conn`) so both
/// layers report failures in the same vocabulary — a hand-rolled embedder and a
/// tokio application see one error type, not two that must be translated. It is
/// re-exported here so `quietquic::conn::ConnError` keeps resolving.
pub use quietquic_proto::conn::ConnError;
pub use quietquic_proto::outcome::ConnectionError;

/// A command paired with the connection it targets. The driver owns one
/// `mpsc::Receiver<Tagged>` across all its connections and routes each command
/// to the matching [`ConnState`] by `handle`. (The server owns many connections;
/// the client owns one — the same channel shape serves both.)
pub(crate) struct Tagged {
    pub(crate) handle: ConnectionHandle,
    pub(crate) cmd: Cmd,
}

/// A [`Cmd`] channel sender pre-bound to one connection's handle, so handles can
/// enqueue commands without knowing the routing key. Cloned freely across a
/// connection's [`Connection`] / [`SendStream`] / [`RecvStream`] /
/// [`QuinnHandle`] handles.
#[derive(Clone)]
pub(crate) struct CmdSender {
    handle: ConnectionHandle,
    tx: mpsc::Sender<Tagged>,
}

impl CmdSender {
    pub(crate) fn new(handle: ConnectionHandle, tx: mpsc::Sender<Tagged>) -> Self {
        Self { handle, tx }
    }

    async fn send(&self, cmd: Cmd) -> Result<(), ConnError> {
        self.tx
            .send(Tagged {
                handle: self.handle,
                cmd,
            })
            .await
            .map_err(|_| ConnError::Closed)
    }

    fn try_send(&self, cmd: Cmd) -> Result<(), mpsc::error::TrySendError<Tagged>> {
        self.tx.try_send(Tagged {
            handle: self.handle,
            cmd,
        })
    }
}

/// One command the driver applies against its owned `quinn_proto::Connection`.
///
/// Every variant that produces a result carries a [`oneshot::Sender`] the driver
/// fires once it has serviced the command (immediately for open/finish, or once
/// data/FIN arrives for a read). This keeps the driver in sole control of the
/// `Connection` while letting handles await outcomes.
pub(crate) enum Cmd {
    /// Open a new bidirectional stream; reply with its assigned id.
    OpenBi(oneshot::Sender<Result<StreamId, ConnError>>),
    /// Await the next peer-initiated bidirectional stream; reply with its id.
    AcceptBi(oneshot::Sender<Result<StreamId, ConnError>>),
    /// Append `data` to a send stream. Replies once fully buffered (the driver
    /// handles write-blocking internally and re-tries on `Writable`).
    Write {
        id: StreamId,
        data: Vec<u8>,
        reply: oneshot::Sender<Result<(), ConnError>>,
    },
    /// Finish (FIN) a send stream.
    Finish {
        id: StreamId,
        reply: oneshot::Sender<Result<(), ConnError>>,
    },
    /// Wait until a previously finished send stream reaches a terminal fact.
    WaitFinished {
        id: StreamId,
        reply: oneshot::Sender<Result<(), ConnError>>,
    },
    /// Reset a send stream locally.
    Reset {
        id: StreamId,
        code: VarInt,
        reply: oneshot::Sender<Result<(), ConnError>>,
    },
    /// Stop a receive stream locally.
    Stop {
        id: StreamId,
        code: VarInt,
        reply: oneshot::Sender<Result<(), ConnError>>,
    },
    /// Release the core's send-half finish/stop fact.
    ReleaseSend { id: StreamId },
    /// Read a recv stream to end-of-stream; reply with all bytes once FIN is
    /// observed (or an error if the stream is reset).
    ReadToEnd {
        id: StreamId,
        limit: usize,
        reply: oneshot::Sender<Result<Vec<u8>, ConnError>>,
    },
    /// Read up to `max` bytes, completing as soon as any data or FIN is
    /// available. An empty vector means clean end-of-stream.
    Read {
        id: StreamId,
        max: usize,
        reply: oneshot::Sender<Result<Vec<u8>, ConnError>>,
    },
    /// Close the connection with an application error code, sending a
    /// CONNECTION_CLOSE frame so the peer (and this side's driver) tear down
    /// promptly rather than waiting out the idle timeout.
    Close { code: VarInt, reason: Vec<u8> },
}

/// A post-handshake, PSK-authenticated QUIC connection.
///
/// Produced by the server (on `accept`) and the client (once its handshake
/// reaches `Connected`), so both sides surface the same type. A `Connection` is
/// a handle onto a connection the driver still owns and pumps; dropping it does
/// not tear the connection down (the driver keeps running until the peer closes
/// or the driver's owner is dropped).
#[derive(Clone)]
pub struct Connection {
    remote: std::net::SocketAddr,
    handle: ConnectionHandle,
    client_id: Option<String>,
    cmds: CmdSender,
    closed: watch::Receiver<Option<ConnectionError>>,
}

impl Connection {
    /// Build a handle for a connection the driver owns. `cmds` is the driver's
    /// command channel, pre-tagged with this connection's handle.
    pub(crate) fn new(
        handle: ConnectionHandle,
        remote: std::net::SocketAddr,
        client_id: Option<String>,
        cmds: CmdSender,
        closed: watch::Receiver<Option<ConnectionError>>,
    ) -> Self {
        Self {
            remote,
            handle,
            client_id,
            cmds,
            closed,
        }
    }

    /// The remote peer's socket address.
    pub fn remote_address(&self) -> std::net::SocketAddr {
        self.remote
    }

    /// The endpoint-local handle identifying this connection.
    pub fn handle(&self) -> ConnectionHandle {
        self.handle
    }

    /// Authenticated server-side client identity.
    ///
    /// On a connection accepted by [`crate::server::Server`], this is the
    /// unique configured `client_id` whose PSK admitted the peer. Client-side
    /// connections return `None`.
    pub fn client_id(&self) -> Option<&str> {
        self.client_id.as_deref()
    }

    /// Open a new bidirectional stream.
    pub async fn open_bi(&self) -> Result<(SendStream, RecvStream), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds.send(Cmd::OpenBi(tx)).await?;
        let id = rx.await.map_err(|_| ConnError::Closed)??;
        Ok(bi_stream(id, self.cmds.clone()))
    }

    /// Await the next bidirectional stream the peer opens.
    pub async fn accept_bi(&self) -> Result<(SendStream, RecvStream), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds.send(Cmd::AcceptBi(tx)).await?;
        let id = rx.await.map_err(|_| ConnError::Closed)??;
        Ok(bi_stream(id, self.cmds.clone()))
    }

    /// Close the connection, sending a CONNECTION_CLOSE frame so the peer tears
    /// down promptly (rather than waiting out the idle timeout). Best-effort: if
    /// the driver is already gone the connection is effectively closed anyway.
    pub async fn close(&self, code: u64, reason: &[u8]) -> Result<(), ConnError> {
        let code = varint(code)?;
        let _ = self
            .cmds
            .send(Cmd::Close {
                code,
                reason: reason.to_vec(),
            })
            .await;
        Ok(())
    }

    /// Wait for the connection to terminate and return the terminal reason.
    pub async fn closed(&self) -> ConnectionError {
        let mut closed = self.closed.clone();
        loop {
            if let Some(reason) = closed.borrow().clone() {
                return reason;
            }
            if closed.changed().await.is_err() {
                return ConnectionError::LocallyClosed;
            }
        }
    }

    /// The forward-compat escape hatch: a minimal, `Clone`able handle onto the
    /// underlying QUIC connection that lets `h3` (or any other stream protocol)
    /// be layered on top **without touching the cloaking / pre-filter layer**.
    ///
    /// It intentionally does *not* return `&quinn_proto::Connection`: the driver
    /// owns that value on another task and mutates it behind the command
    /// channel, so a borrow cannot be handed out. Instead this exposes the
    /// operations an h3 layer actually needs — open/accept bidirectional
    /// streams and read/write/finish by `StreamId` — as async methods that route
    /// through the same command channel. When h3 is added it drives its control
    /// and request streams entirely through this handle; nothing in `server.rs`
    /// / `client.rs` (the silence-critical routing) has to change. See
    /// [`QuinnHandle`].
    pub fn quinn_connection(&self) -> QuinnHandle {
        QuinnHandle {
            handle: self.handle,
            cmds: self.cmds.clone(),
        }
    }
}

impl std::fmt::Debug for Connection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Connection")
            .field("handle", &self.handle)
            .field("remote", &self.remote)
            .field("client_id", &self.client_id)
            .finish()
    }
}

/// The minimal command surface onto the driver-owned QUIC connection that a
/// higher-level stream protocol (e.g. `h3`) layers on top of. This is the
/// documented seam that keeps HTTP/3 layering decoupled from the cloaking layer:
/// h3 opens/accepts streams and moves bytes through *this*, never through the
/// server/client driver internals.
///
/// It mirrors [`Connection`]'s stream API (which is why both are thin wrappers
/// over the same `Cmd` channel) but is `Clone` and carries the raw
/// [`ConnectionHandle`], the identity h3 keys its per-connection
/// state on.
#[derive(Clone)]
pub struct QuinnHandle {
    handle: ConnectionHandle,
    cmds: CmdSender,
}

impl QuinnHandle {
    /// The endpoint-local handle identifying this connection.
    pub fn handle(&self) -> ConnectionHandle {
        self.handle
    }

    /// Open a new bidirectional stream.
    pub async fn open_bi(&self) -> Result<(SendStream, RecvStream), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds.send(Cmd::OpenBi(tx)).await?;
        let id = rx.await.map_err(|_| ConnError::Closed)??;
        Ok(bi_stream(id, self.cmds.clone()))
    }

    /// Await the next peer-initiated bidirectional stream.
    pub async fn accept_bi(&self) -> Result<(SendStream, RecvStream), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds.send(Cmd::AcceptBi(tx)).await?;
        let id = rx.await.map_err(|_| ConnError::Closed)??;
        Ok(bi_stream(id, self.cmds.clone()))
    }

    pub async fn finish(&self, id: StreamId) -> Result<(), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds.send(Cmd::Finish { id, reply: tx }).await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }

    pub async fn wait_finished(&self, id: StreamId) -> Result<(), ConnError> {
        wait_finished(&self.cmds, id).await
    }

    pub async fn finish_and_wait(&self, id: StreamId) -> Result<(), ConnError> {
        self.finish(id).await?;
        self.wait_finished(id).await
    }

    pub async fn forget_send(&self, id: StreamId) {
        let _ = self.cmds.send(Cmd::ReleaseSend { id }).await;
    }
}

/// Receive half of a split bidirectional stream.
pub struct RecvStream {
    id: StreamId,
    cmds: CmdSender,
}

impl RecvStream {
    pub fn id(&self) -> StreamId {
        self.id
    }

    pub async fn read(&mut self, max: usize) -> Result<Vec<u8>, ConnError> {
        read_chunk(&self.cmds, self.id, max).await
    }

    pub async fn read_to_end(&mut self, limit: usize) -> Result<Vec<u8>, ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds
            .send(Cmd::ReadToEnd {
                id: self.id,
                limit,
                reply: tx,
            })
            .await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }

    pub async fn stop(&mut self, code: u64) -> Result<(), ConnError> {
        let code = varint(code)?;
        let (tx, rx) = oneshot::channel();
        self.cmds
            .send(Cmd::Stop {
                id: self.id,
                code,
                reply: tx,
            })
            .await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }
}

/// Send half of a split bidirectional stream.
pub struct SendStream {
    id: StreamId,
    cmds: CmdSender,
}

impl SendStream {
    pub fn id(&self) -> StreamId {
        self.id
    }

    pub async fn write_all(&mut self, buf: &[u8]) -> Result<(), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds
            .send(Cmd::Write {
                id: self.id,
                data: buf.to_vec(),
                reply: tx,
            })
            .await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }

    pub async fn finish(&mut self) -> Result<(), ConnError> {
        let (tx, rx) = oneshot::channel();
        self.cmds
            .send(Cmd::Finish {
                id: self.id,
                reply: tx,
            })
            .await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }

    pub async fn wait_finished(&mut self) -> Result<(), ConnError> {
        wait_finished(&self.cmds, self.id).await
    }

    pub async fn finish_and_wait(&mut self) -> Result<(), ConnError> {
        self.finish().await?;
        self.wait_finished().await
    }

    pub async fn reset(&mut self, code: u64) -> Result<(), ConnError> {
        let code = varint(code)?;
        let (tx, rx) = oneshot::channel();
        self.cmds
            .send(Cmd::Reset {
                id: self.id,
                code,
                reply: tx,
            })
            .await?;
        rx.await.map_err(|_| ConnError::Closed)?
    }
}

impl Drop for SendStream {
    fn drop(&mut self) {
        let _ = self.cmds.try_send(Cmd::ReleaseSend { id: self.id });
    }
}

async fn read_chunk(cmds: &CmdSender, id: StreamId, max: usize) -> Result<Vec<u8>, ConnError> {
    if max == 0 {
        return Ok(Vec::new());
    }
    let (tx, rx) = oneshot::channel();
    cmds.send(Cmd::Read { id, max, reply: tx }).await?;
    rx.await.map_err(|_| ConnError::Closed)?
}

async fn wait_finished(cmds: &CmdSender, id: StreamId) -> Result<(), ConnError> {
    let (tx, rx) = oneshot::channel();
    cmds.send(Cmd::WaitFinished { id, reply: tx }).await?;
    rx.await.map_err(|_| ConnError::Closed)?
}

fn bi_stream(id: StreamId, cmds: CmdSender) -> (SendStream, RecvStream) {
    (
        SendStream {
            id,
            cmds: cmds.clone(),
        },
        RecvStream { id, cmds },
    )
}

fn varint(code: u64) -> Result<VarInt, ConnError> {
    VarInt::from_u64(code).map_err(|_| ConnError::InvalidErrorCode { code })
}

// ---------------------------------------------------------------------------
// Driver-side per-connection state. Owned by the driver task; not part of the
// public handle API. Holds only the *waiting* — the core owns the protocol.
// ---------------------------------------------------------------------------

/// How much of a stream to ask the core for per [`CoreConn::stream_read`] call.
/// The core copies at most `buf.len()` bytes and never stashes a remainder, so
/// this is purely a batching knob; a `read_to_end` loops until `Blocked` or
/// `Finished` regardless.
const READ_CHUNK: usize = 16 * 1024;

/// A write that is blocked on flow control: the remaining bytes, and the reply
/// channel to fire once the whole buffer has been accepted.
struct PendingWrite {
    data: Vec<u8>,
    offset: usize,
    reply: oneshot::Sender<Result<(), ConnError>>,
}

/// A read waiting for end-of-stream: the bytes gathered so far and the reply
/// channel to fire once FIN (or a reset) is seen.
struct PendingRead {
    buf: Vec<u8>,
    /// `Some` for a read-to-FIN operation. We read at most one byte beyond this
    /// bound to distinguish an exact-size stream from an oversized one.
    end_limit: Option<usize>,
    max: Option<usize>,
    reply: oneshot::Sender<Result<Vec<u8>, ConnError>>,
}

/// One live connection's parked handle operations.
///
/// This is the whole of the tokio layer's per-connection state: everything else
/// — streams, flow control, CIDs, timers, lifecycle — belongs to the core's
/// [`CoreConn`], which the driver borrows via
/// `Endpoint::conn_mut(handle)` and passes into every method here.
///
/// Each map holds operations the core answered with "not right now". They are
/// retried from the driver's event dispatch:
///
/// | parked in           | offered again on                        |
/// |---------------------|-----------------------------------------|
/// | `pending_accepts`   | `Event::StreamOpened`                   |
/// | `blocked_writes`    | `Event::StreamWritable`                 |
/// | `pending_reads`     | `Event::StreamReadable`                 |
///
/// and all three are failed with [`ConnError::Closed`] by [`Parked::fail_all`]
/// when `Event::ConnectionLost` names this connection.
pub(crate) struct Parked {
    /// Accept requests waiting for a peer-opened bi stream, FIFO.
    pending_accepts: VecDeque<oneshot::Sender<Result<StreamId, ConnError>>>,
    /// Writes blocked on flow control, keyed by stream.
    blocked_writes: HashMap<StreamId, PendingWrite>,
    /// Reads awaiting end-of-stream, keyed by stream.
    pending_reads: HashMap<StreamId, PendingRead>,
    /// Waiters awaiting this stream's send-half terminal fact.
    fin_waiters: HashMap<StreamId, Vec<oneshot::Sender<Result<(), ConnError>>>>,
    closed: watch::Sender<Option<ConnectionError>>,
}

impl Parked {
    pub(crate) fn new(closed: watch::Sender<Option<ConnectionError>>) -> Self {
        Self {
            pending_accepts: VecDeque::new(),
            blocked_writes: HashMap::new(),
            pending_reads: HashMap::new(),
            fin_waiters: HashMap::new(),
            closed,
        }
    }

    pub(crate) fn subscribe_closed(&self) -> watch::Receiver<Option<ConnectionError>> {
        self.closed.subscribe()
    }

    pub(crate) fn mark_closed(&self, reason: ConnectionError) {
        let _ = self.closed.send(Some(reason));
    }

    /// Apply one handle-issued command against `core`, answering immediately
    /// where the core can and parking where it cannot.
    ///
    /// Note what is *absent*: no transmit is sent from here and no timer is
    /// read. Every operation below marks its connection dirty inside the core,
    /// and the driver's pump drains `poll_transmit` after this returns — which
    /// is the documented order (stream work first, transmits last) and what
    /// gets the flow-control credit a read released onto the wire.
    pub(crate) fn apply_cmd(&mut self, core: &mut CoreConn, cmd: Cmd, now: Instant) {
        match cmd {
            Cmd::OpenBi(reply) => {
                let _ = reply.send(core.open_bi());
            }
            Cmd::AcceptBi(reply) => match core.accept_bi() {
                Ok(Some(id)) => {
                    let _ = reply.send(Ok(id));
                }
                // Nothing pending: park until `Event::StreamOpened`.
                Ok(None) => self.pending_accepts.push_back(reply),
                Err(e) => {
                    let _ = reply.send(Err(e));
                }
            },
            Cmd::Write { id, data, reply } => {
                let mut pending = PendingWrite {
                    data,
                    offset: 0,
                    reply,
                };
                if !Self::pump_write(core, id, &mut pending) {
                    self.blocked_writes.insert(id, pending);
                }
            }
            Cmd::Finish { id, reply } => {
                let _ = reply.send(core.stream_finish(id));
            }
            Cmd::WaitFinished { id, reply } => match core.send_fin(id) {
                Some(SendFin::Acked) => {
                    let _ = reply.send(Ok(()));
                }
                Some(SendFin::Stopped(code)) => {
                    let _ = reply.send(Err(ConnError::Stopped { code }));
                }
                Some(SendFin::Queued) => self.fin_waiters.entry(id).or_default().push(reply),
                Some(_) => {
                    let _ = reply.send(Err(ConnError::ClosedStream));
                }
                None => {
                    let _ = reply.send(Err(ConnError::ClosedStream));
                }
            },
            Cmd::Reset { id, code, reply } => {
                let result = core.stream_reset(id, code.into_inner());
                if result.is_ok() {
                    self.fail_fin_waiters(id, ConnError::ClosedStream);
                    self.fail_blocked_write(id, ConnError::ClosedStream);
                }
                let _ = reply.send(result);
            }
            Cmd::Stop { id, code, reply } => {
                let result = core.stream_stop(id, code.into_inner());
                if result.is_ok() {
                    self.fail_pending_read(id, ConnError::ClosedStream);
                }
                let _ = reply.send(result);
            }
            Cmd::ReleaseSend { id } => {
                core.forget_send(id);
            }
            Cmd::ReadToEnd { id, limit, reply } => {
                let mut pending = PendingRead {
                    buf: Vec::new(),
                    end_limit: Some(limit),
                    max: None,
                    reply,
                };
                if !Self::pump_read(core, id, &mut pending) {
                    self.pending_reads.insert(id, pending);
                }
            }
            Cmd::Read { id, max, reply } => {
                let mut pending = PendingRead {
                    buf: Vec::new(),
                    end_limit: None,
                    max: Some(max.max(1)),
                    reply,
                };
                if !Self::pump_read(core, id, &mut pending) {
                    self.pending_reads.insert(id, pending);
                }
            }
            Cmd::Close { code, reason } => {
                // The core deliberately exposes no `close`: it is a
                // connection-level operation with no non-blocking/blocking
                // distinction, so it goes straight to the owned connection.
                // The CONNECTION_CLOSE frame it queues leaves on the pump's
                // next `poll_transmit` drain, and the close timer it arms is
                // what eventually drives the connection to `Drained` — which
                // the core reaps and reports as `Event::ConnectionLost`.
                core.conn_mut().close(now, code, Bytes::from(reason));
            }
        }
    }

    /// A peer-opened stream arrived: hand queued streams to parked accepts,
    /// FIFO, for as long as both are available.
    ///
    /// The stream id is taken from `core.accept_bi()` rather than from the
    /// event, so the core's own accept queue is consumed in step with the
    /// replies — otherwise the next `accept_bi` would re-issue an id we have
    /// already handed out.
    pub(crate) fn on_stream_opened(&mut self, core: &mut CoreConn) {
        while !self.pending_accepts.is_empty() {
            match core.accept_bi() {
                Ok(Some(id)) => {
                    if let Some(reply) = self.pending_accepts.pop_front() {
                        let _ = reply.send(Ok(id));
                    }
                }
                Ok(None) => return,
                Err(e) => {
                    if let Some(reply) = self.pending_accepts.pop_front() {
                        let _ = reply.send(Err(e));
                    }
                    return;
                }
            }
        }
    }

    /// `id` has data buffered: resume a parked `read_to_end`, if any.
    pub(crate) fn on_readable(&mut self, core: &mut CoreConn, id: StreamId) {
        let Some(mut pending) = self.pending_reads.remove(&id) else {
            return;
        };
        if !Self::pump_read(core, id, &mut pending) {
            self.pending_reads.insert(id, pending);
        }
    }

    /// `id`'s flow control opened: resume a parked `write_all`, if any.
    pub(crate) fn on_writable(&mut self, core: &mut CoreConn, id: StreamId) {
        let Some(mut pending) = self.blocked_writes.remove(&id) else {
            return;
        };
        if !Self::pump_write(core, id, &mut pending) {
            self.blocked_writes.insert(id, pending);
        }
    }

    /// Complete a finish waiter when the peer acknowledges the stream's FIN.
    pub(crate) fn on_fin_acked(&mut self, id: StreamId) {
        if let Some(waiters) = self.fin_waiters.remove(&id) {
            for reply in waiters {
                let _ = reply.send(Ok(()));
            }
        }
    }

    /// Complete waiters and writes when the peer asks us to stop sending.
    pub(crate) fn on_stopped(&mut self, core: &mut CoreConn, id: StreamId, code: u64) {
        self.fail_fin_waiters(id, ConnError::Stopped { code });
        self.on_writable(core, id);
    }

    /// Fail every parked handle operation with [`ConnError::Closed`].
    ///
    /// Called when the connection is lost, so awaiting handles wake with an
    /// error rather than hanging until their oneshot senders happen to drop.
    pub(crate) fn fail_all(&mut self) {
        for reply in self.pending_accepts.drain(..) {
            let _ = reply.send(Err(ConnError::Closed));
        }
        for (_, pending) in self.blocked_writes.drain() {
            let _ = pending.reply.send(Err(ConnError::Closed));
        }
        for (_, pending) in self.pending_reads.drain() {
            let _ = pending.reply.send(Err(ConnError::Closed));
        }
        for (_, waiters) in self.fin_waiters.drain() {
            for reply in waiters {
                let _ = reply.send(Err(ConnError::Closed));
            }
        }
    }

    fn fail_fin_waiters(&mut self, id: StreamId, err: ConnError) {
        if let Some(waiters) = self.fin_waiters.remove(&id) {
            for reply in waiters {
                let _ = reply.send(Err(err.clone()));
            }
        }
    }

    fn fail_blocked_write(&mut self, id: StreamId, err: ConnError) {
        if let Some(pending) = self.blocked_writes.remove(&id) {
            let _ = pending.reply.send(Err(err));
        }
    }

    fn fail_pending_read(&mut self, id: StreamId, err: ConnError) {
        if let Some(pending) = self.pending_reads.remove(&id) {
            let _ = pending.reply.send(Err(err));
        }
    }

    /// Offer the rest of `pending` to the core, looping while it accepts bytes.
    /// Returns true when the write is complete or has errored (the reply has
    /// been sent); false when it is still blocked and should stay parked.
    fn pump_write(core: &mut CoreConn, id: StreamId, pending: &mut PendingWrite) -> bool {
        loop {
            if pending.offset >= pending.data.len() {
                let reply = replace_reply_ok(&mut pending.reply);
                let _ = reply.send(Ok(()));
                return true;
            }
            match core.stream_write(id, &pending.data[pending.offset..]) {
                // `stream_write` only reports `Wrote(0)` for an empty buffer,
                // which the length check above has already excluded, so this
                // always advances.
                Ok(WriteOutcome::Wrote(n)) => pending.offset += n,
                Ok(WriteOutcome::Blocked) => return false,
                Err(e) => {
                    let reply = replace_reply_ok(&mut pending.reply);
                    let _ = reply.send(Err(e));
                    return true;
                }
            }
        }
    }

    /// Drain everything the core has buffered for `id` into `pending`. Returns
    /// true when end-of-stream (or an error) was reached and the reply has been
    /// sent; false when more data may still arrive and the read stays parked.
    ///
    /// This loop **is** `read_to_end`: the core offers only the incremental
    /// `Read`/`Blocked`/`Finished` answer, and accumulating across `Blocked`s
    /// until `Finished` is what turns it back into the crate's one-shot
    /// `RecvStream::read_to_end` promise.
    fn pump_read(core: &mut CoreConn, id: StreamId, pending: &mut PendingRead) -> bool {
        loop {
            // Read straight into the tail of the accumulator, so a large
            // transfer costs no per-chunk allocation and no extra copy.
            let filled = pending.buf.len();
            let request = pending
                .max
                .map(|max| max.saturating_sub(filled).min(READ_CHUNK))
                .unwrap_or_else(|| {
                    pending
                        .end_limit
                        .map(|limit| {
                            limit
                                .saturating_add(1)
                                .saturating_sub(filled)
                                .min(READ_CHUNK)
                        })
                        .unwrap_or(READ_CHUNK)
                })
                .max(1);
            pending.buf.resize(filled + request, 0);
            let outcome = core.stream_read(id, &mut pending.buf[filled..]);
            match outcome {
                Ok(ReadOutcome::Read(n)) => {
                    pending.buf.truncate(filled + n);
                    if pending
                        .end_limit
                        .is_some_and(|limit| pending.buf.len() > limit)
                    {
                        let limit = pending.end_limit.expect("checked above");
                        let reply = replace_reply_read(&mut pending.reply);
                        let _ = reply.send(Err(ConnError::ReadLimitExceeded { limit }));
                        return true;
                    }
                    if pending.max.is_some() {
                        let buf = std::mem::take(&mut pending.buf);
                        let reply = replace_reply_read(&mut pending.reply);
                        let _ = reply.send(Ok(buf));
                        return true;
                    }
                }
                Ok(ReadOutcome::Blocked) => {
                    pending.buf.truncate(filled);
                    return false;
                }
                Ok(ReadOutcome::Finished) => {
                    pending.buf.truncate(filled);
                    // The core keeps one `StreamId` per cleanly-finished stream
                    // so a *repeat* read can answer `Finished` instead of
                    // erroring. This layer has no repeat read to serve — the
                    // `read_to_end` that owns this stream is completing right
                    // now — so release it, which both bounds that set on a
                    // connection carrying many short-lived streams and keeps
                    // this crate's pre-core behaviour (a second `read_to_end`
                    // on a drained stream is an error).
                    if pending.end_limit.is_some() {
                        core.forget_recv(id);
                    }
                    let buf = std::mem::take(&mut pending.buf);
                    let reply = replace_reply_read(&mut pending.reply);
                    let _ = reply.send(Ok(buf));
                    return true;
                }
                Err(e) => {
                    pending.buf.truncate(filled);
                    let reply = replace_reply_read(&mut pending.reply);
                    let _ = reply.send(Err(e));
                    return true;
                }
            }
        }
    }
}

// The reply senders live inside `&mut` structs while we may still need the
// struct afterward, so we swap in a throwaway closed channel to take ownership
// of the real sender. (oneshot::Sender is not Clone and send consumes it.)
fn replace_reply_ok(
    slot: &mut oneshot::Sender<Result<(), ConnError>>,
) -> oneshot::Sender<Result<(), ConnError>> {
    let (dead, _) = oneshot::channel();
    std::mem::replace(slot, dead)
}

fn replace_reply_read(
    slot: &mut oneshot::Sender<Result<Vec<u8>, ConnError>>,
) -> oneshot::Sender<Result<Vec<u8>, ConnError>> {
    let (dead, _) = oneshot::channel();
    std::mem::replace(slot, dead)
}